answer
stringlengths
17
10.2M
package com.atlassian.plugin.osgi.container.felix; import com.atlassian.plugin.event.PluginEventListener; import com.atlassian.plugin.event.PluginEventManager; import com.atlassian.plugin.event.events.PluginFrameworkShutdownEvent; import com.atlassian.plugin.event.events.PluginFrameworkStartingEvent; import com.atlassian.plugin.event.events.PluginUpgradedEvent; import com.atlassian.plugin.osgi.container.OsgiContainerException; import com.atlassian.plugin.osgi.container.OsgiContainerManager; import com.atlassian.plugin.osgi.container.PackageScannerConfiguration; import com.atlassian.plugin.osgi.container.OsgiPersistentCache; import com.atlassian.plugin.osgi.container.impl.DefaultOsgiPersistentCache; import com.atlassian.plugin.osgi.hostcomponents.HostComponentProvider; import com.atlassian.plugin.osgi.hostcomponents.HostComponentRegistration; import com.atlassian.plugin.osgi.hostcomponents.impl.DefaultComponentRegistrar; import com.atlassian.plugin.osgi.util.OsgiHeaderUtil; import com.atlassian.plugin.util.ClassLoaderUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.Validate; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.felix.framework.Felix; import org.apache.felix.framework.Logger; import org.apache.felix.framework.cache.BundleCache; import org.apache.felix.framework.util.FelixConstants; import org.apache.felix.framework.util.StringMap; import org.osgi.framework.Bundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.BundleException; import org.osgi.framework.BundleListener; import org.osgi.framework.Constants; import org.osgi.framework.FrameworkEvent; import org.osgi.framework.FrameworkListener; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.osgi.service.packageadmin.PackageAdmin; import org.osgi.util.tracker.ServiceTracker; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ThreadFactory; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.jar.JarFile; /** * Felix implementation of the OSGi container manager */ public class FelixOsgiContainerManager implements OsgiContainerManager { public static final String OSGI_FRAMEWORK_BUNDLES_ZIP = "osgi-framework-bundles.zip"; private static final Log log = LogFactory.getLog(FelixOsgiContainerManager.class); private static final String OSGI_BOOTDELEGATION = "org.osgi.framework.bootdelegation"; private static final String ATLASSIAN_PREFIX = "atlassian."; private final OsgiPersistentCache persistentCache; private final URL frameworkBundlesUrl; private final PackageScannerConfiguration packageScannerConfig; private final HostComponentProvider hostComponentProvider; private final Set<ServiceTracker> trackers; private final ExportsBuilder exportsBuilder; private final ThreadFactory threadFactory = new ThreadFactory() { public Thread newThread(final Runnable r) { final Thread thread = new Thread(r, "Felix:Startup"); thread.setDaemon(true); return thread; } }; private BundleRegistration registration = null; private Felix felix = null; private boolean felixRunning = false; private boolean disableMultipleBundleVersions = true; private Logger felixLogger; /** * Constructs the container manager using the framework bundles zip file located in this library * @param frameworkBundlesDir The directory to unzip the framework bundles into. * @param packageScannerConfig The configuration for package scanning * @param provider The host component provider. May be null. * @param eventManager The plugin event manager to register for init and shutdown events * @deprecated Since 2.2.0, use * {@link #FelixOsgiContainerManager(OsgiPersistentCache,PackageScannerConfiguration,HostComponentProvider,PluginEventManager)} instead */ @Deprecated public FelixOsgiContainerManager(final File frameworkBundlesDir, final PackageScannerConfiguration packageScannerConfig, final HostComponentProvider provider, final PluginEventManager eventManager) { this(ClassLoaderUtils.getResource(OSGI_FRAMEWORK_BUNDLES_ZIP, FelixOsgiContainerManager.class), frameworkBundlesDir, packageScannerConfig, provider, eventManager); } /** * Constructs the container manager * @param frameworkBundlesZip The location of the zip file containing framework bundles * @param frameworkBundlesDir The directory to unzip the framework bundles into. * @param packageScannerConfig The configuration for package scanning * @param provider The host component provider. May be null. * @param eventManager The plugin event manager to register for init and shutdown events * @deprecated Since 2.2.0, use * {@link #FelixOsgiContainerManager(URL, OsgiPersistentCache,PackageScannerConfiguration,HostComponentProvider,PluginEventManager)} instead */ @Deprecated public FelixOsgiContainerManager(final URL frameworkBundlesZip, final File frameworkBundlesDir, final PackageScannerConfiguration packageScannerConfig, final HostComponentProvider provider, final PluginEventManager eventManager) { this(frameworkBundlesZip, new DefaultOsgiPersistentCache(new File(frameworkBundlesDir.getParentFile(), "osgi-cache")), packageScannerConfig, provider, eventManager); } /** * Constructs the container manager using the framework bundles zip file located in this library * @param persistentCache The persistent cache configuration. * @param packageScannerConfig The configuration for package scanning * @param provider The host component provider. May be null. * @param eventManager The plugin event manager to register for init and shutdown events * * @since 2.2.0 */ public FelixOsgiContainerManager(final OsgiPersistentCache persistentCache, final PackageScannerConfiguration packageScannerConfig, final HostComponentProvider provider, final PluginEventManager eventManager) { this(ClassLoaderUtils.getResource(OSGI_FRAMEWORK_BUNDLES_ZIP, FelixOsgiContainerManager.class), persistentCache, packageScannerConfig, provider, eventManager); } /** * Constructs the container manager * @param frameworkBundlesZip The location of the zip file containing framework bundles * @param persistentCache The persistent cache to use for the framework and framework bundles * @param packageScannerConfig The configuration for package scanning * @param provider The host component provider. May be null. * @param eventManager The plugin event manager to register for init and shutdown events * * @since 2.2.0 * @throws com.atlassian.plugin.osgi.container.OsgiContainerException If the host version isn't supplied and the * cache directory cannot be cleaned. */ public FelixOsgiContainerManager(final URL frameworkBundlesZip, OsgiPersistentCache persistentCache, final PackageScannerConfiguration packageScannerConfig, final HostComponentProvider provider, final PluginEventManager eventManager) throws OsgiContainerException { Validate.notNull(frameworkBundlesZip, "The framework bundles zip is required"); Validate.notNull(persistentCache, "The framework bundles directory must not be null"); Validate.notNull(packageScannerConfig, "The package scanner configuration must not be null"); Validate.notNull(eventManager, "The plugin event manager is required"); frameworkBundlesUrl = frameworkBundlesZip; this.packageScannerConfig = packageScannerConfig; this.persistentCache = persistentCache; hostComponentProvider = provider; trackers = Collections.synchronizedSet(new HashSet<ServiceTracker>()); eventManager.register(this); felixLogger = new FelixLoggerBridge(log); exportsBuilder = new ExportsBuilder(); } public void setFelixLogger(final Logger logger) { felixLogger = logger; } public void setDisableMultipleBundleVersions(final boolean val) { disableMultipleBundleVersions = val; } @PluginEventListener public void onStart(final PluginFrameworkStartingEvent event) { start(); } @PluginEventListener public void onShutdown(final PluginFrameworkShutdownEvent event) { stop(); } @PluginEventListener public void onPluginUpgrade(PluginUpgradedEvent event) { registration.refreshPackages(); } public void start() throws OsgiContainerException { if (isRunning()) { return; } detectIncorrectOsgiVersion(); final DefaultComponentRegistrar registrar = collectHostComponents(hostComponentProvider); // Create a case-insensitive configuration property map. final StringMap configMap = new StringMap(false); // Configure the Felix instance to be embedded. configMap.put(FelixConstants.EMBEDDED_EXECUTION_PROP, "true"); // Add the bundle provided service interface package and the core OSGi // packages to be exported from the class path via the system bundle. configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES, exportsBuilder.determineExports(registrar.getRegistry(), packageScannerConfig, persistentCache.getOsgiBundleCache())); // Explicitly specify the directory to use for caching bundles. configMap.put(BundleCache.CACHE_PROFILE_DIR_PROP, persistentCache.getOsgiBundleCache().getAbsolutePath()); configMap.put(FelixConstants.LOG_LEVEL_PROP, String.valueOf(felixLogger.getLogLevel())); String bootDelegation = getAtlassianSpecificOsgiSystemProperty(OSGI_BOOTDELEGATION); if ((bootDelegation == null) || (bootDelegation.trim().length() == 0)) { bootDelegation = "weblogic.*,META-INF.services,com.yourkit.*,com.jprofiler.*,org.apache.xerces.*"; } configMap.put(Constants.FRAMEWORK_BOOTDELEGATION, bootDelegation); if (log.isDebugEnabled()) { log.debug("Felix configuration: " + configMap); } validateCaches(configMap); try { // Create host activator; registration = new BundleRegistration(frameworkBundlesUrl, persistentCache.getFrameworkBundleCache(), registrar); final List<BundleActivator> list = new ArrayList<BundleActivator>(); list.add(registration); // Now create an instance of the framework with // our configuration properties and activator. felix = new Felix(felixLogger, configMap, list); // Now start Felix instance. Starting in a different thread to explicity set daemon status final Runnable start = new Runnable() { public void run() { try { felix.start(); felixRunning = true; } catch (final BundleException e) { throw new OsgiContainerException("Unable to start felix", e); } } }; final Thread t = threadFactory.newThread(start); t.start(); // Give it 10 seconds t.join(10 * 60 * 1000); } catch (final Exception ex) { throw new OsgiContainerException("Unable to start OSGi container", ex); } } /** * Validate caches based on the list of packages exported from the application. If the list has changed, the cache * directories should be cleared. * * @param configMap The felix configuration */ private void validateCaches(StringMap configMap) { String cacheKey = String.valueOf(configMap.get(Constants.FRAMEWORK_SYSTEMPACKAGES).hashCode()); persistentCache.validate(cacheKey); log.debug("Using Felix bundle cache directory :" + persistentCache.getOsgiBundleCache().getAbsolutePath()); } /** * Detects incorrect configuration of WebSphere 6.1 that leaks OSGi 4.0 jars into the application */ private void detectIncorrectOsgiVersion() { try { Bundle.class.getMethod("getBundleContext"); } catch (final NoSuchMethodException e) { throw new OsgiContainerException( "Detected older version (4.0 or earlier) of OSGi. If using WebSphere " + "6.1, please enable application-first (parent-last) classloading and the 'Single classloader for " + "application' WAR classloader policy."); } } public void stop() throws OsgiContainerException { if (felixRunning) { for (final ServiceTracker tracker : new HashSet<ServiceTracker>(trackers)) { tracker.close(); } felix.stopAndWait(); } felixRunning = false; felix = null; } public Bundle[] getBundles() { if (isRunning()) { return registration.getBundles(); } else { throw new IllegalStateException( "Cannot retrieve the bundles if the Felix container isn't running. Check earlier in the logs for the possible cause as to why Felix didn't start correctly."); } } public ServiceReference[] getRegisteredServices() { return felix.getRegisteredServices(); } public ServiceTracker getServiceTracker(final String cls) { if (!isRunning()) { throw new IllegalStateException("Unable to create a tracker when osgi is not running"); } final ServiceTracker tracker = registration.getServiceTracker(cls, trackers); tracker.open(); trackers.add(tracker); return tracker; } public Bundle installBundle(final File file) throws OsgiContainerException { try { return registration.install(file, disableMultipleBundleVersions); } catch (final BundleException e) { throw new OsgiContainerException("Unable to install bundle", e); } } DefaultComponentRegistrar collectHostComponents(final HostComponentProvider provider) { final DefaultComponentRegistrar registrar = new DefaultComponentRegistrar(); if (provider != null) { provider.provide(registrar); } return registrar; } public boolean isRunning() { return felixRunning; } public List<HostComponentRegistration> getHostComponentRegistrations() { return registration.getHostComponentRegistrations(); } private String getAtlassianSpecificOsgiSystemProperty(final String originalSystemProperty) { return System.getProperty(ATLASSIAN_PREFIX + originalSystemProperty); } /** * Manages framework-level framework bundles and host components registration, and individual plugin bundle * installation and removal. */ static class BundleRegistration implements BundleActivator, BundleListener, FrameworkListener { private BundleContext bundleContext; private final DefaultComponentRegistrar registrar; private List<ServiceRegistration> hostServicesReferences; private List<HostComponentRegistration> hostComponentRegistrations; private final URL frameworkBundlesUrl; private final File frameworkBundlesDir; private PackageAdmin packageAdmin; public BundleRegistration(final URL frameworkBundlesUrl, final File frameworkBundlesDir, final DefaultComponentRegistrar registrar) { this.registrar = registrar; this.frameworkBundlesUrl = frameworkBundlesUrl; this.frameworkBundlesDir = frameworkBundlesDir; } public void start(final BundleContext context) throws Exception { bundleContext = context; final ServiceReference ref = context.getServiceReference(org.osgi.service.packageadmin.PackageAdmin.class.getName()); packageAdmin = (PackageAdmin) context.getService(ref); context.addBundleListener(this); context.addFrameworkListener(this); loadHostComponents(registrar); extractAndInstallFrameworkBundles(); } public void stop(final BundleContext ctx) throws Exception { ctx.removeBundleListener(this); ctx.removeFrameworkListener(this); } public void bundleChanged(final BundleEvent evt) { switch (evt.getType()) { case BundleEvent.INSTALLED: log.info("Installed bundle " + evt.getBundle().getSymbolicName() + " (" + evt.getBundle().getBundleId() + ")"); break; case BundleEvent.RESOLVED: log.info("Resolved bundle " + evt.getBundle().getSymbolicName() + " (" + evt.getBundle().getBundleId() + ")"); break; case BundleEvent.UNRESOLVED: log.info("Unresolved bundle " + evt.getBundle().getSymbolicName() + " (" + evt.getBundle().getBundleId() + ")"); break; case BundleEvent.STARTED: log.info("Started bundle " + evt.getBundle().getSymbolicName() + " (" + evt.getBundle().getBundleId() + ")"); break; case BundleEvent.STOPPED: log.info("Stopped bundle " + evt.getBundle().getSymbolicName() + " (" + evt.getBundle().getBundleId() + ")"); break; case BundleEvent.UNINSTALLED: log.info("Uninstalled bundle " + evt.getBundle().getSymbolicName() + " (" + evt.getBundle().getBundleId() + ")"); break; } } public Bundle install(final File path, final boolean uninstallOtherVersions) throws BundleException { boolean bundleUninstalled = false; if (uninstallOtherVersions) { try { final JarFile jar = new JarFile(path); final String pluginKey = OsgiHeaderUtil.getPluginKey(jar.getManifest()); for (final Bundle oldBundle : bundleContext.getBundles()) { if (pluginKey.equals(OsgiHeaderUtil.getPluginKey(oldBundle))) { log.info("Uninstalling existing version " + oldBundle.getHeaders().get(Constants.BUNDLE_VERSION)); oldBundle.uninstall(); bundleUninstalled = true; } } } catch (final IOException e) { throw new BundleException("Invalid bundle format", e); } } final Bundle bundle = bundleContext.installBundle(path.toURI().toString()); if (bundleUninstalled) { refreshPackages(); } return bundle; } public Bundle[] getBundles() { return bundleContext.getBundles(); } public ServiceTracker getServiceTracker(final String clazz, final Set<ServiceTracker> trackedTrackers) { return new ServiceTracker(bundleContext, clazz, null) { @Override public void close() { trackedTrackers.remove(this); } }; } public List<HostComponentRegistration> getHostComponentRegistrations() { return hostComponentRegistrations; } private void loadHostComponents(final DefaultComponentRegistrar registrar) { // Unregister any existing host components if (hostServicesReferences != null) { for (final ServiceRegistration reg : hostServicesReferences) { reg.unregister(); } } // Register host components as OSGi services hostServicesReferences = registrar.writeRegistry(bundleContext); hostComponentRegistrations = registrar.getRegistry(); } private void extractAndInstallFrameworkBundles() throws BundleException { final List<Bundle> bundles = new ArrayList<Bundle>(); com.atlassian.plugin.util.FileUtils.conditionallyExtractZipFile(frameworkBundlesUrl, frameworkBundlesDir); for (final File bundleFile : frameworkBundlesDir.listFiles(new FilenameFilter() { public boolean accept(final File file, final String s) { return s.endsWith(".jar"); } })) { bundles.add(install(bundleFile, false)); } for (final Bundle bundle : bundles) { bundle.start(); } } public void refreshPackages() { final CountDownLatch latch = new CountDownLatch(1); FrameworkListener refreshListener = new FrameworkListener() { public void frameworkEvent(FrameworkEvent event) { if (event.getType() == FrameworkEvent.PACKAGES_REFRESHED) { log.info("Packages refreshed"); latch.countDown(); } } }; bundleContext.addFrameworkListener(refreshListener); try { packageAdmin.refreshPackages(null); boolean refreshed = false; try { refreshed = latch.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { // ignore } if (!refreshed) { log.warn("Timeout exceeded waiting for package refresh"); } } finally { bundleContext.removeFrameworkListener(refreshListener); } } public void frameworkEvent(FrameworkEvent event) { String bundleBits = ""; if (event.getBundle() != null) { bundleBits = " in bundle " + event.getBundle().getSymbolicName(); } switch (event.getType()) { case FrameworkEvent.ERROR: log.error("Framework error" + bundleBits, event.getThrowable()); break; case FrameworkEvent.WARNING: log.warn("Framework warning" + bundleBits, event.getThrowable()); break; case FrameworkEvent.INFO: log.info("Framework info" + bundleBits, event.getThrowable()); break; } } } }
package com.exedio.cope.console; import java.io.PrintStream; import java.util.Iterator; import javax.servlet.http.HttpServletRequest; import com.exedio.cope.Model; import com.exedio.cops.XMLEncoder; import com.exedio.dsmf.Column; import com.exedio.dsmf.Constraint; import com.exedio.dsmf.Schema; import com.exedio.dsmf.StatementListener; import com.exedio.dsmf.Table; final class SchemaCop extends ConsoleCop { SchemaCop() { super(TAB_SCHEMA, "schema"); } @Override void writeHead(final PrintStream out) { Schema_Jspm.writeHead(out); } @Override final void writeBody( final PrintStream out, final Model model, final HttpServletRequest request, final History history, final boolean historyModelShown) { Schema_Jspm.writeBody(this, out, model, request); } private static final Column getColumn(final Schema schema, final String param) { final int pos = param.indexOf(' if(pos<=0) throw new RuntimeException(param); final Table table = schema.getTable(param.substring(0, pos)); if(table==null) throw new RuntimeException(param); final Column result = table.getColumn(param.substring(pos+1)); if(result==null) throw new RuntimeException(param); return result; } private static final Constraint getConstraint(final Schema schema, final String param) { final int pos = param.indexOf(' if(pos<=0) throw new RuntimeException(param); final Table table = schema.getTable(param.substring(0, pos)); if(table==null) throw new RuntimeException(param); final Constraint result = table.getConstraint(param.substring(pos+1)); if(result==null) throw new RuntimeException(param); return result; } static final String DROP_CONSTRAINT = "DROP_CONSTRAINT"; static final String CREATE_CONSTRAINT = "CREATE_CONSTRAINT"; final static void writeApply(final PrintStream out, final HttpServletRequest request, final Model model, final boolean dryRun) { final Schema schema = model.getVerifiedSchema(); final StatementListener listener = new StatementListener() { long beforeExecuteTime = Long.MIN_VALUE; public boolean beforeExecute(final String statement) { out.print("\n\t\t<li>"); out.print(XMLEncoder.encode(statement)); out.print("</li>"); if(dryRun) { return false; } else { out.flush(); beforeExecuteTime = System.currentTimeMillis(); return true; } } public void afterExecute(final String statement, final int rows) { final long time = System.currentTimeMillis()-beforeExecuteTime; out.print("\n\t\t<li class=\"timelog\">"); out.print(time); out.print("ms, "); out.print(rows); out.print(" rows</li>"); } }; { final String[] dropConstraints = (String[]) request.getParameterMap().get(DROP_CONSTRAINT); if (dropConstraints != null) { for(final String dropConstraint : dropConstraints) { final Constraint constraint = getConstraint(schema, dropConstraint); constraint.drop(listener); } } } { final String[] dropColumns = (String[]) request.getParameterMap().get("DROP_COLUMN"); // TODO use constant and use the constant in Schema.jspm if (dropColumns != null) { for(final String dropColumn : dropColumns) { final Column column = getColumn(schema, dropColumn); column.drop(listener); } } } { final String[] dropTables = (String[]) request.getParameterMap().get("DROP_TABLE"); // TODO use constant and use the constant in Schema.jspm if (dropTables != null) { for(final String dropTable : dropTables) { final Table table = schema.getTable(dropTable); if (table == null) throw new RuntimeException(dropTable); table.drop(listener); } } } { for (Iterator i = request.getParameterMap().keySet().iterator(); i.hasNext(); ) { final String parameterName = (String) i.next(); if (!parameterName.startsWith("RENAME_TABLE_")) // TODO use constant and use the constant in Schema.jspm continue; final String targetName = request.getParameter(parameterName).trim(); if (targetName.length() == 0) continue; final String sourceName = parameterName.substring("RENAME_TABLE_" // TODO use constant and use the constant in Schema.jspm .length()); final Table table = schema.getTable(sourceName); if (table == null) throw new RuntimeException(sourceName); table.renameTo(targetName, listener); } } { for (Iterator i = request.getParameterMap().keySet().iterator(); i.hasNext(); ) { final String parameterName = (String) i.next(); if (!parameterName.startsWith("MODIFY_COLUMN_")) // TODO use constant and use the constant in Schema.jspm continue; final String targetType = request.getParameter(parameterName).trim(); if (targetType.length() == 0) continue; final String sourceName = parameterName.substring("MODIFY_COLUMN_" // TODO use constant and use the constant in Schema.jspm .length()); final Column column = getColumn(schema, sourceName); if (column == null) throw new RuntimeException(sourceName); column.modify(targetType, listener); } } { for (Iterator i = request.getParameterMap().keySet().iterator(); i.hasNext(); ) { final String parameterName = (String) i.next(); if (!parameterName.startsWith("RENAME_COLUMN_")) // TODO use constant and use the constant in Schema.jspm continue; final String targetName = request.getParameter(parameterName).trim(); if (targetName.length() == 0) continue; final String sourceName = parameterName.substring("RENAME_COLUMN_" // TODO use constant and use the constant in Schema.jspm .length()); final Column column = getColumn(schema, sourceName); if (column == null) throw new RuntimeException(sourceName); column.renameTo(targetName, listener); } } { final String[] createTables = (String[]) request.getParameterMap().get("CREATE_TABLE"); // TODO use constant and use the constant in Schema.jspm if (createTables != null) { for(final String createTable : createTables) { final Table table = schema.getTable(createTable); if (table == null) throw new RuntimeException(createTable); table.create(listener); } } } { final String[] createColumns = (String[]) request.getParameterMap().get("CREATE_COLUMN"); // TODO use constant and use the constant in Schema.jspm if (createColumns != null) { for(final String createColumn : createColumns) { final Column column = getColumn(schema, createColumn); column.create(listener); } } } { final String[] createConstraints = (String[]) request.getParameterMap().get(CREATE_CONSTRAINT); if (createConstraints != null) { for(final String createConstraint : createConstraints) { final Constraint constraint = getConstraint(schema, createConstraint); constraint.create(listener); } } } } }
package reborncore.common.fluid; import net.minecraft.fluid.Fluids; import reborncore.common.fluid.container.FluidInstance; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.fluid.Fluid; import net.minecraft.item.ItemStack; import net.minecraft.util.Hand; import net.minecraft.util.registry.Registry; import org.apache.commons.lang3.StringUtils; import reborncore.common.util.Tank; import javax.annotation.Nonnull; public class FluidUtil { @Deprecated public static FluidInstance getFluidHandler(ItemStack stack) { return null; } @Deprecated public static boolean interactWithFluidHandler(PlayerEntity playerIn, Hand hand, Tank tank) { return false; } @Deprecated public static ItemStack getFilledBucket(FluidInstance stack) { return null; } public static String getFluidName(@Nonnull FluidInstance fluidInstance){ return getFluidName(fluidInstance.getFluid()); } public static String getFluidName(@Nonnull Fluid fluid){ return StringUtils.capitalize(Registry.FLUID.getId(fluid).getPath()); } public static void transferFluid(Tank source, Tank destination, FluidValue amount) { if (source == null || destination == null) { return; } if (source.getFluid() == Fluids.EMPTY || source.getFluidAmount().isEmpty()) { return; } if (destination.getFluid() != Fluids.EMPTY && source.getFluid() != destination.getFluid()) { return; } FluidValue transferAmount = source.getFluidAmount().min(amount); if (destination.getFreeSpace().equalOrMoreThan(transferAmount)) { FluidInstance fluidInstance = destination.getFluidInstance(); if (fluidInstance.isEmpty()) { fluidInstance = new FluidInstance(source.getFluid(), transferAmount); } else { fluidInstance.addAmount(transferAmount); } source.setFluidAmount(source.getFluidAmount().subtract(transferAmount)); destination.setFluidInstance(fluidInstance); if (source.getFluidAmount().equals(FluidValue.EMPTY)) { source.setFluid(Fluids.EMPTY); } } } }
package com.sequenceiq.authorization.resource; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.ws.rs.NotFoundException; public enum AuthorizationResourceAction { CHANGE_CREDENTIAL("environments/changeCredential", AuthorizationResourceType.ENVIRONMENT), EDIT_CREDENTIAL("environments/editCredential", AuthorizationResourceType.CREDENTIAL), EDIT_ENVIRONMENT("environments/editEnvironment", AuthorizationResourceType.ENVIRONMENT), START_ENVIRONMENT("environments/startEnvironment", AuthorizationResourceType.ENVIRONMENT), STOP_ENVIRONMENT("environments/stopEnvironment", AuthorizationResourceType.ENVIRONMENT), DELETE_CREDENTIAL("environments/deleteCredential", AuthorizationResourceType.CREDENTIAL), DESCRIBE_CREDENTIAL("environments/describeCredential", AuthorizationResourceType.CREDENTIAL), DESCRIBE_CREDENTIAL_ON_ENVIRONMENT("environments/describeCredential", AuthorizationResourceType.ENVIRONMENT), DELETE_ENVIRONMENT("environments/deleteCdpEnvironment", AuthorizationResourceType.ENVIRONMENT), DESCRIBE_ENVIRONMENT("environments/describeEnvironment", AuthorizationResourceType.ENVIRONMENT), ACCESS_ENVIRONMENT("environments/accessEnvironment", AuthorizationResourceType.ENVIRONMENT), ADMIN_FREEIPA("environments/adminFreeIPA", AuthorizationResourceType.ENVIRONMENT), REPAIR_FREEIPA("environments/repairFreeIPA", AuthorizationResourceType.ENVIRONMENT), SCALE_FREEIPA("environments/scaleFreeIPA", AuthorizationResourceType.ENVIRONMENT), UPGRADE_FREEIPA("environments/upgradeFreeIPA", AuthorizationResourceType.ENVIRONMENT), CREATE_CREDENTIAL("environments/createCredential", AuthorizationResourceType.CREDENTIAL), CREATE_ENVIRONMENT("environments/createEnvironment", AuthorizationResourceType.ENVIRONMENT), GET_KEYTAB("environments/getKeytab", AuthorizationResourceType.ENVIRONMENT), CREATE_IMAGE_CATALOG("environments/createImageCatalog", AuthorizationResourceType.IMAGE_CATALOG), EDIT_IMAGE_CATALOG("environments/editImageCatalog", AuthorizationResourceType.IMAGE_CATALOG), DESCRIBE_IMAGE_CATALOG("environments/useSharedResource", AuthorizationResourceType.IMAGE_CATALOG), DELETE_IMAGE_CATALOG("environments/deleteImageCatalog", AuthorizationResourceType.IMAGE_CATALOG), DESCRIBE_CLUSTER_DEFINITION("environments/useSharedResource", AuthorizationResourceType.CLUSTER_DEFINITION), DELETE_CLUSTER_DEFINITION("environments/deleteClusterDefinitions", AuthorizationResourceType.CLUSTER_DEFINITION), CREATE_CLUSTER_DEFINITION("environments/createClusterDefinitions", AuthorizationResourceType.CLUSTER_DEFINITION), DESCRIBE_CLUSTER_TEMPLATE("environments/useSharedResource", AuthorizationResourceType.CLUSTER_TEMPLATE), DELETE_CLUSTER_TEMPLATE("datahub/deleteClusterTemplate", AuthorizationResourceType.CLUSTER_TEMPLATE), CREATE_CLUSTER_TEMPLATE("datahub/createClusterTemplate", AuthorizationResourceType.CLUSTER_TEMPLATE), GET_OPERATION_STATUS("environments/getFreeipaOperationStatus", AuthorizationResourceType.ENVIRONMENT), CREATE_DATALAKE("datalake/createDatalake", AuthorizationResourceType.DATALAKE), RESIZE_DATALAKE("datalake/resizeDatalake", AuthorizationResourceType.DATALAKE), DESCRIBE_DATALAKE("datalake/describeDatalake", AuthorizationResourceType.DATALAKE), DESCRIBE_DETAILED_DATALAKE("datalake/describeDetailedDatalake", AuthorizationResourceType.DATALAKE), DELETE_DATALAKE("datalake/deleteDatalake", AuthorizationResourceType.DATALAKE), REPAIR_DATALAKE("datalake/repairDatalake", AuthorizationResourceType.DATALAKE), SYNC_DATALAKE("datalake/syncDatalake", AuthorizationResourceType.DATALAKE), RETRY_DATALAKE_OPERATION("datalake/retryDatalakeOperation", AuthorizationResourceType.DATALAKE), START_DATALAKE("datalake/startDatalake", AuthorizationResourceType.DATALAKE), STOP_DATALAKE("datalake/stopDatalake", AuthorizationResourceType.DATALAKE), UPGRADE_DATALAKE("datalake/upgradeDatalake", AuthorizationResourceType.DATALAKE), RECOVER_DATALAKE("datalake/recoverDatalake", AuthorizationResourceType.DATALAKE), SYNC_COMPONENT_VERSIONS_FROM_CM_DATALAKE("datalake/syncComponentVersionsFromCm", AuthorizationResourceType.DATALAKE), CHANGE_IMAGE_CATALOG_DATALAKE("datalake/changeImageCatalog", AuthorizationResourceType.DATALAKE), ROTATE_CERT_DATALAKE("datalake/rotateAutoTlsCertDatalake", AuthorizationResourceType.DATALAKE), ENVIRONMENT_CREATE_DATAHUB("environments/createDatahub", AuthorizationResourceType.ENVIRONMENT), DESCRIBE_DATAHUB("datahub/describeDatahub", AuthorizationResourceType.DATAHUB), RECOVER_DATAHUB("datahub/recoverDatahub", AuthorizationResourceType.DATAHUB), DELETE_DATAHUB("datahub/deleteDatahub", AuthorizationResourceType.DATAHUB), REPAIR_DATAHUB("datahub/repairDatahub", AuthorizationResourceType.DATAHUB), SYNC_DATAHUB("datahub/syncDatahub", AuthorizationResourceType.DATAHUB), RETRY_DATAHUB_OPERATION("datahub/retryDatahubOperation", AuthorizationResourceType.DATAHUB), DESCRIBE_RETRYABLE_DATAHUB_OPERATION("datahub/describeRetryableDatahubOperation", AuthorizationResourceType.DATAHUB), START_DATAHUB("datahub/startDatahub", AuthorizationResourceType.DATAHUB), STOP_DATAHUB("datahub/stopDatahub", AuthorizationResourceType.DATAHUB), SCALE_DATAHUB("datahub/scaleDatahub", AuthorizationResourceType.DATAHUB), DELETE_DATAHUB_INSTANCE("datahub/deleteDatahubInstance", AuthorizationResourceType.DATAHUB), SET_DATAHUB_MAINTENANCE_MODE("datahub/setDatahubMaintenanceMode", AuthorizationResourceType.DATAHUB), ROTATE_AUTOTLS_CERT_DATAHUB("datahub/rotateAutoTlsCertDatahub", AuthorizationResourceType.DATAHUB), REFRESH_RECIPES_DATAHUB("datahub/refreshRecipes", AuthorizationResourceType.DATAHUB), REFRESH_RECIPES_DATALAKE("datalake/refreshRecipes", AuthorizationResourceType.DATALAKE), UPGRADE_DATAHUB("datahub/upgradeDatahub", AuthorizationResourceType.DATAHUB), SYNC_COMPONENT_VERSIONS_FROM_CM_DATAHUB("datahub/syncComponentVersionsFromCm", AuthorizationResourceType.DATAHUB), CHANGE_IMAGE_CATALOG_DATAHUB("datahub/changeImageCatalog", AuthorizationResourceType.DATAHUB), DESCRIBE_DATABASE("environments/describeDatabase", AuthorizationResourceType.DATABASE), DESCRIBE_DATABASE_SERVER("environments/describeDatabaseServer", AuthorizationResourceType.DATABASE_SERVER), DELETE_DATABASE("environments/deleteDatabase", AuthorizationResourceType.DATABASE), DELETE_DATABASE_SERVER("environments/deleteDatabaseServer", AuthorizationResourceType.DATABASE_SERVER), REGISTER_DATABASE("environments/registerDatabase", AuthorizationResourceType.DATABASE), REGISTER_DATABASE_SERVER("environments/registerDatabaseServer", AuthorizationResourceType.DATABASE_SERVER), CREATE_DATABASE_SERVER("environments/createDatabaseServer", AuthorizationResourceType.DATABASE_SERVER), CREATE_DATABASE("environments/createDatabase", AuthorizationResourceType.DATABASE_SERVER), START_DATABASE_SERVER("environments/startDatabaseServer", AuthorizationResourceType.DATABASE_SERVER), STOP_DATABASE_SERVER("environments/stopDatabaseServer", AuthorizationResourceType.DATABASE_SERVER), BACKUP_DATALAKE("datalake/backupDatalake", AuthorizationResourceType.DATALAKE), RESTORE_DATALAKE("datalake/restoreDatalake", AuthorizationResourceType.DATALAKE), DESCRIBE_RECIPE("environments/useSharedResource", AuthorizationResourceType.RECIPE), CREATE_RECIPE("environments/createRecipe", AuthorizationResourceType.RECIPE), DELETE_RECIPE("environments/deleteRecipe", AuthorizationResourceType.RECIPE), UPGRADE_CCM("environments/upgradeCcm", AuthorizationResourceType.ENVIRONMENT), DESCRIBE_CUSTOM_CONFIGS("datahub/describeCustomConfigs", AuthorizationResourceType.CUSTOM_CONFIGURATIONS), CREATE_CUSTOM_CONFIGS("datahub/createCustomConfigs", AuthorizationResourceType.CUSTOM_CONFIGURATIONS), DELETE_CUSTOM_CONFIGS("datahub/deleteCustomConfigs", AuthorizationResourceType.CUSTOM_CONFIGURATIONS), CREATE_AUDIT_CREDENTIAL("environments/createAuditCredential", AuthorizationResourceType.AUDIT_CREDENTIAL), DESCRIBE_AUDIT_CREDENTIAL("environments/describeAuditCredential", AuthorizationResourceType.AUDIT_CREDENTIAL), ROTATE_SALTUSER_PASSWORD_ENVIRONMENT("environments/rotateSaltuserPassword", AuthorizationResourceType.ENVIRONMENT), MODIFY_AUDIT_CREDENTIAL("environments/modifyAuditCredential", AuthorizationResourceType.AUDIT_CREDENTIAL), POWERUSER_ONLY("cloudbreak/allowPowerUserOnly", null), LIST_ASSIGNED_ROLES("iam/listAssignedResourceRoles", null), STRUCTURED_EVENTS_READ("structured_events/read", AuthorizationResourceType.STRUCTURED_EVENT), UPDATE_AZURE_ENCRYPTION_RESOURCES("environments/updateAzureEncryptionResources", AuthorizationResourceType.ENVIRONMENT), ENVIRONMENT_CHANGE_FREEIPA_IMAGE("environments/changeFreeipaImageCatalog", AuthorizationResourceType.ENVIRONMENT), // deprecated actions, please do not use them ENVIRONMENT_READ("environments/read", AuthorizationResourceType.ENVIRONMENT), ENVIRONMENT_WRITE("environments/write", AuthorizationResourceType.ENVIRONMENT), DATALAKE_READ("datalake/read", AuthorizationResourceType.DATALAKE), DATALAKE_WRITE("datalake/write", AuthorizationResourceType.DATALAKE), DATAHUB_READ("datahub/read", AuthorizationResourceType.DATAHUB), DATAHUB_WRITE("datahub/write", AuthorizationResourceType.DATAHUB); private static final Map<String, List<AuthorizationResourceAction>> BY_RIGHT = Stream.of(AuthorizationResourceAction.values()) .collect(Collectors.groupingBy(AuthorizationResourceAction::getRight)); private final String right; private final AuthorizationResourceType authorizationResourceType; AuthorizationResourceAction(String right, AuthorizationResourceType authorizationResourceType) { this.right = right; this.authorizationResourceType = authorizationResourceType; } public String getRight() { return right; } public AuthorizationResourceType getAuthorizationResourceType() { return authorizationResourceType; } public static AuthorizationResourceAction getByRight(String right) { List<AuthorizationResourceAction> result = BY_RIGHT.get(right); if (result == null || result.isEmpty()) { throw new NotFoundException(String.format("Action not found by right %s", right)); } else if (result.size() > 1) { throw new NotFoundException(String.format("Multiple results found by right %s, thus we cannot lookup for action!", right)); } return result.get(0); } }
package ru.carabi.server.kernel; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonArrayBuilder; import javax.json.JsonException; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonReader; import javax.json.JsonValue; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.persistence.TypedQuery; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.text.StrBuilder; import ru.carabi.libs.CarabiEventType; import ru.carabi.server.CarabiException; import ru.carabi.server.Settings; import ru.carabi.server.UserLogon; import ru.carabi.server.Utls; import ru.carabi.server.entities.CarabiUser; import ru.carabi.server.entities.ConnectionSchema; import ru.carabi.server.entities.FileOnServer; import ru.carabi.server.entities.Phone; import ru.carabi.server.entities.PhoneType; import ru.carabi.server.entities.QueryCategory; import ru.carabi.server.entities.QueryEntity; import ru.carabi.server.entities.QueryParameterEntity; import ru.carabi.server.entities.UserRelation; import ru.carabi.server.entities.UserRelationType; import ru.carabi.server.entities.UserStatus; @Stateless public class AdminBean { private static final Logger logger = Logger.getLogger(AdminBean.class.getName()); @PersistenceContext(unitName = "ru.carabi.server_carabiserver-kernel") private EntityManager em; private @EJB ConnectionsGateBean cg; private @EJB EventerBean eventer; private @EJB ImagesBean images; private @EJB UsersControllerBean uc; public List<String> getUserAllowedSchemas(UserLogon logon, String login) throws CarabiException { if (!logon.getUser().getLogin().equals(login)) { logon.assertAllowed("ADMINISTRATING-USERS-VIEW"); } logger.log(Level.FINEST, "package ru.carabi.server.kernel.AdminBean" +".getUserAllowedSchemas(String login)" +" caller params: {0}", new Object[]{login}); close(); final CarabiUser user = uc.findUser(login); final Collection<ConnectionSchema> allowedSchemas = user.getAllowedSchemas(); List<String> schemasList = new ArrayList<>(allowedSchemas.size()); for (ConnectionSchema allowedSchema: allowedSchemas) { logger.log(Level.INFO, "{0} allowed {1} ({2}, {3})", new Object[]{login, allowedSchema.getName(), allowedSchema.getSysname(), allowedSchema.getJNDI()}); schemasList.add(allowedSchema.getSysname()); } close(); return schemasList; } public String getUsersList(UserLogon logon, String statusSysname) throws CarabiException { logon.assertAllowed("ADMINISTRATING-USERS-VIEW"); Query query; if (statusSysname != null) { query = em.createNamedQuery("getSchemaUsersWithStatusList"); query.setParameter("status", statusSysname); } else { query = em.createNamedQuery("getSchemaUsersList"); } query.setParameter("schema_id", logon.getSchema().getId()); final List resultList = query.getResultList(); close(); final JsonArrayBuilder jsonUsers = Json.createArrayBuilder(); final Iterator usersIterator = resultList.iterator(); while (usersIterator.hasNext()) { final Object[] dbUser = (Object[]) usersIterator.next(); final JsonObjectBuilder jsonUserDetails = Json.createObjectBuilder(); Utls.addJsonObject(jsonUserDetails, "id", dbUser[0]); Utls.addJsonObject(jsonUserDetails, "login", dbUser[1]); final StrBuilder name = new StrBuilder(); name.setNullText(""); name.append(dbUser[2]).append(" ").append(dbUser[3]).append(" ") .append(dbUser[4]); Utls.addJsonObject(jsonUserDetails, "name", name.toString()); final JsonObjectBuilder jsonUser = Json.createObjectBuilder(); jsonUser.add("carabiuser", jsonUserDetails); jsonUsers.add(jsonUser); } // handles empty list case - just add root object "carabiusers" final JsonObjectBuilder result = Json.createObjectBuilder(); result.add("carabiusers", jsonUsers); // returns results return result.build().toString(); } public String getUser(UserLogon logon, Long id) throws CarabiException { if (!logon.getUser().getId().equals(id)) { logon.assertAllowed("ADMINISTRATING-USERS-VIEW"); } final CarabiUser carabiUser = em.find(CarabiUser.class, id); if (null == carabiUser) { final CarabiException e = new CarabiException( "Пользователь не найден по ID: " + id.toString()); logger.log(Level.WARNING, "" , e); throw e; } // fill in user fields final JsonObjectBuilder jsonUserDetails = Json.createObjectBuilder(); jsonUserDetails.add("id", carabiUser.getId()); Utls.addJsonObject(jsonUserDetails, "firstName", carabiUser.getFirstname()); Utls.addJsonObject(jsonUserDetails, "middleName", carabiUser.getMiddlename()); Utls.addJsonObject(jsonUserDetails, "lastName", carabiUser.getLastname()); Utls.addJsonObject(jsonUserDetails, "department", carabiUser.getCarabiDepartment()); Utls.addJsonObject(jsonUserDetails, "role", carabiUser.getCarabiRole()); Utls.addJsonObject(jsonUserDetails, "login", carabiUser.getLogin()); Utls.addJsonObject(jsonUserDetails, "password", carabiUser.getPassword()); Utls.addJsonObject(jsonUserDetails, "defaultSchemaId", (null == carabiUser.getDefaultSchema()) ? "" : carabiUser.getDefaultSchema().getId()); // fill in schemas list with regard to whether a schema is allowed or not // 1. read from kernel db final TypedQuery<ConnectionSchema> query = em.createNamedQuery("fullSelectAllSchemas", ConnectionSchema.class); final List<ConnectionSchema> connectionSchemas = query.getResultList(); close(); // 2. make json final JsonArrayBuilder jsonConnectionSchemas = Json.createArrayBuilder(); for (ConnectionSchema connectionSchema: connectionSchemas) { // see if the current is allowed for user boolean isAllowed = false; close(); final Collection allowedSchemas = carabiUser.getAllowedSchemas(); final Iterator<ConnectionSchema> allowedSchemasIterator = allowedSchemas.iterator(); while (allowedSchemasIterator.hasNext()) { final ConnectionSchema allowedSchema = allowedSchemasIterator.next(); if (allowedSchema.getId().equals(connectionSchema.getId())) { isAllowed = true; break; } } final JsonObjectBuilder jsonConnectionSchemaDetails = Json.createObjectBuilder(); jsonConnectionSchemaDetails.add("id", connectionSchema.getId()); Utls.addJsonObject(jsonConnectionSchemaDetails, "name", connectionSchema.getName()); Utls.addJsonObject(jsonConnectionSchemaDetails, "sysName", connectionSchema.getSysname()); Utls.addJsonObject(jsonConnectionSchemaDetails, "jndi", connectionSchema.getJNDI()); jsonConnectionSchemaDetails.add("isAllowed", isAllowed); final JsonObjectBuilder jsonConnectionSchema = Json.createObjectBuilder(); jsonConnectionSchema.add("connectionSchema", jsonConnectionSchemaDetails); jsonConnectionSchemas.add(jsonConnectionSchema); } jsonUserDetails.add("connectionSchemas", jsonConnectionSchemas); // add the list of user phones to jsonUserDetails final TypedQuery<Phone> phonesQuery = em.createNamedQuery("selectUserPhones", Phone.class); phonesQuery.setParameter("ownerId", id); final List<Phone> phones = phonesQuery.getResultList(); close(); final JsonArrayBuilder jsonPhones = Json.createArrayBuilder(); for (Phone phone: phones) { final JsonObjectBuilder jsonPhoneDetails = Json.createObjectBuilder(); // add all fileds, but ownerId, which is the parameter of this method (so caller already has it) jsonPhoneDetails.add("id", phone.getId()); Utls.addJsonObject(jsonPhoneDetails, "phoneType", null == phone.getPhoneType() ? null : phone.getPhoneType().getId()); Utls.addJsonObject(jsonPhoneDetails, "countryCode", phone.getCountryCode()); Utls.addJsonObject(jsonPhoneDetails, "regionCode", phone.getRegionCode()); Utls.addJsonObject(jsonPhoneDetails, "mainNumber", phone.getMainNumber()); Utls.addJsonObject(jsonPhoneDetails, "suffix", phone.getSuffix()); Utls.addJsonObject(jsonPhoneDetails, "schemaId", null == phone.getSipSchema() ? null : phone.getSipSchema().getId()); Utls.addJsonObject(jsonPhoneDetails, "orderNumber", phone.getOrdernumber()); // pack all phone details (write to jsonPhone and add it to jsonPhones) final JsonObjectBuilder jsonPhone = Json.createObjectBuilder(); jsonPhone.add("phone", jsonPhoneDetails); jsonPhones.add(jsonPhone); } jsonUserDetails.add("phones", jsonPhones); // build a response string out of json and return it as the result final JsonObjectBuilder jsonUser = Json.createObjectBuilder(); jsonUser.add("carabiuser", jsonUserDetails); return jsonUser.build().toString(); } public Long saveUser(UserLogon logon, String strUser) throws CarabiException { return saveUser(logon, strUser, true); } public Long saveUser(UserLogon logon, String strUser, boolean updateSchemas) throws CarabiException { logon.assertAllowed("ADMINISTRATING-USERS-EDIT"); // parse url string and obtain json object final String nonUrlNewData = strUser.replace("&quot;", "\""); JsonReader jsonReader = Json.createReader(new StringReader(nonUrlNewData)); final JsonObject userDetails = jsonReader.readObject(); // create or fetch user CarabiUser user; if (!userDetails.containsKey("id") || "".equals(Utls.getNativeJsonString(userDetails,"id"))) { user = new CarabiUser(); } else { Long userId; try { userId = Long.decode(Utls.getNativeJsonString(userDetails,"id")); } catch (NumberFormatException nfe) { final CarabiException e = new CarabiException( "Неверный формат ID пользователя. " + "Ожидется: java.lang.Long", nfe); logger.log(Level.WARNING, "" , e); throw e; } user = em.find(CarabiUser.class, userId); } // set simple user fields user.setFirstname(userDetails.getString("firstName")); user.setMiddlename(userDetails.getString("middleName")); user.setLastname(userDetails.getString("lastName")); user.setLogin(userDetails.getString("login")); user.setPassword(userDetails.getString("password")); user.setCarabiDepartment(userDetails.getString("department")); user.setCarabiRole(userDetails.getString("role")); // update phones if (user.getPhonesList() != null) { for (Phone phone: user.getPhonesList()) { em.remove(phone); } close(); // fix for error: non persisted object in a relationship marked for cascade persist. // releasing a user object before updating its list of phones. } String[] phones = {}; if(!("".equals(userDetails.getString("phones")))) { // if phones string is empty, just use empty phones list phones = userDetails.getString("phones").replace("||||", "| | ||").replace("^||", "^| |").replace("|||", "| ||").split("\\|\\|"); // using replace to handle the cases when "" is set for phone schema, phone type or both of them. interpret " " as NULL below. // there is an important assumption made that we have trailing "^" at the end of all numbers (so the client-side must set it even // if suffix is empty) } ArrayList<Phone> phonesList = new ArrayList<>(phones.length); int phoneOrderNumber = 1; for (String phoneStr: phones) { String[] phoneElements = phoneStr.split("\\|"); Phone phone = new Phone(); if (phoneElements.length > 0) { phone.parse(phoneElements[0]); } PhoneType phoneType = null; if (phoneElements.length > 1 && !" ".equals(phoneElements[1])) { final String phoneTypeName = phoneElements[1]; final TypedQuery<PhoneType> findPhoneType = em.createNamedQuery("findPhoneType", PhoneType.class); findPhoneType.setParameter("name", phoneTypeName); final List<PhoneType> resultList = findPhoneType.getResultList(); if (resultList.isEmpty()) { phoneType = new PhoneType(); phoneType.setName(phoneTypeName); phoneType.setSysname(phoneTypeName); } else { phoneType = resultList.get(0); } if (phoneType.getSysname().equals("SIP")) { phone.setSipSchema(user.getDefaultSchema()); } } if (phoneElements.length > 2) { if (!("".equals(phoneElements[2]) || " ".equals(phoneElements[2]))) { final ConnectionSchema phoneSchema = em.find(ConnectionSchema.class, Integer.parseInt(phoneElements[2])); phone.setSipSchema(phoneSchema); } else { phone.setSipSchema(null); } } phone.setPhoneType(phoneType); phone.setOrdernumber(phoneOrderNumber); phoneOrderNumber++; phone.setOwner(user); phonesList.add(phone); } user.setPhonesList(phonesList); // updates schemas if (updateSchemas) { if (!userDetails.containsKey("defaultSchemaId")) { user.setDefaultSchema(null); } else { int schemaId; try { schemaId = userDetails.getInt("defaultSchemaId"); } catch (NumberFormatException nfe) { final CarabiException e = new CarabiException( "Неверный формат ID схемы подключения. " + "Ожидется: java.lang.Integer", nfe); logger.log(Level.WARNING, "" , e); throw e; } final ConnectionSchema schema = em.find(ConnectionSchema.class, schemaId); user.setDefaultSchema(schema); } final JsonArray allowedSchemaIds = userDetails.getJsonArray("allowedSchemaIds"); if (allowedSchemaIds.size()>0) { final Collection<Integer> listAllowedSchemaIds = new ArrayList(allowedSchemaIds.size()); for (int i = 0; i < allowedSchemaIds.size(); i++) { listAllowedSchemaIds.add(allowedSchemaIds.getInt(i)); } final TypedQuery<ConnectionSchema> allowedSchemasQuery = em.createQuery( "select cs from ConnectionSchema cs where cs.id IN :ids", ConnectionSchema.class); allowedSchemasQuery.setParameter("ids", listAllowedSchemaIds); final List<ConnectionSchema> allowedSchemas = allowedSchemasQuery.getResultList(); user.setAllowedSchemas(allowedSchemas); } else { user.setAllowedSchemas(Collections.EMPTY_LIST); } } // save user data user = em.merge(user); close(); return user.getId(); } public void deleteUser(UserLogon logon, String login) throws CarabiException { logon.assertAllowed("ADMINISTRATING-USERS-EDIT"); if (login == null) { final CarabiException e = new CarabiException("Невозможно удалить " + "пользователя, т.к. не задан login удаляемой записи."); logger.log(Level.WARNING, "" , e); throw e; } final Query query = em.createQuery("DELETE FROM CarabiUser cu WHERE cu.login = :login"); int deletedCount = query.setParameter("login", login).executeUpdate(); if (deletedCount != 1) { final CarabiException e = new CarabiException("Нет записи с таким login-ом. Ошибка удаления " + "пользователя при выполнении JPA-запроса."); logger.log(Level.WARNING, "" , e); throw e; } } public String getSchemasList(UserLogon logon) throws CarabiException { logon.assertAllowed("ADMINISTRATING-SCHEMAS-VIEW"); // gets oracle databases from kernel db final TypedQuery query = em.createQuery( "select CS from ConnectionSchema CS order by CS.name", ConnectionSchema.class); final List resultList = query.getResultList(); close(); // creates json object of the following form // { "connectionSchemes": [ // { "connectionSchema", [ // { "name", ""}, // { "sysName", ""}, // { "jndiName", ""} final JsonArrayBuilder jsonSchemas = Json.createArrayBuilder(); final Iterator<ConnectionSchema> schemasIterator = resultList.iterator(); while (schemasIterator.hasNext()) { final ConnectionSchema schema = schemasIterator.next(); JsonObjectBuilder jsonSchemaDetails = createJsonSchema(schema); final JsonObjectBuilder jsonSchema = Json.createObjectBuilder(); jsonSchema.add("connectionSchema", jsonSchemaDetails); jsonSchemas.add(jsonSchema); } // handles empty list case - just add root object "carabiusers" final JsonObjectBuilder result = Json.createObjectBuilder(); result.add("connectionSchemes", jsonSchemas); // returns results return result.build().toString(); } private JsonObjectBuilder createJsonSchema(final ConnectionSchema schema) { JsonObjectBuilder jsonSchemaDetails = Json.createObjectBuilder(); jsonSchemaDetails.add("id", schema.getId()); Utls.addJsonObject(jsonSchemaDetails, "name", schema.getName()); Utls.addJsonObject(jsonSchemaDetails, "sysName", schema.getSysname()); Utls.addJsonObject(jsonSchemaDetails, "jndiName", schema.getJNDI()); return jsonSchemaDetails; } public String getSchema(UserLogon logon, Integer id) throws CarabiException { logon.assertAllowed("ADMINISTRATING-SCHEMAS-VIEW"); final ConnectionSchema schema = em.find(ConnectionSchema.class, id); if (null == schema) { CarabiException e = new CarabiException("Cхема подключения не " + "найдена по ID: " + id.toString()); logger.log(Level.WARNING, "" , e); throw e; } // fill in user fields final JsonObjectBuilder jsonSchema = createJsonSchema(schema); // returns results return jsonSchema.build().toString(); } public Integer saveSchema(UserLogon logon, String strSchema) throws CarabiException { logon.assertAllowed("ADMINISTRATING-SCHEMAS-EDIT"); // parse url string and obtain json object final String nonUrlStrSchema = strSchema.replace("&quot;", "\""); final JsonReader jsonSchemaReader = Json.createReader(new StringReader(nonUrlStrSchema)); final JsonObject jsonSchema = jsonSchemaReader.readObject(); // create or fetch schema ConnectionSchema schema; if (!jsonSchema.containsKey("id") || "".equals(Utls.getNativeJsonString(jsonSchema,"id"))) { schema = new ConnectionSchema(); } else { int schemaId; try { schemaId = Integer.decode(jsonSchema.getString("id")); } catch (NumberFormatException nfe) { final CarabiException e = new CarabiException( "Неверный формат ID. Ожидется: java.lang.Integer", nfe); logger.log(Level.WARNING, "" , e); throw e; } schema = em.find(ConnectionSchema.class, schemaId); close(); } schema.setName(jsonSchema.getString("name")); schema.setSysname(jsonSchema.getString("sysName")); schema.setJNDI(jsonSchema.getString("jndiName")); // save user data schema = em.merge(schema); close(); return schema.getId(); } public void deleteSchema(UserLogon logon, Integer id) throws CarabiException { logon.assertAllowed("ADMINISTRATING-SCHEMAS-EDIT"); if (null == id) { final CarabiException e = new CarabiException("Невозможно удалить " + "схему подключения, т.к. не задан ID удаляемой записи."); logger.log(Level.WARNING, "" , e); throw e; } final Query query = em.createQuery("DELETE FROM ConnectionSchema cs WHERE cs.id = :id"); int deletedCount = query.setParameter("id", id).executeUpdate(); if (deletedCount != 1) { final CarabiException e = new CarabiException("Нет записи с таким id. Ошибка удаления " + "схемы подключения при выполнении JPA-запроса."); logger.log(Level.WARNING, "" , e); throw e; } } public String getCategoriesList(UserLogon logon) throws CarabiException { logon.assertAllowed("ADMINISTRATING-QUERIES-VIEW"); final TypedQuery query = em.createQuery( "select Q from QueryCategory Q order by Q.name", QueryCategory.class); final List resultList = query.getResultList(); close(); JsonArrayBuilder categories = Json.createArrayBuilder(); final JsonObjectBuilder jsonFieldsAll = Json.createObjectBuilder(); jsonFieldsAll.add("id", -1); jsonFieldsAll.add("name", "Все"); jsonFieldsAll.add("description", "Все запросы из всех категорий"); categories.add(jsonFieldsAll); final Iterator<QueryCategory> categoryIterator = resultList.iterator(); while (categoryIterator.hasNext()) { final QueryCategory queryCategory = categoryIterator.next(); final JsonObjectBuilder jsonFields = Json.createObjectBuilder(); jsonFields.add("id", queryCategory.getId()); jsonFields.add("name", queryCategory.getName()); if (queryCategory.getDescription() == null) { jsonFields.addNull("description"); } else { jsonFields.add("description", queryCategory.getDescription()); } categories.add(jsonFields); } final JsonObjectBuilder result = Json.createObjectBuilder(); result.add("categories", categories); return result.build().toString(); } public Long saveCategory(UserLogon logon, String strCategory) throws CarabiException { logon.assertAllowed("ADMINISTRATING-QUERIES-EDIT"); // log the call logger.log(Level.INFO, "package ru.carabi.server.kernel" +".AdminBean.saveCategory(String strCategory)" +" caller params: {0}", strCategory); // parse url string and obtain json object final String nonUrlStrCategory = strCategory.replace("&quot;", "\""); final JsonReader jsonCategoryReader = Json.createReader(new StringReader(nonUrlStrCategory)); final JsonObject jsonCategory = jsonCategoryReader.readObject(); // create or fetch category QueryCategory queryCategory; if (!jsonCategory.containsKey("id") || jsonCategory.get("id").getValueType().equals(JsonValue.ValueType.NULL) || "".equals(Utls.getNativeJsonString(jsonCategory,"id"))) { queryCategory = new QueryCategory(); } else { long queryCategoryId; try { queryCategoryId = Long.decode(jsonCategory.getString("id")); } catch (NumberFormatException nfe) { final CarabiException e = new CarabiException( "Неверный формат ID. Ожидется: java.lang.Integer", nfe); logger.log(Level.WARNING, "" , e); throw e; } queryCategory = em.find(QueryCategory.class, queryCategoryId); close(); } queryCategory.setName(jsonCategory.getString("name")); queryCategory.setDescription(jsonCategory.getString("name")); // note: in the current implementation category name== category decription. // this is because the description field in becoming obsolete, as we are not using it in the interfaces. // save user data queryCategory = em.merge(queryCategory); close(); return queryCategory.getId(); } public void deleteCategory(UserLogon logon, Integer id) throws CarabiException { logon.assertAllowed("ADMINISTRATING-QUERIES-EDIT"); if (null == id) { final CarabiException e = new CarabiException("Невозможно удалить " + "категорию запросов, т.к. не задан ID удаляемой записи."); logger.log(Level.WARNING, "" , e); throw e; } final Query query = em.createQuery("DELETE FROM QueryCategory qc WHERE qc.id = :id"); int deletedCount = query.setParameter("id", id).executeUpdate(); if (deletedCount != 1) { final CarabiException e = new CarabiException("Нет записи с таким id. Ошибка удаления " + "категории запросов при выполнении JPA-запроса."); logger.log(Level.WARNING, "" , e); throw e; } } public String getQueriesList(UserLogon logon, int categoryId) throws CarabiException { logon.assertAllowed("ADMINISTRATING-QUERIES-VIEW"); TypedQuery query; if (categoryId >= 0) { query = em.createNamedQuery("selectCategoryQueries", QueryEntity.class); query.setParameter("categoryId", categoryId); } else { query = em.createNamedQuery("selectAllQueries", QueryEntity.class); } final List resultList = query.getResultList(); close(); // creates json object of the following form // { "queries": [ // { "query", // { "category": "" }, // { "name", ""} final JsonArrayBuilder jsonQueries = Json.createArrayBuilder(); final Iterator<QueryEntity> schemasIterator = resultList.iterator(); while (schemasIterator.hasNext()) { final QueryEntity queryEntity = schemasIterator.next(); final JsonObjectBuilder jsonFields = Json.createObjectBuilder(); jsonFields.add("id", queryEntity.getId()); jsonFields.add("category", queryEntity.getCategory().getName()); jsonFields.add("name", queryEntity.getName()); jsonFields.add("sysname", queryEntity.getSysname()); jsonFields.add("isExecutable", queryEntity.getIsExecutable()); String schemaId = queryEntity.getSchema() == null ? "" : queryEntity.getSchema().getId().toString(); jsonFields.add("schemaId", schemaId); final JsonObjectBuilder jsonQuery = Json.createObjectBuilder(); jsonQuery.add("query", jsonFields); jsonQueries.add(jsonQuery); } // handles empty list case - just add root object "carabiusers" final JsonObjectBuilder result = Json.createObjectBuilder(); result.add("queries", jsonQueries); // returns results return result.build().toString(); } public String getQuery(UserLogon logon, Long id) throws CarabiException { logon.assertAllowed("ADMINISTRATING-QUERIES-VIEW"); final QueryEntity queryEntity = em.find(QueryEntity.class, id); if (queryEntity == null) { final CarabiException e = new CarabiException( "Запрос не найден по ID: " + id.toString()); logger.log(Level.WARNING, "" , e); throw e; } // fill in user fields final JsonObjectBuilder jsonQuery = Json.createObjectBuilder(); jsonQuery.add("id", queryEntity.getId()); jsonQuery.add("сategoryId", queryEntity.getCategory().getId()); jsonQuery.add("name", queryEntity.getName()); jsonQuery.add("isExecutable", queryEntity.getIsExecutable()); jsonQuery.add("schemaId", queryEntity.getSchema() == null ? "" : queryEntity.getSchema().getId().toString()); jsonQuery.add("text", queryEntity.getBody()); jsonQuery.add("sysname", queryEntity.getSysname()); // fill params final JsonArrayBuilder jsonParams = Json.createArrayBuilder(); for (QueryParameterEntity p : queryEntity.getParameters()) { final JsonObjectBuilder jsonParam = Json.createObjectBuilder(); jsonParam.add("id", p.getId()); jsonParam.add("orderNumber", p.getOrdernumber()); jsonParam.add("name", p.getName()); jsonParam.add("type", p.getType()); jsonParam.add("isIn", p.getIsIn()); jsonParam.add("isOut", p.getIsOut()); final JsonObjectBuilder jsonParamWrapper = Json.createObjectBuilder(); jsonParamWrapper.add("param", jsonParam); jsonParams.add(jsonParamWrapper); } jsonQuery.add("params", jsonParams); // returns results return jsonQuery.build().toString(); } public Long saveQuery(UserLogon logon, String strQuery) throws CarabiException { logon.assertAllowed("ADMINISTRATING-QUERIES-EDIT"); // log the call logger.log(Level.INFO, "package ru.carabi.server.kernel" +".AdminBean.saveQuery(String strQuery)" +" caller params: {0}", strQuery); // parse url string and obtain json object final String nonUrlStrQuery = strQuery.replace("&quot;", "\""); JsonReader queryReader = Json.createReader(new StringReader(nonUrlStrQuery)); final JsonObject jsonQuery = queryReader.readObject(); // create or fetch query QueryEntity queryEntity; if (!jsonQuery.containsKey("id")) { queryEntity = new QueryEntity(); } else { long queryId; try { queryId = jsonQuery.getJsonNumber("id").longValueExact(); } catch (NumberFormatException nfe) { final CarabiException e = new CarabiException("Неверный формат ID. " + "Ожидется: java.lang.Long", nfe); logger.log(Level.WARNING, "" , e); throw e; } queryEntity = em.find(QueryEntity.class, queryId); } int schemaId; try { schemaId = jsonQuery.getInt("schemaId"); } catch (NumberFormatException nfe) { final CarabiException e = new CarabiException("Неверный формат " + "ID схемы. Ожидется: java.lang.Integer", nfe); logger.log(Level.WARNING, "" , e); throw e; } final ConnectionSchema schema = em.find(ConnectionSchema.class, schemaId); long categoryId; try { categoryId = jsonQuery.getJsonNumber("categoryId").longValueExact(); } catch (NumberFormatException nfe) { final CarabiException e = new CarabiException("Неверный формат " + "ID категории. Ожидется: java.lang.Long", nfe); logger.log(Level.WARNING, "" , e); throw e; } final QueryCategory category = em.find(QueryCategory.class, categoryId); queryEntity.setCategory(category); queryEntity.setName(jsonQuery.getString("name")); queryEntity.setIsExecutable(jsonQuery.getBoolean("isExecutable")); queryEntity.setSchema(schema); queryEntity.setBody(jsonQuery.getString("text")); queryEntity.setSysname(jsonQuery.getString("sysname")); final JsonArray jsonParams = jsonQuery.getJsonArray("params"); if (null == queryEntity.getId()) { queryEntity.setParameters(new ArrayList<QueryParameterEntity>(jsonParams.size())); } else { final Query query = em.createQuery( "DELETE FROM QueryParameterEntity p " + "WHERE p.queryEntity.id = :id"); query.setParameter("id", queryEntity.getId()).executeUpdate(); queryEntity.getParameters().clear(); } for (int i=0; i<jsonParams.size(); i++) { final JsonObject jsonParam = jsonParams.getJsonObject(i).getJsonObject("param"); final QueryParameterEntity param = new QueryParameterEntity(); param.setOrdernumber(jsonParam.getInt("orderNumber")); param.setName(jsonParam.getString("name")); param.setType(jsonParam.getString("type")); param.setIsIn(jsonParam.getBoolean("isIn") ? 1 : 0); param.setIsOut(jsonParam.getBoolean("isOut") ? 1 : 0); param.setQueryEntity(queryEntity); queryEntity.getParameters().add(param); } // save user data queryEntity = em.merge(queryEntity); close(); return queryEntity.getId(); } public void deleteQuery(UserLogon logon, Long id) throws CarabiException { logon.assertAllowed("ADMINISTRATING-QUERIES-EDIT"); if (null == id) { final CarabiException e = new CarabiException("Невозможно удалить " + "хранимый запрос, т.к. не задан ID удаляемой записи."); logger.log(Level.WARNING, "" , e); throw e; } final Query query = em.createQuery("DELETE FROM QueryEntity q WHERE q.id = :id"); int deletedCount = query.setParameter("id", id).executeUpdate(); if (deletedCount != 1) { final CarabiException e = new CarabiException("Нет записи с таким id. Ошибка удаления " + "хранимого запроса при выполнении JPA-запроса."); logger.log(Level.WARNING, "" , e); throw e; } } public void setQueryDeprecated(UserLogon logon, Long id, boolean isDeprecated) throws CarabiException { logon.assertAllowed("ADMINISTRATING-QUERIES-EDIT"); if (null == id) { final CarabiException e = new CarabiException("Невозможно обработать " + "хранимый запрос, т.к. не задан ID записи."); logger.log(Level.WARNING, "" , e); throw e; } final Query query = em.createNativeQuery("update ORACLE_QUERY set IS_DEPRECATED = ? where QUERY_ID = ?"); query.setParameter(1, isDeprecated); query.setParameter(2, id); query.executeUpdate(); } private void close() { em.flush(); em.clear(); } public FileOnServer createUserAvatar(UserLogon logon, CarabiUser targetUser) throws CarabiException { CarabiUser user; if (targetUser == null) { user = logon.getUser(); } else { logon.assertAllowed("ADMINISTRATING-USERS-EDIT"); user = targetUser; } String login = user.getLogin(); FileOnServer avatar = user.getAvatar(); if (avatar != null) { user.setAvatar(null); user = em.merge(user); deleteAvatar(avatar); } avatar = new FileOnServer(); avatar.setName(login); avatar = em.merge(avatar); em.flush(); avatar.setContentAddress(Settings.AVATARS_LOCATION + "/" + avatar.getId() + "_" + login); user.setAvatar(avatar); user = em.merge(user); em.flush(); if (targetUser == null) { logon.setUser(user); } return avatar; } public FileOnServer refreshAvatar(FileOnServer fileMetadata) { return em.merge(fileMetadata); } private void deleteAvatar(FileOnServer avatar) { images.removeThumbnails(avatar, true); File avatarFile = new File(avatar.getContentAddress()); avatarFile.delete(); em.remove(em.find(FileOnServer.class, avatar.getId())); em.flush(); } public void addUserRelations(CarabiUser mainUser, String relatedUsersListStr, String relationName) throws CarabiException { List<CarabiUser> relatedUsersList = makeRelatedUsersList(relatedUsersListStr); UserRelationType relationType = getUserRelationType(relationName); for (CarabiUser relatedUser: relatedUsersList) { TypedQuery<UserRelation> findUsersRelation = em.createNamedQuery("findUsersRelation", UserRelation.class); findUsersRelation.setParameter("mainUser", mainUser); findUsersRelation.setParameter("relatedUser", relatedUser); UserRelation relation; List<UserRelation> findUsersRelationResult = findUsersRelation.getResultList(); if (findUsersRelationResult.isEmpty()) { relation = new UserRelation(); relation.setMainUser(mainUser); relation.setRelatedUser(relatedUser); relation.setRelationTypes(new ArrayList<UserRelationType>()); } else { relation = findUsersRelationResult.get(0); } relation.getRelationTypes().add(relationType); em.merge(relation); } em.flush(); try { fireRelationEvent(relatedUsersListStr, relationName, mainUser, CarabiEventType.usersRelationsAdd.getCode()); } catch (IOException ex) { Logger.getLogger(AdminBean.class.getName()).log(Level.SEVERE, null, ex); } } private void fireRelationEvent(String relatedUsersListStr, String relationName, CarabiUser mainUser, short code) throws CarabiException, IOException { String event = "{\"users\":" + relatedUsersListStr + ", \"relation\":"; if (StringUtils.isEmpty(relationName)) { event += "null}"; } else { event += "\"" + relationName + "\"}"; } eventer.fireEvent("", mainUser.getLogin(), code, event); } private UserRelationType getUserRelationType(String relationName) { TypedQuery<UserRelationType> findRelationType = em.createNamedQuery("findRelationType", UserRelationType.class); findRelationType.setParameter("name", relationName); UserRelationType relationType; List<UserRelationType> findRelationTypeResult = findRelationType.getResultList(); if (!findRelationTypeResult.isEmpty()) { return findRelationType.getSingleResult(); } else if (!StringUtils.isEmpty(relationName)) { relationType = new UserRelationType(); relationType.setName(relationName); relationType.setSysname(relationName); return em.merge(relationType); } return null; } private List<CarabiUser> makeRelatedUsersList(String relatedUsersListStr) throws CarabiException { List<String> relatedUsersLoginList = new LinkedList<>(); try { JsonReader usersListReader = Json.createReader(new StringReader(relatedUsersListStr)); JsonArray usersJsonArray = usersListReader.readArray(); for (int i=0; i<usersJsonArray.size(); i++) { String relatedUser = usersJsonArray.getString(i); relatedUsersLoginList.add(relatedUser); } } catch (JsonException | ClassCastException e) { relatedUsersLoginList.add(relatedUsersListStr); } List<CarabiUser> relatedUsersList = new ArrayList<>(relatedUsersLoginList.size()); for (String relatedUserLogin: relatedUsersLoginList) { CarabiUser relatedUser = uc.findUser(relatedUserLogin); relatedUsersList.add(relatedUser); } return relatedUsersList; } public void removeUserRelations(CarabiUser mainUser, String relatedUsersListStr, String relationName) throws CarabiException { List<CarabiUser> relatedUsersList = makeRelatedUsersList(relatedUsersListStr); UserRelationType relationType = getUserRelationType(relationName); for (CarabiUser relatedUser: relatedUsersList) { if (StringUtils.isEmpty(relationName)) { TypedQuery<UserRelation> deleteUsersRelation = em.createNamedQuery("deleteUsersRelation", UserRelation.class); deleteUsersRelation.setParameter("mainUser", mainUser); deleteUsersRelation.setParameter("relatedUser", relatedUser); deleteUsersRelation.executeUpdate(); } else { TypedQuery<UserRelation> findUsersRelation = em.createNamedQuery("findUsersRelation", UserRelation.class); findUsersRelation.setParameter("mainUser", mainUser); findUsersRelation.setParameter("relatedUser", relatedUser); List<UserRelation> findUsersRelationResult = findUsersRelation.getResultList(); if (!findUsersRelationResult.isEmpty()) { UserRelation usersRelation = findUsersRelationResult.get(0); usersRelation.getRelationTypes().remove(relationType); em.merge(usersRelation); } } } em.flush(); try { fireRelationEvent(relatedUsersListStr, relationName, mainUser, CarabiEventType.usersRelationsRemove.getCode()); } catch (IOException ex) { Logger.getLogger(AdminBean.class.getName()).log(Level.SEVERE, null, ex); } } public CarabiUser chooseEditableUser(UserLogon logon, String userLogin) throws CarabiException { CarabiUser mainUser; if (StringUtils.isEmpty(userLogin)) { mainUser = logon.getUser(); } else { logon.assertAllowed("ADMINISTRATING-USERS-EDIT"); mainUser= uc.findUser(userLogin); } return mainUser; } public void setShowOnlineMode(UserLogon logon, CarabiUser user, boolean showOnline) throws CarabiException { if (!user.equals(logon.getUser())) { logon.assertAllowed("ADMINISTRATING-USERS-EDIT"); } user.setShowOnline(showOnline); em.merge(user); try { JsonObjectBuilder event = Json.createObjectBuilder(); event.add("showOnline", showOnline); eventer.fireEvent("", user.getLogin(), CarabiEventType.toggleOnlineDisplay.getCode(), event.build().toString()); event = Json.createObjectBuilder(); event.add("login", user.getLogin()); event.add("online", showOnline); eventer.fireEvent("", "", CarabiEventType.userOnlineEvent.getCode(), event.build().toString()); } catch (IOException ex) { Logger.getLogger(AdminBean.class.getName()).log(Level.SEVERE, null, ex); } } public void setUserStatus(UserLogon logon, String login, String statusSysname) throws CarabiException { logon.assertAllowed("ADMINISTRATING-USERS-EDIT"); CarabiUser user = uc.findUser(login); try { TypedQuery<UserStatus> getUserStatus = em.createNamedQuery("getUserStatus", UserStatus.class); getUserStatus.setParameter("sysname", statusSysname); UserStatus status = getUserStatus.getSingleResult(); user.setStatus(status); em.merge(user); em.flush(); } catch (NoResultException e) { throw new CarabiException("status " + statusSysname + " not found"); } } public String getPhoneTypes() throws CarabiException { // read kernel db final TypedQuery<PhoneType> query = em.createNamedQuery("selectAllPhoneTypes", PhoneType.class);// select PT from PhoneType PT final List<PhoneType> phoneTypes = query.getResultList(); close(); // build json JsonArrayBuilder phoneTypesJson = Json.createArrayBuilder(); for (PhoneType phoneType: phoneTypes) { JsonObjectBuilder phoneTypeJson = Json.createObjectBuilder(); Utls.addJsonNumber(phoneTypeJson, "id", phoneType.getId()); Utls.addJsonObject(phoneTypeJson, "name", phoneType.getName()); Utls.addJsonObject(phoneTypeJson, "sysName", phoneType.getSysname()); phoneTypesJson.add(phoneTypeJson); } return phoneTypesJson.build().toString(); } }
package com.axelor.apps.supplychain.service; import com.axelor.apps.base.db.Product; import com.axelor.apps.base.db.Unit; import com.axelor.apps.base.service.PriceListService; import com.axelor.apps.base.service.UnitConversionService; import com.axelor.apps.base.service.app.AppBaseService; import com.axelor.apps.base.service.tax.AccountManagementService; import com.axelor.apps.purchase.db.PurchaseOrderLine; import com.axelor.apps.sale.db.SaleOrderLine; import com.axelor.apps.stock.db.StockLocation; import com.axelor.apps.stock.db.StockLocationLine; import com.axelor.apps.stock.db.StockMove; import com.axelor.apps.stock.db.StockMoveLine; import com.axelor.apps.stock.db.TrackingNumber; import com.axelor.apps.stock.db.repo.StockMoveLineRepository; import com.axelor.apps.stock.db.repo.StockMoveRepository; import com.axelor.apps.stock.service.StockLocationLineService; import com.axelor.apps.stock.service.StockMoveLineServiceImpl; import com.axelor.apps.stock.service.StockMoveService; import com.axelor.apps.stock.service.TrackingNumberService; import com.axelor.apps.stock.service.app.AppStockService; import com.axelor.apps.supplychain.exception.IExceptionMessage; import com.axelor.exception.AxelorException; import com.axelor.exception.db.repo.TraceBackRepository; import com.axelor.exception.service.TraceBackService; import com.axelor.inject.Beans; import com.google.inject.Inject; import com.google.inject.persist.Transactional; import com.google.inject.servlet.RequestScoped; import java.math.BigDecimal; import java.time.LocalDate; @RequestScoped public class StockMoveLineSupplychainServiceImpl extends StockMoveLineServiceImpl { protected AccountManagementService accountManagementService; protected PriceListService priceListService; @Inject public StockMoveLineSupplychainServiceImpl( TrackingNumberService trackingNumberService, AppBaseService appBaseService, AppStockService appStockService, StockMoveService stockMoveService, AccountManagementService accountManagementService, PriceListService priceListService, UnitConversionService unitConversionService, StockMoveLineRepository stockMoveLineRepository, StockLocationLineService stockLocationLineService) { super( trackingNumberService, appBaseService, appStockService, stockMoveService, stockMoveLineRepository, stockLocationLineService, unitConversionService); this.accountManagementService = accountManagementService; this.priceListService = priceListService; } @Override public StockMoveLine compute(StockMoveLine stockMoveLine, StockMove stockMove) throws AxelorException { // the case when stockMove is null is made in super. if (stockMove == null) { return super.compute(stockMoveLine, null); } // if this is a pack do not compute price if (stockMoveLine.getProduct() == null || (stockMoveLine.getLineTypeSelect() != null && stockMoveLine.getLineTypeSelect() == StockMoveLineRepository.TYPE_PACK)) { return stockMoveLine; } if (stockMove.getOriginId() != null && stockMove.getOriginId() != 0L) { // the stock move comes from a sale or purchase order, we take the price from the order. stockMoveLine = computeFromOrder(stockMoveLine, stockMove); } else { stockMoveLine = super.compute(stockMoveLine, stockMove); } return stockMoveLine; } protected StockMoveLine computeFromOrder(StockMoveLine stockMoveLine, StockMove stockMove) throws AxelorException { BigDecimal unitPriceUntaxed = BigDecimal.ZERO; BigDecimal unitPriceTaxed = BigDecimal.ZERO; Unit orderUnit = null; if (StockMoveRepository.ORIGIN_SALE_ORDER.equals(stockMove.getOriginTypeSelect())) { SaleOrderLine saleOrderLine = stockMoveLine.getSaleOrderLine(); if (saleOrderLine == null) { // log the exception TraceBackService.trace( new AxelorException( TraceBackRepository.TYPE_TECHNICAL, IExceptionMessage.STOCK_MOVE_MISSING_SALE_ORDER, stockMove.getOriginId(), stockMove.getName())); } else { unitPriceUntaxed = saleOrderLine.getExTaxTotal(); unitPriceTaxed = saleOrderLine.getInTaxTotal(); orderUnit = saleOrderLine.getUnit(); } } else { PurchaseOrderLine purchaseOrderLine = stockMoveLine.getPurchaseOrderLine(); if (purchaseOrderLine == null) { // log the exception TraceBackService.trace( new AxelorException( TraceBackRepository.TYPE_TECHNICAL, IExceptionMessage.STOCK_MOVE_MISSING_PURCHASE_ORDER, stockMove.getOriginId(), stockMove.getName())); } else { unitPriceUntaxed = purchaseOrderLine.getExTaxTotal(); unitPriceTaxed = purchaseOrderLine.getInTaxTotal(); orderUnit = purchaseOrderLine.getUnit(); } } stockMoveLine.setUnitPriceUntaxed(unitPriceUntaxed); stockMoveLine.setUnitPriceTaxed(unitPriceTaxed); Unit stockUnit = getStockUnit(stockMoveLine); return convertUnitPrice(stockMoveLine, orderUnit, stockUnit); } protected StockMoveLine convertUnitPrice(StockMoveLine stockMoveLine, Unit fromUnit, Unit toUnit) throws AxelorException { // convert units if (toUnit != null && fromUnit != null) { BigDecimal unitPriceUntaxed = unitConversionService.convert(fromUnit, toUnit, stockMoveLine.getUnitPriceUntaxed()); BigDecimal unitPriceTaxed = unitConversionService.convert(fromUnit, toUnit, stockMoveLine.getUnitPriceTaxed()); stockMoveLine.setUnitPriceUntaxed(unitPriceUntaxed); stockMoveLine.setUnitPriceTaxed(unitPriceTaxed); } return stockMoveLine; } @Transactional(rollbackOn = {AxelorException.class, Exception.class}) public void updateReservedQty(StockMoveLine stockMoveLine, BigDecimal reservedQty) throws AxelorException { StockMove stockMove = stockMoveLine.getStockMove(); int statusSelect = stockMove.getStatusSelect(); if (statusSelect == StockMoveRepository.STATUS_PLANNED || statusSelect == StockMoveRepository.STATUS_REALIZED) { StockMoveService stockMoveService = Beans.get(StockMoveService.class); stockMoveService.cancel(stockMoveLine.getStockMove()); stockMoveLine.setReservedQty(reservedQty); stockMoveService.goBackToDraft(stockMove); stockMoveService.plan(stockMove); if (statusSelect == StockMoveRepository.STATUS_REALIZED) { stockMoveService.realize(stockMove); } } else { stockMoveLine.setReservedQty(stockMoveLine.getReservedQty()); } } @Override public void updateLocations( StockMoveLine stockMoveLine, StockLocation fromStockLocation, StockLocation toStockLocation, Product product, BigDecimal qty, int fromStatus, int toStatus, LocalDate lastFutureStockMoveDate, TrackingNumber trackingNumber, BigDecimal reservedQty) throws AxelorException { BigDecimal realReservedQty = stockMoveLine.getReservedQty(); Unit productUnit = product.getUnit(); Unit stockMoveLineUnit = stockMoveLine.getUnit(); if (productUnit != null && !productUnit.equals(stockMoveLineUnit)) { qty = unitConversionService.convertWithProduct( stockMoveLineUnit, productUnit, qty, stockMoveLine.getProduct()); realReservedQty = unitConversionService.convertWithProduct( stockMoveLineUnit, productUnit, realReservedQty, stockMoveLine.getProduct()); } super.updateLocations( stockMoveLine, fromStockLocation, toStockLocation, product, qty, fromStatus, toStatus, lastFutureStockMoveDate, trackingNumber, realReservedQty); } @Override public void updateAvailableQty(StockMoveLine stockMoveLine, StockLocation stockLocation) { BigDecimal availableQty = BigDecimal.ZERO; BigDecimal availableQtyForProduct = BigDecimal.ZERO; if (stockMoveLine.getProduct() != null) { if (stockMoveLine.getProduct().getTrackingNumberConfiguration() != null) { if (stockMoveLine.getTrackingNumber() != null) { StockLocationLine stockLocationLine = stockLocationLineService.getDetailLocationLine( stockLocation, stockMoveLine.getProduct(), stockMoveLine.getTrackingNumber()); if (stockLocationLine != null) { availableQty = stockLocationLine .getCurrentQty() .add(stockMoveLine.getReservedQty()) .subtract(stockLocationLine.getReservedQty()); } } if (availableQty.compareTo(stockMoveLine.getRealQty()) < 0) { StockLocationLine stockLocationLineForProduct = stockLocationLineService.getStockLocationLine( stockLocation, stockMoveLine.getProduct()); if (stockLocationLineForProduct != null) { availableQtyForProduct = stockLocationLineForProduct .getCurrentQty() .add(stockMoveLine.getReservedQty()) .subtract(stockLocationLineForProduct.getReservedQty()); } } } else { StockLocationLine stockLocationLine = stockLocationLineService.getStockLocationLine( stockLocation, stockMoveLine.getProduct()); if (stockLocationLine != null) { availableQty = stockLocationLine .getCurrentQty() .add(stockMoveLine.getReservedQty()) .subtract(stockLocationLine.getReservedQty()); } } } stockMoveLine.setAvailableQty(availableQty); stockMoveLine.setAvailableQtyForProduct(availableQtyForProduct); } }
package ru.taximaxim.pgsqlblocks; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.eclipse.jface.action.*; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.*; import org.eclipse.jface.window.ApplicationWindow; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTException; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.*; import ru.taximaxim.pgsqlblocks.dbcdata.*; import ru.taximaxim.pgsqlblocks.process.Process; import ru.taximaxim.pgsqlblocks.process.ProcessTreeContentProvider; import ru.taximaxim.pgsqlblocks.process.ProcessTreeLabelProvider; import ru.taximaxim.pgsqlblocks.ui.AddDbcDataDlg; import ru.taximaxim.pgsqlblocks.ui.FilterDlg; import ru.taximaxim.pgsqlblocks.ui.SettingsDlg; import ru.taximaxim.pgsqlblocks.ui.UIAppender; import ru.taximaxim.pgsqlblocks.utils.FilterProcess; import ru.taximaxim.pgsqlblocks.utils.Images; import ru.taximaxim.pgsqlblocks.utils.PathBuilder; import ru.taximaxim.pgsqlblocks.utils.Settings; import java.io.IOException; import java.net.URL; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.MessageFormat; import java.util.List; import java.util.concurrent.*; import java.util.jar.Attributes; import java.util.jar.Manifest; public class MainForm extends ApplicationWindow implements IUpdateListener { private static final Logger LOG = Logger.getLogger(MainForm.class); private static final String APP_NAME = "pgSqlBlocks"; private static final String SORT_DIRECTION = "sortDirection"; private static final String PID = " pid="; private static final int ZERO_MARGIN = 0; private static final int[] VERTICAL_WEIGHTS = new int[] {80, 20}; private static final int[] HORIZONTAL_WEIGHTS = new int[] {12, 88}; private static final int SASH_WIDTH = 2; // some problem with 512px: (SWT:4175): Gdk-WARNING **: gdk_window_set_icon_list: icons too large private static final int[] ICON_SIZES = { 32, 48, 256/*, 512*/ }; private static Display display; private volatile DbcData selectedDbcData; private Process selectedProcess; private Text procText; private SashForm caTreeSf; protected TableViewer caServersTable; private TreeViewer caMainTree; private Composite procComposite; private TableViewer bhServersTable; private TreeViewer bhMainTree; private Action addDb; private Action deleteDB; private Action editDB; private Action connectDB; private Action disconnectDB; private Action update; private Action autoUpdate; private Action cancelUpdate; private Action onlyBlocked; private static SortColumn sortColumn = SortColumn.BLOCKED_COUNT; private static SortDirection sortDirection = SortDirection.UP; private Settings settings = Settings.getInstance(); private FilterProcess filterProcess = FilterProcess.getInstance(); private final ScheduledExecutorService mainService = Executors.newScheduledThreadPool(1); private final ScheduledExecutorService otherService = Executors.newScheduledThreadPool(1); private final DbcDataListBuilder dbcDataBuilder = DbcDataListBuilder.getInstance(this); private ConcurrentMap<String, Image> imagesMap = new ConcurrentHashMap<>(); private MenuManager serversTableMenuMgr = new MenuManager(); private int[] caMainTreeColsSize = new int[]{80, 110, 150, 110, 110, 110, 145, 145, 145, 55, 145, 70, 65, 150, 80}; private String[] caMainTreeColsName = new String[]{ "pid", "blocked_count", "application_name", "datname", "usename", "client", "backend_start", "query_start", "xact_stat", "state", "state_change", "blocked", "waiting", "query" , "slowquery"}; private String[] caColName = {"PID", "BLOCKED_COUNT", "APPLICATION_NAME", "DATNAME", "USENAME", "CLIENT", "BACKEND_START", "QUERY_START", "XACT_STAT", "STATE", "STATE_CHANGE", "BLOCKED", "WAITING", "QUERY", "SLOWQUERY"}; public static void main(String[] args) { try { display = new Display(); MainForm wwin = new MainForm(); wwin.setBlockOnOpen(true); wwin.open(); display.dispose(); } catch (Exception e) { LOG.error("Произошла ошибка:", e); } } public MainForm() { super(null); addToolBar(SWT.RIGHT | SWT.FLAT); } // TODO temporary getter, should not be used outside this class public static SortColumn getSortColumn() { return sortColumn; } // TODO temporary getter, should not be used outside this class public static SortDirection getSortDirection() { return sortDirection; } public ScheduledExecutorService getMainService() { return mainService; } @Override protected void constrainShellSize() { super.constrainShellSize(); getShell().setMaximized( true ); } @Override protected void configureShell(Shell shell) { super.configureShell(shell); shell.setText(APP_NAME); shell.setImages(loadIcons()); } private Image[] loadIcons() { Image[] icons = new Image[ICON_SIZES.length]; for (int i = 0; i < ICON_SIZES.length; ++i) { icons[i] = new Image(null, getClass().getClassLoader().getResourceAsStream(MessageFormat.format("images/block-{0}x{0}.png", ICON_SIZES[i]))); } return icons; } @Override protected boolean canHandleShellCloseEvent() { if (!MessageDialog.openQuestion(getShell(), "Подтверждение действия", "Вы действительно хотите выйти из pgSqlBlocks?")) { return false; } mainService.shutdown(); otherService.shutdown(); return super.canHandleShellCloseEvent(); } @Override protected Control createContents(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout()); GridLayout gridLayout = new GridLayout(); gridLayout.marginHeight = ZERO_MARGIN; gridLayout.marginWidth = ZERO_MARGIN; GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true); SashForm verticalSf = new SashForm(composite, SWT.VERTICAL); { verticalSf.setLayout(gridLayout); verticalSf.setLayoutData(gridData); verticalSf.SASH_WIDTH = SASH_WIDTH; verticalSf.setBackground(composite.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); Composite topComposite = new Composite(verticalSf, SWT.NONE); topComposite.setLayout(gridLayout); TabFolder tabPanel = new TabFolder(topComposite, SWT.BORDER); { tabPanel.setLayoutData(gridData); TabItem currentActivityTi = new TabItem(tabPanel, SWT.NONE); { currentActivityTi.setText("Текущая активность"); SashForm currentActivitySf = new SashForm(tabPanel, SWT.HORIZONTAL); { currentActivitySf.setLayout(gridLayout); currentActivitySf.setLayoutData(gridData); currentActivitySf.SASH_WIDTH = SASH_WIDTH; currentActivitySf.setBackground(topComposite.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); caServersTable = new TableViewer(currentActivitySf, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION); { caServersTable.getTable().setHeaderVisible(true); caServersTable.getTable().setLinesVisible(true); caServersTable.getTable().setLayoutData(gridData); TableViewerColumn tvColumn = new TableViewerColumn(caServersTable, SWT.NONE); tvColumn.getColumn().setText("Сервер"); tvColumn.getColumn().setWidth(200); caServersTable.setContentProvider(new DbcDataListContentProvider()); caServersTable.setLabelProvider(new DbcDataListLabelProvider()); caServersTable.setInput(dbcDataBuilder.getDbcDataList()); } Menu menu = serversTableMenuMgr.createContextMenu(caServersTable.getControl()); serversTableMenuMgr.addMenuListener(manager -> { if (caServersTable.getSelection() instanceof IStructuredSelection) { manager.add(cancelUpdate); manager.add(update); manager.add(connectDB); manager.add(disconnectDB); manager.add(addDb); manager.add(editDB); manager.add(deleteDB); } }); serversTableMenuMgr.setRemoveAllWhenShown(true); caServersTable.getControl().setMenu(menu); caTreeSf = new SashForm(currentActivitySf, SWT.VERTICAL); { caMainTree = new TreeViewer(caTreeSf, SWT.VIRTUAL | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION); caMainTree.getTree().setHeaderVisible(true); caMainTree.getTree().setLinesVisible(true); caMainTree.getTree().setLayoutData(gridData); for(int i=0;i<caMainTreeColsName.length;i++) { TreeViewerColumn treeColumn = new TreeViewerColumn(caMainTree, SWT.NONE); treeColumn.getColumn().setText(caMainTreeColsName[i]); treeColumn.getColumn().setWidth(caMainTreeColsSize[i]); treeColumn.getColumn().setData("colName",caColName[i]); treeColumn.getColumn().setData(SORT_DIRECTION, SortDirection.UP); } caMainTree.setContentProvider(new ProcessTreeContentProvider()); caMainTree.setLabelProvider(new ProcessTreeLabelProvider()); ViewerFilter[] filters = new ViewerFilter[1]; filters[0] = new ViewerFilter() { @Override public boolean select(Viewer viewer, Object parentElement, Object element) { return !(element instanceof Process) || filterProcess.isFiltered((Process) element); } }; caMainTree.setFilters(filters); procComposite = new Composite(caTreeSf, SWT.BORDER); { procComposite.setLayout(gridLayout); GridData procCompositeGd = new GridData(SWT.FILL, SWT.FILL, true, true); procComposite.setLayoutData(procCompositeGd); procComposite.setVisible(false); ToolBar pcToolBar = new ToolBar(procComposite, SWT.FLAT | SWT.RIGHT); pcToolBar.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); ToolItem terminateProc = new ToolItem(pcToolBar, SWT.PUSH); terminateProc.setText("Уничтожить процесс"); terminateProc.addListener(SWT.Selection, event -> { if (selectedProcess != null) { terminate(selectedProcess); updateUi(); } }); ToolItem cancelProc = new ToolItem(pcToolBar, SWT.PUSH); cancelProc.setText("Послать сигнал отмены процесса"); cancelProc.addListener(SWT.Selection, event -> { if (selectedProcess != null) { cancel(selectedProcess); updateUi(); } }); procText = new Text(procComposite, SWT.MULTI | SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL | SWT.H_SCROLL); procText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); procText.setBackground(composite.getDisplay().getSystemColor(SWT.COLOR_WHITE)); } } caTreeSf.setWeights(VERTICAL_WEIGHTS); } currentActivitySf.setWeights(HORIZONTAL_WEIGHTS); currentActivityTi.setControl(currentActivitySf); } TabItem blocksHistoryTi = new TabItem(tabPanel, SWT.NONE); { blocksHistoryTi.setText("История блокировок"); SashForm blocksHistorySf = new SashForm(tabPanel, SWT.HORIZONTAL); { blocksHistorySf.setLayout(gridLayout); blocksHistorySf.setLayoutData(gridData); blocksHistorySf.SASH_WIDTH = SASH_WIDTH; blocksHistorySf.setBackground(topComposite.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); bhServersTable = new TableViewer(blocksHistorySf, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION); { bhServersTable.getTable().setHeaderVisible(true); bhServersTable.getTable().setLinesVisible(true); bhServersTable.getTable().setLayoutData(gridData); TableViewerColumn serversTc = new TableViewerColumn(bhServersTable, SWT.NONE); serversTc.getColumn().setText("Сервер"); serversTc.getColumn().setWidth(200); bhServersTable.setContentProvider(new DbcDataListContentProvider()); bhServersTable.setLabelProvider(new DbcDataListLabelProvider()); } bhMainTree = new TreeViewer(blocksHistorySf, SWT.VIRTUAL | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION); { bhMainTree.getTree().setHeaderVisible(true); bhMainTree.getTree().setLinesVisible(true); bhMainTree.getTree().setLayoutData(gridData); for(int i = 0; i < caMainTreeColsName.length; i++) { TreeViewerColumn treeColumn = new TreeViewerColumn(bhMainTree, SWT.NONE); treeColumn.getColumn().setText(caMainTreeColsName[i]); treeColumn.getColumn().setWidth(caMainTreeColsSize[i]); } bhMainTree.setContentProvider(new ProcessTreeContentProvider()); bhMainTree.setLabelProvider(new ProcessTreeLabelProvider()); } } blocksHistorySf.setWeights(HORIZONTAL_WEIGHTS); blocksHistoryTi.setControl(blocksHistorySf); } } Composite logComposite = new Composite(verticalSf, SWT.NONE); { logComposite.setLayout(gridLayout); } verticalSf.setWeights(VERTICAL_WEIGHTS); UIAppender uiAppender = new UIAppender(logComposite); uiAppender.setThreshold(Level.INFO); Logger.getRootLogger().addAppender(uiAppender); Composite statusBar = new Composite(composite, SWT.NONE); { statusBar.setLayout(gridLayout); statusBar.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false)); Label appVersionLabel = new Label(statusBar, SWT.HORIZONTAL); appVersionLabel.setText("PgSqlBlocks v." + getAppVersion()); } dbcDataBuilder.getDbcDataList().stream().filter(DbcData::isEnabled) .forEach(dbcDataBuilder::addOnceScheduledUpdater); } caMainTree.addSelectionChangedListener(event -> { if (!caMainTree.getSelection().isEmpty()) { IStructuredSelection selected = (IStructuredSelection) event.getSelection(); selectedProcess = (Process) selected.getFirstElement(); if(!procComposite.isVisible()) { procComposite.setVisible(true); caTreeSf.layout(true, true); } procText.setText(String.format("pid=%s%n%s", selectedProcess.getPid(), selectedProcess.getQuery())); } }); caServersTable.addSelectionChangedListener(event -> { if (!caServersTable.getSelection().isEmpty()) { IStructuredSelection selected = (IStructuredSelection) event.getSelection(); selectedDbcData = (DbcData) selected.getFirstElement(); if(procComposite.isVisible()) { procComposite.setVisible(false); caTreeSf.layout(false, false); } serversToolBarState(); updateUi(); } }); for (TreeColumn column : caMainTree.getTree().getColumns()) { column.addListener(SWT.Selection, event -> { caMainTree.getTree().setSortColumn(column); column.setData(SORT_DIRECTION, ((SortDirection)column.getData(SORT_DIRECTION)).getOpposite()); sortDirection = (SortDirection)column.getData(SORT_DIRECTION); caMainTree.getTree().setSortDirection(sortDirection.getSwtData()); sortColumn = SortColumn.valueOf((String)column.getData("colName")); updateUi(); }); } caServersTable.addDoubleClickListener(event -> { if (!caServersTable.getSelection().isEmpty()) { IStructuredSelection selected = (IStructuredSelection) event.getSelection(); selectedDbcData = (DbcData) selected.getFirstElement(); if (selectedDbcData.getStatus() == DbcStatus.CONNECTED) { dbcDataDisconnect(); } else { dbcDataConnect(); } } }); otherService.scheduleAtFixedRate(this::updateUi, 0, settings.getUpdateUIPeriod(), TimeUnit.SECONDS); return parent; } protected ToolBarManager createToolBarManager(int style) { ToolBarManager toolBarManager = new ToolBarManager(style); addDb = new Action(Images.ADD_DATABASE.getDescription(), ImageDescriptor.createFromImage(getImage(Images.ADD_DATABASE))) { @Override public void run() { AddDbcDataDlg addDbcDlg = new AddDbcDataDlg(getShell(), null, dbcDataBuilder.getDbcDataList()); if (Window.OK == addDbcDlg.open()) { selectedDbcData = addDbcDlg.getNewDbcData(); if (selectedDbcData != null) { dbcDataBuilder.add(selectedDbcData); caServersTable.getTable().setSelection(dbcDataBuilder.getDbcDataList().indexOf(selectedDbcData)); } serversToolBarState(); updateUi(); } } }; toolBarManager.add(addDb); deleteDB = new Action(Images.DELETE_DATABASE.getDescription(), ImageDescriptor.createFromImage(getImage(Images.DELETE_DATABASE))) { @Override public void run() { boolean okPress = MessageDialog.openQuestion(getShell(), "Подтверждение действия", String.format("Вы действительно хотите удалить %s?", selectedDbcData.getName())); if (okPress) { dbcDataBuilder.delete(selectedDbcData); if (dbcDataBuilder.getDbcDataList().isEmpty()) { selectedDbcData = null; } else { selectedDbcData = dbcDataBuilder.getDbcDataList() .get(dbcDataBuilder.getDbcDataList().size() - 1); caServersTable.getTable().setSelection(dbcDataBuilder.getDbcDataList().indexOf(selectedDbcData)); } updateUi(); } } }; deleteDB.setEnabled(false); toolBarManager.add(deleteDB); editDB = new Action(Images.EDIT_DATABASE.getDescription(), ImageDescriptor.createFromImage(getImage(Images.EDIT_DATABASE))) { @Override public void run() { AddDbcDataDlg editDbcDlg = new AddDbcDataDlg(getShell(), selectedDbcData, dbcDataBuilder.getDbcDataList()); if (Window.OK == editDbcDlg.open()) { DbcData oldOne = editDbcDlg.getEditedDbcData(); DbcData newOne = editDbcDlg.getNewDbcData(); dbcDataBuilder.edit(oldOne, newOne); updateUi(); } } }; editDB.setEnabled(false); toolBarManager.add(editDB); toolBarManager.add(new Separator()); connectDB = new Action(Images.CONNECT_DATABASE.getDescription(), ImageDescriptor.createFromImage(getImage(Images.CONNECT_DATABASE))) { @Override public void run() { dbcDataConnect(); } }; connectDB.setEnabled(false); toolBarManager.add(connectDB); disconnectDB = new Action(Images.DISCONNECT_DATABASE.getDescription(), ImageDescriptor.createFromImage(getImage(Images.DISCONNECT_DATABASE))) { @Override public void run() { dbcDataDisconnect(); } }; disconnectDB.setEnabled(false); toolBarManager.add(disconnectDB); toolBarManager.add(new Separator()); update = new Action(Images.UPDATE.getDescription(), ImageDescriptor.createFromImage(getImage(Images.UPDATE))) { @Override public void run() { if (selectedDbcData != null) { dbcDataBuilder.removeScheduledUpdater(selectedDbcData); dbcDataBuilder.removeOnceScheduledUpdater(selectedDbcData); if (settings.isAutoUpdate()) { dbcDataBuilder.addScheduledUpdater(selectedDbcData); } else { dbcDataBuilder.addOnceScheduledUpdater(selectedDbcData); } } } }; toolBarManager.add(update); autoUpdate = new Action(Images.AUTOUPDATE.getDescription(), ImageDescriptor.createFromImage(getImage(Images.AUTOUPDATE))) { @Override public void run() { if (autoUpdate.isChecked()) { dbcDataBuilder.getDbcDataList().stream().filter(x -> x.isConnected() || x.isEnabled() && x.getStatus() != DbcStatus.ERROR) .forEach(dbcDataBuilder::addScheduledUpdater); } else { dbcDataBuilder.getDbcDataList().forEach(dbcDataBuilder::removeScheduledUpdater); } settings.setAutoUpdate(autoUpdate.isChecked()); } }; autoUpdate.setChecked(settings.isAutoUpdate()); toolBarManager.add(autoUpdate); cancelUpdate = new Action(Images.CANCEL_UPDATE.getDescription(), ImageDescriptor.createFromImage(getImage(Images.CANCEL_UPDATE))) { @Override public void run() { if (selectedDbcData != null) { dbcDataBuilder.removeOnceScheduledUpdater(selectedDbcData); if (selectedDbcData.isConnected()){ selectedDbcData.setStatus(DbcStatus.CONNECTED); } } } }; cancelUpdate.setEnabled(false); toolBarManager.add(new Separator()); Action filterSetting = new Action(Images.FILTER.getDescription(), ImageDescriptor.createFromImage(getImage(Images.FILTER))) { @Override public void run() { FilterDlg filterDlg = new FilterDlg(getShell(), filterProcess); filterDlg.open(); updateUi(); } }; toolBarManager.add(filterSetting); onlyBlocked = new Action(Images.VIEW_ONLY_BLOCKED.getDescription(), ImageDescriptor.createFromImage(getImage(Images.VIEW_ONLY_BLOCKED))) { @Override public void run() { settings.setOnlyBlocked(onlyBlocked.isChecked()); updateUi(); } }; onlyBlocked.setChecked(settings.isOnlyBlocked()); toolBarManager.add(onlyBlocked); toolBarManager.add(new Separator()); Action exportBlocks = new Action(Images.EXPORT_BLOCKS.getDescription(), ImageDescriptor.createFromImage(getImage(Images.EXPORT_BLOCKS))) { @Override public void run() { if (dbcDataBuilder.getDbcDataList().stream() .filter(DbcData::hasBlockedProcess).count() > 0) { BlocksHistory.getInstance().save(dbcDataBuilder.getDbcDataList()); LOG.info("Блокировка сохранена..."); } else { LOG.info("Не найдено блокировок для сохранения"); } } }; toolBarManager.add(exportBlocks); Action importBlocks = new Action(Images.IMPORT_BLOCKS.getDescription()) { @Override public void run() { FileDialog dialog = new FileDialog(getShell()); dialog.setFilterPath(PathBuilder.getInstance().getBlockHistoryDir().toString()); dialog.setText("Открыть историю блокировок"); dialog.setFilterExtensions(new String[]{"*.xml"}); List<DbcData> blockedDbsDataList = BlocksHistory.getInstance().open(dialog.open()); if (!blockedDbsDataList.isEmpty()) { bhServersTable.setInput(blockedDbsDataList); bhMainTree.setInput(blockedDbsDataList.get(0).getProcess()); bhMainTree.refresh(); bhServersTable.refresh(); } } }; importBlocks.setImageDescriptor(ImageDescriptor.createFromImage(getImage(Images.IMPORT_BLOCKS))); toolBarManager.add(importBlocks); toolBarManager.add(new Separator()); Action settingsAction = new Action(Images.SETTINGS.getDescription(), ImageDescriptor.createFromImage(getImage(Images.SETTINGS))) { @Override public void run() { SettingsDlg settingsDlg = new SettingsDlg(getShell(), settings); settingsDlg.open(); } }; toolBarManager.add(settingsAction); return toolBarManager; } private Image getImage(Images type) { Image image = imagesMap.get(type.toString()); if (image == null) { image = new Image(null, getClass().getClassLoader().getResourceAsStream(type.getImageAddr())); imagesMap.put(type.toString(), image); } return image; } private String getAppVersion() { URL manifestPath = MainForm.class.getClassLoader().getResource("META-INF/MANIFEST.MF"); Manifest manifest = null; try { manifest = new Manifest(manifestPath != null ? manifestPath.openStream() : null); } catch (IOException e) { LOG.error("Ошибка при чтении манифеста", e); } Attributes manifestAttributes = manifest != null ? manifest.getMainAttributes() : null; String appVersion = manifestAttributes != null ? manifestAttributes.getValue("Implementation-Version") : null; if(appVersion == null) { return ""; } return appVersion; } public void terminate(Process process) { String term = "select pg_terminate_backend(?);"; boolean kill = false; int pid = process.getPid(); try (PreparedStatement termPs = selectedDbcData.getConnection().prepareStatement(term)) { termPs.setInt(1, pid); try (ResultSet resultSet = termPs.executeQuery()) { if (resultSet.next()) { kill = resultSet.getBoolean(1); } } } catch (SQLException e) { selectedDbcData.setStatus(DbcStatus.ERROR); LOG.error(selectedDbcData.getName() + " " + e.getMessage(), e); } if(kill) { LOG.info(selectedDbcData.getName() + PID + pid + " is terminated."); } else { LOG.info(selectedDbcData.getName() + PID + pid + " is terminated failed."); } } public void cancel(Process process) { String cancel = "select pg_cancel_backend(?);"; int pid = process.getPid(); boolean kill = false; try (PreparedStatement cancelPs = selectedDbcData.getConnection().prepareStatement(cancel)) { cancelPs.setInt(1, pid); try (ResultSet resultSet = cancelPs.executeQuery()) { if (resultSet.next()) { kill = resultSet.getBoolean(1); } } } catch (SQLException e) { selectedDbcData.setStatus(DbcStatus.ERROR); LOG.error(selectedDbcData.getName() + " " + e.getMessage(), e); } if(kill) { LOG.info(selectedDbcData.getName() + PID + pid + " is canceled."); } else { LOG.info(selectedDbcData.getName() + PID + pid + " is canceled failed."); } } private void dbcDataConnect() { synchronized (selectedDbcData) { if (settings.isAutoUpdate()) { LOG.debug(MessageFormat.format("Add on connect dbcData \"{0}\" to updaterList", selectedDbcData.getName())); dbcDataBuilder.addScheduledUpdater(selectedDbcData); } else { dbcDataBuilder.addOnceScheduledUpdater(selectedDbcData); } connectState(); } } private void dbcDataDisconnect() { synchronized (selectedDbcData) { LOG.debug(MessageFormat.format("Remove dbcData on disconnect \"{0}\" from updaterList", selectedDbcData.getName())); selectedDbcData.disconnect(); dbcDataBuilder.removeScheduledUpdater(selectedDbcData); dbcDataBuilder.removeOnceScheduledUpdater(selectedDbcData); disconnectState(); } updateUi(); } private void serversToolBarState() { if (selectedDbcData != null && (selectedDbcData.getStatus() == DbcStatus.ERROR || selectedDbcData.getStatus() == DbcStatus.DISABLED)) { disconnectState(); } else { connectState(); } } private void connectState() { deleteDB.setEnabled(false); editDB.setEnabled(false); connectDB.setEnabled(false); disconnectDB.setEnabled(true); cancelUpdate.setEnabled(true); } private void disconnectState() { deleteDB.setEnabled(true); editDB.setEnabled(true); connectDB.setEnabled(true); disconnectDB.setEnabled(false); cancelUpdate.setEnabled(false); } private void updateUi() { display.asyncExec(() -> { if (!display.isDisposed()) { caServersTable.refresh(); serversToolBarState(); if (selectedDbcData != null) { try { Object[] expanded = caMainTree.getExpandedElements(); caMainTree.setInput(selectedDbcData.getProcess()); caMainTree.setExpandedElements(expanded); caMainTree.refresh(); bhMainTree.refresh(); } catch (SWTException e) { LOG.error("Ошибка при отрисовке таблицы!", e); } } LOG.debug(" Finish updating tree."); } }); } @Override public void serverUpdated() { updateUi(); } }
package ru.taximaxim.pgsqlblocks; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.*; import org.eclipse.jface.window.ApplicationWindow; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.*; import ru.taximaxim.pgsqlblocks.dbcdata.*; import ru.taximaxim.pgsqlblocks.process.Process; import ru.taximaxim.pgsqlblocks.process.ProcessTreeContentProvider; import ru.taximaxim.pgsqlblocks.process.ProcessTreeLabelProvider; import ru.taximaxim.pgsqlblocks.ui.AddDbcDataDlg; import ru.taximaxim.pgsqlblocks.ui.FilterDlg; import ru.taximaxim.pgsqlblocks.ui.SettingsDlg; import ru.taximaxim.pgsqlblocks.ui.UIAppender; import ru.taximaxim.pgsqlblocks.utils.FilterProcess; import ru.taximaxim.pgsqlblocks.utils.Images; import ru.taximaxim.pgsqlblocks.utils.PathBuilder; import ru.taximaxim.pgsqlblocks.utils.Settings; import java.io.IOException; import java.net.URL; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.MessageFormat; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.concurrent.*; import java.util.jar.Attributes; import java.util.jar.Manifest; public class MainForm extends ApplicationWindow implements IUpdateListener { private static final Logger LOG = Logger.getLogger(MainForm.class); private static final String APP_NAME = "pgSqlBlocks"; private static final String SORT_DIRECTION = "sortDirection"; private static final String PID = " pid="; private static final int ZERO_MARGIN = 0; private static final int[] VERTICAL_WEIGHTS = new int[] {80, 20}; private static final int[] HORIZONTAL_WEIGHTS = new int[] {12, 88}; private static final int SASH_WIDTH = 2; // some problem with 512px: (SWT:4175): Gdk-WARNING **: gdk_window_set_icon_list: icons too large private static final int[] ICON_SIZES = { 32, 48, 256/*, 512*/ }; private static Display display; private volatile DbcData selectedDbcData; private Process selectedProcess; private Text procText; private SashForm caTreeSf; private TableViewer caServersTable; private TreeViewer caMainTree; private Composite procComposite; private TableViewer bhServersTable; private TreeViewer bhMainTree; private Action addDb; private Action deleteDB; private Action editDB; private Action connectDB; private Action disconnectDB; private Action update; private Action autoUpdate; private Action cancelUpdate; private Action onlyBlocked; private ToolItem cancelProc; private ToolItem terminateProc; private TrayItem trayItem; private static SortColumn sortColumn = SortColumn.BLOCKED_COUNT; private static SortDirection sortDirection = SortDirection.UP; private Settings settings = Settings.getInstance(); private FilterProcess filterProcess = FilterProcess.getInstance(); private final ScheduledExecutorService mainService = Executors.newScheduledThreadPool(1); private final DbcDataListBuilder dbcDataBuilder = DbcDataListBuilder.getInstance(this); private ConcurrentMap<String, Image> imagesMap = new ConcurrentHashMap<>(); private MenuManager serversTableMenuMgr = new MenuManager(); private String[] visibleColumns = settings.getColumnsList().split(","); public static void main(String[] args) { try { display = new Display(); MainForm wwin = new MainForm(); wwin.setBlockOnOpen(true); wwin.open(); display.dispose(); } catch (Exception e) { LOG.error("Произошла ошибка:", e); } } public MainForm() { super(null); addToolBar(SWT.RIGHT | SWT.FLAT); } // TODO temporary getter, should not be used outside this class public static SortColumn getSortColumn() { return sortColumn; } // TODO temporary getter, should not be used outside this class public static SortDirection getSortDirection() { return sortDirection; } public ScheduledExecutorService getMainService() { return mainService; } @Override protected void constrainShellSize() { super.constrainShellSize(); getShell().setMaximized( true ); } @Override protected void configureShell(Shell shell) { super.configureShell(shell); shell.setText(APP_NAME); shell.setImages(loadIcons()); } private Image[] loadIcons() { Image[] icons = new Image[ICON_SIZES.length]; for (int i = 0; i < ICON_SIZES.length; ++i) { icons[i] = new Image(null, getClass().getClassLoader().getResourceAsStream(MessageFormat.format("images/block-{0}x{0}.png", ICON_SIZES[i]))); } return icons; } @Override protected boolean canHandleShellCloseEvent() { if (!MessageDialog.openQuestion(getShell(), "Подтверждение действия", "Вы действительно хотите выйти из pgSqlBlocks?")) { return false; } mainService.shutdown(); return super.canHandleShellCloseEvent(); } @Override protected Control createContents(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout()); GridLayout gridLayout = new GridLayout(); gridLayout.marginHeight = ZERO_MARGIN; gridLayout.marginWidth = ZERO_MARGIN; GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true); SashForm verticalSf = new SashForm(composite, SWT.VERTICAL); { verticalSf.setLayout(gridLayout); verticalSf.setLayoutData(gridData); verticalSf.SASH_WIDTH = SASH_WIDTH; verticalSf.setBackground(composite.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); Composite topComposite = new Composite(verticalSf, SWT.NONE); topComposite.setLayout(gridLayout); TabFolder tabPanel = new TabFolder(topComposite, SWT.BORDER); { tabPanel.setLayoutData(gridData); TabItem currentActivityTi = new TabItem(tabPanel, SWT.NONE); { currentActivityTi.setText("Текущая активность"); SashForm currentActivitySf = new SashForm(tabPanel, SWT.HORIZONTAL); { currentActivitySf.setLayout(gridLayout); currentActivitySf.setLayoutData(gridData); currentActivitySf.SASH_WIDTH = SASH_WIDTH; currentActivitySf.setBackground(topComposite.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); caServersTable = new TableViewer(currentActivitySf, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION); { caServersTable.getTable().setHeaderVisible(true); caServersTable.getTable().setLayoutData(gridData); TableViewerColumn tvColumn = new TableViewerColumn(caServersTable, SWT.NONE); tvColumn.getColumn().setText("Сервер"); tvColumn.getColumn().setWidth(200); caServersTable.setContentProvider(new DbcDataListContentProvider()); caServersTable.setLabelProvider(new DbcDataListLabelProvider()); caServersTable.setInput(dbcDataBuilder.getDbcDataList()); } Menu mainMenu = serversTableMenuMgr.createContextMenu(caServersTable.getControl()); serversTableMenuMgr.addMenuListener(manager -> { if (caServersTable.getSelection() instanceof IStructuredSelection) { manager.add(cancelUpdate); manager.add(update); manager.add(connectDB); manager.add(disconnectDB); manager.add(addDb); manager.add(editDB); manager.add(deleteDB); } }); serversTableMenuMgr.setRemoveAllWhenShown(true); caServersTable.getControl().setMenu(mainMenu); caTreeSf = new SashForm(currentActivitySf, SWT.VERTICAL); { caMainTree = new TreeViewer(caTreeSf, SWT.VIRTUAL | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION); caMainTree.getTree().setHeaderVisible(true); caMainTree.getTree().setLinesVisible(true); caMainTree.getTree().setLayoutData(gridData); fillTreeViewer(caMainTree); caMainTree.setContentProvider(new ProcessTreeContentProvider()); caMainTree.setLabelProvider(new ProcessTreeLabelProvider()); ViewerFilter[] filters = new ViewerFilter[1]; filters[0] = new ViewerFilter() { @Override public boolean select(Viewer viewer, Object parentElement, Object element) { return !(element instanceof Process) || filterProcess.isFiltered((Process) element); } }; caMainTree.setFilters(filters); procComposite = new Composite(caTreeSf, SWT.BORDER); { procComposite.setLayout(gridLayout); GridData procCompositeGd = new GridData(SWT.FILL, SWT.FILL, true, true); procComposite.setLayoutData(procCompositeGd); procComposite.setVisible(false); ToolBar pcToolBar = new ToolBar(procComposite, SWT.FLAT | SWT.RIGHT); pcToolBar.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); terminateProc = new ToolItem(pcToolBar, SWT.PUSH); terminateProc.setText("Уничтожить процесс"); terminateProc.addListener(SWT.Selection, event -> { if (selectedProcess != null) { terminate(selectedProcess); } }); cancelProc = new ToolItem(pcToolBar, SWT.PUSH); cancelProc.setText("Послать сигнал отмены процесса"); cancelProc.addListener(SWT.Selection, event -> { if (selectedProcess != null) { cancel(selectedProcess); } }); procText = new Text(procComposite, SWT.MULTI | SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL | SWT.H_SCROLL); procText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); } } caTreeSf.setWeights(VERTICAL_WEIGHTS); } currentActivitySf.setWeights(HORIZONTAL_WEIGHTS); currentActivityTi.setControl(currentActivitySf); } TabItem blocksHistoryTi = new TabItem(tabPanel, SWT.NONE); { blocksHistoryTi.setText("История блокировок"); SashForm blocksHistorySf = new SashForm(tabPanel, SWT.HORIZONTAL); { blocksHistorySf.setLayout(gridLayout); blocksHistorySf.setLayoutData(gridData); blocksHistorySf.SASH_WIDTH = SASH_WIDTH; blocksHistorySf.setBackground(topComposite.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); bhServersTable = new TableViewer(blocksHistorySf, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION); { bhServersTable.getTable().setHeaderVisible(true); bhServersTable.getTable().setLinesVisible(true); bhServersTable.getTable().setLayoutData(gridData); TableViewerColumn serversTc = new TableViewerColumn(bhServersTable, SWT.NONE); serversTc.getColumn().setText("Сервер"); serversTc.getColumn().setWidth(200); bhServersTable.setContentProvider(new DbcDataListContentProvider()); bhServersTable.setLabelProvider(new DbcDataListLabelProvider()); } bhMainTree = new TreeViewer(blocksHistorySf, SWT.VIRTUAL | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION); { bhMainTree.getTree().setHeaderVisible(true); bhMainTree.getTree().setLinesVisible(true); bhMainTree.getTree().setLayoutData(gridData); fillTreeViewer(bhMainTree); bhMainTree.setContentProvider(new ProcessTreeContentProvider()); bhMainTree.setLabelProvider(new ProcessTreeLabelProvider()); } } blocksHistorySf.setWeights(HORIZONTAL_WEIGHTS); blocksHistoryTi.setControl(blocksHistorySf); } } Composite logComposite = new Composite(verticalSf, SWT.NONE); { logComposite.setLayout(gridLayout); } verticalSf.setWeights(VERTICAL_WEIGHTS); UIAppender uiAppender = new UIAppender(logComposite); uiAppender.setThreshold(Level.INFO); Logger.getRootLogger().addAppender(uiAppender); Composite statusBar = new Composite(composite, SWT.NONE); { statusBar.setLayout(gridLayout); statusBar.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false)); Label appVersionLabel = new Label(statusBar, SWT.HORIZONTAL); appVersionLabel.setText("pgSqlBlocks v." + getAppVersion()); } dbcDataBuilder.getDbcDataList().stream().filter(DbcData::isEnabled) .forEach(dbcDataBuilder::addOnceScheduledUpdater); } caMainTree.addSelectionChangedListener(event -> { if (!caMainTree.getSelection().isEmpty()) { IStructuredSelection selected = (IStructuredSelection) event.getSelection(); selectedProcess = (Process) selected.getFirstElement(); if(!procComposite.isVisible()) { procComposite.setVisible(true); caTreeSf.layout(true, true); } procText.setText(String.format("pid=%s%n%s", selectedProcess.getPid(), selectedProcess.getQuery())); } }); caServersTable.addSelectionChangedListener(event -> { if (!caServersTable.getSelection().isEmpty()) { IStructuredSelection selected = (IStructuredSelection) event.getSelection(); DbcData newSelection = (DbcData) selected.getFirstElement(); if (selectedDbcData != newSelection){ selectedDbcData = newSelection; if(procComposite.isVisible()) { procComposite.setVisible(false); caTreeSf.layout(false, false); } serversToolBarState(); caMainTree.setInput(selectedDbcData.getProcess()); updateUi(); } } }); for (TreeColumn column : caMainTree.getTree().getColumns()) { column.addListener(SWT.Selection, event -> { if (selectedDbcData != null) { caMainTree.getTree().setSortColumn(column); column.setData(SORT_DIRECTION, ((SortDirection)column.getData(SORT_DIRECTION)).getOpposite()); sortDirection = (SortDirection)column.getData(SORT_DIRECTION); caMainTree.getTree().setSortDirection(sortDirection.getSwtData()); sortColumn = (SortColumn)column.getData("colName"); if (settings.isOnlyBlocked()){ selectedDbcData.getOnlyBlockedProcessTree(false); } else { selectedDbcData.getProcessTree(false); } updateUi(); } }); } caServersTable.addDoubleClickListener(event -> { if (!caServersTable.getSelection().isEmpty()) { IStructuredSelection selected = (IStructuredSelection) event.getSelection(); selectedDbcData = (DbcData) selected.getFirstElement(); if (selectedDbcData.getStatus() == DbcStatus.CONNECTED) { dbcDataDisconnect(); } else { dbcDataConnect(); } } }); final Tray tray = display.getSystemTray(); if (tray == null) { LOG.warn("The system tray is not available"); } else { trayItem = new TrayItem(tray, SWT.NONE); trayItem.setImage(getIconImage()); trayItem.setToolTipText("pgSqlBlocks v." + getAppVersion()); final Menu trayMenu = new Menu(getShell(), SWT.POP_UP); MenuItem trayMenuItem = new MenuItem(trayMenu, SWT.PUSH); trayMenuItem.setText("Выход"); trayMenuItem.addListener(SWT.Selection, event -> getShell().close()); trayItem.addListener(SWT.MenuDetect, event -> trayMenu.setVisible(true)); } return parent; } private void fillTreeViewer(TreeViewer treeViewer) { for (Iterator<SortColumn> it = Arrays.stream(SortColumn.values()).iterator(); it.hasNext(); ) { SortColumn column = it.next(); TreeViewerColumn treeColumn = new TreeViewerColumn(treeViewer, SWT.NONE); treeColumn.getColumn().setText(column.getName()); treeColumn.getColumn().setData("colName", column); treeColumn.getColumn().setData(SORT_DIRECTION, SortDirection.UP); treeColumn.getColumn().setMoveable(true); if (Arrays.stream(visibleColumns).anyMatch(x -> x.equals(column.toString()))) { treeColumn.getColumn().setWidth(column.getColSize()); } else { treeColumn.getColumn().setWidth(0); treeColumn.getColumn().setResizable(false); } } } private void updateTreeViewer(TreeViewer treeViewer) { visibleColumns = settings.getColumnsList().split(","); TreeColumn[] treeColumns = treeViewer.getTree().getColumns(); for (TreeColumn treeColumn : treeColumns) { SortColumn thisSortColumn = (SortColumn)treeColumn.getData("colName"); if (Arrays.stream(visibleColumns).anyMatch(x -> x.equals(thisSortColumn.toString()))) { treeColumn.setWidth(thisSortColumn.getColSize()); } else { treeColumn.setWidth(0); treeColumn.setResizable(false); } } } private Image getIconImage() { if (dbcDataBuilder.getDbcDataList().stream().anyMatch(DbcData::hasBlockedProcess)) { return getImage(Images.BLOCKED); } return getImage(Images.UNBLOCKED); } protected ToolBarManager createToolBarManager(int style) { ToolBarManager toolBarManager = new ToolBarManager(style); addDb = new Action(Images.ADD_DATABASE.getDescription(), ImageDescriptor.createFromImage(getImage(Images.ADD_DATABASE))) { @Override public void run() { AddDbcDataDlg addDbcDlg = new AddDbcDataDlg(getShell(), null, dbcDataBuilder.getDbcDataList()); if (Window.OK == addDbcDlg.open()) { selectedDbcData = addDbcDlg.getNewDbcData(); if (selectedDbcData != null) { dbcDataBuilder.add(selectedDbcData); caServersTable.getTable().setSelection(dbcDataBuilder.getDbcDataList().indexOf(selectedDbcData)); } serversToolBarState(); updateUi(); } } }; toolBarManager.add(addDb); deleteDB = new Action(Images.DELETE_DATABASE.getDescription(), ImageDescriptor.createFromImage(getImage(Images.DELETE_DATABASE))) { @Override public void run() { if (MessageDialog.openQuestion(getShell(), "Подтверждение действия", String.format("Вы действительно хотите удалить %s?", selectedDbcData.getName()))) { dbcDataBuilder.delete(selectedDbcData); selectedDbcData = null; caMainTree.setInput(null); updateUi(); } } }; deleteDB.setEnabled(false); toolBarManager.add(deleteDB); editDB = new Action(Images.EDIT_DATABASE.getDescription(), ImageDescriptor.createFromImage(getImage(Images.EDIT_DATABASE))) { @Override public void run() { AddDbcDataDlg editDbcDlg = new AddDbcDataDlg(getShell(), selectedDbcData, dbcDataBuilder.getDbcDataList()); if (Window.OK == editDbcDlg.open()) { DbcData oldOne = editDbcDlg.getEditedDbcData(); DbcData newOne = editDbcDlg.getNewDbcData(); dbcDataBuilder.edit(oldOne, newOne); updateUi(); } } }; editDB.setEnabled(false); toolBarManager.add(editDB); toolBarManager.add(new Separator()); connectDB = new Action(Images.CONNECT_DATABASE.getDescription(), ImageDescriptor.createFromImage(getImage(Images.CONNECT_DATABASE))) { @Override public void run() { dbcDataConnect(); } }; connectDB.setEnabled(false); toolBarManager.add(connectDB); disconnectDB = new Action(Images.DISCONNECT_DATABASE.getDescription(), ImageDescriptor.createFromImage(getImage(Images.DISCONNECT_DATABASE))) { @Override public void run() { dbcDataDisconnect(); } }; disconnectDB.setEnabled(false); toolBarManager.add(disconnectDB); toolBarManager.add(new Separator()); update = new Action(Images.UPDATE.getDescription(), ImageDescriptor.createFromImage(getImage(Images.UPDATE))) { @Override public void run() { if (selectedDbcData != null) { runUpdate(selectedDbcData); } } }; toolBarManager.add(update); autoUpdate = new Action(Images.AUTOUPDATE.getDescription(), ImageDescriptor.createFromImage(getImage(Images.AUTOUPDATE))) { @Override public void run() { if (autoUpdate.isChecked()) { dbcDataBuilder.getDbcDataList().stream() .filter(x -> x.isConnected() || x.isEnabled()) .filter(x -> x.getStatus() != DbcStatus.CONNECTION_ERROR) .forEach(dbcDataBuilder::addScheduledUpdater); } else { dbcDataBuilder.getDbcDataList().forEach(dbcDataBuilder::removeScheduledUpdater); } settings.setAutoUpdate(autoUpdate.isChecked()); } }; autoUpdate.setChecked(settings.isAutoUpdate()); toolBarManager.add(autoUpdate); cancelUpdate = new Action(Images.CANCEL_UPDATE.getDescription(), ImageDescriptor.createFromImage(getImage(Images.CANCEL_UPDATE))) { @Override public void run() { if (selectedDbcData != null) { dbcDataBuilder.removeOnceScheduledUpdater(selectedDbcData); if (selectedDbcData.isConnected()){ selectedDbcData.setStatus(DbcStatus.CONNECTED); } } } }; cancelUpdate.setEnabled(false); toolBarManager.add(new Separator()); Action filterSetting = new Action(Images.FILTER.getDescription(), ImageDescriptor.createFromImage(getImage(Images.FILTER))) { @Override public void run() { FilterDlg filterDlg = new FilterDlg(getShell(), filterProcess); filterDlg.open(); updateUi(); } }; toolBarManager.add(filterSetting); onlyBlocked = new Action(Images.VIEW_ONLY_BLOCKED.getDescription(), ImageDescriptor.createFromImage(getImage(Images.VIEW_ONLY_BLOCKED))) { @Override public void run() { settings.setOnlyBlocked(onlyBlocked.isChecked()); runUpdateForAllEnabled(); updateUi(); } }; onlyBlocked.setChecked(settings.isOnlyBlocked()); toolBarManager.add(onlyBlocked); toolBarManager.add(new Separator()); Action exportBlocks = new Action(Images.EXPORT_BLOCKS.getDescription(), ImageDescriptor.createFromImage(getImage(Images.EXPORT_BLOCKS))) { @Override public void run() { if (dbcDataBuilder.getDbcDataList().stream() .filter(DbcData::hasBlockedProcess).count() > 0) { BlocksHistory.getInstance().save(dbcDataBuilder.getDbcDataList()); LOG.info("Блокировка сохранена..."); } else { LOG.info("Не найдено блокировок для сохранения"); } } }; toolBarManager.add(exportBlocks); Action importBlocks = new Action(Images.IMPORT_BLOCKS.getDescription()) { @Override public void run() { FileDialog dialog = new FileDialog(getShell()); dialog.setFilterPath(PathBuilder.getInstance().getBlockHistoryDir().toString()); dialog.setText("Открыть историю блокировок"); dialog.setFilterExtensions(new String[]{"*.xml"}); List<DbcData> blockedDbsDataList = BlocksHistory.getInstance().open(dialog.open()); if (!blockedDbsDataList.isEmpty()) { bhServersTable.setInput(blockedDbsDataList); bhMainTree.setInput(blockedDbsDataList.get(0).getProcess()); bhMainTree.refresh(); bhServersTable.refresh(); } } }; importBlocks.setImageDescriptor(ImageDescriptor.createFromImage(getImage(Images.IMPORT_BLOCKS))); toolBarManager.add(importBlocks); toolBarManager.add(new Separator()); Action settingsAction = new Action(Images.SETTINGS.getDescription(), ImageDescriptor.createFromImage(getImage(Images.SETTINGS))) { @Override public void run() { SettingsDlg settingsDlg = new SettingsDlg(getShell(), settings); if (Window.OK == settingsDlg.open()) { updateUi(); updateTreeViewer(caMainTree); updateTreeViewer(bhMainTree); runUpdateForAllEnabled(); } } }; toolBarManager.add(settingsAction); return toolBarManager; } private void runUpdateForAllEnabled() { dbcDataBuilder.getDbcDataList().forEach(dbcDataBuilder::removeScheduledUpdater); dbcDataBuilder.getDbcDataList().forEach(dbcDataBuilder::removeOnceScheduledUpdater); if (autoUpdate.isChecked()) { dbcDataBuilder.getDbcDataList().stream() .filter(x -> x.isConnected() || x.isEnabled()) .filter(x -> x.getStatus() != DbcStatus.CONNECTION_ERROR) .forEach(dbcDataBuilder::addScheduledUpdater); } else { dbcDataBuilder.getDbcDataList().stream() .filter(x -> x.isConnected() || x.isEnabled()) .forEach(dbcDataBuilder::addOnceScheduledUpdater); } } private void runUpdate(DbcData dbcData) { dbcDataBuilder.removeScheduledUpdater(dbcData); dbcDataBuilder.removeOnceScheduledUpdater(dbcData); if (settings.isAutoUpdate()) { LOG.debug(MessageFormat.format("Add dbcData \"{0}\" to updaterList", dbcData.getName())); dbcDataBuilder.addScheduledUpdater(dbcData); } else { dbcDataBuilder.addOnceScheduledUpdater(dbcData); } } private Image getImage(Images type) { return imagesMap.computeIfAbsent(type.toString(), k -> new Image(null, getClass().getClassLoader().getResourceAsStream(type.getImageAddr()))); } private String getAppVersion() { URL manifestPath = MainForm.class.getClassLoader().getResource("META-INF/MANIFEST.MF"); Manifest manifest = null; try { manifest = new Manifest(manifestPath != null ? manifestPath.openStream() : null); } catch (IOException e) { LOG.error("Ошибка при чтении манифеста", e); } Attributes manifestAttributes = manifest != null ? manifest.getMainAttributes() : null; String appVersion = manifestAttributes != null ? manifestAttributes.getValue("Implementation-Version") : null; if(appVersion == null) { return ""; } return appVersion; } private void terminate(Process process) { String term = "select pg_terminate_backend(?);"; boolean kill = false; int pid = process.getPid(); try (PreparedStatement termPs = selectedDbcData.getConnection().prepareStatement(term)) { termPs.setInt(1, pid); try (ResultSet resultSet = termPs.executeQuery()) { if (resultSet.next()) { kill = resultSet.getBoolean(1); } } } catch (SQLException e) { LOG.error(selectedDbcData.getName() + " " + e.getMessage(), e); } if(kill) { LOG.info(selectedDbcData.getName() + PID + pid + " is terminated."); runUpdate(selectedDbcData); } else { LOG.info(selectedDbcData.getName() + " failed to terminate " + PID + pid); } } private void cancel(Process process) { String cancel = "select pg_cancel_backend(?);"; int pid = process.getPid(); boolean kill = false; try (PreparedStatement cancelPs = selectedDbcData.getConnection().prepareStatement(cancel)) { cancelPs.setInt(1, pid); try (ResultSet resultSet = cancelPs.executeQuery()) { if (resultSet.next()) { kill = resultSet.getBoolean(1); } } } catch (SQLException e) { LOG.error(selectedDbcData.getName() + " " + e.getMessage(), e); } if(kill) { LOG.info(selectedDbcData.getName() + PID + pid + " is canceled."); runUpdate(selectedDbcData); } else { LOG.info(selectedDbcData.getName() + " failed to cancel " + PID + pid); } } private void dbcDataConnect() { synchronized (selectedDbcData) { caMainTree.setInput(selectedDbcData.getProcess()); runUpdate(selectedDbcData); connectState(); } } private void dbcDataDisconnect() { synchronized (selectedDbcData) { LOG.debug(MessageFormat.format("Remove dbcData on disconnect \"{0}\" from updaterList", selectedDbcData.getName())); selectedDbcData.disconnect(); dbcDataBuilder.removeScheduledUpdater(selectedDbcData); dbcDataBuilder.removeOnceScheduledUpdater(selectedDbcData); disconnectState(); } updateUi(); } private void serversToolBarState() { if (selectedDbcData != null && (selectedDbcData.getStatus() == DbcStatus.CONNECTION_ERROR || selectedDbcData.getStatus() == DbcStatus.DISABLED)) { disconnectState(); } else { connectState(); } } private void connectState() { deleteDB.setEnabled(false); editDB.setEnabled(false); connectDB.setEnabled(false); disconnectDB.setEnabled(true); cancelUpdate.setEnabled(true); cancelProc.setEnabled(true); terminateProc.setEnabled(true); } private void disconnectState() { deleteDB.setEnabled(true); editDB.setEnabled(true); connectDB.setEnabled(true); disconnectDB.setEnabled(false); cancelUpdate.setEnabled(false); cancelProc.setEnabled(false); terminateProc.setEnabled(false); } private void updateUi() { display.asyncExec(() -> { if (!display.isDisposed()) { caServersTable.refresh(); serversToolBarState(); caMainTree.refresh(); bhMainTree.refresh(); trayItem.setImage(getIconImage()); } }); } @Override public void serverUpdated() { updateUi(); } }
package gov.nih.nci.cabig.caaers.rules.business.service; import gov.nih.nci.cabig.caaers.CaaersSystemException; import gov.nih.nci.cabig.caaers.dao.OrganizationDao; import gov.nih.nci.cabig.caaers.dao.report.ReportDefinitionDao; import gov.nih.nci.cabig.caaers.domain.*; import gov.nih.nci.cabig.caaers.domain.dto.ApplicableReportDefinitionsDTO; import gov.nih.nci.cabig.caaers.domain.dto.EvaluationResultDTO; import gov.nih.nci.cabig.caaers.domain.dto.ReportDefinitionWrapper; import gov.nih.nci.cabig.caaers.domain.dto.ReportDefinitionWrapper.ActionType; import gov.nih.nci.cabig.caaers.domain.dto.SafetyRuleEvaluationResultDTO; import gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection; import gov.nih.nci.cabig.caaers.domain.report.*; import gov.nih.nci.cabig.caaers.rules.common.AdverseEventEvaluationResult; import gov.nih.nci.cabig.caaers.rules.common.CaaersRuleUtil; import gov.nih.nci.cabig.caaers.rules.common.RuleType; import gov.nih.nci.cabig.caaers.service.EvaluationService; import gov.nih.nci.cabig.caaers.validation.ValidationErrors; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.apache.commons.collections15.Closure; import org.apache.commons.collections15.CollectionUtils; import org.apache.commons.collections15.ListUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.transaction.annotation.Transactional; /** * * This class is a facade to the @{AdverseEventEvaluationService}, provides methods to evaluate serious adverse events * * @author Srini Akkala * @author Biju Joseph */ @Transactional(readOnly = true) public class EvaluationServiceImpl implements EvaluationService { private AdverseEventEvaluationService adverseEventEvaluationService; private static final Log log = LogFactory.getLog(EvaluationServiceImpl.class); private ReportDefinitionDao reportDefinitionDao; private OrganizationDao organizationDao; ReportDefinitionFilter reportDefinitionFilter; public EvaluationServiceImpl() { reportDefinitionFilter = new ReportDefinitionFilter(); } /** * This method evaluates the SAE reporting rules on the reporting period. The output evaluation result will have the following * - For new data collection , what are the suggestions * - For existing data collection, what are the suggestions. * - An index relating which AdverseEvent is evaluated for a data collection. * - An index relating which AdverseEvent is associated to which completed reports * - An index mapping which AdverseEvent is associated which suggested report definition. * - Report definitions, getting amended, withdrawn, edited and created. * * @param reportingPeriod * @return */ public EvaluationResultDTO evaluateSAERules(AdverseEventReportingPeriod reportingPeriod){ assert reportingPeriod != null : "Reporting period should not be null"; EvaluationResultDTO result = new EvaluationResultDTO(); List<ExpeditedAdverseEventReport> aeReports = reportingPeriod.getAeReports(); //determine discrete set of AdverseEvents, against which the rules should be fired. List<AdverseEvent> newlyAddedAdverseEvents = reportingPeriod.getNonExpeditedAdverseEvents(); // CAAERS-4881 : have to remove unmodified duplicate adverse events from the newly added adverse events; if(aeReports != null && !aeReports.isEmpty()){ removeUnModifiedDuplicateAdverseEvents(newlyAddedAdverseEvents, aeReports.get(aeReports.size()-1)); } //find the evaluation for default (new data collection) if(!newlyAddedAdverseEvents.isEmpty()) { //fake expedited report with TreatmentInformation ExpeditedAdverseEventReport fakeAeReport = new ExpeditedAdverseEventReport(); fakeAeReport.setTreatmentInformation(new TreatmentInformation()); fakeAeReport.getTreatmentInformation().setTreatmentAssignment(new TreatmentAssignment()); String tac = reportingPeriod.getTreatmentAssignment() != null ? reportingPeriod.getTreatmentAssignment().getCode() : ""; fakeAeReport.getTreatmentInformation().getTreatmentAssignment().setCode(tac); findRequiredReportDefinitions(fakeAeReport, newlyAddedAdverseEvents, reportingPeriod.getStudy(), result); } result.addAllAdverseEvents(new Integer(0), newlyAddedAdverseEvents); //for each data collection (existing) find the evaluation if(aeReports != null && !aeReports.isEmpty()){ for(ExpeditedAdverseEventReport aeReport : aeReports){ List<AdverseEvent> evaluatableAdverseEvents = new ArrayList<AdverseEvent>(newlyAddedAdverseEvents); List<AdverseEvent> existingAdverseEvents = aeReport.isActive() ? aeReport.getActiveAdverseEvents() : aeReport.getActiveModifiedAdverseEvents() ; List<AdverseEvent> deletedAdverseEvents = aeReport.getRetiredAdverseEvents(); evaluatableAdverseEvents.addAll(existingAdverseEvents); evaluatableAdverseEvents.addAll(deletedAdverseEvents); List<AdverseEvent> allAdverseEvents = new ArrayList<AdverseEvent>(newlyAddedAdverseEvents); allAdverseEvents.addAll(aeReport.getAdverseEvents()); removeUnModifiedDuplicateAdverseEvents(evaluatableAdverseEvents, aeReport); if(!evaluatableAdverseEvents.isEmpty()) findRequiredReportDefinitions(aeReport, evaluatableAdverseEvents, reportingPeriod.getStudy(), result); result.addAllAdverseEvents(aeReport.getId(), allAdverseEvents); //populate the reported adverse event - report definition map. List<Report> completedAmendableReports = aeReport.findCompletedAmendableReports(); for(AdverseEvent ae : aeReport.getAdverseEvents()){ List<ReportDefinition> rdList = new ArrayList<ReportDefinition>(); for(Report completedReport : completedAmendableReports){ if(completedReport.isReported(ae)){ rdList.add(completedReport.getReportDefinition()); } } result.getReportedAEIndexMap().put(ae.getId(), rdList); } } } result.refreshAdverseEventIndexMap(); if(log.isInfoEnabled()){ log.info("============== Evaluation result ============="); log.info(result.toString()); log.info("=============================================="); } return result; } private void removeUnModifiedDuplicateAdverseEvents(List<AdverseEvent> adverseEvents, ExpeditedAdverseEventReport aeReport){ Iterator<AdverseEvent> aeIterator = adverseEvents.iterator(); while(aeIterator.hasNext()){ AdverseEvent ae = aeIterator.next(); if(aeReport.doesAnotherAeWithSameTermExist(ae) != null){ // remove the AE from evaluation input if the AE is already part of the report and is not modified according to the signature if(ae.getAddedToReportAtLeastOnce() != null && ae.getAddedToReportAtLeastOnce() && !ae.isModified()){ aeIterator.remove(); } } } } /** * This method invokes the {@link AdverseEventEvaluationService} to obtain the report definitions suggested. * Then process that information, to get the adverse event result {@link EvaluationResultDTO} * * Overview on extra processing * 0. Ignore all the 'soft deleted' reports suggested by rules engine. * 1. If child report or a report of the same group is active , parent report suggested by rules is ignored. * 2. All manually selected active reports are suggested by caAERS * 3. If there is a manual selection, ignore the others suggested by rules * 4. If there is an AE modified, which is part of submitted report, force amend it. * 5. If any, Withdraw all active reports (non manually selected), that are not suggested. * * @param aeReport - The {@link ExpeditedAdverseEventReport} */ public void findRequiredReportDefinitions(ExpeditedAdverseEventReport aeReport, List<AdverseEvent> aeList, Study study, EvaluationResultDTO evaluationResult) { List<AdverseEvent> deletedAeList = new ArrayList<AdverseEvent>(); List<AdverseEvent> newAeList = new ArrayList<AdverseEvent>(); List<AdverseEvent> modifiedAeList = new ArrayList<AdverseEvent>(); List<AdverseEvent> evaluatableAeList = new ArrayList<AdverseEvent>(); for(AdverseEvent ae : aeList) { if(ae.isRetired()) { deletedAeList.add(ae); } else if(ae.getReport() == null) { newAeList.add(ae); } else { modifiedAeList.add(ae); } } evaluatableAeList.addAll(modifiedAeList); evaluatableAeList.addAll(newAeList); ExpeditedAdverseEventReport expeditedData = aeReport.getId() == null ? null : aeReport; //to hold the report defnitions while cleaning up. Map<String , ReportDefinition> loadedReportDefinitionsMap = new HashMap<String, ReportDefinition>(); Map<AdverseEvent, List<AdverseEventEvaluationResult>> adverseEventEvaluationResultMap; Map<AdverseEvent, List<String>> map; boolean alertNeeded = false; Integer aeReportId = expeditedData == null ? new Integer(0) : expeditedData.getId(); try { //evaluate the SAE reporting rules adverseEventEvaluationResultMap = adverseEventEvaluationService.evaluateSAEReportSchedule(aeReport, evaluatableAeList, study); evaluationResult.getRulesEngineRawResultMap().put(aeReportId, adverseEventEvaluationResultMap); map = new HashMap<AdverseEvent, List<String>>(); // clear the recommended reports map evaluationResult.getAdverseEventRecommendedReportsMap().clear(); //clean up - by eliminating the deleted report definitions. for(Map.Entry<AdverseEvent, List<AdverseEventEvaluationResult>> entry : adverseEventEvaluationResultMap.entrySet()){ Set<String> rdNameSet = new HashSet<String>(); AdverseEvent adverseEvent = entry.getKey(); Set<ReportDefinition> recommendedAeReports = new HashSet<ReportDefinition>(); for(AdverseEventEvaluationResult aeEvalResult : entry.getValue()){ for(String response : aeEvalResult.getRuleEvaluationResult().getResponses()){ if(!StringUtils.isBlank(response)){ ReportDefinition rd = reportDefinitionDao.getByName(response); if(rd != null){ recommendedAeReports.add(rd); } } } } evaluationResult.getAdverseEventRecommendedReportsMap().put(adverseEvent, new ArrayList<ReportDefinition>(recommendedAeReports)); List<String> validReportDefNames = new ArrayList<String>(); map.put(adverseEvent, validReportDefNames); evaluationResult.addProcessingStep(aeReportId, "RulesEngine: Evaluation for adverse event (" + AdverseEvent.toReadableString(adverseEvent) + ") :", null); for(AdverseEventEvaluationResult adverseEventEvaluationResult : entry.getValue()){ evaluationResult.addProcessingStep(aeReportId, " RuleSet:", adverseEventEvaluationResult.getRuleMetadata() ); evaluationResult.addProcessingStep(aeReportId, " Raw message :", adverseEventEvaluationResult.getMessage() ); if(adverseEventEvaluationResult.getRuleEvaluationResult() != null){ evaluationResult.addProcessingStep(aeReportId, " Bind URL :", adverseEventEvaluationResult.getRuleEvaluationResult().getBindURI() ); evaluationResult.addProcessingStep(aeReportId, " Matched rules :", adverseEventEvaluationResult.getRuleEvaluationResult().getMatchedRules().toString() ); for(String note : adverseEventEvaluationResult.getNotes()) { evaluationResult.addProcessingStep(aeReportId, " Notes: " , note); } evaluationResult.addProcessingStep(aeReportId, " Matched rules :", adverseEventEvaluationResult.getRuleEvaluationResult().getMatchedRules().toString() ); } else { evaluationResult.addProcessingStep(aeReportId, " Bind URL :", null ); evaluationResult.addProcessingStep(aeReportId, " Matched rules :", null ); } if(adverseEventEvaluationResult.isCannotDetermine() || adverseEventEvaluationResult.isNoRulesFound()) continue; evaluationResult.addProcessingStep(aeReportId, " Raw suggestions :", adverseEventEvaluationResult.getRuleEvaluationResult().getResponses().toString() ); rdNameSet.addAll(adverseEventEvaluationResult.getRuleEvaluationResult().getResponses()); } //CAAERS-5702 if(rdNameSet.contains("IGNORE")){ rdNameSet.clear(); evaluationResult.addProcessingStep(aeReportId, "caAERS : Protocol specific exception, so removing all recommendations",""); } for(String reportDefName : rdNameSet){ ReportDefinition rd = loadedReportDefinitionsMap.get(reportDefName); if(rd == null) { rd = reportDefinitionDao.getByName(reportDefName); if(rd == null){ evaluationResult.addProcessingStep(aeReportId, "report definition missing in database " , reportDefName); log.warn("Report definition (" + reportDefName + "), is referred in rules but is not found"); continue; //we cannot find the report referred by the rule } loadedReportDefinitionsMap.put(reportDefName, rd); } if(rd.getEnabled()){ validReportDefNames.add(reportDefName); } } evaluationResult.addProcessingStep(aeReportId, "caAERS : Plausible suggestions :", validReportDefNames.toString() ); evaluationResult.addProcessingStep(aeReportId, " ", null ); } for(Map.Entry<AdverseEvent,List<ReportDefinition>> entry : evaluationResult.getAdverseEventRecommendedReportsMap().entrySet()){ List<ReportDefinition> filteredRdList = reportDefinitionFilter.filter(entry.getValue()); entry.setValue(filteredRdList); } //save this for reference. evaluationResult.addRulesEngineResult(aeReportId, map); //now load report definitions List<ReportDefinition> defList = new ArrayList<ReportDefinition>(); defList.addAll(loadedReportDefinitionsMap.values()); List<Report> completedReports = expeditedData == null ? new ArrayList<Report>() : expeditedData.listReportsHavingStatus(ReportStatus.COMPLETED); if(!completedReports.isEmpty()){ for(AdverseEvent adverseEvent : evaluatableAeList){ if(adverseEvent.getReport() == null) continue; //unreported AE - continue List<String> nameList = map.get(adverseEvent); if(adverseEvent.isModified()) { //throw away notifications if AE is already reported. for(Report report : completedReports) { if(report.isReported(adverseEvent)) { List<ReportDefinition> rdList = ReportDefinition.findByName(defList, nameList.toArray(new String[0])); List<ReportDefinition> sameOrgGroupList = ReportDefinition.findBySameOrganizationAndGroup(rdList, report.getReportDefinition()); if(sameOrgGroupList.size() > 1) { List<ReportDefinition> rdNotificationList = ReportDefinition.findByReportType(sameOrgGroupList, ReportType.NOTIFICATION); for(ReportDefinition rd : rdNotificationList) { // we must remove these from suggestions. nameList.remove(rd.getName()); boolean removed = defList.remove(rd); evaluationResult.removeReportDefinitionName(aeReportId, adverseEvent, rd.getName()); evaluationResult.addProcessingStep(aeReportId, "caAERS : Adverse event (" + AdverseEvent.toReadableString(adverseEvent) + ") is already reported in :", "" + report.getId()); evaluationResult.addProcessingStep(aeReportId, " Notifications are not needed again, removing:", rd.getName() ); evaluationResult.addProcessingStep(aeReportId, " removed ? :", String.valueOf(removed) ); } } } } } else { //throw away rules suggestion - if AE is not modified and is part of a submitted report OR if AE is new for(Report report : completedReports){ if(report.isReported(adverseEvent)){ nameList.remove(report.getName()); List<ReportDefinition> rdList = ReportDefinition.findByName(defList,new String[]{report.getName()}); if(!rdList.isEmpty()) defList.remove(rdList.get(0)); evaluationResult.removeReportDefinitionName(aeReportId, adverseEvent, report.getName()); evaluationResult.addProcessingStep(aeReportId, "caAERS : Adverse event (" + AdverseEvent.toReadableString(adverseEvent) + "):", null); evaluationResult.addProcessingStep(aeReportId, " Unmodified and belongs to completed report :", null ); evaluationResult.addProcessingStep(aeReportId, " Removing suggestion :", report.getName() ); } } } } } //Update AE reporting flag (or sae flag) for(AdverseEvent ae : map.keySet()){ List<String> nameList = map.get(ae); ae.setRequiresReporting(!nameList.isEmpty()); evaluationResult.addProcessingStep(aeReportId, "caAERS: Adverse event (" + AdverseEvent.toReadableString(ae) + ") may need reporting ? : ", String.valueOf(ae.getRequiresReporting()) ); } //logging if(log.isDebugEnabled()){ log.debug("Rules Engine Result for : " + aeReportId + ", " + String.valueOf(map)); } // - If child report is active, select that instead of parent. // - If there is a manual selection, ignore rules engine suggestions from the same group // - If the manual selection is always a preferred one (ie. by default add active manual selected reports). // - If there is an ae modified, which is part of completed report, force amending it. List<Report> activeReports = null; if(expeditedData != null){ activeReports = expeditedData.getActiveReports(); List<Report> manuallySelectedReports = expeditedData.getManuallySelectedReports(); //a temporary list List<ReportDefinition> tmplist = new ArrayList<ReportDefinition>(defList); //keep active child report instead of parent. for(Report activeReport : activeReports){ ReportDefinition rdParent = activeReport.getReportDefinition().getParent(); ReportDefinition rdFound = findReportDefinition(tmplist, rdParent); if(rdFound != null){ //remove parent and keep child defList.remove(rdFound); defList.add(activeReport.getReportDefinition()); evaluationResult.replaceReportDefinitionName(aeReportId, rdFound.getName(), activeReport.getName()); evaluationResult.addProcessingStep(aeReportId, "caAERS: Active child report (" + activeReport.getName() + ") present", null ); evaluationResult.addProcessingStep(aeReportId, " Removing suggestion", rdFound.getName() ); } } //throw away all suggestions of rules engine, (if they belong to the same group as that of manually selected) for(Report manualReport : manuallySelectedReports){ ReportDefinition rdManual = manualReport.getReportDefinition(); for(ReportDefinition rdSuggested : tmplist){ if(rdSuggested.isOfSameReportTypeAndOrganization(rdManual) && manualReport.isActive() ){ //remove it from rules engine suggestions defList.remove(rdSuggested); evaluationResult.replaceReportDefinitionName(aeReportId, rdSuggested.getName(), rdManual.getName()); evaluationResult.addProcessingStep(aeReportId, "caAERS: Manually selected report (" + rdManual.getName() + ") present", null ); evaluationResult.addProcessingStep(aeReportId, " Removing suggestion", rdSuggested.getName() ); } } //now add the manually selected report. defList.add(rdManual); evaluationResult.addReportDefinitionName(aeReportId, rdManual.getName()); evaluationResult.addProcessingStep(aeReportId, " Adding to suggestion ", rdManual.getName() ); } //any ae modified/got completed reports ? add those report definitions. if(!modifiedAeList.isEmpty()){ //Any completed report, suggest amending it to proceed (but no alert). for(Report report : completedReports){ ReportDefinition rdCompleted = report.getReportDefinition(); if(!rdCompleted.getAmendable()) continue; defList.add(rdCompleted); for(AdverseEvent ae : modifiedAeList){ evaluationResult.addReportDefinitionName(aeReportId, ae, rdCompleted.getName()); evaluationResult.addProcessingStep(aeReportId, "caAERS: Submitted adverse event (" + AdverseEvent.toReadableString(ae) + ") is modified : ", null); evaluationResult.addProcessingStep(aeReportId, " Adding to suggestion ", rdCompleted.getName() ); } } } //CAAERS-7067 - the deletions must suggest an Amend (ONLY if the AE was reported on last submitted report) if(!deletedAeList.isEmpty()) { // find latest submission from each group and org List<Report> lastSubmittedReports = new ArrayList<Report>(); Set<Integer> rdIdSet = new HashSet<Integer>(); //using Set for reports may complicate stuff with equals on hibernate proxy for(Report completedReport : completedReports) { Report latestReport = aeReport.findLastSubmittedReport(completedReport.getReportDefinition()); if(rdIdSet.add(latestReport.getReportDefinition().getId())) { lastSubmittedReports.add(latestReport); } } //for each such report, if the AE deleted is submitted on that, then suggest ammend. for(Report submittedReport : lastSubmittedReports) { ReportDefinition rdCompleted = submittedReport.getReportDefinition(); if(rdCompleted.getReportType() == ReportType.NOTIFICATION) continue; //CAAERS-7041 if(!rdCompleted.getAmendable()) continue; for(AdverseEvent ae : deletedAeList) { boolean reported = submittedReport.isReported(ae); if(reported) { defList.add(rdCompleted); evaluationResult.addReportDefinitionName(aeReportId, ae, rdCompleted.getName()); evaluationResult.addProcessingStep(aeReportId, "caAERS: Submitted adverse event (" + AdverseEvent.toReadableString(ae) + ") is deleted : ", null); evaluationResult.addProcessingStep(aeReportId, " Adding to suggestion ", rdCompleted.getName() ); } } } } } //logging if(log.isDebugEnabled()){ log.debug("Report Definitions before filtering for aeReportId: " + aeReportId + ", " + String.valueOf(defList)); } //filter the report definitions List<ReportDefinition> reportDefinitions = reportDefinitionFilter.filter(defList); if(reportDefinitions != null){ List<String> filteredReportDefnitionNames = new ArrayList<String>(); for(ReportDefinition rd: reportDefinitions){ filteredReportDefnitionNames.add(rd.getName()); } evaluationResult.addProcessingStep(aeReportId, " ", null ); evaluationResult.addProcessingStep(aeReportId, "caAERS: Final suggestion after filtering :", filteredReportDefnitionNames.toString()); } //modify the alert necessary flag, based on eventual set of report definitions if(expeditedData == null){ alertNeeded = !reportDefinitions.isEmpty(); }else{ for(ReportDefinition reportDefinition : reportDefinitions){ alertNeeded |= expeditedData.findReportsToEdit(reportDefinition).isEmpty(); } } evaluationResult.getAeReportAlertMap().put(aeReportId, alertNeeded); evaluationResult.addProcessingStep(aeReportId, "caAERS: Alert is needed ? ", String.valueOf(alertNeeded)); //logging if(log.isDebugEnabled()){ log.debug("Report Definitions after filtering for aeReportId: " + aeReportId + ", " + String.valueOf(reportDefinitions)); } //now go through each report definition and set amend/create edit/withdraw/create maps properly Set<ReportDefinitionWrapper> rdCreateSet = new HashSet<ReportDefinitionWrapper>(); Set<ReportDefinitionWrapper> rdEditSet = new HashSet<ReportDefinitionWrapper>(); Set<ReportDefinitionWrapper> rdWithdrawSet = new HashSet<ReportDefinitionWrapper>(); Set<ReportDefinitionWrapper> rdAmmendSet = new HashSet<ReportDefinitionWrapper>(); ReportDefinitionWrapper wrapper; for(ReportDefinition rd : reportDefinitions){ if(expeditedData == null){ //all report definitions, should go in the createMap. wrapper = new ReportDefinitionWrapper(rd, null, ActionType.CREATE); wrapper.setStatus("Not started"); rdCreateSet.add(wrapper); }else{ //find reports getting amended List<Report> reportsAmmended = expeditedData.findReportsToAmmend(rd); for(Report report : reportsAmmended){ wrapper = new ReportDefinitionWrapper(report.getReportDefinition(), rd, ActionType.AMEND); wrapper.setStatus(report.getLastVersion().getStatusAsString()); wrapper.setSubmittedOn(report.getSubmittedOn()); rdAmmendSet.add(wrapper); } //find reports getting withdrawn List<Report> reportsWithdrawn = expeditedData.findReportsToWithdraw(rd); for(Report report : reportsWithdrawn){ wrapper = new ReportDefinitionWrapper(report.getReportDefinition(), rd, ActionType.WITHDRAW); wrapper.setStatus("In process"); wrapper.setDueOn(report.getDueOn()); rdWithdrawSet.add(wrapper); } //find the reports getting edited List<Report> reportsEdited = expeditedData.findReportsToEdit(rd); for(Report report : reportsEdited){ wrapper = new ReportDefinitionWrapper(report.getReportDefinition(), rd, ActionType.EDIT); wrapper.setStatus("In process"); wrapper.setDueOn(report.getDueOn()); rdEditSet.add(wrapper); } //Nothing getting edited, add in this report def in create list if(reportsEdited.isEmpty() && reportsAmmended.isEmpty() && reportsWithdrawn.isEmpty()){ wrapper = new ReportDefinitionWrapper(rd, null, ActionType.CREATE); wrapper.setStatus("Not started"); rdCreateSet.add(wrapper); } }//if expeditedData }//for rd //Check if there is a need to withdraw any active report. if(expeditedData != null && activeReports != null){ for(Report report : activeReports){ ReportDefinition rdActive = report.getReportDefinition(); if(report.isManuallySelected()) continue; boolean toBeWithdrawn = true; for(ReportDefinitionWrapper editWrapper : rdEditSet){ if(editWrapper.getDef().equals(rdActive)){ toBeWithdrawn = false; break; } } if(toBeWithdrawn){ for(ReportDefinitionWrapper withdrawWrapper :rdWithdrawSet){ if(withdrawWrapper.getDef().equals(rdActive)){ toBeWithdrawn = false; break; } } } if(toBeWithdrawn){ wrapper = new ReportDefinitionWrapper(rdActive, null, ActionType.WITHDRAW); wrapper.setDueOn(report.getDueOn()); wrapper.setStatus("In process"); rdWithdrawSet.add(wrapper); } } } //add everything to the result. evaluationResult.getCreateMap().put(aeReportId, rdCreateSet); evaluationResult.getAmendmentMap().put(aeReportId, rdAmmendSet); evaluationResult.getEditMap().put(aeReportId, rdEditSet); evaluationResult.getWithdrawalMap().put(aeReportId, rdWithdrawSet); if(!rdCreateSet.isEmpty()){ evaluationResult.addProcessingStep(aeReportId, "caAERS: Create options :", null); for(ReportDefinitionWrapper rdWrapper : rdCreateSet){ evaluationResult.addProcessingStep(aeReportId, " " + rdWrapper.getReadableMessage(), null); } } if(!rdAmmendSet.isEmpty()){ evaluationResult.addProcessingStep(aeReportId, "caAERS: Amend options :", null); for(ReportDefinitionWrapper rdWrapper : rdAmmendSet){ evaluationResult.addProcessingStep(aeReportId, " " + rdWrapper.getReadableMessage(), null); } } if(!rdEditSet.isEmpty()){ evaluationResult.addProcessingStep(aeReportId, "caAERS: Edit options :", null); for(ReportDefinitionWrapper rdWrapper : rdEditSet){ evaluationResult.addProcessingStep(aeReportId, " " + rdWrapper.getReadableMessage(), null); } } if(!rdWithdrawSet.isEmpty()){ evaluationResult.addProcessingStep(aeReportId, "caAERS: Withdraw options :", null); for(ReportDefinitionWrapper rdWrapper : rdWithdrawSet){ evaluationResult.addProcessingStep(aeReportId, " " + rdWrapper.getReadableMessage(), null); } } //update the result object evaluationResult.addEvaluatedAdverseEvents(aeReportId, evaluatableAeList); // evaluationResult.addResult(aeList, reportDefinitions); evaluationResult.addResult(expeditedData, reportDefinitions); } catch (Exception e) { throw new CaaersSystemException("Could not determine the reports necessary for the given expedited adverse event data", e); } } /** * This method will find all the report definitions belonging to the Study */ public ApplicableReportDefinitionsDTO applicableReportDefinitions(Study study, StudyParticipantAssignment assignment) { List<ReportDefinition> reportDefinitions = new ArrayList<ReportDefinition>(); // Same organization play multiple roles. Set<Integer> orgIdSet = new HashSet<Integer>(); List<StudyOrganization> studyOrgs = study.getStudyOrganizations(); for (StudyOrganization studyOrganization : studyOrgs) { // Ignore the organization if its just a study site and not the one where assignment belongs to. if(studyOrganization instanceof StudySite && !studyOrganization.getId().equals(assignment.getStudySite().getId())) continue; if(orgIdSet.add(studyOrganization.getOrganization().getId())) reportDefinitions.addAll(reportDefinitionDao.getAll(studyOrganization.getOrganization().getId())); } /** * Get REport definitions of CTEP for DCP studies , because DCP uses CTEP * report definitions also . TEMP fix */ Organization primarySponsor = study.getPrimaryFundingSponsorOrganization(); //CAAERS-4215 //if (primarySponsor.getName().equals("Division of Cancer Prevention")) { //reportDefinitions.addAll(reportDefinitionDao.getAll(this.organizationDao.getByName("Cancer Therapy Evaluation Program").getId())); ApplicableReportDefinitionsDTO dto = new ApplicableReportDefinitionsDTO(); for(ReportDefinition rd : reportDefinitions){ dto.addReportDefinition(rd); } return dto; } /** * Will find the mandatory sections associated with the report definitions. * @param expeditedData * @param reportDefinitions * @return */ public Map<Integer, Collection<ExpeditedReportSection>> mandatorySections( ExpeditedAdverseEventReport expeditedData, ReportDefinition... reportDefinitions) { Map<Integer, Collection<ExpeditedReportSection>> mandatorySectionMap = new HashMap<Integer, Collection<ExpeditedReportSection>>(); try { for(ReportDefinition reportDefinition : reportDefinitions ){ Collection<ExpeditedReportSection> sections = adverseEventEvaluationService.mandatorySections(expeditedData, reportDefinition); mandatorySectionMap.put(reportDefinition.getId(), sections); } if (log.isDebugEnabled()) log.debug("Mandatory sections: " + mandatorySectionMap); return mandatorySectionMap; } catch (Exception e) { throw new CaaersSystemException("Could not get mandatory sections", e); } } public ValidationErrors validateReportingBusinessRules(ExpeditedAdverseEventReport aeReport, ExpeditedReportSection... sections) { try { return adverseEventEvaluationService.validateReportingBusinessRules(aeReport, sections); } catch (Exception e) { log.error("Error while evaluating business rules", e); throw new CaaersSystemException("Error while evaluating business rules", e); } } /** * Evaluate the mandatoryness of a specific report, the {@link gov.nih.nci.cabig.caaers.domain.report.ReportMandatoryField} will be populated in the Report. * @param aeReport * @param report */ public void evaluateMandatoryness(final ExpeditedAdverseEventReport aeReport, final Report report) { final ReportDefinition rd = report.getReportDefinition(); //clear the mandatory fields in report final List<ReportMandatoryField> mfList = new ArrayList<ReportMandatoryField>(); report.setMandatoryFields(mfList); if(log.isDebugEnabled()) log.debug("Static Mandatory field evaluation"); //evaluation of static field rules CollectionUtils.forAllDo(rd.getAllNonRuleBasedMandatoryFields(), new Closure<ReportMandatoryFieldDefinition>(){ public void execute(ReportMandatoryFieldDefinition mfd) { ReportMandatoryField mf = new ReportMandatoryField(mfd.getFieldPath(), Mandatory.NA); //update the mandatory flag if(mfd.getMandatory().equals(RequirednessIndicator.OPTIONAL)) mf.setMandatory(Mandatory.OPTIONAL); if(mfd.getMandatory().equals(RequirednessIndicator.MANDATORY)) mf.setMandatory(Mandatory.MANDATORY); if(log.isDebugEnabled()) log.debug( mfd.getFieldPath() + " -->" + mf.getMandatory().getName()); mfList.add(mf); } }); final List<Object> baseInputObjects = new ArrayList<Object>(); baseInputObjects.add(aeReport); baseInputObjects.add(rd); if(aeReport.getStudy() != null) baseInputObjects.add(aeReport.getStudy()); if(aeReport.getTreatmentInformation() != null) baseInputObjects.add(aeReport.getTreatmentInformation()); //non self referenced rules final List<Object> inputObjects = new ArrayList(baseInputObjects); inputObjects.addAll(aeReport.getActiveAdverseEvents()); final HashMap<String, Mandatory> rulesDecisionCache = new HashMap<String, Mandatory>(); if(log.isDebugEnabled()) log.debug("Non Self referenced rule evaluation"); final String fieldRulesBindURL = adverseEventEvaluationService.fetchBindURI(RuleType.FIELD_LEVEL_RULES, null, null, null); if(StringUtils.isEmpty(fieldRulesBindURL)){ log.warn("No active field level rules found, so ignoring rule based mandatoryness evaluation"); } CollectionUtils.forAllDo(rd.getNonSelfReferencedRuleBasedMandatoryFields(), new Closure<ReportMandatoryFieldDefinition>(){ public void execute(ReportMandatoryFieldDefinition mfd) { String ruleName = mfd.getRuleName(); String path = mfd.getFieldPath(); Mandatory m = rulesDecisionCache.get(ruleName); if(StringUtils.isEmpty(fieldRulesBindURL)) { log.info(mfd.getFieldPath() + " marking it as optional, as there is no field rules found"); m = Mandatory.OPTIONAL; } if(m == null){ String decision = adverseEventEvaluationService.evaluateFieldLevelRules(fieldRulesBindURL, ruleName, inputObjects); if(log.isDebugEnabled()) log.debug("rules decision : " + decision); m = translateRulesMandatorynessResult(decision); rulesDecisionCache.put(ruleName, m); if(log.isDebugEnabled()) log.debug( "caching --> " + m.getName()); } if(log.isDebugEnabled()) log.debug( mfd.getFieldPath() + " -->" + m.getName()); mfList.add(new ReportMandatoryField(path, m)); } }); //self referenced rules if(log.isDebugEnabled()) log.debug("Self referenced rule evaluation"); CollectionUtils.forAllDo(rd.getSelfReferencedRuleBasedMandatoryFields(), new Closure<ReportMandatoryFieldDefinition>(){ public void execute(ReportMandatoryFieldDefinition mfd) { Map<String, Object> map = CaaersRuleUtil.multiplexAndEvaluate(aeReport, mfd.getFieldPath()); for(String path : map.keySet()){ List<Object> inputObjects = new ArrayList(baseInputObjects); Object o = map.get(path); if(o == null) continue; if(o instanceof Collection){ inputObjects.addAll((Collection) o); }else { inputObjects.add(o); } String decision = null; if(StringUtils.isEmpty(fieldRulesBindURL)) { log.info(mfd.getFieldPath() + " marking it as optional, as there is no field rules found"); }else { decision = adverseEventEvaluationService.evaluateFieldLevelRules(fieldRulesBindURL, mfd.getRuleName(), inputObjects); } if(log.isDebugEnabled()) log.debug("rules decision : " + decision); Mandatory m = translateRulesMandatorynessResult(decision); if(log.isDebugEnabled()) log.debug( mfd.getFieldPath() + " -->" + m.getName()); mfList.add(new ReportMandatoryField(path, m)); } } }); } protected Mandatory translateRulesMandatorynessResult(String decision){ if(StringUtils.isEmpty(decision)) return Mandatory.OPTIONAL; String[] nameArray = StringUtils.split(decision,"||"); Set<Mandatory> set = new TreeSet<Mandatory>(new Comparator<Mandatory>(){ public int compare(Mandatory o1, Mandatory o2) { return o1.ordinal() - o2.ordinal(); } }); for(String s : nameArray) set.add(Mandatory.valueOf(s)); if(!set.isEmpty()) return set.iterator().next(); return Mandatory.OPTIONAL; } /////move this else where private ReportDefinition findReportDefinition(List<ReportDefinition> rdList, ReportDefinition toFind){ if(toFind == null) return null; for(ReportDefinition rd : rdList){ if(rd.getId().equals( toFind.getId())) return rd; } return null; } public SafetyRuleEvaluationResultDTO evaluateSafetySignallingRules(ObservedAdverseEventProfile observedAEProfile) { if(observedAEProfile.getNotificationStatus() == NotificationStatus.NOTIFY || observedAEProfile.getNotificationStatus() == NotificationStatus.IGNORE_ALREADY_NOTIFIED){ SafetyRuleEvaluationResultDTO result = new SafetyRuleEvaluationResultDTO(); result.setNotificationStatus(NotificationStatus.IGNORE_ALREADY_NOTIFIED); result.setRulesMatched(Arrays.asList(new String[]{})); return result; } return adverseEventEvaluationService.evaluateSafetySignallingRules(observedAEProfile); } // //// CONFIGURATION public void setReportDefinitionDao(ReportDefinitionDao reportDefinitionDao) { this.reportDefinitionDao = reportDefinitionDao; } public void setAdverseEventEvaluationService( AdverseEventEvaluationService adverseEventEvaluationService) { this.adverseEventEvaluationService = adverseEventEvaluationService; } public AdverseEventEvaluationService getAdverseEventEvaluationService() { return adverseEventEvaluationService; } public void setOrganizationDao(OrganizationDao organizationDao) { this.organizationDao = organizationDao; } }
package sc.iview.commands.view; import static sc.iview.commands.MenuWeights.VIEW; import static sc.iview.commands.MenuWeights.VIEW_ROTATE; import org.scijava.command.Command; import org.scijava.plugin.Menu; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; import sc.iview.SciView; @Plugin(type = Command.class, menuRoot = "SciView", menu = { @Menu(label = "View", weight = VIEW), @Menu(label = "Circle camera around current object", weight = VIEW_ROTATE) }) public class RotateView implements Command { @Parameter private SciView sciView; @Parameter private int xSpeed = 3; @Parameter private int ySpeed = 0; @Override public void run() { sciView.animate( 30, () -> { sciView.getTargetArcball().init( 1, 1 ); sciView.getTargetArcball().drag( 1+xSpeed, 1+ySpeed ); sciView.getTargetArcball().end( 1+xSpeed, 1+ySpeed ); } ); } }
package aQute.lib.deployer; import java.io.*; import java.security.*; import java.util.*; import java.util.jar.*; import java.util.regex.*; import aQute.bnd.header.*; import aQute.bnd.osgi.*; import aQute.bnd.service.*; import aQute.bnd.version.*; import aQute.lib.io.*; import aQute.libg.command.*; import aQute.service.reporter.*; public class FileRepo implements Plugin, RepositoryPlugin, Refreshable, RegistryPlugin { public final static String LOCATION = "location"; public final static String READONLY = "readonly"; public final static String NAME = "name"; public static final String CMD_PATH = "cmd.path"; public static final String CMD_INIT = "cmd.init"; public static final String CMD_AFTER_PUT = "cmd.after.put"; public static final String CMD_REFRESH = "cmd.refresh"; public static final String CMD_BEFORE_PUT = "cmd.before.put"; public static final String CMD_ABORT_PUT = "cmd.abort.put"; public static final String CMD_SHELL = "cmd.shell"; String before; String refresh; String after; String path; String init; String abort; String shell; File[] EMPTY_FILES = new File[0]; protected File root; Registry registry; boolean canWrite = true; Pattern REPO_FILE = Pattern.compile("([-a-zA-z0-9_\\.]+)-([0-9\\.]+|latest)\\.(jar|lib)"); Reporter reporter; boolean dirty; String name; boolean inited; public FileRepo() {} public FileRepo(String name, File location, boolean canWrite) { this.name = name; this.root = location; this.canWrite = canWrite; } protected void init() throws Exception { if (inited) return; inited = true; if (!getRoot().isDirectory()) { getRoot().mkdirs(); } exec(init, null); } public void setProperties(Map<String,String> map) { String location = map.get(LOCATION); if (location == null) throw new IllegalArgumentException("Location must be set on a FileRepo plugin"); root = new File(location); String readonly = map.get(READONLY); if (readonly != null && Boolean.valueOf(readonly).booleanValue()) canWrite = false; name = map.get(NAME); before = map.get(CMD_BEFORE_PUT); refresh = map.get(CMD_REFRESH); after = map.get(CMD_AFTER_PUT); init = map.get(CMD_INIT); path = map.get(CMD_PATH); abort = map.get(CMD_ABORT_PUT); shell = map.get(CMD_SHELL); } /** * Get a list of URLs to bundles that are constrained by the bsn and * versionRange. */ private File[] get(String bsn, String versionRange) throws Exception { init(); // If the version is set to project, we assume it is not // for us. A project repo will then get it. if (versionRange != null && versionRange.equals("project")) return null; // Check if the entry exists File f = new File(root, bsn); if (!f.isDirectory()) return null; // The version range we are looking for can // be null (for all) or a version range. VersionRange range; if (versionRange == null || versionRange.equals("latest")) { range = new VersionRange("0"); } else range = new VersionRange(versionRange); // Iterator over all the versions for this BSN. // Create a sorted map over the version as key // and the file as URL as value. Only versions // that match the desired range are included in // this list. File instances[] = f.listFiles(); SortedMap<Version,File> versions = new TreeMap<Version,File>(); for (int i = 0; i < instances.length; i++) { Matcher m = REPO_FILE.matcher(instances[i].getName()); if (m.matches() && m.group(1).equals(bsn)) { String versionString = m.group(2); Version version; if (versionString.equals("latest")) version = new Version(Integer.MAX_VALUE); else version = new Version(versionString); if (range.includes(version) || versionString.equals(versionRange)) versions.put(version, instances[i]); } } File[] files = versions.values().toArray(EMPTY_FILES); if ("latest".equals(versionRange) && files.length > 0) { return new File[] { files[files.length - 1] }; } return files; } public boolean canWrite() { return canWrite; } protected PutResult putArtifact(File tmpFile, PutOptions options) throws Exception { assert (tmpFile != null); assert (options != null); Jar jar = null; try { dirty = true; jar = new Jar(tmpFile); Manifest manifest = jar.getManifest(); if (manifest == null) throw new IllegalArgumentException("No manifest in JAR: " + jar); String bsn = manifest.getMainAttributes().getValue(Analyzer.BUNDLE_SYMBOLICNAME); if (bsn == null) throw new IllegalArgumentException("No Bundle SymbolicName set"); Parameters b = Processor.parseHeader(bsn, null); if (b.size() != 1) throw new IllegalArgumentException("Multiple bsn's specified " + b); for (String key : b.keySet()) { bsn = key; if (!Verifier.SYMBOLICNAME.matcher(bsn).matches()) throw new IllegalArgumentException("Bundle SymbolicName has wrong format: " + bsn); } String versionString = manifest.getMainAttributes().getValue(Analyzer.BUNDLE_VERSION); Version version; if (versionString == null) version = new Version(); else version = new Version(versionString); if (reporter != null) reporter.trace("bsn=%s version=%s", bsn, version); File dir = new File(root, bsn); if (!dir.exists() && !dir.mkdirs()) { throw new IOException("Could not create directory " + dir); } String fName = bsn + "-" + version.getWithoutQualifier() + ".jar"; File file = new File(dir, fName); boolean renamed = false; PutResult result = new PutResult(); if (reporter != null) reporter.trace("updating %s ", file.getAbsolutePath()); if (!file.exists() || file.lastModified() < jar.lastModified()) { if (file.exists()) { IO.delete(file); } IO.rename(tmpFile, file); renamed = true; result.artifact = file.toURI(); if (reporter != null) reporter.progress(-1, "updated " + file.getAbsolutePath()); fireBundleAdded(jar, file); } else { if (reporter != null) { reporter.progress(-1, "Did not update " + jar + " because repo has a newer version"); reporter.trace("NOT Updating " + fName + " (repo is newer)"); } } File latest = new File(dir, bsn + "-latest.jar"); boolean latestExists = latest.exists() && latest.isFile(); boolean latestIsOlder = latestExists && (latest.lastModified() < jar.lastModified()); if ((options.createLatest && !latestExists) || latestIsOlder) { if (latestExists) { IO.delete(latest); } if (!renamed) { IO.rename(tmpFile, latest); } else { IO.copy(file, latest); } result.latest = latest.toURI(); } return result; } finally { if (jar != null) { jar.close(); } } } /* a straight copy of this method lives in LocalIndexedRepo */ public PutResult put(InputStream stream, PutOptions options) throws Exception { /* both parameters are required */ if ((stream == null) || (options == null)) { throw new IllegalArgumentException("No stream and/or options specified"); } /* determine if the put is allowed */ if (!canWrite) { throw new IOException("Repository is read-only"); } /* the root directory of the repository has to be a directory */ if (!root.isDirectory()) { throw new IOException("Repository directory " + root + " is not a directory"); } init(); /* determine if the artifact needs to be verified */ boolean verifyFetch = (options.digest != null); boolean verifyPut = !options.allowArtifactChange; /* determine which digests are needed */ boolean needFetchDigest = verifyFetch || verifyPut; boolean needPutDigest = verifyPut || options.generateDigest; /* * setup a new stream that encapsulates the stream and calculates (when * needed) the digest */ DigestInputStream dis = new DigestInputStream(stream, MessageDigest.getInstance("SHA-1")); dis.on(needFetchDigest); exec(before, null); File tmpFile = null; try { /* * copy the artifact from the (new/digest) stream into a temporary * file in the root directory of the repository */ tmpFile = IO.createTempFile(root, "put", ".jar"); IO.copy(dis, tmpFile); /* get the digest if available */ byte[] disDigest = needFetchDigest ? dis.getMessageDigest().digest() : null; /* verify the digest when requested */ if (verifyFetch && !MessageDigest.isEqual(options.digest, disDigest)) { throw new IOException("Retrieved artifact digest doesn't match specified digest"); } /* put the artifact into the repository (from the temporary file) */ PutResult r = putArtifact(tmpFile, options); /* calculate the digest when requested */ if (needPutDigest && (r.artifact != null)) { MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); IO.copy(new File(r.artifact), sha1); r.digest = sha1.digest(); } /* verify the artifact when requested */ if (verifyPut && (r.digest != null) && !MessageDigest.isEqual(disDigest, r.digest)) { File f = new File(r.artifact); if (f.exists()) { IO.delete(f); } throw new IOException("Stored artifact digest doesn't match specified digest"); } exec(after, new File(r.artifact)); return r; } catch (Exception e) { exec(abort, null); throw e; } finally { if (tmpFile != null && tmpFile.exists()) { IO.delete(tmpFile); } } } protected void fireBundleAdded(Jar jar, File file) { if (registry == null) return; List<RepositoryListenerPlugin> listeners = registry.getPlugins(RepositoryListenerPlugin.class); for (RepositoryListenerPlugin listener : listeners) { try { listener.bundleAdded(this, jar, file); } catch (Exception e) { if (reporter != null) reporter.warning("Repository listener threw an unexpected exception: %s", e); } } } public void setLocation(String string) { root = new File(string); if (!root.isDirectory()) throw new IllegalArgumentException("Invalid repository directory"); } public void setReporter(Reporter reporter) { this.reporter = reporter; } public List<String> list(String regex) throws Exception { init(); Instruction pattern = null; if (regex != null) pattern = new Instruction(regex); List<String> result = new ArrayList<String>(); if (root == null) { if (reporter != null) reporter.error("FileRepo root directory is not set."); } else { File[] list = root.listFiles(); if (list != null) { for (File f : list) { if (!f.isDirectory()) continue; // ignore non-directories String fileName = f.getName(); if (fileName.charAt(0) == '.') continue; // ignore hidden files if (pattern == null || pattern.matches(fileName)) result.add(fileName); } } else if (reporter != null) reporter.error("FileRepo root directory (%s) does not exist", root); } return result; } public List<Version> versions(String bsn) throws Exception { init(); File dir = new File(root, bsn); if (dir.isDirectory()) { String versions[] = dir.list(); List<Version> list = new ArrayList<Version>(); for (String v : versions) { Matcher m = REPO_FILE.matcher(v); if (m.matches()) { String version = m.group(2); if (version.equals("latest")) version = Integer.MAX_VALUE + ""; list.add(new Version(version)); } } return list; } return null; } @Override public String toString() { return String.format("%-40s r/w=%s", root.getAbsolutePath(), canWrite()); } public File getRoot() { return root; } public boolean refresh() throws Exception { init(); exec(refresh, null); if (dirty) { dirty = false; return true; } return false; } public String getName() { if (name == null) { return toString(); } return name; } public Jar get(String bsn, Version v) throws Exception { init(); File bsns = new File(root, bsn); File version = new File(bsns, bsn + "-" + v.getMajor() + "." + v.getMinor() + "." + v.getMicro() + ".jar"); if (version.exists()) return new Jar(version); return null; } public File get(String bsn, String version, Strategy strategy, Map<String,String> properties) throws Exception { if (version == null) version = "0.0.0"; if (strategy == Strategy.EXACT) { VersionRange vr = new VersionRange(version); if (vr.isRange()) return null; if (vr.getHigh().getMajor() == Integer.MAX_VALUE) version = "latest"; File file = IO.getFile(root, bsn + "/" + bsn + "-" + version + ".jar"); if (file.isFile()) return file; file = IO.getFile(root, bsn + "/" + bsn + "-" + version + ".lib"); if (file.isFile()) return file; return null; } File[] files = get(bsn, version); if (files == null || files.length == 0) return null; if (files.length >= 0) { switch (strategy) { case LOWEST : return files[0]; case HIGHEST : return files[files.length - 1]; case EXACT : // TODO break; } } return null; } public File get(String bsn, Version version, Map<String,String> properties) { File file = IO.getFile(root, bsn + "/" + bsn + "-" + version.getWithoutQualifier() + ".jar"); if (file.isFile()) return file; file = IO.getFile(root, bsn + "/" + bsn + "-" + version.getWithoutQualifier() + ".lib"); if (file.isFile()) return file; return null; } public void setRegistry(Registry registry) { this.registry = registry; } public String getLocation() { return root.toString(); } void exec(String line, File target) { if (line == null) return; try { if (target != null) line = line.replaceAll("\\$\\{@\\}", target.getAbsolutePath()); System.out.println("Cmd: " + line); Command cmd = new Command("sh"); cmd.inherit(); String oldpath = cmd.var("PATH"); if (path != null) { path = path.replaceAll("\\s*,\\s*", File.pathSeparator); path = path.replaceAll("\\$\\{@\\}", oldpath); cmd.var("PATH", path); } cmd.setCwd(getRoot()); StringBuilder stdout = new StringBuilder(); StringBuilder stderr = new StringBuilder(); int result = cmd.execute(line, stdout, stderr); if (result != 0) { if (reporter != null) reporter.error("Command %s failed with %s %s %s", line, result, stdout, stderr); else throw new Exception("Command " + line + " failed " + result + " " + stdout + " " + stderr); } } catch (Exception e) { if (reporter != null) reporter.exception(e, e.getMessage()); else throw new RuntimeException(e); } } }
package edu.duke.cabig.catrip.test.system.steps; import gov.nci.nih.cagrid.tests.core.compare.BeanComparator; import gov.nih.nci.cagrid.common.Utils; import gov.nih.nci.cagrid.cqlresultset.CQLQueryResults; import gov.nih.nci.catrip.dcql.DCQLQueryDocument; import gov.nih.nci.catrip.fqe.engine.FederatedQueryEngineImpl; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import javax.xml.namespace.QName; import com.atomicobject.haste.framework.Step; public class DQEInvokeStep extends Step { private File queryDir; public DQEInvokeStep(File queryDir) { super(); this.queryDir = queryDir; } public void runStep() throws Exception { // parse dcql File dcqlFile = new File(queryDir, "0_dcqlQuery.xml"); DCQLQueryDocument query = DCQLQueryDocument.Factory.parse(dcqlFile); // run query FederatedQueryEngineImpl dqe = new FederatedQueryEngineImpl(); CQLQueryResults results = dqe.execute(query); // write the results BufferedWriter out = new BufferedWriter(new FileWriter(new File(queryDir, "out_dynamic.xml"))); try { Utils.serializeObject(results, new QName("queryResults"), out); } finally { out.flush(); out.close(); } // check results File resultsFile = new File(queryDir, "out.xml"); if (resultsFile.exists()) { BeanComparator bc = new BeanComparator(this); bc.assertEquals( Utils.deserializeDocument(resultsFile.toString(), CQLQueryResults.class), results ); } } }
package java.awt; import java.util.Arrays; import java.util.Timer; import java.util.TimerTask; import org.videolan.Logger; import org.videolan.Libbluray; public class BDRootWindow extends Frame { public BDRootWindow () { super(); setUndecorated(true); setBackground(new Color(0, 0, 0, 0)); BDToolkit.setFocusedWindow(this); } public Area getDirtyArea() { return dirty; } public Font getDefaultFont() { return defaultFont; } public void setDefaultFont(String fontId) { if (fontId == null || fontId.equals("*****")) { defaultFont = null; } else { try { defaultFont = (new org.dvb.ui.FontFactory()).createFont(fontId); } catch (Exception ex) { logger.error("Failed setting default font " + fontId + ".otf: " + ex); } } logger.info("setting default font to " + fontId + ".otf (" + defaultFont + ")"); setFont(defaultFont); } public void setBounds(int x, int y, int width, int height) { if (!isVisible()) { if ((width > 0) && (height > 0)) { if ((backBuffer == null) || (getWidth() * getHeight() < width * height)) { backBuffer = new int[width * height]; Arrays.fill(backBuffer, 0); } } super.setBounds(x, y, width, height); } else if (width != getWidth() || height != getHeight()){ logger.error("setBounds(" + x + "," + y + "," + width + "," + height + ") FAILED: already visible"); } } public int[] getBdBackBuffer() { return backBuffer; } public Image getBackBuffer() { /* exists only in J2SE */ logger.unimplemented("getBackBuffer"); return null; } private boolean isBackBufferClear() { int v = 0; for (int i = 0; i < height * width; i++) v |= backBuffer[i]; return v == 0; } public void notifyChanged() { if (!isVisible()) { logger.error("sync(): not visible"); return; } synchronized (this) { if (timer == null) { logger.error("notifyChanged(): window already disposed"); return; } changeCount++; if (timerTask == null) { timerTask = new RefreshTimerTask(this); timer.schedule(timerTask, 40, 40); } } } public void sync() { synchronized (this) { if (timerTask != null) { timerTask.cancel(); timerTask = null; } changeCount = 0; Area a = dirty.getBounds(); dirty.clear(); if (!a.isEmpty()) { if (!overlay_open) { /* delay opening overlay until something has been drawn */ if (isBackBufferClear()) { logger.info("sync() ignored (overlay not open, empty overlay)"); return; } Libbluray.updateGraphic(getWidth(), getHeight(), null); overlay_open = true; a = new Area(getWidth(), getHeight()); /* force full plane update */ } Libbluray.updateGraphic(getWidth(), getHeight(), backBuffer, a.x0, a.y0, a.x1, a.y1); } } } private class RefreshTimerTask extends TimerTask { public RefreshTimerTask(BDRootWindow window) { this.window = window; this.changeCount = window.changeCount; } public void run() { synchronized (window) { if (this.changeCount == window.changeCount) window.sync(); else this.changeCount = window.changeCount; } } private BDRootWindow window; private int changeCount; } private void close() { synchronized (this) { if (overlay_open) { Libbluray.updateGraphic(0, 0, null); overlay_open = false; } } } public void setVisible(boolean visible) { super.setVisible(visible); if (!visible) { close(); } } /* called when new title starts (window is "created" again) */ public void clearOverlay() { synchronized (this) { if (overlay_open) { logger.error("clearOverlay() ignored (overlay is visible)"); } else { Arrays.fill(backBuffer, 0); dirty.clear(); } } } public void dispose() { synchronized (this) { if (timerTask != null) { timerTask.cancel(); timerTask = null; } if (timer != null) { timer.cancel(); timer = null; } } if (isVisible()) { hide(); } BDToolkit.setFocusedWindow(null); super.dispose(); backBuffer = null; } private int[] backBuffer = null; private Area dirty = new Area(); private int changeCount = 0; private Timer timer = new Timer(); private TimerTask timerTask = null; private boolean overlay_open = false; private Font defaultFont = null; private static final Logger logger = Logger.getLogger(BDRootWindow.class.getName()); private static final long serialVersionUID = -8325961861529007953L; }
package seedu.address.model.task; import java.util.Iterator; import java.util.List; import java.util.Optional; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import seedu.address.commons.core.UnmodifiableObservableList; /** * A list of tasks. * * Supports a minimal set of list operations. */ public class TaskList implements Iterable<Task> { private final ObservableList<Task> internalList = FXCollections.observableArrayList(); /** Get the task with given ID */ public Optional<Task> getTaskByID(IdentificationNumber ID) { for (Task task : internalList) { if (task.getID().equals(ID)) { return Optional.of(task); } } return null; } /** Adds a task to the list. */ public void add(Task toAdd) { assert toAdd != null; internalList.add(toAdd); } /** * Updates the task in the list at position {@code index} with {@code editedTask}. * * @throws IndexOutOfBoundsException if {@code index} < 0 or >= the size of the list. */ public void updateTask(int index, ReadOnlyTask editedTask) { assert editedTask != null; Task taskToUpdate = internalList.get(index); taskToUpdate.resetData(editedTask); // TODO: The code below is just a workaround to notify observers of the updated person. // The right way is to implement observable properties in the Person class. // Then, PersonCard should then bind its text labels to those observable properties. internalList.set(index, taskToUpdate); } /** * Removes the equivalent task from the list. * * @throws PersonNotFoundException if no such person could be found in the list. */ public boolean removeTask(ReadOnlyTask toRemove) throws TaskNotFoundException { assert toRemove != null; final boolean taskFoundAndDeleted = internalList.remove(toRemove); if (!taskFoundAndDeleted) { throw new TaskNotFoundException(); } return taskFoundAndDeleted; } /** * Remove task with given ID. * * @throws TaskNotFoundException if no such task could be found in the list. */ public boolean removeById(IdentificationNumber ID) throws TaskNotFoundException { assert ID != null; final Optional<Task> toRemove = getTaskByID(ID); if (!toRemove.isPresent()) { throw new TaskNotFoundException(); } return internalList.remove(toRemove); } public void setTasks(TaskList replacement) { this.internalList.setAll(replacement.internalList); } public void setTasks(List<? extends ReadOnlyTask> tasks) { final TaskList replacement = new TaskList(); for (final ReadOnlyTask task : tasks) { replacement.add(new Task(task)); } setTasks(replacement); } public UnmodifiableObservableList<Task> asObservableList() { return new UnmodifiableObservableList<>(internalList); } @Override public Iterator<Task> iterator() { return internalList.iterator(); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof TaskList // instanceof handles nulls && this.internalList.equals( ((TaskList) other).internalList)); } @Override public int hashCode() { return internalList.hashCode(); } /** * Signals that an operation targeting a specified task in the list would fail because * there is no such matching task in the list. */ public static class TaskNotFoundException extends Exception {} }
package org.eclipse.birt.chart.internal.factory; import java.text.FieldPosition; import java.util.Date; import com.ibm.icu.text.DateFormat; import com.ibm.icu.text.SimpleDateFormat; import com.ibm.icu.util.Calendar; import com.ibm.icu.util.ULocale; /** * An internal factory help to generate IDateFormatWrapper. */ public class DateFormatWrapperFactory { /** * Prevent from instanciation */ private DateFormatWrapperFactory( ) { } /** * Returns a preferred format specifier for tick labels that represent axis * values that will be computed based on the difference between cdt1 and * cdt2 * * @param iUnit * The unit for which a preferred pattern is being requested * * @return A preferred datetime format for the given unit */ public static final IDateFormatWrapper getPreferredDateFormat( int iUnit ) { return getPreferredDateFormat( iUnit, ULocale.getDefault( ) ); } /** * Returns a preferred format specifier for tick labels that represent axis * values that will be computed based on the difference between cdt1 and * cdt2 * * @param iUnit * The unit for which a preferred pattern is being requested * @param locale * The locale for format style * * @return A preferred datetime format for the given unit */ public static final IDateFormatWrapper getPreferredDateFormat( int iUnit, ULocale locale ) { IDateFormatWrapper df = null; switch ( iUnit ) { case Calendar.YEAR : df = new CommonDateFormatWrapper( new SimpleDateFormat( "yyyy", //$NON-NLS-1$ locale ) ); break; case Calendar.MONTH : df = new MonthDateFormat( locale ); break; case Calendar.DATE : df = new CommonDateFormatWrapper( DateFormat.getDateInstance( DateFormat.LONG, locale ) ); break; case Calendar.HOUR_OF_DAY : df = new HourDateFormat( locale ); break; case Calendar.MINUTE : case Calendar.SECOND : df = new CommonDateFormatWrapper( new SimpleDateFormat( "HH:mm:ss", //$NON-NLS-1$ locale ) ); break; } return df; } static class CommonDateFormatWrapper implements IDateFormatWrapper { private DateFormat formater; public CommonDateFormatWrapper( DateFormat formater ) { this.formater = formater; } public String format( Date date ) { return formater.format( date ); } } static class HourDateFormat implements IDateFormatWrapper { private ULocale locale; public HourDateFormat( ULocale locale ) { super( ); this.locale = locale; } public String format( Date date ) { return DateFormat.getDateInstance( DateFormat.LONG, locale ) .format( date ) + "\n" //$NON-NLS-1$ + new SimpleDateFormat( "HH:mm", locale ).format( date ); //$NON-NLS-1$ } } static class MonthDateFormat implements IDateFormatWrapper { private ULocale locale; public MonthDateFormat( ULocale locale ) { super( ); this.locale = locale; } public String format( Date date ) { StringBuffer str = new StringBuffer( ); FieldPosition pos = new FieldPosition( DateFormat.DATE_FIELD ); DateFormat df = DateFormat.getDateInstance( DateFormat.LONG, locale ); df.format( date, str, pos ); int endIndex; if ( pos.getEndIndex( ) >= str.length( ) ) { endIndex = pos.getEndIndex( ); } else { endIndex = pos.getEndIndex( ) + ( str.charAt( pos.getEndIndex( ) ) == ',' ? 2 : 1 ); } if ( endIndex >= str.length( ) ) { return str.substring( 0, pos.getBeginIndex( ) ).trim( ); } return str.substring( 0, pos.getBeginIndex( ) ) + str.substring( endIndex ); } } }
package tigase.server; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Map; import java.util.logging.Logger; import tigase.util.DNSResolver; import static tigase.conf.Configurable.*; /** * Describe class MessageRouterConfig here. * * * Created: Fri Jan 6 14:54:21 2006 * * @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a> * @version $Rev$ */ public class MessageRouterConfig { private static final Logger log = Logger.getLogger("tigase.server.MessageRouterConfig"); public static final String LOCAL_ADDRESSES_PROP_KEY = "hostnames"; private static String[] LOCAL_ADDRESSES_PROP_VALUE = {"localhost", "hostname"}; public static final String MSG_RECEIVERS_PROP_KEY = "components/msg-receivers/"; public static final String MSG_RECEIVERS_NAMES_PROP_KEY = MSG_RECEIVERS_PROP_KEY + "id-names"; public static final String DEF_SM_NAME = "sess-man"; public static final String DEF_C2S_NAME = "c2s"; public static final String DEF_S2S_NAME = "s2s"; public static final String DEF_EXT_COMP_NAME = "ext-comp"; public static final String DEF_SSEND_NAME = "ssend"; public static final String DEF_SRECV_NAME = "srecv"; public static final String DEF_BOSH_NAME = "bosh"; private static final String[] ALL_MSG_RECEIVERS_NAMES_PROP_VAL = { DEF_C2S_NAME, DEF_S2S_NAME, DEF_SM_NAME, DEF_SSEND_NAME, DEF_SRECV_NAME, DEF_BOSH_NAME}; private static final String[] DEF_MSG_RECEIVERS_NAMES_PROP_VAL = { DEF_C2S_NAME, DEF_S2S_NAME, DEF_SM_NAME, DEF_BOSH_NAME }; private static final String[] SM_MSG_RECEIVERS_NAMES_PROP_VAL = { DEF_EXT_COMP_NAME, DEF_SM_NAME }; private static final String[] CS_MSG_RECEIVERS_NAMES_PROP_VAL = { DEF_C2S_NAME, DEF_S2S_NAME, DEF_EXT_COMP_NAME, DEF_BOSH_NAME }; private static final Map<String, String> MSG_RCV_CLASSES = new LinkedHashMap<String, String>(); static { MSG_RCV_CLASSES.put(DEF_C2S_NAME, C2S_COMP_CLASS_NAME); MSG_RCV_CLASSES.put(DEF_S2S_NAME, S2S_COMP_CLASS_NAME); MSG_RCV_CLASSES.put(DEF_EXT_COMP_NAME, EXT_COMP_CLASS_NAME); MSG_RCV_CLASSES.put(DEF_SM_NAME, SM_COMP_CLASS_NAME); MSG_RCV_CLASSES.put(DEF_SSEND_NAME, SSEND_COMP_CLASS_NAME); MSG_RCV_CLASSES.put(DEF_SRECV_NAME, SRECV_COMP_CLASS_NAME); MSG_RCV_CLASSES.put(DEF_BOSH_NAME, BOSH_COMP_CLASS_NAME); } public static final String REGISTRATOR_PROP_KEY = "components/registrators/"; public static final String REGISTRATOR_NAMES_PROP_KEY = REGISTRATOR_PROP_KEY + "id-names"; private static final String[] REGISTRATOR_NAMES_PROP_VAL = { "stat-1" }; public static final String STAT_1_CLASS_PROP_KEY = REGISTRATOR_PROP_KEY + "stat-1.class"; public static final String STAT_1_CLASS_PROP_VAL = "tigase.stats.StatisticsCollector"; public static final String STAT_1_ACTIVE_PROP_KEY = REGISTRATOR_PROP_KEY + "stat-1.active"; public static final boolean STAT_1_ACTIVE_PROP_VAL = true; public static void getDefaults(Map<String, Object> defs, Map<String, Object> params, String comp_name) { String config_type = (String)params.get("config-type"); String[] rcv_names = DEF_MSG_RECEIVERS_NAMES_PROP_VAL; Object par_names = params.get(comp_name + "/" + MSG_RECEIVERS_NAMES_PROP_KEY); if (par_names != null) { rcv_names = (String[])par_names; } else { if (config_type.equals(GEN_CONFIG_ALL)) { rcv_names = ALL_MSG_RECEIVERS_NAMES_PROP_VAL; } if (config_type.equals(GEN_CONFIG_SM)) { rcv_names = SM_MSG_RECEIVERS_NAMES_PROP_VAL; } if (config_type.equals(GEN_CONFIG_CS)) { rcv_names = CS_MSG_RECEIVERS_NAMES_PROP_VAL; } // You can now add a component for any server instance type // and you can also add many different components this way... // if (config_type.equals(GEN_CONFIG_COMP)) { // String c_name = (String)params.get(GEN_COMP_NAME); // String c_class = (String)params.get(GEN_COMP_CLASS); // rcv_names = new String[] {c_name}; // defs.put(MSG_RECEIVERS_PROP_KEY + c_name + ".class", c_class); // defs.put(MSG_RECEIVERS_PROP_KEY + c_name + ".active", true); } Arrays.sort(rcv_names); // Now init defaults for all external components: for (String key: params.keySet()) { if (key.startsWith(GEN_EXT_COMP)) { String new_comp_name = DEF_EXT_COMP_NAME + key.substring(GEN_EXT_COMP.length()); if (Arrays.binarySearch(rcv_names, new_comp_name) < 0) { rcv_names = Arrays.copyOf(rcv_names, rcv_names.length+1); rcv_names[rcv_names.length-1] = new_comp_name; Arrays.sort(rcv_names); } } // end of if (key.startsWith(GEN_EXT_COMP)) if (key.startsWith(GEN_COMP_NAME)) { String comp_name_suffix = key.substring(GEN_COMP_NAME.length()); String c_name = (String)params.get(GEN_COMP_NAME + comp_name_suffix); String c_class = (String)params.get(GEN_COMP_CLASS + comp_name_suffix); if (Arrays.binarySearch(rcv_names, c_name) < 0) { defs.put(MSG_RECEIVERS_PROP_KEY + c_name + ".class", c_class); defs.put(MSG_RECEIVERS_PROP_KEY + c_name + ".active", true); rcv_names = Arrays.copyOf(rcv_names, rcv_names.length+1); rcv_names[rcv_names.length-1] = c_name; Arrays.sort(rcv_names); //System.out.println(Arrays.toString(rcv_names)); } } } // end of for () defs.put(MSG_RECEIVERS_NAMES_PROP_KEY, rcv_names); for (String name: rcv_names) { if (defs.get(MSG_RECEIVERS_PROP_KEY + name + ".class") == null) { String def_class = MSG_RCV_CLASSES.get(name); if (def_class == null) { def_class = EXT_COMP_CLASS_NAME; } defs.put(MSG_RECEIVERS_PROP_KEY + name + ".class", def_class); defs.put(MSG_RECEIVERS_PROP_KEY + name + ".active", true); } } defs.put(REGISTRATOR_NAMES_PROP_KEY, REGISTRATOR_NAMES_PROP_VAL); defs.put(STAT_1_CLASS_PROP_KEY, STAT_1_CLASS_PROP_VAL); defs.put(STAT_1_ACTIVE_PROP_KEY, STAT_1_ACTIVE_PROP_VAL); if (params.get(GEN_VIRT_HOSTS) != null) { LOCAL_ADDRESSES_PROP_VALUE = ((String)params.get(GEN_VIRT_HOSTS)).split(","); } else { LOCAL_ADDRESSES_PROP_VALUE = DNSResolver.getDefHostNames(); } defs.put(LOCAL_ADDRESSES_PROP_KEY, LOCAL_ADDRESSES_PROP_VALUE); } private Map<String, Object> props = null; public MessageRouterConfig(Map<String, Object> props) { this.props = props; } public String[] getRegistrNames() { String[] names = (String[])props.get(REGISTRATOR_NAMES_PROP_KEY); log.config(Arrays.toString(names)); ArrayList<String> al = new ArrayList<String>(); for (String name: names) { if ((Boolean)props.get(REGISTRATOR_PROP_KEY + name + ".active")) { al.add(name); } // end of if ((Boolean)props.get()) } // end of for (String name: names) return al.toArray(new String[al.size()]); } public String[] getMsgRcvNames() { String[] names = (String[])props.get(MSG_RECEIVERS_NAMES_PROP_KEY); log.config(Arrays.toString(names)); ArrayList<String> al = new ArrayList<String>(); for (String name: names) { if (props.get(MSG_RECEIVERS_PROP_KEY + name + ".active") != null && (Boolean)props.get(MSG_RECEIVERS_PROP_KEY + name + ".active")) { al.add(name); } } // end of for (String name: names) return al.toArray(new String[al.size()]); } public ComponentRegistrator getRegistrInstance(String name) throws ClassNotFoundException, InstantiationException, IllegalAccessException { String cls_name = (String)props.get(REGISTRATOR_PROP_KEY + name + ".class"); // I changed location for the XMPPServiceCollector class // to avoid problems with old configuration files let's detect it here // and silently convert it to new package name: if (cls_name.equals("tigase.server.XMPPServiceCollector") || cls_name.equals("tigase.disco.XMPPServiceCollector")) { log.warning("This class is not used anymore. Correct your configuration please. Remove all references to class: XMPPServiceCollector."); return null; } return (ComponentRegistrator)Class.forName(cls_name).newInstance(); } public MessageReceiver getMsgRcvInstance(String name) throws ClassNotFoundException, InstantiationException, IllegalAccessException { String cls_name = (String)props.get(MSG_RECEIVERS_PROP_KEY + name + ".class"); return (MessageReceiver)Class.forName(cls_name).newInstance(); } } // MessageRouterConfig
package me.lucko.luckperms.common.storage.dao.sql.connection.hikari; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import me.lucko.luckperms.common.storage.StorageCredentials; import me.lucko.luckperms.common.storage.dao.sql.connection.AbstractConnectionFactory; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.LinkedHashMap; import java.util.Map; public abstract class HikariConnectionFactory extends AbstractConnectionFactory { protected final StorageCredentials configuration; private HikariDataSource hikari; public HikariConnectionFactory(String name, StorageCredentials configuration) { super(name); this.configuration = configuration; } protected String getDriverClass() { return null; } protected void appendProperties(HikariConfig config, StorageCredentials credentials) { for (Map.Entry<String, String> property : credentials.getProperties().entrySet()) { config.addDataSourceProperty(property.getKey(), property.getValue()); } } protected void appendConfigurationInfo(HikariConfig config) { String address = this.configuration.getAddress(); String[] addressSplit = address.split(":"); address = addressSplit[0]; String port = addressSplit.length > 1 ? addressSplit[1] : "3306"; config.setDataSourceClassName(getDriverClass()); config.addDataSourceProperty("serverName", address); config.addDataSourceProperty("port", port); config.addDataSourceProperty("databaseName", this.configuration.getDatabase()); config.setUsername(this.configuration.getUsername()); config.setPassword(this.configuration.getPassword()); } @Override public void init() { HikariConfig config = new HikariConfig(); config.setPoolName("luckperms-hikari"); appendConfigurationInfo(config); appendProperties(config, this.configuration); config.setMaximumPoolSize(this.configuration.getMaxPoolSize()); config.setMinimumIdle(this.configuration.getMinIdleConnections()); config.setMaxLifetime(this.configuration.getMaxLifetime()); config.setConnectionTimeout(this.configuration.getConnectionTimeout()); // don't perform any initial connection validation - we subsequently call #getConnection // to setup the schema anyways config.setInitializationFailTimeout(-1); this.hikari = new HikariDataSource(config); } @Override public void shutdown() { if (this.hikari != null) { this.hikari.close(); } } @Override public Map<String, String> getMeta() { Map<String, String> ret = new LinkedHashMap<>(); boolean success = true; long start = System.currentTimeMillis(); try (Connection c = this.hikari.getConnection()) { try (Statement s = c.createStatement()) { s.execute("/* ping */ SELECT 1"); } } catch (SQLException e) { success = false; } long duration = System.currentTimeMillis() - start; if (success) { ret.put("Ping", "&a" + duration + "ms"); ret.put("Connected", "true"); } else { ret.put("Connected", "false"); } return ret; } @Override public Connection getConnection() throws SQLException { Connection connection = this.hikari.getConnection(); if (connection == null) { throw new SQLException("Unable to get a connection from the pool."); } return connection; } }
package scala.runtime; import java.lang.invoke.*; import java.lang.ref.SoftReference; import java.lang.reflect.Method; public final class StructuralCallSite { private Class<?>[] _parameterTypes; private SoftReference<MethodCache> cache = new SoftReference<>(new EmptyMethodCache()); private StructuralCallSite(MethodType callType) { _parameterTypes = callType.parameterArray(); } public MethodCache get() { MethodCache cache = this.cache.get(); if (cache == null) { cache = new EmptyMethodCache(); this.cache = new SoftReference<>(cache); } return cache; } public Method find(Class<?> receiver) { return get().find(receiver); } public Method add(Class<?> receiver, Method m) { cache = new SoftReference<MethodCache>(get().add(receiver, m)); return m; } public Class<?>[] parameterTypes() { return _parameterTypes; } public static CallSite bootstrap(MethodHandles.Lookup lookup, String invokedName, MethodType invokedType, MethodType reflectiveCallType) throws Throwable { StructuralCallSite structuralCallSite = new StructuralCallSite(reflectiveCallType); return new ConstantCallSite(MethodHandles.constant(StructuralCallSite.class, structuralCallSite)); } }
package xdean.jex.util.lang; import static xdean.jex.util.function.FunctionAdapter.supplierToRunnable; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Optional; import java.util.function.Function; import lombok.extern.slf4j.Slf4j; import xdean.jex.extra.Either; import xdean.jex.extra.Wrapper; import xdean.jex.extra.function.RunnableThrow; import xdean.jex.extra.function.SupplierThrow; @Slf4j public class ExceptionUtil { public static <T extends Throwable, R> R throwIt(T t) throws T { throw t; } @SuppressWarnings("unchecked") public static <T extends Throwable, R> R throwAsUncheck(Throwable t) throws T { throw (T) t; } public static void uncheck(RunnableThrow<?> task) { try { task.run(); } catch (Exception t) { throwAsUncheck(t); } } public static <T> T uncheck(SupplierThrow<T, ?> task) { return supplierToRunnable(task, r -> uncheck(r)); } public static boolean uncatch(RunnableThrow<?> task) { try { task.run(); return true; } catch (Exception t) { log.trace("Dont catch", t); return false; } } /** * @param task * @return can be null */ public static <T> T uncatch(SupplierThrow<T, ?> task) { return supplierToRunnable(task, r -> uncatch(r)); } @SuppressWarnings("unchecked") public static <E extends Exception> Optional<E> throwToReturn(RunnableThrow<E> task) { try { task.run(); } catch (Exception t) { try { return Optional.of((E) t); } catch (ClassCastException cce) { throw new RuntimeException("An unexcepted exception thrown.", t); } } return Optional.empty(); } public static <T, E extends Exception> Either<T, E> throwToReturn(SupplierThrow<T, E> task) { Wrapper<T> w = new Wrapper<>(null); return Either.rightOrDefault(throwToReturn(() -> w.set(task.get())), w.get()); } public static String getStackTraceString(Throwable tr) { if (tr == null) { return ""; } Throwable t = tr; while (t.getCause() != null) { t = t.getCause(); } StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.flush(); return sw.toString(); } public static <E extends Exception> void wrapException(Function<Exception, E> wrapper, RunnableThrow<?> task) throws E { try { task.run(); } catch (Exception e) { throw wrapper.apply(e); } } }
package focusedCrawler.target; import focusedCrawler.util.vsm.VSMElement; import focusedCrawler.util.vsm.VSMVector; import focusedCrawler.util.vsm.VSMElementComparator; import focusedCrawler.util.parser.PaginaURL; import focusedCrawler.util.string.StopList; import focusedCrawler.util.FileComparator; import java.io.File; import org.xml.sax.SAXException; import java.net.MalformedURLException; import java.net.URL; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.StringTokenizer; import java.util.Vector; import java.util.Collections; import java.util.Random; public class CreateWekaInput { protected VSMVector[][] trainingExamples = null; // protected VSMVector[] negativeExamples = null; protected VSMVector[][] testExamples = null; // protected VSMVector[] negativeTestExamples = null; protected int numOfFeatures = Integer.MAX_VALUE; protected int minDF = 5; protected HashMap df = new HashMap(); protected boolean isForm = false; protected StopList stoplist; public CreateWekaInput(File dir, File dirTest, StopList stoplist) throws SAXException, IOException { this(dir,dirTest,stoplist,Integer.MAX_VALUE); } public CreateWekaInput(File input, File inputTest, StopList stoplist, int numOfElems) throws SAXException, IOException { trainingExamples = new VSMVector[2][]; this.stoplist = stoplist; if((new File (input + File.separator + "positive")).isDirectory()){ File[] positiveFiles = new File (input + File.separator + "positive").listFiles(); System.out.println("POSITIVE:" + positiveFiles.length); File[] negativeFiles = new File (input + File.separator + "negative").listFiles(); System.out.println("NEGATIVE:" + negativeFiles.length); int[] negIndexes = selectRandomNum(1,negativeFiles.length, numOfElems); trainingExamples[1] = createVSM(negativeFiles, stoplist,negIndexes,true); int[] posIndexes = selectRandomNum(1,positiveFiles.length, numOfElems); trainingExamples[0] = createVSM(positiveFiles, stoplist,posIndexes,true); }else{ trainingExamples[0] = createVSM(new File (input + File.separator + "positive"), stoplist); trainingExamples[1] = createVSM(new File (input + File.separator + "negative"), stoplist); } if(inputTest != null){ testExamples = new VSMVector[2][]; if((new File (inputTest + File.separator + "positive")).isDirectory()){ File temp = new File (inputTest + File.separator + "positive"); System.out.println(temp.toString()); File[] positiveTestFiles = temp.listFiles(); trainingExamples[0] = createVSM(positiveTestFiles, stoplist,false); File[] negativeTestFiles = new File (inputTest + File.separator + "negative").listFiles(); trainingExamples[1] = createVSM(negativeTestFiles, stoplist,false); }else{ trainingExamples[0] = createVSM(new File (inputTest + File.separator + "positive"), stoplist); trainingExamples[1] = createVSM(new File (inputTest + File.separator + "negative"), stoplist); } } } public CreateWekaInput(String[][] pages, StopList stoplist, int size) throws SAXException, IOException { trainingExamples = new VSMVector[size][]; for (int i = 0; i < size; i++) { String[] levelPages = pages[i]; trainingExamples[i] = createVSM(levelPages,stoplist); } } private int[] selectRandomNum(long seed, int range, int elems){ if(elems > range){ elems = range; } int count = 0; Random random = new Random(seed); int next = random.nextInt(range); HashSet nums = new HashSet(); int[] result = new int[elems]; while(count < elems){ Integer num = new Integer(next); if(!nums.contains(num)){ result[count] = next; nums.add(num); count++; } next = random.nextInt(range); } return result; } protected VSMVector[] createVSM(String[] pages, StopList stoplist) throws SAXException{ Vector<VSMVector> tempVSM = new Vector<VSMVector>(); for (int i = 0; i < pages.length; i++) { try{ if(pages[i] == null){ continue; } VSMVector vsm = new VSMVector(pages[i],stoplist); tempVSM.add(vsm); Iterator iterator1 = vsm.getElements(); while (iterator1.hasNext()) { VSMElement elem = (VSMElement)iterator1.next(); VSMElement value = (VSMElement)df.get(elem.getWord()); if(value == null){ df.put(elem.getWord(), new VSMElement(elem.getWord(),1)); }else{ df.put(elem.getWord(), new VSMElement(elem.getWord(),value.getWeight() +1)); } } }catch(IOException ex){ ex.printStackTrace(); } } VSMVector[] examples = new VSMVector[tempVSM.size()]; tempVSM.toArray(examples); return examples; } protected VSMVector[] createVSM(File file, StopList stoplist) throws SAXException{ Vector<VSMVector> tempVSM = new Vector<VSMVector>(); try{ BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); for(String line = reader.readLine(); line != null; line = reader.readLine()){ VSMVector vsm = new VSMVector(line,stoplist); tempVSM.add(vsm); Iterator iterator1 = vsm.getElements(); while (iterator1.hasNext()) { VSMElement elem = (VSMElement)iterator1.next(); VSMElement value = (VSMElement)df.get(elem.getWord()); if(value == null){ df.put(elem.getWord(), new VSMElement(elem.getWord(),1)); }else{ df.put(elem.getWord(), new VSMElement(elem.getWord(),value.getWeight() +1)); } } } }catch(IOException ex){ ex.printStackTrace(); } VSMVector[] examples = new VSMVector[tempVSM.size()]; tempVSM.toArray(examples); return examples; } protected VSMVector[] createVSM(File[] files, StopList stoplist, int[] indexes, boolean addToFeatures) throws SAXException{ Vector<VSMVector> tempVSM = new Vector<VSMVector>(); for (int i = 0; i < files.length && i < indexes.length; i++) { try{ VSMVector vsm = new VSMVector(files[indexes[i]].toString(),isForm,stoplist); tempVSM.add(vsm); if(addToFeatures){ Iterator iterator1 = vsm.getElements(); while (iterator1.hasNext()) { VSMElement elem = (VSMElement)iterator1.next(); VSMElement value = (VSMElement)df.get(elem.getWord()); if(value == null){ df.put(elem.getWord(), new VSMElement(elem.getWord(),1)); }else{ df.put(elem.getWord(), new VSMElement(elem.getWord(),value.getWeight() +1)); } } } }catch(IOException ex){ ex.printStackTrace(); } } VSMVector[] examples = new VSMVector[tempVSM.size()]; tempVSM.toArray(examples); return examples; } protected VSMVector[] createVSM(File[] files, StopList stoplist, boolean addToFeatures) throws IOException, SAXException{ int[] indexes = new int[files.length]; for (int i = 0; i < indexes.length; i++) { indexes[i] = i; } return createVSM(files, stoplist, indexes, addToFeatures); } Vector<String> attributes = new Vector<String>(); public String[] centroid2Weka(String output) throws FileNotFoundException,IOException { OutputStream fout= new FileOutputStream(output,false); OutputStream bout= new BufferedOutputStream(fout); OutputStreamWriter outputFile = new OutputStreamWriter(bout); StringBuffer header = new StringBuffer(); header.append("@RELATION TSFC"); header.append("\n"); header.append("\n"); StringBuffer tail = new StringBuffer(); Vector bestWordsForm = new Vector(df.values()); Collections.sort(bestWordsForm, new VSMElementComparator()); for(int i=0; i<=numOfFeatures && i < bestWordsForm.size(); i++){ VSMElement elem = (VSMElement)bestWordsForm.elementAt(i); if(elem.getWeight() > minDF){ header.append("@ATTRIBUTE "); if(elem.getWord().equals("class")){ //This is a hack, weka does not allow attribute with name class. elem.setWord("class-random-string"); } header.append(elem.getWord()); attributes.add(elem.getWord()); header.append(" REAL"); header.append("\n"); } } header.append("@ATTRIBUTE class {"); for (int i = 0; i < trainingExamples.length-1; i++) { header.append("CLASS_"+i+","); } header.append("CLASS_"+ (trainingExamples.length-1) +"}"); tail.append("\n"); tail.append("\n"); tail.append("@DATA"); tail.append("\n"); for (int l = 0; l < trainingExamples.length; l++) { for (int i = 0; i < trainingExamples[l].length; i++) { VSMVector formTemp = trainingExamples[l][i]; tail.append("{"); for (int j = 0; j < attributes.size(); j++) { VSMElement elemForm = formTemp.getElement(attributes.elementAt(j)); if (elemForm != null){ tail.append(j); tail.append(" "); tail.append((int)elemForm.getWeight()); tail.append(","); } } tail.append(attributes.size() + " CLASS_"+l+"}"); tail.append("\n"); } } outputFile.write(header.toString()); outputFile.flush(); outputFile.write(tail.toString()); outputFile.close(); if(testExamples != null){ createTestFile(output, bestWordsForm,header); } String[] atts = new String[attributes.size()]; attributes.toArray(atts); return atts; } private void createTestFile(String output, Vector bestWordsForm, StringBuffer header) throws FileNotFoundException, IOException { OutputStream fout= new FileOutputStream(output+"_test",false); OutputStream bout= new BufferedOutputStream(fout); OutputStreamWriter outputFile = new OutputStreamWriter(bout); StringBuffer tail = new StringBuffer(); tail.append("\n"); tail.append("\n"); tail.append("@DATA"); tail.append("\n"); for (int l = 0; l < testExamples.length; l++) { for (int i = 0; i < testExamples[l].length; i++) { VSMVector examples = testExamples[l][i]; tail.append("{"); for (int j = 0; j < attributes.size(); j++) { VSMElement elemForm = examples.getElement(attributes.elementAt(j)); if (elemForm != null){ tail.append(j); tail.append(" "); tail.append((int)elemForm.getWeight()); tail.append(","); } } tail.append(attributes.size() + " CLASS_"+l+"}"); tail.append("\n"); } } outputFile.write(header.toString()); outputFile.flush(); outputFile.write(tail.toString()); outputFile.close(); } public static void main(String[] args) { StopList st = null; try { st = new focusedCrawler.util.string.StopListArquivo(args[0]); File dir = new File(args[1]); File dirTest = null; CreateWekaInput createwekainput = new CreateWekaInput(dir, dirTest, st); createwekainput.centroid2Weka(args[2]); } catch (MalformedURLException ex1) { ex1.printStackTrace(); } catch (IOException ex1) { ex1.printStackTrace(); } catch (SAXException ex1) { ex1.printStackTrace(); } } }
package org.phenotips.data.internal.controller; import org.phenotips.data.IndexedPatientData; import org.phenotips.data.Patient; import org.phenotips.data.PatientData; import org.phenotips.data.PatientDataController; import org.xwiki.bridge.DocumentAccessBridge; import org.xwiki.component.manager.ComponentLookupException; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.EntityReference; import org.xwiki.test.mockito.MockitoComponentMockingRule; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.BaseStringProperty; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Test for the {@link GeneListController} Component, only the overridden methods from {@link AbstractComplexController} * are tested here */ public class GeneListControllerTest { @Rule public MockitoComponentMockingRule<PatientDataController<Map<String, String>>> mocker = new MockitoComponentMockingRule<PatientDataController<Map<String, String>>>(GeneListController.class); @Mock private DocumentAccessBridge documentAccessBridge; @Mock private Patient patient; @Mock private XWikiDocument doc; private List<BaseObject> geneXWikiObjects; private static final String GENES_STRING = "genes"; private static final String CONTROLLER_NAME = GENES_STRING; private static final String GENES_ENABLING_FIELD_NAME = GENES_STRING; private static final String GENES_COMMENTS_ENABLING_FIELD_NAME = "genes_comments"; private static final String GENE_KEY = "gene"; private static final String COMMENTS_KEY = "comments"; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); this.documentAccessBridge = this.mocker.getInstance(DocumentAccessBridge.class); DocumentReference patientDocument = new DocumentReference("wiki", "patient", "00000001"); doReturn(patientDocument).when(this.patient).getDocument(); doReturn(this.doc).when(this.documentAccessBridge).getDocument(patientDocument); this.geneXWikiObjects = new LinkedList<>(); doReturn(this.geneXWikiObjects).when(this.doc).getXObjects(any(EntityReference.class)); } @Test public void checkGetName() throws ComponentLookupException { Assert.assertEquals(CONTROLLER_NAME, this.mocker.getComponentUnderTest().getName()); } @Test public void checkGetJsonPropertyName() throws ComponentLookupException { Assert.assertEquals(CONTROLLER_NAME, ((AbstractComplexController<Map<String, String>>) this.mocker.getComponentUnderTest()) .getJsonPropertyName()); } @Test public void checkGetProperties() throws ComponentLookupException { List<String> result = ((AbstractComplexController<Map<String, String>>) this.mocker.getComponentUnderTest()).getProperties(); Assert.assertTrue(result.contains(GENE_KEY)); Assert.assertTrue(result.contains(COMMENTS_KEY)); Assert.assertEquals(2, result.size()); } @Test public void checkGetBooleanFields() throws ComponentLookupException { Assert.assertTrue( ((AbstractComplexController<Map<String, String>>) this.mocker.getComponentUnderTest()).getBooleanFields() .isEmpty()); } @Test public void checkGetCodeFields() throws ComponentLookupException { Assert.assertTrue(((AbstractComplexController<Map<String, String>>) this.mocker.getComponentUnderTest()) .getCodeFields().isEmpty()); } @Test public void loadCatchesExceptionFromDocumentAccess() throws Exception { Exception exception = new Exception(); doThrow(exception).when(this.documentAccessBridge).getDocument(any(DocumentReference.class)); PatientData<Map<String, String>> result = this.mocker.getComponentUnderTest().load(this.patient); Assert.assertNull(result); verify(this.mocker.getMockedLogger()).error("Could not find requested document or some unforeseen " + "error has occurred during controller loading ", exception.getMessage()); } @Test public void loadReturnsNullWhenPatientDoesNotHaveGeneClass() throws ComponentLookupException { doReturn(null).when(this.doc).getXObjects(any(EntityReference.class)); PatientData<Map<String, String>> result = this.mocker.getComponentUnderTest().load(this.patient); Assert.assertNull(result); } @Test public void loadReturnsNullWhenGeneIsEmpty() throws ComponentLookupException { doReturn(new LinkedList<BaseObject>()).when(this.doc).getXObjects(any(EntityReference.class)); PatientData<Map<String, String>> result = this.mocker.getComponentUnderTest().load(this.patient); Assert.assertNull(result); } @Test public void loadIgnoresNullFields() throws ComponentLookupException { BaseObject obj = mock(BaseObject.class); doReturn(null).when(obj).getField(anyString()); this.geneXWikiObjects.add(obj); PatientData<Map<String, String>> result = this.mocker.getComponentUnderTest().load(this.patient); Assert.assertNull(result); } @Test public void loadIgnoresNullGenes() throws ComponentLookupException { // Deleted objects appear as nulls in XWikiObjects list this.geneXWikiObjects.add(null); addGeneFields(GENE_KEY, new String[] { "SRCAP" }); PatientData<Map<String, String>> result = this.mocker.getComponentUnderTest().load(this.patient); Assert.assertEquals(1, result.size()); } @Test public void checkLoadParsingOfGeneKey() throws ComponentLookupException { String[] genes = new String[] { "A", "<!'>;", "two words", " ", "" }; addGeneFields(GENE_KEY, genes); PatientData<Map<String, String>> result = this.mocker.getComponentUnderTest().load(this.patient); Assert.assertNotNull(result); for (int i = 0; i < genes.length; i++) { Assert.assertEquals(genes[i], result.get(i).get(GENE_KEY)); } } @Test public void checkLoadParsingOfCommentsKey() throws ComponentLookupException { String[] comments = new String[] { "Hello world!", "<script></script>", "", "{{html}}" }; addGeneFields(COMMENTS_KEY, comments); PatientData<Map<String, String>> result = this.mocker.getComponentUnderTest().load(this.patient); Assert.assertNotNull(result); Assert.assertNotNull(result); for (int i = 0; i < comments.length; i++) { Assert.assertEquals(comments[i], result.get(i).get(COMMENTS_KEY)); } } @Test public void writeJSONReturnsWhenGetDataReturnsNull() throws ComponentLookupException { doReturn(null).when(this.patient).getData(CONTROLLER_NAME); JSONObject json = new JSONObject(); Collection<String> selectedFields = new LinkedList<>(); selectedFields.add(GENES_ENABLING_FIELD_NAME); this.mocker.getComponentUnderTest().writeJSON(this.patient, json, selectedFields); Assert.assertNull(json.get(CONTROLLER_NAME)); verify(this.patient).getData(CONTROLLER_NAME); } @Test public void writeJSONReturnsWhenDataIsEmpty() throws ComponentLookupException { List<Map<String, String>> internalList = new LinkedList<>(); PatientData<Map<String, String>> patientData = new IndexedPatientData<>(CONTROLLER_NAME, internalList); doReturn(patientData).when(this.patient).getData(CONTROLLER_NAME); JSONObject json = new JSONObject(); Collection<String> selectedFields = new LinkedList<>(); selectedFields.add(GENES_ENABLING_FIELD_NAME); this.mocker.getComponentUnderTest().writeJSON(this.patient, json, selectedFields); Assert.assertNull(json.get(CONTROLLER_NAME)); verify(this.patient).getData(CONTROLLER_NAME); } @Test public void writeJSONReturnsWhenSelectedFieldsDoesNotContainGeneEnabler() throws ComponentLookupException { List<Map<String, String>> internalList = new LinkedList<>(); PatientData<Map<String, String>> patientData = new IndexedPatientData<>(CONTROLLER_NAME, internalList); doReturn(patientData).when(this.patient).getData(CONTROLLER_NAME); JSONObject json = new JSONObject(); Collection<String> selectedFields = new LinkedList<>(); selectedFields.add("some_string"); this.mocker.getComponentUnderTest().writeJSON(this.patient, json, selectedFields); Assert.assertNull(json.get(CONTROLLER_NAME)); } @Test public void writeJSONIgnoresItemsWhenGeneIsBlank() throws ComponentLookupException { List<Map<String, String>> internalList = new LinkedList<>(); Map<String, String> item = new LinkedHashMap<>(); item.put(GENE_KEY, ""); internalList.add(item); item = new LinkedHashMap<>(); item.put(GENE_KEY, null); internalList.add(item); PatientData<Map<String, String>> patientData = new IndexedPatientData<>(CONTROLLER_NAME, internalList); doReturn(patientData).when(this.patient).getData(CONTROLLER_NAME); JSONObject json = new JSONObject(); Collection<String> selectedFields = new LinkedList<>(); selectedFields.add(GENES_ENABLING_FIELD_NAME); this.mocker.getComponentUnderTest().writeJSON(this.patient, json, selectedFields); Assert.assertNotNull(json.get(CONTROLLER_NAME)); Assert.assertTrue(json.get(CONTROLLER_NAME) instanceof JSONArray); Assert.assertTrue(json.getJSONArray(CONTROLLER_NAME).isEmpty()); } @Test @SuppressWarnings("unchecked") public void writeJSONAddsContainerWithAllValuesWhenSelectedFieldsNull() throws ComponentLookupException { List<Map<String, String>> internalList = new LinkedList<>(); Map<String, String> item = new LinkedHashMap<>(); item.put(GENE_KEY, "geneName"); item.put(COMMENTS_KEY, null); internalList.add(item); PatientData<Map<String, String>> patientData = new IndexedPatientData<>(CONTROLLER_NAME, internalList); doReturn(patientData).when(this.patient).getData(CONTROLLER_NAME); JSONObject json = new JSONObject(); this.mocker.getComponentUnderTest().writeJSON(this.patient, json, null); Assert.assertNotNull(json.get(CONTROLLER_NAME)); Assert.assertTrue(json.get(CONTROLLER_NAME) instanceof JSONArray); item = (Map<String, String>) json.getJSONArray(CONTROLLER_NAME).get(0); Assert.assertEquals("geneName", item.get(GENE_KEY)); } @Test @SuppressWarnings("unchecked") public void writeJSONAddsContainerWithOnlySelectedFields() throws ComponentLookupException { List<Map<String, String>> internalList = new LinkedList<>(); Map<String, String> item = new LinkedHashMap<>(); item.put(GENE_KEY, "GENE"); item.put(COMMENTS_KEY, "Comment"); internalList.add(item); PatientData<Map<String, String>> patientData = new IndexedPatientData<>(CONTROLLER_NAME, internalList); doReturn(patientData).when(this.patient).getData(CONTROLLER_NAME); JSONObject json = new JSONObject(); Collection<String> selectedFields = new LinkedList<>(); selectedFields.add(GENES_ENABLING_FIELD_NAME); selectedFields.add(GENES_COMMENTS_ENABLING_FIELD_NAME); this.mocker.getComponentUnderTest().writeJSON(this.patient, json, selectedFields); Assert.assertNotNull(json.get(CONTROLLER_NAME)); Assert.assertTrue(json.get(CONTROLLER_NAME) instanceof JSONArray); item = (Map<String, String>) json.getJSONArray(CONTROLLER_NAME).get(0); Assert.assertEquals("GENE", item.get(GENE_KEY)); Assert.assertEquals("Comment", item.get(COMMENTS_KEY)); json = new JSONObject(); internalList = new LinkedList<>(); item = new LinkedHashMap<>(); item.put(GENE_KEY, "GENE"); item.put(COMMENTS_KEY, "Comment"); internalList.add(item); patientData = new IndexedPatientData<>(CONTROLLER_NAME, internalList); doReturn(patientData).when(this.patient).getData(CONTROLLER_NAME); selectedFields = new LinkedList<>(); selectedFields.add(GENES_ENABLING_FIELD_NAME); this.mocker.getComponentUnderTest().writeJSON(this.patient, json, selectedFields); Assert.assertNotNull(json.get(CONTROLLER_NAME)); Assert.assertTrue(json.get(CONTROLLER_NAME) instanceof JSONArray); item = (Map<String, String>) json.getJSONArray(CONTROLLER_NAME).get(0); Assert.assertEquals("GENE", item.get(GENE_KEY)); Assert.assertEquals(1, item.size()); } private void addGeneFields(String key, String[] fieldValues) { BaseObject obj; BaseStringProperty property; for (String value : fieldValues) { obj = mock(BaseObject.class); property = mock(BaseStringProperty.class); List<String> list = new ArrayList<>(); list.add(value); doReturn(value).when(property).getValue(); doReturn(property).when(obj).getField(key); doReturn(list).when(obj).getFieldList(); this.geneXWikiObjects.add(obj); } } }
// Location.java package loci.common; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; // HACK: for scan-deps.pl: The following packages are not actually "optional": // optional org.apache.log4j, optional org.slf4j.impl public class Location { // -- Constants -- private static final Logger LOGGER = LoggerFactory.getLogger(Location.class); // -- Static fields -- /** Map from given filenames to actual filenames. */ private static HashMap<String, Object> idMap = new HashMap<String, Object>(); private static boolean cacheListings = false; // By default, cache for one hour. private static long cacheNanos = 60L * 60L * 1000L * 1000L * 1000L; protected class ListingsResult { public final String [] listing; public final long time; ListingsResult(String [] listing, long time) { this.listing = listing; this.time = time; } } private static ConcurrentHashMap<String, ListingsResult> fileListings = new ConcurrentHashMap<String, ListingsResult>(); // -- Fields -- private boolean isURL = true; private URL url; private File file; // -- Constructors -- public Location(String pathname) { LOGGER.trace("Location({})", pathname); try { url = new URL(getMappedId(pathname)); } catch (MalformedURLException e) { LOGGER.trace("Location is not a URL", e); isURL = false; } if (!isURL) file = new File(getMappedId(pathname)); } public Location(File file) { LOGGER.trace("Location({})", file); isURL = false; this.file = file; } public Location(String parent, String child) { this(parent + File.separator + child); } public Location(Location parent, String child) { this(parent.getAbsolutePath(), child); } // -- Location API methods -- /** * Turn cacheing of directory listings on or off. * Cacheing is turned off by default. * * Reasons to cache - directory listings over network shares * can be very expensive, especially in HCS experiments with thousands * of files in the same directory. Technically, if you use a directory * listing and then go and access the file, you are using stale information. * Unlike a database, there's no transactional integrity to file system * operations, so the directory could change by the time you access the file. * * Reasons not to cache - the contents of the directories might change * during the program invocation. * * @param cache - true to turn cacheing on, false to leave it off. */ public static void cacheDirectoryListings(boolean cache) { cacheListings = cache; } /** * Cache directory listings for this many seconds before relisting. * * @param sec - use the cache if a directory list was done within this many * seconds. */ public static void setCacheDirectoryTimeout(double sec) { cacheNanos = (long)(sec * 1000. * 1000. * 1000.); } /** * Clear the directory listings cache. * * Do this if directory contents might have changed in a significant way. */ public static void clearDirectoryListingsCache() { fileListings = new ConcurrentHashMap<String, ListingsResult>(); } /** * Remove any cached directory listings that have expired. */ public static void cleanStaleCacheEntries() { long t = System.nanoTime() - cacheNanos; ArrayList<String> staleKeys = new ArrayList(); for (String key : fileListings.keySet()) { if (fileListings.get(key).time < t) { staleKeys.add(key); } } for (String key : staleKeys) { fileListings.remove(key); } } /** * Maps the given id to an actual filename on disk. Typically actual * filenames are used for ids, making this step unnecessary, but in some * cases it is useful; e.g., if the file has been renamed to conform to a * standard naming scheme and the original file extension is lost, then * using the original filename as the id assists format handlers with type * identification and pattern matching, and the id can be mapped to the * actual filename for reading the file's contents. * @see #getMappedId(String) */ public static void mapId(String id, String filename) { if (id == null) return; if (filename == null) idMap.remove(id); else idMap.put(id, filename); LOGGER.debug("Location.mapId: {} -> {}", id, filename); } /** Maps the given id to the given IRandomAccess object. */ public static void mapFile(String id, IRandomAccess ira) { if (id == null) return; if (ira == null) idMap.remove(id); else idMap.put(id, ira); LOGGER.debug("Location.mapFile: {} -> {}", id, ira); } /** * Gets the actual filename on disk for the given id. Typically the id itself * is the filename, but in some cases may not be; e.g., if OMEIS has renamed * a file from its original name to a standard location such as Files/101, * the original filename is useful for checking the file extension and doing * pattern matching, but the renamed filename is required to read its * contents. * @see #mapId(String, String) */ public static String getMappedId(String id) { if (idMap == null) return id; String filename = null; if (id != null && (idMap.get(id) instanceof String)) { filename = (String) idMap.get(id); } return filename == null ? id : filename; } /** Gets the random access handle for the given id. */ public static IRandomAccess getMappedFile(String id) { if (idMap == null) return null; IRandomAccess ira = null; if (id != null && (idMap.get(id) instanceof IRandomAccess)) { ira = (IRandomAccess) idMap.get(id); } return ira; } /** Return the id mapping. */ public static HashMap<String, Object> getIdMap() { return idMap; } public static void setIdMap(HashMap<String, Object> map) { if (map == null) throw new IllegalArgumentException("map cannot be null"); idMap = map; } /** * Gets an IRandomAccess object that can read from the given file. * @see IRandomAccess */ public static IRandomAccess getHandle(String id) throws IOException { return getHandle(id, false); } /** * Gets an IRandomAccess object that can read from or write to the given file. * @see IRandomAccess */ public static IRandomAccess getHandle(String id, boolean writable) throws IOException { LOGGER.trace("getHandle(id = {}, writable = {})", id, writable); IRandomAccess handle = getMappedFile(id); if (handle == null) { LOGGER.trace("no handle was mapped for this ID"); String mapId = getMappedId(id); if (id.startsWith("http: handle = new URLHandle(mapId); } else if (ZipHandle.isZipFile(id)) { handle = new ZipHandle(mapId); } else if (GZipHandle.isGZipFile(id)) { handle = new GZipHandle(mapId); } else if (BZip2Handle.isBZip2File(id)) { handle = new BZip2Handle(mapId); } else { handle = new NIOFileHandle(mapId, writable ? "rw" : "r"); } } LOGGER.trace("Location.getHandle: {} -> {}", id, handle); return handle; } /** * Return a list of all of the files in this directory. If 'noHiddenFiles' is * set to true, then hidden files are omitted. * * @see java.io.File#list() */ public String[] list(boolean noHiddenFiles) { String key = getAbsolutePath() + Boolean.toString(noHiddenFiles); String [] result = null; if (cacheListings) { cleanStaleCacheEntries(); ListingsResult listingsResult = fileListings.get(key); if (listingsResult != null) { return listingsResult.listing; } } ArrayList<String> files = new ArrayList<String>(); if (isURL) { try { URLConnection c = url.openConnection(); InputStream is = c.getInputStream(); boolean foundEnd = false; while (!foundEnd) { byte[] b = new byte[is.available()]; is.read(b); String s = new String(b); if (s.toLowerCase().indexOf("</html>") != -1) foundEnd = true; while (s.indexOf("a href") != -1) { int ndx = s.indexOf("a href") + 8; int idx = s.indexOf("\"", ndx); if (idx < 0) break; String f = s.substring(ndx, idx); if (files.size() > 0 && f.startsWith("/")) { return null; } s = s.substring(idx + 1); if (f.startsWith("?")) continue; Location check = new Location(getAbsolutePath(), f); if (check.exists() && (!noHiddenFiles || !check.isHidden())) { files.add(check.getName()); } } } } catch (IOException e) { LOGGER.trace("Could not retrieve directory listing", e); return null; } } else { if (file == null) return null; String[] f = file.list(); if (f == null) return null; for (String name : f) { if (!noHiddenFiles || !new Location(file.getAbsolutePath(), name).isHidden()) { files.add(name); } } } result = files.toArray(new String[files.size()]); if (cacheListings) { fileListings.put(key, new ListingsResult(result, System.nanoTime())); } return result; } // -- File API methods -- /** * If the underlying location is a URL, this method will return true if * the URL exists. * Otherwise, it will return true iff the file exists and is readable. * * @see java.io.File#canRead() */ public boolean canRead() { return isURL ? (isDirectory() || isFile()) : file.canRead(); } /** * If the underlying location is a URL, this method will always return false. * Otherwise, it will return true iff the file exists and is writable. * * @see java.io.File#canWrite() */ public boolean canWrite() { return isURL ? false : file.canWrite(); } /** * Creates a new empty file named by this Location's path name iff a file * with this name does not already exist. Note that this operation is * only supported if the path name can be interpreted as a path to a file on * disk (i.e. is not a URL). * * @return true if the file was created successfully * @throws IOException if an I/O error occurred, or the * abstract pathname is a URL * @see java.io.File#createNewFile() */ public boolean createNewFile() throws IOException { if (isURL) throw new IOException("Unimplemented"); return file.createNewFile(); } /** * Deletes this file. If {@link #isDirectory()} returns true, then the * directory must be empty in order to be deleted. URLs cannot be deleted. * * @return true if the file was successfully deleted * @see java.io.File#delete() */ public boolean delete() { return isURL ? false : file.delete(); } /** * Request that this file be deleted when the JVM terminates. * This method will do nothing if the pathname represents a URL. * * @see java.io.File#deleteOnExit() */ public void deleteOnExit() { if (!isURL) file.deleteOnExit(); } /** * @see java.io.File#equals(Object) * @see java.net.URL#equals(Object) */ public boolean equals(Object obj) { return isURL ? url.equals(obj) : file.equals(obj); } /** * Returns whether or not the pathname exists. * If the pathname is a URL, then existence is determined based on whether * or not we can successfully read content from the URL. * * @see java.io.File#exists() */ public boolean exists() { if (isURL) { try { url.getContent(); return true; } catch (IOException e) { LOGGER.trace("Failed to retrieve content from URL", e); return false; } } if (file.exists()) return true; if (getMappedFile(file.getPath()) != null) return true; String mappedId = getMappedId(file.getPath()); return mappedId != null && new File(mappedId).exists(); } /* @see java.io.File#getAbsoluteFile() */ public Location getAbsoluteFile() { return new Location(getAbsolutePath()); } /* @see java.io.File#getAbsolutePath() */ public String getAbsolutePath() { return isURL ? url.toExternalForm() : file.getAbsolutePath(); } /* @see java.io.File#getCanonicalFile() */ public Location getCanonicalFile() throws IOException { return isURL ? getAbsoluteFile() : new Location(file.getCanonicalFile()); } /** * Returns the canonical path to this file. * If the file is a URL, then the canonical path is equivalent to the * absolute path ({@link #getAbsolutePath()}). Otherwise, this method * will delegate to {@link java.io.File#getCanonicalPath()}. */ public String getCanonicalPath() throws IOException { return isURL ? getAbsolutePath() : file.getCanonicalPath(); } /** * Returns the name of this file, i.e. the last name in the path name * sequence. * * @see java.io.File#getName() */ public String getName() { if (isURL) { String name = url.getFile(); name = name.substring(name.lastIndexOf("/") + 1); return name; } return file.getName(); } /** * Returns the name of this file's parent directory, i.e. the path name prefix * and every name in the path name sequence except for the last. * If this file does not have a parent directory, then null is returned. * * @see java.io.File#getParent() */ public String getParent() { if (isURL) { String absPath = getAbsolutePath(); absPath = absPath.substring(0, absPath.lastIndexOf("/")); return absPath; } return file.getParent(); } /* @see java.io.File#getParentFile() */ public Location getParentFile() { return new Location(getParent()); } /* @see java.io.File#getPath() */ public String getPath() { return isURL ? url.getHost() + url.getPath() : file.getPath(); } /** * Tests whether or not this path name is absolute. * If the path name is a URL, this method will always return true. * * @see java.io.File#isAbsolute() */ public boolean isAbsolute() { return isURL ? true : file.isAbsolute(); } /** * Returns true if this pathname exists and represents a directory. * * @see java.io.File#isDirectory() */ public boolean isDirectory() { if (isURL) { String[] list = list(); return list != null; } return file.isDirectory(); } /** * Returns true if this pathname exists and represents a regular file. * * @see java.io.File#exists() */ public boolean isFile() { return isURL ? (!isDirectory() && exists()) : file.isFile(); } /** * Returns true if the pathname is 'hidden'. This method will always * return false if the pathname corresponds to a URL. * * @see java.io.File#isHidden() */ public boolean isHidden() { return isURL ? false : file.isHidden(); } /** * Return the last modification time of this file, in milliseconds since * the UNIX epoch. * If the file does not exist, 0 is returned. * * @see java.io.File#lastModified() * @see java.net.URLConnection#getLastModified() */ public long lastModified() { if (isURL) { try { return url.openConnection().getLastModified(); } catch (IOException e) { LOGGER.trace("Could not determine URL's last modification time", e); return 0; } } return file.lastModified(); } /** * @see java.io.File#length() * @see java.net.URLConnection#getContentLength() */ public long length() { if (isURL) { try { return url.openConnection().getContentLength(); } catch (IOException e) { LOGGER.trace("Could not determine URL's content length", e); return 0; } } return file.length(); } /** * Return a list of file names in this directory. Hidden files will be * included in the list. * If this is not a directory, return null. */ public String[] list() { return list(false); } /** * Return a list of absolute files in this directory. Hidden files will * be included in the list. * If this is not a directory, return null. */ public Location[] listFiles() { String[] s = list(); if (s == null) return null; Location[] f = new Location[s.length]; for (int i=0; i<f.length; i++) { f[i] = new Location(getAbsolutePath(), s[i]); f[i] = f[i].getAbsoluteFile(); } return f; } /** * Return the URL corresponding to this pathname. * * @see java.io.File#toURL() */ public URL toURL() throws MalformedURLException { return isURL ? url : file.toURI().toURL(); } /** * @see java.io.File#toString() * @see java.net.URL#toString() */ public String toString() { return isURL ? url.toString() : file.toString(); } }
// XMLTools.java package loci.common; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.util.StringTokenizer; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.xml.sax.Attributes; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; public final class XMLTools { // -- Constants -- /** Factory for generating SAX parsers. */ public static final SAXParserFactory SAX_FACTORY = SAXParserFactory.newInstance(); // -- Constructor -- private XMLTools() { } // -- Utility methods -- /** Remove invalid characters from an XML string. */ public static String sanitizeXML(String s) { for (int i=0; i<s.length(); i++) { char c = s.charAt(i); if (Character.isISOControl(c) || !Character.isDefined(c) || c > '~') { s = s.replace(c, ' '); } } return s; } public static void parseXML(String xml, DefaultHandler handler) throws IOException { parseXML(xml.getBytes(), handler); } public static void parseXML(RandomAccessInputStream stream, DefaultHandler handler) throws IOException { byte[] b = new byte[(int) (stream.length() - stream.getFilePointer())]; stream.read(b); parseXML(b, handler); b = null; } public static void parseXML(byte[] xml, DefaultHandler handler) throws IOException { try { SAXParser parser = SAX_FACTORY.newSAXParser(); parser.parse(new ByteArrayInputStream(xml), handler); } catch (ParserConfigurationException exc) { IOException e = new IOException(); e.initCause(exc); throw e; } catch (SAXException exc) { IOException e = new IOException(); e.initCause(exc); throw e; } } /** * Attempts to validate the given XML string using * Java's XML validation facility. Requires Java 1.5+. * @param xml The XML string to validate. * @return whether or not validation was successful. */ public static boolean validateXML(String xml) { return validateXML(xml, null); } /** * Attempts to validate the given XML string using * Java's XML validation facility. Requires Java 1.5+. * @param xml The XML string to validate. * @param label String describing the type of XML being validated. * @return whether or not validation was successful. */ public static boolean validateXML(String xml, String label) { if (label == null) label = "XML"; // get path to schema from root element using SAX LogTools.println("Parsing schema path"); ValidationSAXHandler saxHandler = new ValidationSAXHandler(); Exception exception = null; try { SAXParser saxParser = SAX_FACTORY.newSAXParser(); InputStream is = new ByteArrayInputStream(xml.getBytes()); saxParser.parse(is, saxHandler); } catch (ParserConfigurationException exc) { exception = exc; } catch (SAXException exc) { exception = exc; } catch (IOException exc) { exception = exc; } if (exception != null) { LogTools.println("Error parsing schema path from " + label + ":"); LogTools.trace(exception); return false; } String schemaPath = saxHandler.getSchemaPath(); if (schemaPath == null) { LogTools.println("No schema path found. Validation cannot continue."); return false; } else LogTools.println(schemaPath); LogTools.println("Validating " + label); // look up a factory for the W3C XML Schema language String xmlSchemaPath = "http: SchemaFactory factory = SchemaFactory.newInstance(xmlSchemaPath); // compile the schema URL schemaLocation = null; try { schemaLocation = new URL(schemaPath); } catch (MalformedURLException exc) { LogTools.println("Error accessing schema at " + schemaPath + ":"); LogTools.trace(exc); return false; } Schema schema = null; try { schema = factory.newSchema(schemaLocation); } catch (SAXException exc) { LogTools.println("Error parsing schema at " + schemaPath + ":"); LogTools.trace(exc); return false; } // get a validator from the schema Validator validator = schema.newValidator(); // prepare the XML source StringReader reader = new StringReader(xml); InputSource is = new InputSource(reader); SAXSource source = new SAXSource(is); // validate the XML ValidationErrorHandler errorHandler = new ValidationErrorHandler(); validator.setErrorHandler(errorHandler); try { validator.validate(source); } catch (IOException exc) { exception = exc; } catch (SAXException exc) { exception = exc; } if (exception != null) { LogTools.println("Error validating document:"); LogTools.trace(exception); return false; } if (errorHandler.ok()) LogTools.println("No validation errors found."); return errorHandler.ok(); } /** Indents XML to be more readable. */ public static String indentXML(String xml) { return indentXML(xml, 3, false); } /** Indents XML by the given spacing to be more readable. */ public static String indentXML(String xml, int spacing) { return indentXML(xml, spacing, false); } /** * Indents XML by the given spacing to be more readable, avoiding any * whitespace injection into CDATA if the preserveCData flag is set. */ public static String indentXML(String xml, int spacing, boolean preserveCData) { if (xml == null) return null; // garbage in, garbage out StringBuffer sb = new StringBuffer(); StringTokenizer st = new StringTokenizer(xml, "<>", true); int indent = 0, noSpace = 0; boolean first = true, element = false; while (st.hasMoreTokens()) { String token = st.nextToken().trim(); if (token.equals("")) continue; if (token.equals("<")) { element = true; continue; } if (element && token.equals(">")) { element = false; continue; } if (!element && preserveCData) noSpace = 2; if (noSpace == 0) { // advance to next line if (first) first = false; else sb.append("\n"); } // adjust indent backwards if (element && token.startsWith("/")) indent -= spacing; if (noSpace == 0) { // apply indent for (int j=0; j<indent; j++) sb.append(" "); } // output element contents if (element) sb.append("<"); sb.append(token); if (element) sb.append(">"); if (noSpace == 0) { // adjust indent forwards if (element && !token.startsWith("?") && // ?xml tag, probably !token.startsWith("/") && // end element !token.endsWith("/") && // standalone element !token.startsWith("!")) // comment { indent += spacing; } } if (noSpace > 0) noSpace } sb.append("\n"); return sb.toString(); } // -- Helper classes -- /** Used by validateXML to parse the XML block's schema path using SAX. */ private static class ValidationSAXHandler extends DefaultHandler { private String schemaPath; private boolean first; public String getSchemaPath() { return schemaPath; } public void startDocument() { schemaPath = null; first = true; } public void startElement(String uri, String localName, String qName, Attributes attributes) { if (!first) return; first = false; int len = attributes.getLength(); String xmlns = null, xsiSchemaLocation = null; for (int i=0; i<len; i++) { String name = attributes.getQName(i); if (name.equals("xmlns")) xmlns = attributes.getValue(i); else if (name.equals("schemaLocation") || name.endsWith(":schemaLocation")) { xsiSchemaLocation = attributes.getValue(i); } } if (xmlns == null || xsiSchemaLocation == null) return; // not found StringTokenizer st = new StringTokenizer(xsiSchemaLocation); while (st.hasMoreTokens()) { String token = st.nextToken(); if (xmlns.equals(token)) { // next token is the actual schema path if (st.hasMoreTokens()) schemaPath = st.nextToken(); break; } } } } /** Used by validateXML to handle XML validation errors. */ private static class ValidationErrorHandler implements ErrorHandler { private boolean ok = true; public boolean ok() { return ok; } public void error(SAXParseException e) { LogTools.println("error: " + e.getMessage()); ok = false; } public void fatalError(SAXParseException e) { LogTools.println("fatal error: " + e.getMessage()); ok = false; } public void warning(SAXParseException e) { LogTools.println("warning: " + e.getMessage()); ok = false; } } }
package com.yahoo.vespa.hosted.controller.restapi.contactinfo; import com.yahoo.config.provision.TenantName; import com.yahoo.container.jdisc.HttpRequest; import com.yahoo.container.jdisc.HttpResponse; import com.yahoo.container.jdisc.LoggingRequestHandler; import com.yahoo.io.IOUtils; import com.yahoo.restapi.Path; import com.yahoo.slime.ArrayTraverser; import com.yahoo.slime.Cursor; import com.yahoo.slime.Inspector; import com.yahoo.slime.Slime; import com.yahoo.vespa.config.SlimeUtils; import com.yahoo.vespa.hosted.controller.Controller; import com.yahoo.vespa.hosted.controller.api.identifiers.PropertyId; import com.yahoo.vespa.hosted.controller.api.integration.organization.Organization; import com.yahoo.vespa.hosted.controller.api.integration.organization.User; import com.yahoo.vespa.hosted.controller.restapi.ErrorResponse; import com.yahoo.vespa.hosted.controller.restapi.SlimeJsonResponse; import com.yahoo.vespa.hosted.controller.restapi.StringResponse; import com.yahoo.vespa.hosted.controller.tenant.AthenzTenant; import com.yahoo.vespa.hosted.controller.tenant.Contact; import com.yahoo.yolean.Exceptions; import java.io.IOException; import java.io.ObjectInputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Optional; import java.util.logging.Level; import java.util.stream.Collectors; /** * @author olaa */ public class ContactInfoHandler extends LoggingRequestHandler { private final Controller controller; private final Organization organization; public ContactInfoHandler(Context ctx, Controller controller, Organization organization) { super(ctx); this.controller = controller; this.organization = organization; } @Override public HttpResponse handle(HttpRequest request) { try { switch (request.getMethod()) { case GET: return get(request); case POST: return post(request); default: return ErrorResponse.methodNotAllowed("Method '" + request.getMethod() + "' is unsupported"); } } catch (IllegalArgumentException e) { return ErrorResponse.badRequest(Exceptions.toMessageString(e)); } catch (RuntimeException e) { log.log(Level.WARNING, "Unexpected error handling '" + request.getUri() + "'", e); return ErrorResponse.internalServerError(Exceptions.toMessageString(e)); } } private HttpResponse get(HttpRequest request) { Path path = new Path(request.getUri().getPath()); if (!path.matches("/contactinfo/v1/tenant/{tenant}")) return getContactInfo(path.get("tenant"), request); return ErrorResponse.notFoundError("Nothing at " + path); } private HttpResponse post(HttpRequest request) { Path path = new Path(request.getUri().getPath()); if (path.matches("/contactinfo/v1/tenant/{tenant}")) return postContactInfo(path.get("tenant"), request); return ErrorResponse.notFoundError("Nothing at " + path); } private HttpResponse getContactInfo(String tenantName, HttpRequest request) { Optional<AthenzTenant> tenant = controller.tenants().athenzTenant(TenantName.from(tenantName)); if (! tenant.isPresent()) { return ErrorResponse.notFoundError("Invalid tenant " + tenantName); } boolean useOpsDb = getUseOpsDbFromRequest(request); Optional<Contact> contact = Optional.empty(); if (useOpsDb) { contact = findContactFromOpsDb(tenant.get()); } else { contact = tenant.get().contact(); } if (contact.isPresent()) { Slime response = new Slime(); Cursor cursor = response.setObject(); cursor.setString("issueTrackerUrl", contact.get().issueTrackerUrl().toString()); cursor.setString("propertyUrl", contact.get().propertyUrl().toString()); Cursor persons = cursor.setArray("persons"); for (List<String> personList : contact.get().persons()) { Cursor sublist = persons.addArray(); for(String person : personList) { sublist.addString(person); } } return new SlimeJsonResponse(response); } return ErrorResponse.notFoundError("Could not find contact info for " + tenantName); } private HttpResponse postContactInfo(String tenantName, HttpRequest request) { try { Contact contact = getContactFromRequest(request); controller.tenants().lockIfPresent(TenantName.from(tenantName), lockedTenant -> controller.tenants().store(lockedTenant.with(contact))); return new StringResponse("Added contact info for " + tenantName + " - " + contact.toString()); } catch (URISyntaxException | IOException e) { return ErrorResponse.notFoundError("Unable to create Contact object from request data"); } } private boolean getUseOpsDbFromRequest(HttpRequest request) { String query = request.getUri().getQuery(); if (query == null) { return false; } HashMap<String, String> keyValPair = new HashMap<>(); Arrays.stream(query.split("&")).forEach(pair -> { String[] splitPair = pair.split("="); keyValPair.put(splitPair[0], splitPair[1]); }); if (keyValPair.containsKey("useOpsDb")) { return Boolean.valueOf(keyValPair.get("useOpsDb")); } return false; } private PropertyId getPropertyIdFromRequest(HttpRequest request) { return new PropertyId(request.getProperty("propertyId")); } private Contact getContactFromRequest(HttpRequest request) throws IOException, URISyntaxException { Slime slime = SlimeUtils.jsonToSlime(IOUtils.readBytes(request.getData(), 1000 * 1000)); Inspector inspector = slime.get(); URI propertyUrl = new URI(inspector.field("propertyUrl").asString()); URI url = new URI(inspector.field("url").asString()); URI issueTrackerUrl = new URI(inspector.field("issueTrackerUrl").asString()); Inspector personInspector = inspector.field("persons"); List<List<String>> personList = new ArrayList<>(); personInspector.traverse((ArrayTraverser) (index, entry) -> { List<String> subList = new ArrayList<>(); entry.traverse((ArrayTraverser) (idx, subEntry) -> { subList.add(subEntry.asString()); }); personList.add(subList); }); return new Contact(url, propertyUrl, issueTrackerUrl, personList); } private Optional<Contact> findContactFromOpsDb(AthenzTenant tenant) { if (!tenant.propertyId().isPresent()) { return Optional.empty(); } List<List<String>> persons = organization.contactsFor(tenant.propertyId().get()) .stream() .map(personList -> personList.stream() .map(User::displayName) .collect(Collectors.toList())) .collect(Collectors.toList()); return Optional.of(new Contact(organization.contactsUri(tenant.propertyId().get()), organization.propertyUri(tenant.propertyId().get()), organization.issueCreationUri(tenant.propertyId().get()), persons)); } }
package org.apereo.cas.support.events.listener; import org.apereo.cas.authentication.adaptive.geo.GeoLocationRequest; import org.apereo.cas.configuration.CasConfigurationProperties; import org.apereo.cas.support.events.CasConfigurationModifiedEvent; import org.apereo.cas.support.events.CasRiskyAuthenticationDetectedEvent; import org.apereo.cas.support.events.CasTicketGrantingTicketCreatedEvent; import org.apereo.cas.support.events.dao.CasEvent; import org.apereo.cas.support.events.dao.CasEventRepository; import org.apereo.cas.util.DateTimeUtils; import org.apereo.cas.util.serialization.TicketIdSanitizationUtils; import org.apereo.cas.web.support.WebUtils; import org.apereo.inspektr.common.web.ClientInfo; import org.apereo.inspektr.common.web.ClientInfoHolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor; import org.springframework.cloud.bus.event.RefreshRemoteApplicationEvent; import org.springframework.cloud.context.environment.EnvironmentChangeEvent; import org.springframework.cloud.context.refresh.ContextRefresher; import org.springframework.context.ApplicationContext; import org.springframework.context.event.EventListener; import java.io.File; import java.util.Collection; import java.util.Map; import java.util.regex.Pattern; /** * This is {@link DefaultCasEventListener} that attempts to consume CAS events * upon various authentication events. Event data is persisted into a repository * via {@link CasEventRepository}. * * @author Misagh Moayyed * @since 5.0.0 */ public class DefaultCasEventListener { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultCasEventListener.class); private static final Pattern CONFIG_FILE_PATTERN = Pattern.compile("\\.(properties|yml)", Pattern.CASE_INSENSITIVE); @Autowired private ConfigurationPropertiesBindingPostProcessor binder; @Autowired(required = false) private ContextRefresher contextRefresher; @Autowired private ApplicationContext applicationContext; private final CasEventRepository casEventRepository; public DefaultCasEventListener(final CasEventRepository casEventRepository) { this.casEventRepository = casEventRepository; } /** * Handle application ready event. * * @param event the event */ @EventListener public void handleApplicationReadyEvent(final ApplicationReadyEvent event) { LOGGER.info("CAS is ready to process requests @ [{}]", DateTimeUtils.zonedDateTimeOf(event.getTimestamp())); } /** * Handle refresh event when issued to this CAS server locally. * * @param event the event */ @EventListener public void handleRefreshEvent(final EnvironmentChangeEvent event) { LOGGER.debug("Received event [{}]", event); rebindCasConfigurationProperties(); } /** * Handle refresh event when issued by the cloud bus. * * @param event the event */ @EventListener public void handleRefreshEvent(final RefreshRemoteApplicationEvent event) { LOGGER.debug("Received event [{}]", event); rebindCasConfigurationProperties(); } /** * Handle configuration modified event. * * @param event the event */ @EventListener public void handleConfigurationModifiedEvent(final CasConfigurationModifiedEvent event) { if (this.contextRefresher == null) { LOGGER.warn("Unable to refresh application context, since no refresher is available"); return; } final File file = event.getFile().toFile(); if (CONFIG_FILE_PATTERN.matcher(file.getName()).find()) { LOGGER.info("Received event [{}]. Refreshing CAS configuration...", event); final Collection<String> keys = this.contextRefresher.refresh(); LOGGER.debug("Refreshed the following settings: [{}].", keys); rebindCasConfigurationProperties(); LOGGER.info("CAS finished rebinding configuration with new settings [{}]", keys); } } /** * Rebind cas configuration properties. */ public void rebindCasConfigurationProperties() { final Map<String, CasConfigurationProperties> map = this.applicationContext.getBeansOfType(CasConfigurationProperties.class); final String name = map.keySet().iterator().next(); LOGGER.debug("Reloading CAS configuration via [{}]", name); final Object e = this.applicationContext.getBean(name); this.binder.postProcessBeforeInitialization(e, name); final Object bean = this.applicationContext.getAutowireCapableBeanFactory().initializeBean(e, name); this.applicationContext.getAutowireCapableBeanFactory().autowireBean(bean); LOGGER.debug("Reloaded CAS configuration [{}]", name); } /** * Handle TGT creation event. * * @param event the event */ @EventListener public void handleCasTicketGrantingTicketCreatedEvent(final CasTicketGrantingTicketCreatedEvent event) { if (this.casEventRepository != null) { final CasEvent dto = new CasEvent(); dto.setType(event.getClass().getCanonicalName()); dto.putTimestamp(event.getTimestamp()); dto.putCreationTime(event.getTicketGrantingTicket().getCreationTime()); dto.putId(TicketIdSanitizationUtils.sanitize(event.getTicketGrantingTicket().getId())); dto.setPrincipalId(event.getTicketGrantingTicket().getAuthentication().getPrincipal().getId()); final ClientInfo clientInfo = ClientInfoHolder.getClientInfo(); dto.putClientIpAddress(clientInfo.getClientIpAddress()); dto.putServerIpAddress(clientInfo.getServerIpAddress()); dto.putAgent(WebUtils.getHttpServletRequestUserAgent()); final GeoLocationRequest location = WebUtils.getHttpServletRequestGeoLocation(); dto.putGeoLocation(location); this.casEventRepository.save(dto); } } /** * Handle cas risky authentication detected event. * * @param event the event */ @EventListener public void handleCasRiskyAuthenticationDetectedEvent(final CasRiskyAuthenticationDetectedEvent event) { if (this.casEventRepository != null) { final CasEvent dto = new CasEvent(); dto.setType(event.getClass().getCanonicalName()); dto.putTimestamp(event.getTimestamp()); dto.putCreationTime(DateTimeUtils.zonedDateTimeOf(event.getTimestamp())); dto.putId(event.getService().getName()); dto.setPrincipalId(event.getAuthentication().getPrincipal().getId()); final ClientInfo clientInfo = ClientInfoHolder.getClientInfo(); dto.putClientIpAddress(clientInfo.getClientIpAddress()); dto.putServerIpAddress(clientInfo.getServerIpAddress()); dto.putAgent(WebUtils.getHttpServletRequestUserAgent()); final GeoLocationRequest location = WebUtils.getHttpServletRequestGeoLocation(); dto.putGeoLocation(location); this.casEventRepository.save(dto); } } public CasEventRepository getCasEventRepository() { return casEventRepository; } }
package org.apache.cloudstack.mom.rabbitmq; import com.cloud.utils.Ternary; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.exception.CloudRuntimeException; import org.apache.cloudstack.framework.events.Event; import org.apache.cloudstack.framework.events.EventBus; import org.apache.cloudstack.framework.events.EventBusException; import org.apache.cloudstack.framework.events.EventSubscriber; import org.apache.cloudstack.framework.events.EventTopic; import org.apache.cloudstack.managed.context.ManagedContextRunnable; import javax.naming.ConfigurationException; import java.io.IOException; import java.net.ConnectException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeoutException; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.AlreadyClosedException; import com.rabbitmq.client.BlockedListener; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.DefaultConsumer; import com.rabbitmq.client.Envelope; import com.rabbitmq.client.MessageProperties; import com.rabbitmq.client.ShutdownListener; import com.rabbitmq.client.ShutdownSignalException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RabbitMQEventBus extends ManagerBase implements EventBus { private static final Logger s_logger = LoggerFactory.getLogger(RabbitMQEventBus.class); private static String secureProtocol = "TLSv1"; // AMQP server should consider messages acknowledged once delivered if _autoAck is true private static final boolean s_autoAck = true; // details of AMQP server private static String amqpHost; private static Integer port; private static String username; private static String password; private static String virtualHost; private static String useSsl; // AMQP exchange name where all CloudStack events will be published private static String amqpExchangeName; private static Integer retryInterval; // hashmap to book keep the registered subscribers private static ConcurrentHashMap<String, Ternary<String, Channel, EventSubscriber>> s_subscribers; // connection to AMQP server, private static Connection s_connection = null; private static DisconnectHandler disconnectHandler; private static BlockedConnectionHandler blockedConnectionHandler; private ExecutorService executorService; public static void setServer(final String amqpHost) { RabbitMQEventBus.amqpHost = amqpHost; } public static void setUsername(final String username) { RabbitMQEventBus.username = username; } public static void setPassword(final String password) { RabbitMQEventBus.password = password; } public static void setPort(final Integer port) { RabbitMQEventBus.port = port; } public static void setSecureProtocol(final String protocol) { RabbitMQEventBus.secureProtocol = protocol; } public static void setExchange(final String exchange) { RabbitMQEventBus.amqpExchangeName = exchange; } public static void setRetryInterval(final Integer retryInterval) { RabbitMQEventBus.retryInterval = retryInterval; } public synchronized static void setVirtualHost(final String virtualHost) { RabbitMQEventBus.virtualHost = virtualHost; } public static void setUseSsl(final String useSsl) { RabbitMQEventBus.useSsl = useSsl; } @Override public void publish(final Event event) throws EventBusException { final String routingKey = createRoutingKey(event); final String eventDescription = event.getDescription(); try { final Connection connection = getConnection(); final Channel channel = createChannel(connection); createExchange(channel, amqpExchangeName); publishEventToExchange(channel, amqpExchangeName, routingKey, eventDescription); channel.close(); } catch (final AlreadyClosedException e) { closeConnection(); throw new EventBusException("Failed to publish event to message broker as connection to AMQP broker in lost"); } catch (final Exception e) { throw new EventBusException("Failed to publish event to message broker due to " + e.getMessage()); } } /** * Call to subscribe to interested set of events * * @param topic defines category and type of the events being subscribed to * @param subscriber subscriber that intends to receive event notification * @return UUID that represents the subscription with event bus * @throws EventBusException */ @Override public UUID subscribe(final EventTopic topic, final EventSubscriber subscriber) throws EventBusException { if (subscriber == null || topic == null) { throw new EventBusException("Invalid EventSubscriber/EventTopic object passed."); } // create a UUID, that will be used for managing subscriptions and also used as queue name // for on the queue used for the subscriber on the AMQP broker final UUID queueId = UUID.randomUUID(); final String queueName = queueId.toString(); try { final String bindingKey = createBindingKey(topic); // store the subscriber details before creating channel s_subscribers.put(queueName, new Ternary<>(bindingKey, null, subscriber)); // create a channel dedicated for this subscription final Connection connection = getConnection(); final Channel channel = createChannel(connection); // create a queue and bind it to the exchange with binding key formed from event topic createExchange(channel, amqpExchangeName); channel.queueDeclare(queueName, false, false, false, null); channel.queueBind(queueName, amqpExchangeName, bindingKey); // register a callback handler to receive the events that a subscriber subscribed to channel.basicConsume(queueName, s_autoAck, queueName, new DefaultConsumer(channel) { @Override public void handleDelivery(final String queueName, final Envelope envelope, final AMQP.BasicProperties properties, final byte[] body) throws IOException { RabbitMQEventBus.this.handleDelivery(queueName, envelope, body); } }); // update the channel details for the subscription final Ternary<String, Channel, EventSubscriber> queueDetails = s_subscribers.get(queueName); queueDetails.second(channel); s_subscribers.put(queueName, queueDetails); } catch (final AlreadyClosedException | ConnectException | NoSuchAlgorithmException | KeyManagementException | TimeoutException e) { s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName + " will be active after reconnection", e); } catch (final IOException e) { throw new EventBusException("Failed to subscribe to event due to " + e.getMessage(), e); } return queueId; } @Override public void unsubscribe(final UUID subscriberId, final EventSubscriber subscriber) throws EventBusException { try { final String classname = subscriber.getClass().getName(); final String queueName = UUID.nameUUIDFromBytes(classname.getBytes()).toString(); final Ternary<String, Channel, EventSubscriber> queueDetails = s_subscribers.get(queueName); final Channel channel = queueDetails.second(); channel.basicCancel(queueName); s_subscribers.remove(queueName, queueDetails); } catch (final IOException e) { throw new EventBusException("Failed to unsubscribe from event bus due to " + e.getMessage(), e); } } /** * creates a binding key from the event topic that subscriber specified * binding key will be used to bind the queue created for subscriber to exchange on AMQP server */ private String createBindingKey(final EventTopic topic) { final String eventSource = makeKeyValue(topic.getEventSource()); final String eventCategory = makeKeyValue(topic.getEventCategory()); final String eventType = makeKeyValue(topic.getEventType()); final String resourceType = makeKeyValue(topic.getResourceType()); final String resourceUuid = makeKeyValue(topic.getResourceUUID()); return buildKey(eventSource, eventCategory, eventType, resourceType, resourceUuid); } private void handleDelivery(final String queueName, final Envelope envelope, final byte[] body) { final Ternary<String, Channel, EventSubscriber> queueDetails = s_subscribers.get(queueName); if (queueDetails != null) { final EventSubscriber subscriber = queueDetails.third(); final String routingKey = envelope.getRoutingKey(); final String eventSource = getEventSourceFromRoutingKey(routingKey); final String eventCategory = getEventCategoryFromRoutingKey(routingKey); final String eventType = getEventTypeFromRoutingKey(routingKey); final String resourceType = getResourceTypeFromRoutingKey(routingKey); final String resourceUUID = getResourceUUIDFromRoutingKey(routingKey); final Event event = new Event(eventSource, eventCategory, eventType, resourceType, resourceUUID); event.setDescription(new String(body)); // deliver the event to call back object provided by subscriber subscriber.onEvent(event); } } private String getEventSourceFromRoutingKey(final String routingKey) { final String[] keyParts = routingKey.split("\\."); return keyParts[0]; } private String getEventCategoryFromRoutingKey(final String routingKey) { final String[] keyParts = routingKey.split("\\."); return keyParts[1]; } private String getEventTypeFromRoutingKey(final String routingKey) { final String[] keyParts = routingKey.split("\\."); return keyParts[2]; } private String getResourceTypeFromRoutingKey(final String routingKey) { final String[] keyParts = routingKey.split("\\."); return keyParts[3]; } private String getResourceUUIDFromRoutingKey(final String routingKey) { final String[] keyParts = routingKey.split("\\."); return keyParts[4]; } /** * creates a routing key from the event details. * created routing key will be used while publishing the message to exchange on AMQP server */ private String createRoutingKey(final Event event) { final String eventSource = makeKeyValue(event.getEventSource()); final String eventCategory = makeKeyValue(event.getEventCategory()); final String eventType = makeKeyValue(event.getEventType()); final String resourceType = makeKeyValue(event.getResourceType()); final String resourceUuid = makeKeyValue(event.getResourceUUID()); return buildKey(eventSource, eventCategory, eventType, resourceType, resourceUuid); } private synchronized Connection getConnection() throws IOException, TimeoutException, NoSuchAlgorithmException, KeyManagementException { if (s_connection == null) { try { return createConnection(); } catch (KeyManagementException | NoSuchAlgorithmException | IOException | TimeoutException e) { s_logger.warn("Failed to create a connection to AMQP server due to " + e.getMessage()); throw e; } } else { return s_connection; } } private Channel createChannel(final Connection connection) throws IOException { try { return connection.createChannel(); } catch (final IOException e) { s_logger.warn("Failed to create a channel due to " + e.getMessage(), e); throw e; } } private void createExchange(final Channel channel, final String exchangeName) throws IOException { try { channel.exchangeDeclare(exchangeName, "topic", true); } catch (final IOException e) { s_logger.warn("Failed to create exchange" + e + " on RabbitMQ server"); throw e; } } private void publishEventToExchange(final Channel channel, final String exchangeName, final String routingKey, final String eventDescription) throws IOException { final byte[] messageBodyBytes = eventDescription.getBytes(); try { channel.basicPublish(exchangeName, routingKey, MessageProperties.PERSISTENT_TEXT_PLAIN, messageBodyBytes); } catch (final IOException e) { s_logger.warn("Failed to publish event " + routingKey + " on exchange " + exchangeName + " of message broker due to " + e.getMessage(), e); throw e; } } private synchronized void closeConnection() { try { if (s_connection != null) { s_connection.close(); } } catch (final Exception e) { s_logger.warn("Failed to close connection to AMQP server due to " + e.getMessage()); } s_connection = null; } private String makeKeyValue(final String value) { return replaceNullWithWildcard(value).replace(".", "-"); } private String buildKey(final String eventSource, final String eventCategory, final String eventType, final String resourceType, final String resourceUuid) { return eventSource + "." + eventCategory + "." + eventType + "." + resourceType + "." + resourceUuid; } private synchronized Connection createConnection() throws KeyManagementException, NoSuchAlgorithmException, IOException, TimeoutException { final ConnectionFactory factory = new ConnectionFactory(); factory.setUsername(username); factory.setPassword(password); factory.setHost(amqpHost); factory.setPort(port); if (virtualHost != null && !virtualHost.isEmpty()) { factory.setVirtualHost(virtualHost); } else { factory.setVirtualHost("/"); } if (useSsl != null && !useSsl.isEmpty() && useSsl.equalsIgnoreCase("true")) { factory.useSslProtocol(secureProtocol); } final Connection connection = factory.newConnection(); connection.addShutdownListener(disconnectHandler); connection.addBlockedListener(blockedConnectionHandler); s_connection = connection; return s_connection; } private String replaceNullWithWildcard(final String key) { if (key == null || key.isEmpty()) { return "*"; } else { return key; } } private synchronized void abortConnection() { if (s_connection == null) { return; } try { s_connection.abort(); } catch (final Exception e) { s_logger.warn("Failed to abort connection due to " + e.getMessage()); } s_connection = null; } @Override public String getName() { return _name; } @Override public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException { try { if (amqpHost == null || amqpHost.isEmpty()) { throw new ConfigurationException("Unable to get the AMQP server details"); } if (username == null || username.isEmpty()) { throw new ConfigurationException("Unable to get the username details"); } if (password == null || password.isEmpty()) { throw new ConfigurationException("Unable to get the password details"); } if (amqpExchangeName == null || amqpExchangeName.isEmpty()) { throw new ConfigurationException("Unable to get the _exchange details on the AMQP server"); } if (port == null) { throw new ConfigurationException("Unable to get the port details of AMQP server"); } if (useSsl != null && !useSsl.isEmpty()) { if (!useSsl.equalsIgnoreCase("true") && !useSsl.equalsIgnoreCase("false")) { throw new ConfigurationException("Invalid configuration parameter for 'ssl'."); } } if (retryInterval == null) { retryInterval = 10000;// default to 10s to try out reconnect } } catch (final NumberFormatException e) { throw new ConfigurationException("Invalid port number/retry interval"); } s_subscribers = new ConcurrentHashMap<>(); executorService = Executors.newCachedThreadPool(); disconnectHandler = new DisconnectHandler(); blockedConnectionHandler = new BlockedConnectionHandler(); return true; } @Override public boolean start() { final ReconnectionTask reconnect = new ReconnectionTask(); // initiate connection to AMQP server executorService.submit(reconnect); return true; } @Override public synchronized boolean stop() { if (s_connection.isOpen()) { for (final String subscriberId : s_subscribers.keySet()) { final Ternary<String, Channel, EventSubscriber> subscriberDetails = s_subscribers.get(subscriberId); final Channel channel = subscriberDetails.second(); try { channel.queueDelete(subscriberId); channel.abort(); } catch (final IOException ioe) { s_logger.warn("Failed to delete queue: " + subscriberId + " on AMQP server due to " + ioe.getMessage()); } } } closeConnection(); return true; } private class BlockedConnectionHandler implements BlockedListener { @Override public void handleBlocked(final String reason) throws IOException { s_logger.error("rabbitmq connection is blocked with reason: " + reason); closeConnection(); throw new CloudRuntimeException("unblocking the parent thread as publishing to rabbitmq server is blocked with reason: " + reason); } @Override public void handleUnblocked() throws IOException { s_logger.info("rabbitmq connection in unblocked"); } } // logic to deal with loss of connection to AMQP server private class DisconnectHandler implements ShutdownListener { @Override public void shutdownCompleted(final ShutdownSignalException shutdownSignalException) { if (!shutdownSignalException.isInitiatedByApplication()) { for (final String subscriberId : s_subscribers.keySet()) { final Ternary<String, Channel, EventSubscriber> subscriberDetails = s_subscribers.get(subscriberId); subscriberDetails.second(null); s_subscribers.put(subscriberId, subscriberDetails); } abortConnection(); // disconnected to AMQP server, so abort the connection and channels s_logger.warn("Connection has been shutdown by AMQP server. Attempting to reconnect."); // initiate re-connect process final ReconnectionTask reconnect = new ReconnectionTask(); executorService.submit(reconnect); } } } // retry logic to connect back to AMQP server after loss of connection private class ReconnectionTask extends ManagedContextRunnable { boolean connected = false; Connection connection = null; @Override protected void runInContext() { while (!connected) { try { Thread.sleep(retryInterval); } catch (final InterruptedException ie) { // ignore timer interrupts } try { try { connection = createConnection(); connected = true; } catch (final IOException | TimeoutException | NoSuchAlgorithmException | KeyManagementException e) { s_logger.warn("Can't establish connection to AMQP server yet, so continue", e); continue; } // prepare consumer on AMQP server for each of subscriber for (final String subscriberId : s_subscribers.keySet()) { final Ternary<String, Channel, EventSubscriber> subscriberDetails = s_subscribers.get(subscriberId); final String bindingKey = subscriberDetails.first(); /** create a queue with subscriber ID as queue name and bind it to the exchange * with binding key formed from event topic */ final Channel channel = createChannel(connection); createExchange(channel, amqpExchangeName); channel.queueDeclare(subscriberId, false, false, false, null); channel.queueBind(subscriberId, amqpExchangeName, bindingKey); // register a callback handler to receive the events that a subscriber subscribed to channel.basicConsume(subscriberId, s_autoAck, subscriberId, new DefaultConsumer(channel) { @Override public void handleDelivery(final String queueName, final Envelope envelope, final AMQP.BasicProperties properties, final byte[] body) throws IOException { RabbitMQEventBus.this.handleDelivery(queueName, envelope, body); } }); // update the channel details for the subscription subscriberDetails.second(channel); s_subscribers.put(subscriberId, subscriberDetails); } } catch (final IOException e) { s_logger.warn("Failed to recreate queues and binding for the subscribers due to " + e.getMessage(), e); } } } } }
package org.voltcore.utils; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.management.ManagementFactory; import java.net.Inet4Address; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.NetworkInterface; import java.net.SocketException; import java.net.URL; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReentrantLock; import org.voltcore.logging.Level; import org.voltcore.logging.VoltLogger; import org.voltcore.network.ReverseDNSCache; import com.google_voltpatches.common.base.Preconditions; import com.google_voltpatches.common.base.Supplier; import com.google_voltpatches.common.base.Suppliers; import com.google_voltpatches.common.collect.ImmutableList; import com.google_voltpatches.common.collect.ImmutableMap; import com.google_voltpatches.common.collect.Sets; import com.google_voltpatches.common.util.concurrent.ListenableFuture; import com.google_voltpatches.common.util.concurrent.ListenableFutureTask; import com.google_voltpatches.common.util.concurrent.ListeningExecutorService; import com.google_voltpatches.common.util.concurrent.MoreExecutors; import com.google_voltpatches.common.util.concurrent.SettableFuture; import jsr166y.LinkedTransferQueue; public class CoreUtils { public static final int SMALL_STACK_SIZE = 1024 * 256; public static final int MEDIUM_STACK_SIZE = 1024 * 512; public static volatile Runnable m_threadLocalDeallocator = new Runnable() { @Override public void run() { } }; public static final ExecutorService SAMETHREADEXECUTOR = new ExecutorService() { @Override public void execute(Runnable command) { if (command == null) throw new NullPointerException(); command.run(); } @Override public void shutdown() { throw new UnsupportedOperationException(); } @Override public List<Runnable> shutdownNow() { throw new UnsupportedOperationException(); } @Override public boolean isShutdown() { return false; } @Override public boolean isTerminated() { return false; } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return true; } @Override public <T> Future<T> submit(Callable<T> task) { Preconditions.checkNotNull(task); FutureTask<T> retval = new FutureTask<T>(task); retval.run(); return retval; } @Override public <T> Future<T> submit(Runnable task, T result) { Preconditions.checkNotNull(task); FutureTask<T> retval = new FutureTask<T>(task, result); retval.run(); return retval; } @Override public Future<?> submit(Runnable task) { Preconditions.checkNotNull(task); FutureTask<Object> retval = new FutureTask<Object>(task, null); retval.run(); return retval; } @Override public <T> List<Future<T>> invokeAll( Collection<? extends Callable<T>> tasks) throws InterruptedException { Preconditions.checkNotNull(tasks); List<Future<T>> retval = new ArrayList<Future<T>>(tasks.size()); for (Callable<T> c : tasks) { FutureTask<T> ft = new FutureTask<T>(c); retval.add(new FutureTask<T>(c)); ft.run(); } return retval; } @Override public <T> List<Future<T>> invokeAll( Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { Preconditions.checkNotNull(tasks); Preconditions.checkNotNull(unit); final long end = System.nanoTime() + unit.toNanos(timeout); List<Future<T>> retval = new ArrayList<Future<T>>(tasks.size()); for (Callable<T> c : tasks) { retval.add(new FutureTask<T>(c)); } int size = retval.size(); int ii = 0; for (; ii < size; ii++) { @SuppressWarnings("rawtypes") FutureTask ft = (FutureTask)retval.get(ii); ft.run(); if (System.nanoTime() > end) break; } for (; ii < size; ii++) { @SuppressWarnings("rawtypes") FutureTask ft = (FutureTask)retval.get(ii); ft.cancel(false); } return retval; } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { T retval = null; Throwable lastException = null; boolean haveRetval = false; for (Callable<T> c : tasks) { try { retval = c.call(); haveRetval = true; break; } catch (Throwable t) { lastException = t; } } if (haveRetval) { return retval; } else { throw new ExecutionException(lastException); } } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { final long end = System.nanoTime() + unit.toNanos(timeout); T retval = null; Throwable lastException = null; boolean haveRetval = false; for (Callable<T> c : tasks) { if (System.nanoTime() > end) throw new TimeoutException(); try { retval = c.call(); haveRetval = true; break; } catch (Throwable t) { lastException = t; } } if (haveRetval) { return retval; } else { throw new ExecutionException(lastException); } } }; public static final ListeningExecutorService LISTENINGSAMETHREADEXECUTOR = new ListeningExecutorService() { @Override public void execute(Runnable command) { if (command == null) throw new NullPointerException(); command.run(); } @Override public void shutdown() { throw new UnsupportedOperationException(); } @Override public List<Runnable> shutdownNow() { throw new UnsupportedOperationException(); } @Override public boolean isShutdown() { return false; } @Override public boolean isTerminated() { return false; } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return true; } @Override public <T> ListenableFuture<T> submit(Callable<T> task) { Preconditions.checkNotNull(task); ListenableFutureTask<T> retval = ListenableFutureTask.create(task); retval.run(); return retval; } @Override public <T> ListenableFuture<T> submit(Runnable task, T result) { Preconditions.checkNotNull(task); ListenableFutureTask<T> retval = ListenableFutureTask.create(task, result); retval.run(); return retval; } @Override public ListenableFuture<?> submit(Runnable task) { Preconditions.checkNotNull(task); ListenableFutureTask<Object> retval = ListenableFutureTask.create(task, null); retval.run(); return retval; } @Override public <T> List<Future<T>> invokeAll( Collection<? extends Callable<T>> tasks) throws InterruptedException { Preconditions.checkNotNull(tasks); List<Future<T>> retval = new ArrayList<Future<T>>(tasks.size()); for (Callable<T> c : tasks) { FutureTask<T> ft = new FutureTask<T>(c); retval.add(new FutureTask<T>(c)); ft.run(); } return retval; } @Override public <T> List<Future<T>> invokeAll( Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { Preconditions.checkNotNull(tasks); Preconditions.checkNotNull(unit); final long end = System.nanoTime() + unit.toNanos(timeout); List<Future<T>> retval = new ArrayList<Future<T>>(tasks.size()); for (Callable<T> c : tasks) { retval.add(new FutureTask<T>(c)); } int size = retval.size(); int ii = 0; for (; ii < size; ii++) { @SuppressWarnings("rawtypes") FutureTask ft = (FutureTask)retval.get(ii); ft.run(); if (System.nanoTime() > end) break; } for (; ii < size; ii++) { @SuppressWarnings("rawtypes") FutureTask ft = (FutureTask)retval.get(ii); ft.cancel(false); } return retval; } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { T retval = null; Throwable lastException = null; boolean haveRetval = false; for (Callable<T> c : tasks) { try { retval = c.call(); haveRetval = true; break; } catch (Throwable t) { lastException = t; } } if (haveRetval) { return retval; } else { throw new ExecutionException(lastException); } } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { final long end = System.nanoTime() + unit.toNanos(timeout); T retval = null; Throwable lastException = null; boolean haveRetval = false; for (Callable<T> c : tasks) { if (System.nanoTime() > end) throw new TimeoutException(); try { retval = c.call(); haveRetval = true; break; } catch (Throwable t) { lastException = t; } } if (haveRetval) { return retval; } else { throw new ExecutionException(lastException); } } }; public static final ListenableFuture<Object> COMPLETED_FUTURE = new ListenableFuture<Object>() { @Override public void addListener(Runnable listener, Executor executor) { executor.execute(listener); } @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return true; } @Override public Object get() { return null; } @Override public Object get(long timeout, TimeUnit unit) { return null; } }; public static final Runnable EMPTY_RUNNABLE = new Runnable() { @Override public void run() {} }; /** * Get a single thread executor that caches its thread meaning that the thread will terminate * after keepAlive milliseconds. A new thread will be created the next time a task arrives and that will be kept * around for keepAlive milliseconds. On creation no thread is allocated, the first task creates a thread. * * Uses LinkedTransferQueue to accept tasks and has a small stack. */ public static ListeningExecutorService getCachedSingleThreadExecutor(String name, long keepAlive) { return MoreExecutors.listeningDecorator(new ThreadPoolExecutor( 0, 1, keepAlive, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), CoreUtils.getThreadFactory(null, name, SMALL_STACK_SIZE, false, null))); } /** * Create an unbounded single threaded executor */ public static ExecutorService getSingleThreadExecutor(String name) { ExecutorService ste = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), CoreUtils.getThreadFactory(null, name, SMALL_STACK_SIZE, false, null)); return ste; } public static ExecutorService getSingleThreadExecutor(String name, int size) { ExecutorService ste = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), CoreUtils.getThreadFactory(null, name, size, false, null)); return ste; } /** * Create an unbounded single threaded executor */ public static ListeningExecutorService getListeningSingleThreadExecutor(String name) { ExecutorService ste = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), CoreUtils.getThreadFactory(null, name, SMALL_STACK_SIZE, false, null)); return MoreExecutors.listeningDecorator(ste); } public static ListeningExecutorService getListeningSingleThreadExecutor(String name, int size) { ExecutorService ste = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), CoreUtils.getThreadFactory(null, name, size, false, null)); return MoreExecutors.listeningDecorator(ste); } /** * Create a bounded single threaded executor that rejects requests if more than capacity * requests are outstanding. */ public static ListeningExecutorService getBoundedSingleThreadExecutor(String name, int capacity) { LinkedBlockingQueue<Runnable> lbq = new LinkedBlockingQueue<Runnable>(capacity); ThreadPoolExecutor tpe = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, lbq, CoreUtils.getThreadFactory(name)); return MoreExecutors.listeningDecorator(tpe); } /* * Have shutdown actually means shutdown. Tasks that need to complete should use * futures. */ public static ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(String name, int poolSize, int stackSize) { ScheduledThreadPoolExecutor ses = new ScheduledThreadPoolExecutor(poolSize, getThreadFactory(null, name, stackSize, poolSize > 1, null)); ses.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); ses.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); return ses; } public static ListeningExecutorService getListeningExecutorService( final String name, final int threads) { return getListeningExecutorService(name, threads, new LinkedTransferQueue<Runnable>(), null); } public static ListeningExecutorService getListeningExecutorService( final String name, final int coreThreads, final int threads) { return getListeningExecutorService(name, coreThreads, threads, new LinkedTransferQueue<Runnable>(), null); } public static ListeningExecutorService getListeningExecutorService( final String name, final int threads, Queue<String> coreList) { return getListeningExecutorService(name, threads, new LinkedTransferQueue<Runnable>(), coreList); } public static ListeningExecutorService getListeningExecutorService( final String name, int threadsTemp, final BlockingQueue<Runnable> queue, final Queue<String> coreList) { if (coreList != null && !coreList.isEmpty()) { threadsTemp = coreList.size(); } final int threads = threadsTemp; if (threads < 1) { throw new IllegalArgumentException("Must specify > 0 threads"); } if (name == null) { throw new IllegalArgumentException("Name cannot be null"); } return MoreExecutors.listeningDecorator( new ThreadPoolExecutor(threads, threads, 0L, TimeUnit.MILLISECONDS, queue, getThreadFactory(null, name, SMALL_STACK_SIZE, threads > 1 ? true : false, coreList))); } public static ListeningExecutorService getListeningExecutorService( final String name, int coreThreadsTemp, int threadsTemp, final BlockingQueue<Runnable> queue, final Queue<String> coreList) { if (coreThreadsTemp < 0) { throw new IllegalArgumentException("Must specify >= 0 core threads"); } if (coreThreadsTemp > threadsTemp) { throw new IllegalArgumentException("Core threads must be <= threads"); } if (coreList != null && !coreList.isEmpty()) { threadsTemp = coreList.size(); if (coreThreadsTemp > threadsTemp) { coreThreadsTemp = threadsTemp; } } final int coreThreads = coreThreadsTemp; final int threads = threadsTemp; if (threads < 1) { throw new IllegalArgumentException("Must specify > 0 threads"); } if (name == null) { throw new IllegalArgumentException("Name cannot be null"); } return MoreExecutors.listeningDecorator( new ThreadPoolExecutor(coreThreads, threads, 1L, TimeUnit.MINUTES, queue, getThreadFactory(null, name, SMALL_STACK_SIZE, threads > 1 ? true : false, coreList))); } /** * Create a bounded thread pool executor. The work queue is synchronous and can cause * RejectedExecutionException if there is no available thread to take a new task. * @param maxPoolSize: the maximum number of threads to allow in the pool. * @param keepAliveTime: when the number of threads is greater than the core, this is the maximum * time that excess idle threads will wait for new tasks before terminating. * @param unit: the time unit for the keepAliveTime argument. * @param threadFactory: the factory to use when the executor creates a new thread. */ public static ThreadPoolExecutor getBoundedThreadPoolExecutor(int maxPoolSize, long keepAliveTime, TimeUnit unit, ThreadFactory tFactory) { return new ThreadPoolExecutor(0, maxPoolSize, keepAliveTime, unit, new SynchronousQueue<Runnable>(), tFactory); } /** * Create an ExceutorService that places tasks in an existing task queue for execution. Used * to create a bridge for using ListenableFutures in classes already built around a queue. * @param taskQueue : place to enqueue Runnables submitted to the service */ public static ExecutorService getQueueingExecutorService(final Queue<Runnable> taskQueue) { return new ExecutorService() { @Override public void execute(Runnable command) { taskQueue.offer(command); } @Override public void shutdown() { throw new UnsupportedOperationException(); } @Override public List<Runnable> shutdownNow() { throw new UnsupportedOperationException(); } @Override public boolean isShutdown() { return false; } @Override public boolean isTerminated() { return false; } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return true; } @Override public <T> Future<T> submit(Callable<T> task) { Preconditions.checkNotNull(task); FutureTask<T> retval = new FutureTask<T>(task); taskQueue.offer(retval); return retval; } @Override public <T> Future<T> submit(Runnable task, T result) { Preconditions.checkNotNull(task); FutureTask<T> retval = new FutureTask<T>(task, result); taskQueue.offer(retval); return retval; } @Override public Future<?> submit(Runnable task) { Preconditions.checkNotNull(task); ListenableFutureTask<Object> retval = ListenableFutureTask.create(task, null); taskQueue.offer(retval); return retval; } @Override public <T> List<Future<T>> invokeAll( Collection<? extends Callable<T>> tasks) throws InterruptedException { throw new UnsupportedOperationException(); } @Override public <T> List<Future<T>> invokeAll( Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { throw new UnsupportedOperationException(); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { throw new UnsupportedOperationException(); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { throw new UnsupportedOperationException(); } }; } public static ThreadFactory getThreadFactory(String name) { return getThreadFactory(name, SMALL_STACK_SIZE); } public static ThreadFactory getThreadFactory(String groupName, String name) { return getThreadFactory(groupName, name, SMALL_STACK_SIZE, true, null); } public static ThreadFactory getThreadFactory(String name, int stackSize) { return getThreadFactory(null, name, stackSize, true, null); } /** * Creates a thread factory that creates threads within a thread group if * the group name is given. The threads created will catch any unhandled * exceptions and log them to the HOST logger. * * @param groupName * @param name * @param stackSize * @return */ public static ThreadFactory getThreadFactory( final String groupName, final String name, final int stackSize, final boolean incrementThreadNames, final Queue<String> coreList) { ThreadGroup group = null; if (groupName != null) { group = new ThreadGroup(Thread.currentThread().getThreadGroup(), groupName); } final ThreadGroup finalGroup = group; return new ThreadFactory() { private final AtomicLong m_createdThreadCount = new AtomicLong(0); private final ThreadGroup m_group = finalGroup; @Override public synchronized Thread newThread(final Runnable r) { final String threadName = name + (incrementThreadNames ? " - " + m_createdThreadCount.getAndIncrement() : ""); String coreTemp = null; if (coreList != null && !coreList.isEmpty()) { coreTemp = coreList.poll(); } final String core = coreTemp; Runnable runnable = new Runnable() { @Override public void run() { if (core != null) { // Remove Affinity for now to make this dependency dissapear from the client. // Goal is to remove client dependency on this class in the medium term. //PosixJNAAffinity.INSTANCE.setAffinity(core); } try { r.run(); } catch (Throwable t) { new VoltLogger("HOST").error("Exception thrown in thread " + threadName, t); } finally { m_threadLocalDeallocator.run(); } } }; Thread t = new Thread(m_group, runnable, threadName, stackSize); t.setDaemon(true); return t; } }; } /** * Return the local hostname, if it's resolvable. If not, * return the IPv4 address on the first interface we find, if it exists. * If not, returns whatever address exists on the first interface. * @return the String representation of some valid host or IP address, * if we can find one; the empty string otherwise */ public static String getHostnameOrAddress() { final InetAddress addr = m_localAddressSupplier.get(); if (addr == null) return ""; return ReverseDNSCache.hostnameOrAddress(addr); } /** * Return the local [hostname]/ip string, attempting a cached lookup * to resolve the local hostname * @return The [hostname]/ip string representation for some valid local * interface, if we can find one; the empty string otherwise */ public static String getHostnameAndAddress() { return addressToString(m_localAddressSupplier.get()); } /** * Return [hostname]/ip string for the given {@link InetAddress}. This * simulates the value of {@link InetAddress#toString()}, except that it * does a cached lookup of the hostname * @param addr * @return If the provided address is not null, its [hostname]/ip * string representation; the empty string otherwise */ public static String addressToString(InetAddress addr) { if (addr == null) return ""; StringBuilder hostnameAndAddress = new StringBuilder(); String address = addr.getHostAddress(); String hostnameOrAddress = ReverseDNSCache.hostnameOrAddress(addr); if (!hostnameOrAddress.equals(address)) { hostnameAndAddress.append(hostnameOrAddress); } hostnameAndAddress.append('/').append(address); return hostnameAndAddress.toString(); } private static final Supplier<InetAddress> m_localAddressSupplier = Suppliers.memoizeWithExpiration(new Supplier<InetAddress>() { @Override public InetAddress get() { try { final InetAddress addr = InetAddress.getLocalHost(); return addr; } catch (UnknownHostException e) { try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); if (interfaces == null) { return null; } NetworkInterface intf = interfaces.nextElement(); Enumeration<InetAddress> addresses = intf.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (address instanceof Inet4Address) { return address; } } addresses = intf.getInetAddresses(); if (addresses.hasMoreElements()) { return addresses.nextElement(); } return null; } catch (SocketException e1) { return null; } } } }, 1, TimeUnit.DAYS); /** * Return the local IP address, if it's resolvable. If not, * return the IPv4 address on the first interface we find, if it exists. * If not, returns whatever address exists on the first interface. * @return the String representation of some valid host or IP address, * if we can find one; the empty string otherwise */ public static InetAddress getLocalAddress() { return m_localAddressSupplier.get(); } public static long getHSIdFromHostAndSite(int host, int site) { long HSId = site; HSId = (HSId << 32) + host; return HSId; } public static int getHostIdFromHSId(long HSId) { return (int) (HSId & 0xffffffff); } public static Set<Integer> getHostIdsFromHSIDs(Collection<Long> hsids) { Set<Integer> hosts = Sets.newHashSet(); for (Long id : hsids) { hosts.add(getHostIdFromHSId(id)); } return hosts; } public static String hsIdToString(long hsId) { return Integer.toString((int)hsId) + ":" + Integer.toString((int)(hsId >> 32)); } public static void hsIdToString(long hsId, StringBuilder sb) { sb.append((int)hsId).append(":").append((int)(hsId >> 32)); } public static String hsIdCollectionToString(Collection<Long> ids) { List<String> idstrings = new ArrayList<String>(); for (Long id : ids) { idstrings.add(hsIdToString(id)); } // Easy hack, sort hsIds lexically. Collections.sort(idstrings); StringBuilder sb = new StringBuilder(); boolean first = false; for (String id : idstrings) { if (!first) { first = true; } else { sb.append(", "); } sb.append(id); } return sb.toString(); } public static int getSiteIdFromHSId(long siteId) { return (int)(siteId>>32); } public static <K,V> ImmutableMap<K, ImmutableList<V>> unmodifiableMapCopy(Map<K, List<V>> m) { ImmutableMap.Builder<K, ImmutableList<V>> builder = ImmutableMap.builder(); for (Map.Entry<K, List<V>> e : m.entrySet()) { builder.put(e.getKey(), ImmutableList.<V>builder().addAll(e.getValue()).build()); } return builder.build(); } public static byte[] urlToBytes(String url) { if (url == null) { return null; } try { // get the URL/path for the deployment and prep an InputStream InputStream input = null; try { URL inputURL = new URL(url); input = inputURL.openStream(); } catch (MalformedURLException ex) { // Invalid URL. Try as a file. try { input = new FileInputStream(url); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } catch (IOException ioex) { throw new RuntimeException(ioex); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte readBytes[] = new byte[1024 * 8]; while (true) { int read = input.read(readBytes); if (read == -1) { break; } baos.write(readBytes, 0, read); } return baos.toByteArray(); } catch (Exception e) { throw new RuntimeException(e); } } public static String throwableToString(Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.flush(); return sw.toString(); } public static String hsIdKeyMapToString(Map<Long, ?> m) { StringBuilder sb = new StringBuilder(); sb.append('{'); boolean first = true; for (Map.Entry<Long, ?> entry : m.entrySet()) { if (!first) sb.append(", "); first = false; sb.append(CoreUtils.hsIdToString(entry.getKey())); sb.append("->").append(entry.getValue()); } sb.append('}'); return sb.toString(); } public static String hsIdValueMapToString(Map<?, Long> m) { StringBuilder sb = new StringBuilder(); sb.append('{'); boolean first = true; for (Map.Entry<?, Long> entry : m.entrySet()) { if (!first) sb.append(", "); first = false; sb.append(entry.getKey()).append("->"); sb.append(CoreUtils.hsIdToString(entry.getValue())); } sb.append('}'); return sb.toString(); } public static String hsIdMapToString(Map<Long, Long> m) { StringBuilder sb = new StringBuilder(); sb.append('{'); boolean first = true; for (Map.Entry<Long, Long> entry : m.entrySet()) { if (!first) sb.append(", "); first = false; sb.append(CoreUtils.hsIdToString(entry.getKey())).append(" -> "); sb.append(CoreUtils.hsIdToString(entry.getValue())); } sb.append('}'); return sb.toString(); } public static int availableProcessors() { return Math.max(1, Runtime.getRuntime().availableProcessors()); } public static final class RetryException extends Exception { private static final long serialVersionUID = 3651804109132974056L; public RetryException() {}; public RetryException(Throwable cause) { super(cause); } public RetryException(String errMsg) { super(errMsg); } } /** * A helper for retrying tasks asynchronously returns a settable future * that can be used to attempt to cancel the task. * * The first executor service is used to schedule retry attempts * The second is where the task will be subsmitted for execution * If the two services are the same only the scheduled service is used * * @param maxAttempts It is the number of total attempts including the first one. * If the value is 0, that means there is no limit. */ public static final<T> ListenableFuture<T> retryHelper( final ScheduledExecutorService ses, final ExecutorService es, final Callable<T> callable, final long maxAttempts, final long startInterval, final TimeUnit startUnit, final long maxInterval, final TimeUnit maxUnit) { SettableFuture<T> future = SettableFuture.create(); retryHelper(ses, es, callable, maxAttempts, startInterval, startUnit, maxInterval, maxUnit, future); return future; } public static final <T> void retryHelper(final ScheduledExecutorService ses, final ExecutorService es, final Callable<T> callable, final long maxAttempts, final long startInterval, final TimeUnit startUnit, final long maxInterval, final TimeUnit maxUnit, final SettableFuture<T> future) { Preconditions.checkNotNull(maxUnit); Preconditions.checkNotNull(startUnit); Preconditions.checkArgument(startUnit.toMillis(startInterval) >= 1); Preconditions.checkArgument(maxUnit.toMillis(maxInterval) >= 1); Preconditions.checkNotNull(callable); Preconditions.checkNotNull(future); /* * Base case with no retry, attempt the task once */ es.execute(new Runnable() { @Override public void run() { try { future.set(callable.call()); } catch (RetryException e) { //Now schedule a retry retryHelper(ses, es, callable, maxAttempts - 1, startInterval, startUnit, maxInterval, maxUnit, 0, future); } catch (Exception e) { future.setException(e); } } }); } private static final <T> void retryHelper( final ScheduledExecutorService ses, final ExecutorService es, final Callable<T> callable, final long maxAttempts, final long startInterval, final TimeUnit startUnit, final long maxInterval, final TimeUnit maxUnit, final long ii, final SettableFuture<T> retval) { if (maxAttempts == 0) { retval.setException(new RuntimeException("Max attempts reached")); return; } long intervalMax = maxUnit.toMillis(maxInterval); final long interval = Math.min(intervalMax, startUnit.toMillis(startInterval) * 2); ses.schedule(new Runnable() { @Override public void run() { Runnable task = new Runnable() { @Override public void run() { if (retval.isCancelled()) return; try { retval.set(callable.call()); } catch (RetryException e) { retryHelper(ses, es, callable, maxAttempts - 1, interval, TimeUnit.MILLISECONDS, maxInterval, maxUnit, ii + 1, retval); } catch (Exception e3) { retval.setException(e3); } } }; if (ses == es) task.run(); else es.execute(task); } }, interval, TimeUnit.MILLISECONDS); } public static final long LOCK_SPIN_MICROSECONDS = TimeUnit.MICROSECONDS.toNanos(Integer.getInteger("LOCK_SPIN_MICROS", 0)); /* * Spin on a ReentrantLock before blocking. Default behavior is not to spin. */ public static void spinLock(ReentrantLock lock) { if (LOCK_SPIN_MICROSECONDS > 0) { long nanos = -1; for (;;) { if (lock.tryLock()) return; if (nanos == -1) { nanos = System.nanoTime(); } else if (System.nanoTime() - nanos > LOCK_SPIN_MICROSECONDS) { lock.lock(); return; } } } else { lock.lock(); } } public static final long QUEUE_SPIN_MICROSECONDS = TimeUnit.MICROSECONDS.toNanos(Integer.getInteger("QUEUE_SPIN_MICROS", 0)); /* * Spin polling a blocking queue before blocking. Default behavior is not to spin. */ public static <T> T queueSpinTake(BlockingQueue<T> queue) throws InterruptedException { if (QUEUE_SPIN_MICROSECONDS > 0) { T retval = null; long nanos = -1; for (;;) { if ((retval = queue.poll()) != null) return retval; if (nanos == -1) { nanos = System.nanoTime(); } else if (System.nanoTime() - nanos > QUEUE_SPIN_MICROSECONDS) { return queue.take(); } } } else { return queue.take(); } } /* * This method manages the whitelist of all acceptable Throwables (and Exceptions) that * will not cause the Server harm if they occur while invoking the initializer of a stored * procedure or while calling the stored procedure. */ public static final boolean isStoredProcThrowableFatalToServer(Throwable th) { if (th instanceof LinkageError || th instanceof AssertionError) { return false; } if (th instanceof Exception) { return false; } return true; }; /** * Utility method to sort the keys and values of a map by their value. */ public static <K extends Comparable< ? super K>,V extends Comparable< ? super V>> List<Entry<K,V>> sortKeyValuePairByValue(Map<K,V> map) { List<Map.Entry<K,V>> entries = new ArrayList<Map.Entry<K,V>>(map.entrySet()); Collections.sort(entries, new Comparator<Map.Entry<K,V>>() { @Override public int compare(Entry<K,V> o1, Entry<K,V> o2) { if (!o1.getValue().equals(o2.getValue())) { return (o1.getValue()).compareTo(o2.getValue()); } return o1.getKey().compareTo(o2.getKey()); } } ); return entries; } /** * @return the process pid if is available from the JVM's runtime bean */ public static String getPID() { String name = ManagementFactory.getRuntimeMXBean().getName(); int atat = name.indexOf('@'); if (atat == -1) { return "(unavailable)"; } return name.substring(0, atat); } /** * Log (to the fatal logger) the list of ports in use. * Uses "lsof -i" internally. * * @param log VoltLogger used to print output or warnings. */ public static synchronized void printPortsInUse(VoltLogger log) { try { /* * Don't do DNS resolution, don't use names for port numbers */ ProcessBuilder pb = new ProcessBuilder("lsof", "-i", "-n", "-P"); pb.redirectErrorStream(true); Process p = pb.start(); java.io.InputStreamReader reader = new java.io.InputStreamReader(p.getInputStream()); java.io.BufferedReader br = new java.io.BufferedReader(reader); String str = br.readLine(); log.fatal("Logging ports that are bound for listening, " + "this doesn't include ports bound by outgoing connections " + "which can also cause a failure to bind"); log.fatal("The PID of this process is " + getPID()); if (str != null) { log.fatal(str); } while((str = br.readLine()) != null) { if (str.contains("LISTEN")) { log.fatal(str); } } } catch (Exception e) { log.fatal("Unable to list ports in use at this time."); } } /** * Print beautiful logs surrounded by stars. This function handles long lines (wrapping * into multiple lines) as well. Please use only spaces and newline characters for word * separation. * @param vLogger The provided VoltLogger * @param msg Message to be printed out beautifully * @param level Logging level */ public static void printAsciiArtLog(VoltLogger vLogger, String msg, Level level) { if (vLogger == null || msg == null || level == Level.OFF) { return; } // 80 stars in a line StringBuilder starBuilder = new StringBuilder(); for (int i = 0; i < 80; i++) { starBuilder.append("*"); } String stars = starBuilder.toString(); // Wrap the message with 2 lines of stars switch (level) { case DEBUG: vLogger.debug(stars); vLogger.debug("* " + msg + " *"); vLogger.debug(stars); break; case WARN: vLogger.warn(stars); vLogger.warn("* " + msg + " *"); vLogger.warn(stars); break; case ERROR: vLogger.error(stars); vLogger.error("* " + msg + " *"); vLogger.error(stars); break; case FATAL: vLogger.fatal(stars); vLogger.fatal("* " + msg + " *"); vLogger.fatal(stars); break; case INFO: vLogger.info(stars); vLogger.info("* " + msg + " *"); vLogger.info(stars); break; case TRACE: vLogger.trace(stars); vLogger.trace("* " + msg + " *"); vLogger.trace(stars); break; default: break; } } public static void logProcedureInvocation(VoltLogger log, String userName, String where, String procedure) { String msg = "User " + userName + " from " + where + " issued a " + procedure; if ("@PrepareShutdown".equals(procedure)) printAsciiArtLog(log, msg, Level.INFO); else log.info(msg); } // Utility method to figure out if this is a test case. Various junit targets in // build.xml set a environment variable to give us a hint public static boolean isJunitTest() { //check os environment variable if ("true".equalsIgnoreCase(System.getenv().get("VOLT_JUSTATEST"))){ return true; } //check system variable return "true".equalsIgnoreCase(System.getProperty("VOLT_JUSTATEST")); } }
package application; import static java.time.Clock.systemDefaultZone; import static java.util.Arrays.asList; import java.time.Clock; import time.SocialTimeClock; import timeline.SocialNetwork; import timeline.TimelineService; import timeline.Timelines; import commands.Commands; import commands.FollowCommand; import commands.ObservableCommand; import commands.PostCommand; import commands.TimelineCommand; import commands.WallCommand; public class ApplicationFactory { private SocialTimeClock clock; private TimelineService timelineService; private Commands commands; private SocialNetworkingConsole console; private SocialNetworkingApplication application; public static ApplicationFactory standardConfiguration() { return new ApplicationFactory().withClock(systemDefaultZone()).withConsole(new SocialNetworkingConsole()); } private ApplicationFactory() { } public ApplicationFactory withClock(Clock clock) { this.clock = new SocialTimeClock(clock); timelineService = new TimelineService(new Timelines(), new SocialNetwork(), this.clock); commands = new Commands(asList( new PostCommand(timelineService), new ObservableCommand(new TimelineCommand(timelineService)), new FollowCommand(timelineService), new ObservableCommand(new WallCommand(timelineService)) )); application = new SocialNetworkingApplication(this.clock, commands); return this; } public ApplicationFactory withCommands(Commands commands) { this.commands = commands; return this; } public ApplicationFactory withConsole(SocialNetworkingConsole console) { this.console = console; return this; } public Commands getCommands() { return commands; } public SocialTimeClock getClock() { return clock; } public SocialNetworkingConsole getConsole() { return console; } public ApplicationFactory withApplication(SocialNetworkingApplication application) { this.application = application; return this; } public SocialNetworkingApplication getApplication() { return application; } }
package org.voltdb; import java.io.IOException; import java.nio.ByteBuffer; import java.util.*; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.apache.cassandra_voltpatches.MurmurHash3; import org.voltcore.utils.Pair; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Maps; import com.google.common.collect.UnmodifiableIterator; import org.voltdb.utils.CompressionService; /** * A hashinator that uses Murmur3_x64_128 to hash values and a consistent hash ring * to pick what partition to route a particular value. */ public class ElasticHashinator extends TheHashinator { public static int DEFAULT_TOTAL_TOKENS = Integer.parseInt(System.getProperty("ELASTIC_TOTAL_TOKENS", "16384")); private static final sun.misc.Unsafe unsafe; private static sun.misc.Unsafe getUnsafe() { try { return sun.misc.Unsafe.getUnsafe(); } catch (SecurityException se) { try { return java.security.AccessController.doPrivileged (new java.security .PrivilegedExceptionAction<sun.misc.Unsafe>() { public sun.misc.Unsafe run() throws Exception { java.lang.reflect.Field f = sun.misc .Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); return (sun.misc.Unsafe) f.get(null); }}); } catch (java.security.PrivilegedActionException e) { throw new RuntimeException("Could not initialize intrinsics", e.getCause()); } } } static { sun.misc.Unsafe unsafeTemp = null; try { unsafeTemp = getUnsafe(); } catch (Exception e) { e.printStackTrace(); } unsafe = unsafeTemp; } /** * Tokens on the ring. A value hashes to a token if the token is the first value <= * the value's hash */ private final Supplier<ImmutableSortedMap<Integer, Integer>> m_tokensMap; /* * Pointer to an array of integers containing the tokens and partitions. Even values are tokens and odd values * are partition ids. */ private final long m_tokens; private final int m_tokenCount; private final Supplier<byte[]> m_configBytes; private final Supplier<byte[]> m_configBytesSupplier = Suppliers.memoize(new Supplier<byte[]>() { @Override public byte[] get() { return toBytes(); } }); private final Supplier<byte[]> m_cookedBytes; private final Supplier<byte[]> m_cookedBytesSupplier = Suppliers.memoize(new Supplier<byte[]>() { @Override public byte[] get() { return toCookedBytes(); } }); private final Supplier<Long> m_signature = Suppliers.memoize(new Supplier<Long>() { @Override public Long get() { return TheHashinator.computeConfigurationSignature(m_configBytes.get()); } }); @Override public int pHashToPartition(VoltType type, Object obj) { return hashinateBytes(valueToBytes(obj)); } /** * The serialization format is big-endian and the first value is the number of tokens * Construct the hashinator from a binary description of the ring. * followed by the token values where each token value consists of the 8-byte position on the ring * and and the 4-byte partition id. All values are signed. * @param configBytes config data * @param cooked compressible wire serialization format if true */ public ElasticHashinator(byte configBytes[], boolean cooked) { Pair<Long, Integer> p = (cooked ? updateCooked(configBytes) : updateRaw(configBytes)); m_tokens = p.getFirst(); m_tokenCount = p.getSecond(); m_configBytes = !cooked ? Suppliers.ofInstance(configBytes) : m_configBytesSupplier; m_cookedBytes = cooked ? Suppliers.ofInstance(configBytes) : m_cookedBytesSupplier; m_tokensMap = Suppliers.memoize(new Supplier<ImmutableSortedMap<Integer, Integer>>() { @Override public ImmutableSortedMap<Integer, Integer> get() { ImmutableSortedMap.Builder<Integer, Integer> builder = ImmutableSortedMap.naturalOrder(); for (int ii = 0; ii < m_tokenCount; ii++) { final long ptr = m_tokens + (ii * 8); final int token = unsafe.getInt(ptr); final int partition = unsafe.getInt(ptr + 4); builder.put(token, partition); } return builder.build(); } }); } /** * Private constructor to initialize a hashinator with known tokens. Used for adding/removing * partitions from existing hashinator. * @param tokens */ private ElasticHashinator(SortedMap<Integer, Integer> tokens) { m_tokensMap = Suppliers.ofInstance(ImmutableSortedMap.copyOf(tokens)); Preconditions.checkArgument(m_tokensMap.get().firstEntry().getKey().equals(Integer.MIN_VALUE)); m_tokens = unsafe.allocateMemory(8 * tokens.size()); int ii = 0; for (Map.Entry<Integer, Integer> e : tokens.entrySet()) { final long ptr = m_tokens + (ii * 8); unsafe.putInt(ptr, e.getKey()); unsafe.putInt(ptr + 4, e.getValue()); ii++; } m_tokenCount = tokens.size(); m_configBytes = m_configBytesSupplier; m_cookedBytes = m_cookedBytesSupplier; } public static byte[] addPartitions(TheHashinator oldHashinator, int partitionsToAdd) { Preconditions.checkArgument(oldHashinator instanceof ElasticHashinator); ElasticHashinator oldElasticHashinator = (ElasticHashinator) oldHashinator; Buckets buckets = new Buckets(oldElasticHashinator.m_tokensMap.get()); buckets.addPartitions(partitionsToAdd); return new ElasticHashinator(buckets.getTokens()).getConfigBytes(); } /** * Convenience method for generating a deterministic token distribution for the ring based * on a given partition count and tokens per partition. Each partition will have N tokens * placed randomly on the ring. */ public static byte[] getConfigureBytes(int partitionCount, int tokenCount) { Preconditions.checkArgument(partitionCount > 0); Preconditions.checkArgument(tokenCount > partitionCount); Buckets buckets = new Buckets(partitionCount, tokenCount); ElasticHashinator hashinator = new ElasticHashinator(buckets.getTokens()); return hashinator.getConfigBytes(); } /** * Serializes the configuration into bytes, also updates the currently cached m_configBytes. * @return The byte[] of the current configuration. */ private byte[] toBytes() { ByteBuffer buf = ByteBuffer.allocate(4 + (m_tokenCount * 8)); buf.putInt(m_tokenCount); int lastToken = Integer.MIN_VALUE; for (int ii = 0; ii < m_tokenCount; ii++) { final long ptr = m_tokens + (ii * 8); final int token = unsafe.getInt(ptr); Preconditions.checkArgument(token >= lastToken); lastToken = token; final int pid = unsafe.getInt(ptr + 4); buf.putInt(token); buf.putInt(pid); } return buf.array(); } /** * For a given a value hash, find the token that corresponds to it. This will * be the first token <= the value hash, or if the value hash is < the first token in the ring, * it wraps around to the last token in the ring closest to Long.MAX_VALUE */ public int partitionForToken(int hash) { long token = getTokenPtr(hash); return unsafe.getInt(token + 4); } /** * Get all the tokens on the ring. */ public ImmutableSortedMap<Integer, Integer> getTokens() { return m_tokensMap.get(); } /** * Add the given tokens to the ring and generate the new hashinator. The current hashinator is not changed. * @param tokensToAdd Tokens to add as a map of tokens to partitions * @return The new hashinator */ public ElasticHashinator addTokens(Map<Integer, Integer> tokensToAdd) { ImmutableSortedMap.Builder<Integer, Integer> b = ImmutableSortedMap.naturalOrder(); for (Map.Entry<Integer, Integer> e : m_tokensMap.get().entrySet()) { if (tokensToAdd.containsKey(e.getKey())) { continue; } b.put(e.getKey(), e.getValue()); } b.putAll(tokensToAdd); return new ElasticHashinator(b.build()); } @Override public int pHashinateLong(long value) { if (value == Long.MIN_VALUE) return 0; return partitionForToken(MurmurHash3.hash3_x64_128(value)); } @Override public int pHashinateBytes(byte[] bytes) { ByteBuffer buf = ByteBuffer.wrap(bytes); final int token = MurmurHash3.hash3_x64_128(buf, 0, bytes.length, 0); return partitionForToken(token); } @Override protected HashinatorConfig pGetCurrentConfig() { return new HashinatorConfig(HashinatorType.ELASTIC, m_configBytes.get(), m_tokens, m_tokenCount) { //Store a reference to this hashinator in the config so it doesn't get GCed and release //the pointer to the config data that is off heap private final ElasticHashinator myHashinator = ElasticHashinator.this; }; } /** * Find the predecessors of the given partition on the ring. This method runs in linear time, * use with caution when the set of partitions is large. * @param partition * @return The map of tokens to partitions that are the predecessors of the given partition. * If the given partition doesn't exist or it's the only partition on the ring, the * map will be empty. */ @Override public Map<Integer, Integer> pPredecessors(int partition) { Map<Integer, Integer> predecessors = new TreeMap<Integer, Integer>(); UnmodifiableIterator<Map.Entry<Integer,Integer>> iter = m_tokensMap.get().entrySet().iterator(); Set<Integer> pTokens = new HashSet<Integer>(); while (iter.hasNext()) { Map.Entry<Integer, Integer> next = iter.next(); if (next.getValue() == partition) { pTokens.add(next.getKey()); } } for (Integer token : pTokens) { Map.Entry<Integer, Integer> predecessor = null; if (token != null) { predecessor = m_tokensMap.get().headMap(token).lastEntry(); // If null, it means partition is the first one on the ring, so predecessor // should be the last entry on the ring because it wraps around. if (predecessor == null) { predecessor = m_tokensMap.get().lastEntry(); } } if (predecessor != null && predecessor.getValue() != partition) { predecessors.put(predecessor.getKey(), predecessor.getValue()); } } return predecessors; } /** * Find the predecessor of the given token on the ring. * @param partition The partition that maps to the given token * @param token The token on the ring * @return The predecessor of the given token. */ @Override public Pair<Integer, Integer> pPredecessor(int partition, int token) { Integer partForToken = m_tokensMap.get().get(token); if (partForToken != null && partForToken == partition) { Map.Entry<Integer, Integer> predecessor = m_tokensMap.get().headMap(token).lastEntry(); if (predecessor == null) { predecessor = m_tokensMap.get().lastEntry(); } if (predecessor.getKey() != token) { return Pair.of(predecessor.getKey(), predecessor.getValue()); } else { // given token is the only one on the ring, umpossible throw new RuntimeException("There is only one token on the hash ring"); } } else { // given token doesn't map to partition throw new IllegalArgumentException("The given token " + token + " does not map to partition " + partition); } } /** * This runs in linear time with respect to the number of tokens on the ring. */ @Override public Map<Integer, Integer> pGetRanges(int partition) { Map<Integer, Integer> ranges = new TreeMap<Integer, Integer>(); Integer first = null; // start of the very first token on the ring Integer start = null; // start of a range UnmodifiableIterator<Map.Entry<Integer,Integer>> iter = m_tokensMap.get().entrySet().iterator(); // Iterate through the token map to find the ranges assigned to // the given partition while (iter.hasNext()) { Map.Entry<Integer, Integer> next = iter.next(); int token = next.getKey(); int pid = next.getValue(); if (first == null) { first = token; } // if start is not null, there's an open range, now is // the time to close it. // else there is no open range, keep on going. if (start != null) { //Range end is inclusive so do token - 1 ranges.put(start, token - 1); start = null; } if (pid == partition) { // if start is null, there's no open range, start one. start = token; } } // if there is an open range when we get here // It is the last token which implicity ends at the next max value if (start != null) { assert first != null; ranges.put(start, Integer.MAX_VALUE); } return ranges; } /** * Returns the configuration signature */ @Override public long pGetConfigurationSignature() { return m_signature.get(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(" Token ").append(" Partition\n"); for (Map.Entry<Integer, Integer> entry : m_tokensMap.get().entrySet()) { sb.append(String.format("[%11d => %9d]\n", entry.getKey(), entry.getValue())); } return sb.toString(); } /** * Returns raw config bytes. * @return config bytes */ @Override public byte[] getConfigBytes() { return m_configBytes.get(); } /** * Returns compressed config bytes. * @return config bytes * @throws IOException */ private byte[] toCookedBytes() { // Allocate for a int pair per token/partition ID entry, plus a size. ByteBuffer buf = ByteBuffer.allocate(4 + (m_tokenCount * 8)); buf.putInt(m_tokenCount); // Keep tokens and partition ids separate to aid compression. for (int zz = 3; zz >= 0; zz int lastToken = Integer.MIN_VALUE; for (int ii = 0; ii < m_tokenCount; ii++) { int token = unsafe.getInt(m_tokens + (ii * 8)); Preconditions.checkArgument(token >= lastToken); lastToken = token; token = token >>> (zz * 8); token = token & 0xFF; buf.put((byte)token); } } for (int ii = 0; ii < m_tokenCount; ii++) { buf.putInt(unsafe.getInt(m_tokens + (ii * 8) + 4)); } try { return CompressionService.gzipBytes(buf.array()); } catch (IOException e) { throw new RuntimeException("Failed to compress bytes", e); } } /** * Update from raw config bytes. * token-1/partition-1 * token-2/partition-2 * ... * tokens are 8 bytes * @param configBytes raw config data * @return token/partition map */ private Pair<Long, Integer> updateRaw(byte configBytes[]) { ByteBuffer buf = ByteBuffer.wrap(configBytes); int numEntries = buf.getInt(); if (numEntries < 0) { throw new RuntimeException("Bad elastic hashinator config"); } long tokens = unsafe.allocateMemory(8 * numEntries); int lastToken = Integer.MIN_VALUE; for (int ii = 0; ii < numEntries; ii++) { long ptr = tokens + (ii * 8); final int token = buf.getInt(); Preconditions.checkArgument(token >= lastToken); lastToken = token; unsafe.putInt(ptr, token); final int partitionId = buf.getInt(); unsafe.putInt(ptr + 4, partitionId); } return Pair.of(tokens, numEntries); } private long getTokenPtr(int hash) { int min = 0; int max = m_tokenCount - 1; while (min <= max) { int mid = (min + max) >>> 1; final long midPtr = m_tokens + (8 * mid); int midval = unsafe.getInt(midPtr); if (midval < hash) { min = mid + 1; } else if (midval > hash) { max = mid - 1; } else { return midPtr; } } return m_tokens + (min - 1) * 8; } /** * Update from optimized (cooked) wire format. * token-1 token-2 ... * partition-1 partition-2 ... * tokens are 4 bytes * @param compressedData optimized and compressed config data * @return token/partition map */ private Pair<Long, Integer> updateCooked(byte[] compressedData) { // Uncompress (inflate) the bytes. byte[] cookedBytes; try { cookedBytes = CompressionService.gunzipBytes(compressedData); } catch (IOException e) { throw new RuntimeException("Unable to decompress elastic hashinator data."); } int numEntries = (cookedBytes.length >= 4 ? ByteBuffer.wrap(cookedBytes).getInt() : 0); int tokensSize = 4 * numEntries; int partitionsSize = 4 * numEntries; if (numEntries <= 0 || cookedBytes.length != 4 + tokensSize + partitionsSize) { throw new RuntimeException("Bad elastic hashinator cooked config size."); } long tokens = unsafe.allocateMemory(8 * numEntries); ByteBuffer tokenBuf = ByteBuffer.wrap(cookedBytes, 4, tokensSize); ByteBuffer partitionBuf = ByteBuffer.wrap(cookedBytes, 4 + tokensSize, partitionsSize); int tokensArray[] = new int[numEntries]; for (int zz = 3; zz >= 0; zz for (int ii = 0; ii < numEntries; ii++) { int value = tokenBuf.get(); value = (value << (zz * 8)) & (0xFF << (zz * 8)); tokensArray[ii] = (tokensArray[ii] | value); } } int lastToken = Integer.MIN_VALUE; for (int ii = 0; ii < numEntries; ii++) { int token = tokensArray[ii]; Preconditions.checkArgument(token >= lastToken); lastToken = token; long ptr = tokens + (ii * 8); unsafe.putInt(ptr, token); final int partitionId = partitionBuf.getInt(); unsafe.putInt(ptr + 4, partitionId); } return Pair.of(tokens, numEntries); } /** * Return (cooked) bytes optimized for serialization. * @return optimized config bytes */ @Override public byte[] getCookedBytes() { return m_cookedBytes.get(); } @Override public HashinatorType getConfigurationType() { return TheHashinator.HashinatorType.ELASTIC; } @Override public void finalize() { unsafe.freeMemory(m_tokens); } }
package by.post.control.ui; import by.post.control.db.DbControl; import by.post.control.db.DbController; import by.post.control.db.Queries; import by.post.data.Column; import by.post.ui.ChoiceColumnTypeDialog; import by.post.ui.ConfirmationDialog; import by.post.ui.InputDialog; import javafx.collections.FXCollections; import javafx.scene.control.*; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; /** * @author Dmitriy V.Yefremov */ public class TableEditor { private DbControl dbControl = null; private TableView mainTable; private static TableEditor instance = new TableEditor(); private static final Logger logger = LogManager.getLogger(TableEditor.class); private TableEditor() { } public static TableEditor getInstance() { return instance; } public void setTable(TableView mainTable) { this.mainTable = mainTable; } /** * Add new row to the table */ public void addRow() throws IOException { int size = mainTable.getColumns().size(); if (size > 0) { int selectedIndex = mainTable.getSelectionModel().getSelectedIndex(); mainTable.getItems().add(++selectedIndex, FXCollections.observableArrayList(Collections.nCopies(size, "New value."))); mainTable.getSelectionModel().select(selectedIndex, null); } else { Optional<String> result = new InputDialog("\tPlease, specify\n the number of columns!", "1", true).showAndWait(); if (result.isPresent()) { Integer num = Integer.valueOf(result.get()); List<Column> columns = new ArrayList<>(num); for (int i = 0; i < num; i++) { columns.add(new Column("NEW", 0)); } mainTable.getColumns().addAll(new TableDataResolver().getColumns(columns)); } } mainTable.refresh(); } /** * Remove selected row from the table */ public void removeRow() { mainTable.getItems().remove(mainTable.getSelectionModel().getSelectedItem()); } /** * Save changes after table editing * *@param name */ public void save(String name) { Optional<ButtonType> result = new ConfirmationDialog("Save changes for table: " + name).showAndWait(); if (result.get() == ButtonType.OK) { logger.log(Level.INFO, "Save changes for table: " + name); } } /** * Add table in the tree * * @param tableTree */ public void addTable(TreeView tableTree) { Optional<String> result = new InputDialog("Please, write table name!", "New table", false).showAndWait(); if (result.isPresent()) { String name = result.get(); dbControl = DbController.getInstance(); dbControl.update(Queries.createTable(name)); tableTree.getRoot().getChildren().add(new TreeItem<>(name)); tableTree.refresh(); logger.log(Level.INFO, "Added new table: " + name); } } /** * Delete table from the tree * * @param tableTree */ public void deleteTable(TreeView tableTree) { Optional<ButtonType> result = new ConfirmationDialog().showAndWait(); if (result.get() == ButtonType.OK) { TreeItem item = (TreeItem) tableTree.getSelectionModel().getSelectedItem(); String name = item.getValue().toString(); dbControl = DbController.getInstance(); dbControl.update(Queries.deleteTable(name)); tableTree.getRoot().getChildren().remove(item); tableTree.refresh(); logger.log(Level.INFO, "Deleted table: " + name); } } /** * @param id */ public void changeColumnName(String id) { TableColumn column = (TableColumn) mainTable.getColumns().get(Integer.valueOf(id)); Optional<String> result = new InputDialog("Set new name of column", "New", false).showAndWait(); if (result.isPresent()) { column.setText(result.get()); } } /** * @param id */ public void changeColumnType(String id) { Optional<String> result = new ChoiceColumnTypeDialog().showAndWait(); if (result.isPresent()) { System.out.println(result.get()); } } }
package ch.ethz.geco.gecko; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.encoder.PatternLayoutEncoder; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.LoggingEvent; import ch.qos.logback.core.rolling.RollingFileAppender; import ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP; import ch.qos.logback.core.rolling.TimeBasedRollingPolicy; import ch.qos.logback.core.util.FileSize; import discord4j.core.event.EventDispatcher; import discord4j.core.event.domain.UserUpdateEvent; import discord4j.core.event.domain.guild.MemberJoinEvent; import discord4j.core.event.domain.guild.MemberLeaveEvent; import discord4j.core.event.domain.guild.MemberUpdateEvent; import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.core.event.domain.message.MessageDeleteEvent; import discord4j.core.event.domain.message.MessageUpdateEvent; import discord4j.core.object.entity.Member; import discord4j.core.object.entity.Message; import discord4j.core.object.entity.User; import org.slf4j.LoggerFactory; import java.nio.charset.StandardCharsets; /** * This class is used to track important user behaviour so that we have * a proof of what happened in case there is a conflict. */ class EventLogger { private static final Logger logger = (Logger) LoggerFactory.getLogger("EventLogger"); private static final RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>(); /** * Attaches the event logger to the given {@link EventDispatcher}, such that the logger can listen to the events of interest. * * @param dispatcher The {@link EventDispatcher} to attach to. */ static void attachTo(EventDispatcher dispatcher) { // Setup logger LoggerContext contextBase = new LoggerContext(); contextBase.start(); TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new TimeBasedRollingPolicy<>(); SizeAndTimeBasedFNATP<ILoggingEvent> sizeAndTimeBasedFNATP = new SizeAndTimeBasedFNATP<>(); sizeAndTimeBasedFNATP.setContext(contextBase); sizeAndTimeBasedFNATP.setTimeBasedRollingPolicy(rollingPolicy); sizeAndTimeBasedFNATP.setMaxFileSize(FileSize.valueOf("20MB")); rollingPolicy.setContext(contextBase); rollingPolicy.setParent(appender); rollingPolicy.setFileNamePattern("data/log/events_%d{yy-MM-dd}.%i.log"); rollingPolicy.setMaxHistory(7); rollingPolicy.setTimeBasedFileNamingAndTriggeringPolicy(sizeAndTimeBasedFNATP); PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder(); patternLayoutEncoder.setContext(contextBase); patternLayoutEncoder.setParent(appender); patternLayoutEncoder.setCharset(StandardCharsets.UTF_8); patternLayoutEncoder.setPattern("%date{dd/MM/yy HH:mm:ss} | %msg%n"); appender.setFile("data/log/events.log"); appender.setRollingPolicy(rollingPolicy); appender.setEncoder(patternLayoutEncoder); appender.setContext(contextBase); appender.setImmediateFlush(true); rollingPolicy.start(); sizeAndTimeBasedFNATP.start(); patternLayoutEncoder.start(); appender.start(); // Message events dispatcher.on(MessageCreateEvent.class).subscribe(EventLogger::handleMessageCreate); dispatcher.on(MessageDeleteEvent.class).subscribe(EventLogger::handleMessageDelete); dispatcher.on(MessageUpdateEvent.class).subscribe(EventLogger::handleMessageUpdate); // User events dispatcher.on(UserUpdateEvent.class).subscribe(EventLogger::handleUserUpdate); dispatcher.on(MemberUpdateEvent.class).subscribe(EventLogger::handleMemberUpdate); dispatcher.on(MemberJoinEvent.class).subscribe(EventLogger::handleMemberJoin); dispatcher.on(MemberLeaveEvent.class).subscribe(EventLogger::handleMemberLeave); } static void close() { appender.stop(); appender.getEncoder().stop(); ((TimeBasedRollingPolicy) appender.getRollingPolicy()).getTimeBasedFileNamingAndTriggeringPolicy().stop(); appender.getRollingPolicy().stop(); } private static void handleMessageCreate(MessageCreateEvent event) { if (event.getMessage().getAuthor().isEmpty()) return; String msg = "MSG_CREATE | MSG_ID: " + event.getMessage().getId().asString() + " | " + "USER_ID: " + event.getMessage().getAuthor().get().getId().asString() + " | " + event.getMessage().getContent().orElse("-"); log(msg); } private static void handleMessageDelete(MessageDeleteEvent event) { String msg = "MSG_DELETE | MSG_ID: " + event.getMessageId().asString(); log(msg); } private static void handleMessageUpdate(MessageUpdateEvent event) { String msg = "MSG_UPDATE | MSG_ID: " + event.getMessageId().asString() + " | "; Message newMessage = event.getMessage().block(); if (newMessage == null) return; if (event.getOld().isPresent()) { msg += event.getOld().get().getContent().orElse("-") + "\n -> " + newMessage.getContent().orElse("-"); } else { msg += event.getCurrentContent().orElse("-"); } log(msg); } private static void handleUserUpdate(UserUpdateEvent event) { if (event.getOld().isEmpty()) // We can only track updates if there is an old user return; User oldUser = event.getOld().get(); User newUser = event.getCurrent(); if (!oldUser.getUsername().equals(newUser.getUsername()) || !oldUser.getDiscriminator().equals(newUser.getDiscriminator())) { String msg = "USER_UPDATE | USER_ID: " + newUser.getId().asString() + " | " + oldUser.getUsername() + "#" + oldUser.getDiscriminator() + " -> " + newUser.getUsername() + "#" + newUser.getDiscriminator(); log(msg); } } private static void handleMemberUpdate(MemberUpdateEvent event) { if (event.getOld().isEmpty()) return; // FIXME: undesired behaviour if nickname is actually "N/A" String oldNick = event.getOld().get().getNickname().orElse("N/A"); String newNick = event.getCurrentNickname().orElse("N/A"); if (!oldNick.equals(newNick)) { String msg = "MEMBER_UPDATE | USER_ID: " + event.getMemberId().asString() + " | " + oldNick + " -> " + newNick; log(msg); } } private static void handleMemberJoin(MemberJoinEvent event) { Member member = event.getMember(); String msg = "MEMBER_JOIN | USER_ID: " + member.getId() + " | " + member.getDisplayName() + "#" + member.getDiscriminator() + " joined the server!"; log(msg); } private static void handleMemberLeave(MemberLeaveEvent event) { User member = event.getUser(); String msg = "MEMBER_LEAVE | USER_ID: " + member.getId() + " | " + member.getUsername() + "#" + member.getDiscriminator() + " left the server!"; log(msg); } private static void log(String msg) { appender.doAppend(new LoggingEvent("", logger, Level.INFO, msg, null, null)); } }
package co.phoenixlab.discord; import co.phoenixlab.discord.api.DiscordApiClient; import co.phoenixlab.discord.api.entities.Channel; import co.phoenixlab.discord.api.entities.Message; import co.phoenixlab.discord.api.entities.User; import java.time.Duration; import java.time.Instant; import java.util.StringJoiner; public class Commands { private Instant registerTime; private final CommandDispatcher adminCommandDispatcher; public Commands(VahrhedralBot bot) { adminCommandDispatcher = new CommandDispatcher(bot, ""); } public void register(CommandDispatcher dispatcher) { registerAdminCommands(); dispatcher.registerAlwaysActiveCommand("admin", this::admin, "Administrative commands"); dispatcher.registerCommand("admins", this::listAdmins, "List admins"); dispatcher.registerCommand("info", this::info, "Display information about the caller or the provided name, if present. @Mentions and partial front " + "matches are supported"); registerTime = Instant.now(); } private void registerAdminCommands() { adminCommandDispatcher.registerAlwaysActiveCommand("start", this::adminStart, "Start bot"); adminCommandDispatcher.registerAlwaysActiveCommand("stop", this::adminStop, "Stop bot"); adminCommandDispatcher.registerAlwaysActiveCommand("status", this::adminStatus, "Bot status"); adminCommandDispatcher.registerAlwaysActiveCommand("kill", this::adminKill, "Kill the bot (terminate app)"); adminCommandDispatcher.registerAlwaysActiveCommand("blacklist", this::adminBlacklist, "Prints the blacklist, or blacklists the given user. Supports @mention and partial front matching"); adminCommandDispatcher.registerAlwaysActiveCommand("pardon", this::adminPardon, "Pardons the given user. Supports @mention and partial front matching"); } private void adminKill(MessageContext context, String args) { context.getApiClient().sendMessage("Sudoku time, bye", context.getMessage().getChannelId()); System.exit(0); } private void adminStart(MessageContext context, String args) { DiscordApiClient apiClient = context.getApiClient(); CommandDispatcher mainDispatcher = context.getBot().getMainCommandDispatcher(); if (mainDispatcher.active().compareAndSet(false, true)) { apiClient.sendMessage("Bot started", context.getMessage().getChannelId()); } else { apiClient.sendMessage("Bot was already started", context.getMessage().getChannelId()); } } private void adminStop(MessageContext context, String args) { DiscordApiClient apiClient = context.getApiClient(); CommandDispatcher mainDispatcher = context.getBot().getMainCommandDispatcher(); if (mainDispatcher.active().compareAndSet(true, false)) { apiClient.sendMessage("Bot stopped", context.getMessage().getChannelId()); } else { apiClient.sendMessage("Bot was already stopped", context.getMessage().getChannelId()); } } private void adminStatus(MessageContext context, String args) { DiscordApiClient apiClient = context.getApiClient(); CommandDispatcher mainDispatcher = context.getBot().getMainCommandDispatcher(); Instant now = Instant.now(); Duration duration = Duration.between(registerTime, now); long s = duration.getSeconds(); String uptime = String.format("%d:%02d:%02d:%02d", s / 86400, (s / 3600) % 24, (s % 3600) / 60, (s % 60)); Runtime r = Runtime.getRuntime(); String memory = String.format("%,dMB Used %,dMB Free %,dMB Max", (r.maxMemory() - r.freeMemory()) / 1024 / 1024, r.freeMemory() / 1024 / 1024, r.maxMemory() / 1024 / 1024); String response = String.format("**Status:** %s\n**Servers:** %d\n**Uptime:** %s\n**Memory:** `%s`", mainDispatcher.active().get() ? "Running" : "Stopped", apiClient.getServers().size(), uptime, memory); apiClient.sendMessage(response, context.getMessage().getChannelId()); } private void adminBlacklist(MessageContext context, String args) { DiscordApiClient apiClient = context.getApiClient(); VahrhedralBot bot = context.getBot(); if (args.isEmpty()) { StringJoiner joiner = new StringJoiner(", "); bot.getConfig().getBlacklist().stream(). map(apiClient::getUserById). filter(user -> user != null). map(User::getUsername). forEach(joiner::add); String res = joiner.toString(); if (res.isEmpty()) { res = "None"; } apiClient.sendMessage("Blacklisted users: " + res, context.getMessage().getChannelId()); return; } User user = findUser(context, args); if (user == null) { apiClient.sendMessage("Unable to find user", context.getMessage().getChannelId()); return; } if (bot.getConfig().getAdmins().contains(user.getId())) { apiClient.sendMessage("Cannot blacklist an admin", context.getMessage().getChannelId()); return; } bot.getConfig().getBlacklist().add(user.getId()); bot.saveConfig(); apiClient.sendMessage(String.format("`%s` has been blacklisted", user.getUsername()), context.getMessage().getChannelId()); } private void adminPardon(MessageContext context, String args) { DiscordApiClient apiClient = context.getApiClient(); if (args.isEmpty()) { apiClient.sendMessage("Please specify a user", context.getMessage().getChannelId()); return; } User user = findUser(context, args); if (user == null) { apiClient.sendMessage("Unable to find user", context.getMessage().getChannelId()); return; } boolean removed = context.getBot().getConfig().getBlacklist().remove(user.getId()); context.getBot().saveConfig(); if (removed) { apiClient.sendMessage(String.format("`%s` has been pardoned", user.getUsername()), context.getMessage().getChannelId()); } else { apiClient.sendMessage(String.format("`%s` was not blacklisted", user.getUsername()), context.getMessage().getChannelId()); } } private User findUser(MessageContext context, String username) { Message message = context.getMessage(); User user = null; Channel channel = context.getApiClient().getChannelById(message.getChannelId()); // Attempt to find the given user // If the user is @mentioned, try that first if (message.getMentions() != null && message.getMentions().length > 0) { user = message.getMentions()[0]; } else { User temp = context.getApiClient().findUser(username, channel.getParent()); if (temp != null) { user = temp; } } return user; } private void admin(MessageContext context, String args) { if (!context.getBot().getConfig().getAdmins().contains(context.getMessage().getAuthor().getId())) { return; } Message original = context.getMessage(); adminCommandDispatcher.handleCommand(new Message(original.getAuthor(), original.getChannelId(), args, original.getChannelId(), original.getMentions(), original.getTime())); } private void listAdmins(MessageContext context, String s) { DiscordApiClient apiClient = context.getApiClient(); VahrhedralBot bot = context.getBot(); StringJoiner joiner = new StringJoiner(", "); bot.getConfig().getAdmins().stream(). map(apiClient::getUserById). filter(user -> user != null). map(User::getUsername). forEach(joiner::add); String res = joiner.toString(); if (res.isEmpty()) { res = "None"; } apiClient.sendMessage("Admins: " + res, context.getMessage().getChannelId()); } private void info(MessageContext context, String args) { Message message = context.getMessage(); Configuration config = context.getBot().getConfig(); User user; if (!args.isEmpty()) { user = findUser(context, args); } else { user = message.getAuthor(); } if (user == null) { context.getApiClient().sendMessage("Unable to find user. Try typing their name EXACTLY or" + " @mention them instead", message.getChannelId()); } else { String avatar = (user.getAvatar() == null ? "N/A" : user.getAvatarUrl().toExternalForm()); String response = String.format("**Username:** %s\n**ID:** %s:%s\n%s%s**Avatar:** %s", user.getUsername(), user.getId(), user.getDiscriminator(), config.getBlacklist().contains(user.getId()) ? "**Blacklisted**\n" : "", config.getAdmins().contains(user.getId()) ? "**Bot Administrator**\n" : "", avatar); context.getApiClient().sendMessage(response, message.getChannelId()); } } }
package com.airbnb.plog.utils; import io.netty.buffer.ByteBuf; public final class ByteBufs { public static byte[] toByteArray(ByteBuf buf) { final int length = buf.readableBytes(); final byte[] payload = new byte[length]; buf.getBytes(0, payload, 0, length); return payload; } }
package org.opennms.features.vaadin.nodemaps.internal; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import com.github.wolfie.refresher.Refresher; import java.util.concurrent.ConcurrentHashMap; import org.opennms.core.criteria.CriteriaBuilder; import org.opennms.features.geocoder.Coordinates; import org.opennms.features.geocoder.GeocoderException; import org.opennms.features.geocoder.GeocoderService; import org.opennms.features.geocoder.TemporaryGeocoderException; import org.opennms.features.topology.api.geo.GeoAssetProvider; import org.opennms.features.topology.api.topo.AbstractVertex; import org.opennms.features.topology.api.topo.VertexRef; import org.opennms.netmgt.dao.api.AlarmDao; import org.opennms.netmgt.dao.api.AssetRecordDao; import org.opennms.netmgt.dao.api.NodeDao; import org.opennms.netmgt.model.OnmsAlarm; import org.opennms.netmgt.model.OnmsAssetRecord; import org.opennms.netmgt.model.OnmsGeolocation; import org.opennms.netmgt.model.OnmsNode; import org.opennms.netmgt.model.OnmsSeverity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionOperations; /** * @author Marcus Hellberg (marcus@vaadin.com) */ public class MapWidgetComponent extends NodeMapComponent implements GeoAssetProvider { private class DynamicUpdateRefresher implements Refresher.RefreshListener{ @Override public void refresh(Refresher refresher) { refreshView(); } } private static final long serialVersionUID = -6364929103619363239L; private static final Logger LOG = LoggerFactory.getLogger(MapWidgetComponent.class); private final ScheduledExecutorService m_executor = Executors.newScheduledThreadPool(1, new ThreadFactory() { @Override public Thread newThread(final Runnable runnable) { return new Thread(runnable, "NodeMapUpdater-Thread"); } }); private NodeDao m_nodeDao; private AssetRecordDao m_assetDao; private AlarmDao m_alarmDao; private GeocoderService m_geocoderService; private TransactionOperations m_transaction; private Boolean m_aclsEnabled = false; private Map<Integer,NodeEntry> m_activeNodes = new HashMap<Integer,NodeEntry>(); public NodeDao getNodeDao() { return m_nodeDao; } public void setNodeDao(final NodeDao nodeDao) { m_nodeDao = nodeDao; } public AssetRecordDao getAssetRecordDao() { return m_assetDao; } public void setAssetRecordDao(final AssetRecordDao assetDao) { m_assetDao = assetDao; } public AlarmDao getAlarmDao() { return m_alarmDao; } public void setAlarmDao(final AlarmDao alarmDao) { m_alarmDao = alarmDao; } public GeocoderService getGeocoderService() { return m_geocoderService; } public void setGeocoderService(final GeocoderService geocoderService) { m_geocoderService = geocoderService; } public void setTransactionOperations(final TransactionOperations tx) { m_transaction = tx; } public void init() { m_executor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { refreshNodeData(); } }, 0, 5, TimeUnit.MINUTES); checkAclsEnabled(); setupAutoRefresher(); } private void checkAclsEnabled() { String aclsPropValue = System.getProperty("org.opennms.web.aclsEnabled"); m_aclsEnabled = aclsPropValue != null && aclsPropValue.equals("true"); } public void setupAutoRefresher(){ Refresher refresher = new Refresher(); refresher.setRefreshInterval(5000); //Pull every two seconds for view updates refresher.addListener(new DynamicUpdateRefresher()); addExtension(refresher); } public void refresh() { refreshView(); } @Override public Collection<VertexRef> getNodesWithCoordinates() { final List<VertexRef> nodes = new ArrayList<VertexRef>(); for (final Map.Entry<Integer,NodeEntry> entry : m_activeNodes.entrySet()) { nodes.add(new AbstractVertex("nodes", entry.getKey().toString(), entry.getValue().getNodeLabel())); } return nodes; } private void refreshView() { if(m_aclsEnabled) { Map<Integer, String> nodes = getNodeDao().getAllLabelsById(); Map<Integer, NodeEntry> aclOnlyNodes = new HashMap<Integer, NodeEntry>(); for (Integer nodeId : nodes.keySet()) { if (m_activeNodes.containsKey(nodeId)) aclOnlyNodes.put(nodeId, m_activeNodes.get(nodeId)); } showNodes(aclOnlyNodes); } else { showNodes(m_activeNodes); } } private void refreshNodeData() { if (getNodeDao() == null) { LOG.warn("No node DAO! Can't refresh node data."); return; } LOG.debug("Refreshing node data."); final CriteriaBuilder cb = new CriteriaBuilder(OnmsNode.class); cb.alias("assetRecord", "asset"); cb.orderBy("id").asc(); final List<OnmsAssetRecord> updatedAssets = new ArrayList<OnmsAssetRecord>(); final Map<Integer, NodeEntry> nodes = new HashMap<Integer, NodeEntry>(); m_transaction.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(final TransactionStatus status) { for (final OnmsNode node : getNodeDao().findMatching(cb.toCriteria())) { LOG.trace("processing node {}", node.getId()); // pass 1: get the nodes with asset data final OnmsAssetRecord assets = node.getAssetRecord(); if (assets != null && assets.getGeolocation() != null) { final OnmsGeolocation geolocation = assets.getGeolocation(); final String addressString = geolocation.asAddressString(); final Float longitude = geolocation.getLongitude(); final Float latitude = geolocation.getLatitude(); if (longitude != null && latitude != null) { if (longitude == Float.NEGATIVE_INFINITY || latitude == Float.NEGATIVE_INFINITY) { // we've already cached it as bad, skip it continue; } else { // we've already got good coordinates, return the node nodes.put(node.getId(), new NodeEntry(node)); continue; } } else if (addressString == null || "".equals(addressString)) { // no real address info, skip it continue; } else { LOG.debug("Node {} has an asset record with address \"{}\", but no coordinates.", new Object[]{node.getId(), addressString}); final Coordinates coordinates = getCoordinates(addressString); if (coordinates == null) { LOG.debug("Node {} has an asset record with address, but we were unable to find valid coordinates.", node.getId()); continue; } geolocation.setLongitude(coordinates.getLongitude()); geolocation.setLatitude(coordinates.getLatitude()); updatedAssets.add(assets); if (coordinates.getLongitude() == Float.NEGATIVE_INFINITY || coordinates.getLatitude() == Float.NEGATIVE_INFINITY) { // we got bad coordinates LOG.debug("Node {} has an asset record with address, but we were unable to find valid coordinates.", node.getId()); continue; } else { // valid coordinates, add to the list nodes.put(node.getId(), new NodeEntry(node)); } } } else { // no asset information } } int lastId = -1; int unackedCount = 0; // pass 2: get alarm data for anything that's been grabbed from the DB if (!nodes.isEmpty()) { LOG.debug("getting alarms for nodes"); final CriteriaBuilder ab = new CriteriaBuilder(OnmsAlarm.class); ab.alias("node", "node"); ab.ge("severity", OnmsSeverity.WARNING); ab.in("node.id", nodes.keySet()); ab.orderBy("node.id").asc(); ab.orderBy("severity").desc(); for (final OnmsAlarm alarm : getAlarmDao().findMatching(ab.toCriteria())) { final int nodeId = alarm.getNodeId(); LOG.debug("nodeId = {}, lastId = {}, unackedCount = {}", new Object[]{nodeId, lastId, unackedCount}); if (nodeId != lastId) { LOG.debug(" setting severity for node {} to {}", new Object[]{nodeId, alarm.getSeverity().getLabel()}); final NodeEntry nodeEntry = nodes.get(nodeId); nodeEntry.setSeverity(alarm.getSeverity()); if (lastId != -1) { nodeEntry.setUnackedCount(unackedCount); unackedCount = 0; } } if (alarm.getAckUser() == null) { unackedCount++; } lastId = nodeId; } } if (lastId != -1) { nodes.get(lastId).setUnackedCount(unackedCount); } // pass 3: save any asset updates to the database LOG.debug("saving {} updated asset records to the database", updatedAssets.size()); for (final OnmsAssetRecord asset : updatedAssets) { getAssetRecordDao().saveOrUpdate(asset); } } }); m_activeNodes = nodes; } /** * Given an address, return the coordinates for that address. * * @param address the complete address, in a format a geolocator can understand * @return the coordinates for the given address */ private Coordinates getCoordinates(final String address) { Coordinates coordinates = null; try { coordinates = getGeocoderService().getCoordinates(address); if (coordinates == null) { coordinates = new Coordinates(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY); } } catch (final TemporaryGeocoderException e) { LOG.debug("Failed to find coordinates for address '{}' due to a temporary failure.", address); } catch (final GeocoderException e) { LOG.debug("Failed to find coordinates for address '{}'.", address); coordinates = new Coordinates(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY); } return coordinates; } public void setSearchString(final String searchString) { getState().searchString = searchString; } }
package com.bina.varsim.util; import com.bina.varsim.types.ChrString; import com.bina.varsim.types.FlexSeq; import com.bina.varsim.types.VCFInfo; import com.bina.varsim.types.variant.Variant; import com.bina.varsim.types.variant.alt.Alt; import com.google.common.base.Splitter; import org.apache.log4j.Logger; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.rmi.UnexpectedException; import java.util.*; import static com.bina.varsim.constants.Constant.MAX_WARNING_REPEAT; import static com.bina.varsim.types.VCFInfo.getType; public class VCFparser extends GzFileParser<Variant> { public static final String DEFAULT_FILTER = "."; //default value for many columns private final static Logger log = Logger.getLogger(VCFparser.class.getName()); private Random random = null; private int sampleIndex = -1; private String sampleId = null; private boolean isPassFilterRequired = false; private boolean chromLineSeen = false; private int illegalPhasingWarningCount = 0; public VCFparser() { sampleIndex = 10; // the first sample } /** * Reads a VCF file line by line * * @param fileName VCF file, doesn't have to be sorted or indexed * @param id ID of individual, essentially selects a column, null to use first ID column * @param pass If true, only output pass lines */ public VCFparser(String fileName, String id, boolean pass, Random rand) { this(new File(fileName), id, pass, rand); log.info("Reading " + fileName); } public VCFparser(File file, String id, boolean pass, Random rand) { random = rand; try { bufferedReader = new BufferedReader(new InputStreamReader(decompressStream(file))); readLine(); } catch (Exception ex) { log.error("Can't open file " + file.getName()); log.error(ex.toString()); } sampleId = id; isPassFilterRequired = pass; if (sampleId == null) { sampleIndex = 10; // the first sample } } /** * Reads a VCF file line by line * * @param fileName VCF file, doesn't have to be sorted or indexed * @param id ID of individual, essentially selects a column, null to use first ID column * @param pass If true, only output pass lines */ public VCFparser(String fileName, String id, boolean pass) { this(fileName, id, pass, null); } public VCFparser(File file, String id, boolean pass) { this(file, id, pass, null); } //TODO: remove unused constructor /** * Reads a VCF file line by line, if there are multiple individuals, takes the first one * * @param fileName VCF file, doesn't have to be sorted or indexed * @param pass If true, only output pass lines */ public VCFparser(String fileName, boolean pass, Random rand) { this(fileName, null, pass, rand); } //TODO: remove unused constructor /** * Reads a VCF file line by line, if there are multiple individuals, takes the first one * * @param fileName VCF file, doesn't have to be sorted or indexed * @param pass If true, only output pass lines */ public VCFparser(String fileName, boolean pass) { this(fileName, null, pass, null); } public VCFparser(File file, boolean pass) { this(file, null, pass, null); } /** * finds where "GT" or similar is in the VCF string so that the genotype can be read * * @param record The column in VCF that contains GT, CN, etc.. * @param key The key to be found "GT" or "CN" or other * @return the index of the key */ private int getFormatKeyIndex(final String record, final String key) { StringTokenizer words = new StringTokenizer(record, ":"); int ret = 0; while (words.hasMoreTokens()) { if (words.nextToken().equals(key)) return ret; else ret++; } return -1; } /** * Takes genotype string and splits it into alleles, supports a maximum of two * * @param geno genotype string corresponding to the GT tag (field index 9) * @param vals Return the genotypes read here [paternal,maternal] * @param chr chromosome we are dealing with, some are haploid, need to assign parent * @return true if the variant is phased */ boolean isPhased(String geno, byte[] vals, ChrString chr) { boolean isPhased = false; geno = geno.trim(); boolean strangePhase = false; if (geno.matches("^[0-9]+$")) { // phase is only a single number, for haploid chromosomes byte val = (byte) Integer.parseInt(geno); if (chr.isX()) { vals[1] = val; // maternal isPhased = true; } else if (chr.isY()) { vals[0] = val; // paternal isPhased = true; } else if (chr.isMT()) { vals[1] = val; isPhased = true; } else { vals[0] = vals[1] = val; } } else if (geno.length() >= 3) { // this is the case where phase looks like "1|0" or "10|4" String[] ll = geno.split("[\\|/]"); int c1 = -1; int c2 = -1; char phasing = '/'; if (ll.length == 2) { try { c1 = Integer.parseInt(ll[0]); c2 = Integer.parseInt(ll[1]); phasing = geno.charAt(ll[0].length()); } catch (NumberFormatException e) { strangePhase = true; } } else { strangePhase = true; } if (c1 >= 0 && c2 >= 0) { vals[0] = (byte) c1; vals[1] = (byte) c2; if (phasing == '|') { isPhased = true; } } else { strangePhase = true; } } else { strangePhase = true; } if (strangePhase) { if (illegalPhasingWarningCount < MAX_WARNING_REPEAT) { log.warn("Unrecognized phasing '" + geno + "'."); illegalPhasingWarningCount++; if (illegalPhasingWarningCount == MAX_WARNING_REPEAT) { log.warn("Reached max number of warnings (" + MAX_WARNING_REPEAT + ") for unrecognized phasing. No more warnings."); } } vals[0] = -1; vals[1] = -1; isPhased = false; } return isPhased; } /** * takes a line from a VCF file, parse it, * return a Variant object * * right now the meta-info lines (beginning with ##) are * not tied with data line parsing. This will be corrected * in the future (perhaps with help of HTSJDK). * @param line * @return */ public Variant processLine(String line) throws UnexpectedException { // try to determine the column we should read for the genotype Iterable<String> toks = Splitter.on('\t').split(line); if (line.startsWith(" if (sampleId != null && line.startsWith("#CHROM")) { chromLineSeen = true; int index = 0; for (String tok : toks) { index++; if (tok.equals(sampleId)) sampleIndex = index; } } else if (sampleId == null) { sampleIndex = 10; // the first sample } return null; } // If we cannot determine, then use the first one if (sampleIndex < 0 && !chromLineSeen) { sampleIndex = 10; } else if (sampleIndex < 0) { sampleIndex = 10; log.warn("Warning!!! ID (" + sampleId + ") does not exist... "); } int index = 0, genotypeIndex = -1, copyNumberIndex = -1; int pos = -1; ChrString chr = null; String REF = "", FILTER = "", ALT = "", variantId = ""; String phase = ".", copyNumber = "0/0", infoString = "", FORMAT; String[] sampleInfo; for (String tok : toks) { index++; if (index == 1) { // Parsing chromosome chr = new ChrString(tok); } else if (index == 2) // Parsing position pos = Integer.parseInt(tok); else if (index == 3) // Parsing position variantId = tok; else if (index == 4) // Parsing reference allele REF = tok; else if (index == 5) // Parsing alternative allele ALT = tok; else if (index == 7) // FILTER field FILTER = tok; else if (index == 8) // INFO field infoString = tok; else if (index == 9) { // Output format FORMAT = tok; genotypeIndex = getFormatKeyIndex(FORMAT, "GT"); copyNumberIndex = getFormatKeyIndex(FORMAT, "CN"); } else if (index == sampleIndex) { // phased or unphased genotype sampleInfo = tok.split(":"); if (genotypeIndex >= 0) { phase = sampleInfo[genotypeIndex]; } if (copyNumberIndex >= 0) { copyNumber = sampleInfo[copyNumberIndex]; } break; } } // unknown chromosome // TODO: throw an exception for unknown chromosome name if (chr == null) { log.warn("Bad chromosome name: " + line); return null; } if (isPassFilterRequired && !(FILTER.contains("PASS") || FILTER.equals(DEFAULT_FILTER))) { log.warn("line is filtered out: " + line); return null; // Filtered out } // parse the phased or unphased genotype byte[] genotypeArray = new byte[2]; // paternal-maternal boolean isGenotypePhased = isPhased(phase, genotypeArray, chr); if (genotypeIndex >= 0 && genotypeArray[0] == 0 && genotypeArray[1] == 0) { return null; // reference alleles... ignore them for now.... } if (!REF.matches("[ATCGN]+")) { log.warn("only ATCGN allowed for REF column"); return null; } // determine copy-number // TODO need to be able to deal with unphased copy-numbers? byte[] copyNumberArray = new byte[2]; // paternal-maternal boolean isCopyNumberPhased; if (copyNumberIndex >= 0) { isCopyNumberPhased = isPhased(copyNumber, copyNumberArray, chr); if (isCopyNumberPhased != isGenotypePhased) { // TODO maybe don't throw error, this is not standard format // anyways log.warn("Inconsistent copy number:"); log.warn("line: " + line); return null; } } // Upper casing REF = REF.toUpperCase(); ALT = ALT.toUpperCase(); String deletedReference = ""; VCFInfo info = new VCFInfo(infoString); /*if symbolic alleles are present, make sure # of alleles equal # of SV lengths. For non-symbolic alleles, SV lengths are not really used or checked. */ /*!!!!!!!!!! CAUTION: we assume symbolic alleles are not mixed with non-symbolic alleles. */ if (ALT.indexOf('<') != -1) { String[] alternativeAlleles = ALT.split(","); int[] svlen = info.getValue("SVLEN", int[].class); if (alternativeAlleles.length != svlen.length) { throw new IllegalArgumentException("ERROR: number of symbolic alleles is unequal to number of SV lengths.\n" + line); } for (int i = 0; i < alternativeAlleles.length; i++) { if (!alternativeAlleles[i].startsWith("<")) { throw new IllegalArgumentException("ERROR: symbolic alleles are mixed with non-symbolic alleles.\n" + line); } } } Alt[] alts = string2Alt(ALT); if (alts[0].getSymbolicAllele() != null) { int[] end = info.getValue("END", int[].class); //SVLEN for alternative allele length int[] svlen = info.getValue("SVLEN", int[].class); int[] end2 = info.getValue("END2", int[].class); int[] pos2 = info.getValue("POS2", int[].class); Boolean isinv = info.getValue("ISINV", Boolean.class); String[] traid = info.getValue("TRAID", String[].class); String[] chr2 = info.getValue("CHR2", String[].class); deletedReference = REF; byte[] refs = new byte[0]; pos++; //1-based start if (Alt.SVType.SVSubtype.TRA.equals(alts[0].getSymbolicAllele().getMinor())) { if (traid == null || traid.length == 0) { throw new IllegalArgumentException("ERROR: <*:TRA> must have TRAID in INFO field.\n" + line); } } //why no alts()? because it's not reference-based operation //alts() will save a deep copy of alts, rathern than reference, so we //cannot assign it until all changes are done. Variant.Builder template = new Variant.Builder().chr(chr).pos(pos). ref(refs).phase(genotypeArray).isPhased(isGenotypePhased). varId(variantId).filter(FILTER).refDeleted(deletedReference). randomNumberGenerator(random); if (alts[0].getSymbolicAllele().getMajor() == Alt.SVType.INV) { // inversion SV if (svlen.length > 0) { for (int i = 0; i < svlen.length; i++) { int alternativeAlleleLength = Math.max(Math.abs(svlen[i]), 1); alts[i].setSeq(new FlexSeq(FlexSeq.Type.INV, alternativeAlleleLength)); } // TODO this assumes only one alt return template.referenceAlleleLength(Math.abs(svlen[0])).alts(alts).build(); //TODO: this assumes only one alt, might not be true } else if (end != null && end.length > 0 && end[0] > 0) { //assume only one END int alternativeAlleleLength = Math.max(Math.abs(end[0] - pos + 1), 1); alts[0].setSeq(new FlexSeq(FlexSeq.Type.INV, alternativeAlleleLength)); return template.referenceAlleleLength(alternativeAlleleLength).alts(alts).build(); } else { log.error("No length information for INV:"); log.error(line); log.error("skipping..."); return null; } } else if (alts[0].getSymbolicAllele().getMajor() == Alt.SVType.DUP && ((alts[0].getSymbolicAllele().getMinor() != Alt.SVType.SVSubtype.TRA && alts[0].getSymbolicAllele().getMinor() != Alt.SVType.SVSubtype.ISP && info.getValue("POS2", getType("POS2")) == null) || alts[0].getSymbolicAllele().getMinor() == Alt.SVType.SVSubtype.TANDEM)) { if (svlen.length > 0) { for (int i = 0; i < svlen.length; i++) { // TODO this is temporary, how to encode copy number? int currentCopyNumber = 1; for (int j = 0; j < 2; j++) { if ((i + 1) == genotypeArray[j]) { /* if i = 0, genotype[0] = 1, genotype[1] = 1 copyNumberArray[0] = 3, copyNumberArray[1] = 2 then currentCopyNumber = 2. what does currentCopyNumber mean in real world? */ if (copyNumberArray[j] > 0) { currentCopyNumber = copyNumberArray[j]; } } } int alternativeAlleleLength = Math.max(Math.abs(svlen[i]), 1); alts[i].setSeq(new FlexSeq(FlexSeq.Type.TANDEM_DUP, alternativeAlleleLength, currentCopyNumber)); } return template.referenceAlleleLength(Math.abs(svlen[0])).alts(alts).build(); //TODO: this assumes only one alt, which might not be true } else if (end != null && end.length > 0 && end[0] > 0) { int alternativeAlleleLength = Math.max(Math.abs(end[0] - pos + 1), 1); alts[0].setSeq(new FlexSeq(FlexSeq.Type.TANDEM_DUP, alternativeAlleleLength, Math.max( copyNumberArray[0], copyNumberArray[1]))); return template.referenceAlleleLength(alternativeAlleleLength).alts(alts).build(); } else { log.error("No length information for DUP:TANDEM:"); log.error(line); log.error("skipping..."); return null; } } else if (alts[0].getSymbolicAllele().getMajor() == Alt.SVType.INS) { // insertion SV if (svlen.length > 0) { for (int i = 0; i < svlen.length; i++) { //if SVLEN=0, we take it as infinitely long int alternativeAlleleLength = svlen[i] == 0 ? Integer.MAX_VALUE : Math.max(Math.abs(svlen[i]), 1); alts[i].setSeq(new FlexSeq(FlexSeq.Type.INS, alternativeAlleleLength)); } return template.referenceAlleleLength(0).alts(alts).build(); //TODO, remove this as END should be equal to POS for insertion } else if (end != null && end.length > 0 && end[0] > 0) { int alternativeAlleleLength = Math.max(Math.abs(end[0] - pos), 1); alts[0].setSeq(new FlexSeq(FlexSeq.Type.INS, alternativeAlleleLength)); return template.referenceAlleleLength(0).alts(alts).build(); } else { log.error("No length information for INS:"); log.error(line); log.error("skipping..."); return null; } } else if (alts[0].getSymbolicAllele().getMajor() == Alt.SVType.DEL) { // deletion SV (maybe part of a translocation) // but... we don't have the reference... so we add some random sequence? template = template.traid(traid == null ? null : traid[0]); if (svlen.length > 0) { for (int i = 0; i < svlen.length; i++) { // deletion has no alt if (Alt.SVType.SVSubtype.TRA == alts[i].getSymbolicAllele().getMinor()) { alts[i].setSeq(new FlexSeq(FlexSeq.Type.TRA_DEL, svlen[i])); } else { alts[i].setSeq(new FlexSeq(FlexSeq.Type.DEL, 0)); } } return template.alts(alts).referenceAlleleLength(Math.abs(svlen[0])).build(); } else if (end != null && end.length > 0 && end[0] > 0) { //END is just one value, whereas there could be multiple alternative alleles with different svlens //so END is in general not a good way to get lengths int alternativeAlleleLength = end[0] - pos + 1; if (Alt.SVType.SVSubtype.TRA == alts[0].getSymbolicAllele().getMinor()) { alts[0].setSeq(new FlexSeq(FlexSeq.Type.TRA_DEL, -alternativeAlleleLength)); } else { alts[0].setSeq(new FlexSeq(FlexSeq.Type.DEL, 0)); } return template.alts(alts).referenceAlleleLength(alternativeAlleleLength).build(); } else { log.error("No length information for DEL:"); log.error(line); log.error("skipping..."); return null; } //TODO major SVTYPE actually does not allow TRA } else if ( alts[0].getSymbolicAllele().getMajor() == Alt.SVType.DUP && (alts[0].getSymbolicAllele().getMinor() == Alt.SVType.SVSubtype.TRA || alts[0].getSymbolicAllele().getMinor() == Alt.SVType.SVSubtype.ISP || info.getValue("POS2", getType("POS2")) != null)) { //translocation SV DUP or interspersed DUP if (svlen.length > 0) { //0 is for reference allele //alternative allele is numbered 1,2,... per VCFSpec for (int altAlleleIndex = 1; altAlleleIndex <= svlen.length; altAlleleIndex++) { int currentCopyNumber = 1; /* implicit assumption here: genotype[0] == genotype[1] => copyNumberArray[0] == copyNumberArray[1] */ //check paternal if (altAlleleIndex == genotypeArray[0]) { currentCopyNumber = copyNumberArray[0]; } //check maternal if (altAlleleIndex == genotypeArray[1]) { currentCopyNumber = copyNumberArray[1]; } currentCopyNumber = Math.max(1, currentCopyNumber); //allow svlen to be negative int altAllelelength = Math.max(Math.abs(svlen[altAlleleIndex - 1]), 1); /* a translocation is decomposed into a duplication (a special translocation) and a deletion */ alts[altAlleleIndex - 1].setSeq(new FlexSeq( alts[altAlleleIndex - 1].getSymbolicAllele().getMinor() == Alt.SVType.SVSubtype.TRA ? FlexSeq.Type.TRA_DUP : FlexSeq.Type.ISP_DUP, altAllelelength, currentCopyNumber)); } //TODO: there could be multiple SVLEN values, but for now we only use one //make sure all SVLEN values are equal if we only use the first one //per VCFv4.1 spec, SVLEN should be length of alternative allele rather than //reference allele for (int i = 1; i < svlen.length; i++) { if (svlen[i] != svlen[0]) { throw new IllegalArgumentException("ERROR: SVLEN values not equal.\n" + line); } } //pos is incremented by 1, so it becomes 1-based start return template.referenceAlleleLength(0).alts(alts). chr2(ChrString.string2ChrString(chr2)).pos2(pos2).end2(end2).isinv(isinv).traid(traid == null? null : traid[0]).build(); //TODO: this assumes only one alt, which might not be true } else { log.error("No length information for DUP:TRA or DUP:ISP:"); log.error(line); log.error("skipping..."); return null; } } else { // imprecise variant log.warn("Imprecise line: " + line); return null; } } else if (alts[0].getSeq() != null){ //ALT field contains actual sequence // Check for (int i = 0; i < alts.length; i++) { if (REF.length() == 1 && alts[i].length() == 1) { // SNP } else if (REF.length() == 0 || alts[i].length() == 0) { log.warn("Skipping invalid record:" + line); return null; } } /* Adjustment of first base basically if first base of ref and alt match, first base of ref and alt will both be removed, pos will increment by 1 to account for the removal. this is updated to account for multiple matching reference bases e.g. ref=AT alt=ATC (VCFv4.1 spec requires only 1-bp before event, but it might not be the case all the time. */ while (REF.length() > 0) { boolean same = true; for (int i = 0; i < alts.length; i++) { if (alts[i].length() == 0 || REF.charAt(0) != alts[i].byteAt(0)) { same = false; break; } } if (same) { pos++; deletedReference = String.valueOf(REF.charAt(0)); REF = REF.substring(1); //System.err.println(varId + " before :" + deletedReference); for (int i = 0; i < alts.length; i++) { alts[i].setSeq(new FlexSeq(alts[i].getSeq().substring(1))); } } else { break; } } // TODO this needs to be done // but if we want to preserve the original VCF record, then this // needs modification if (REF.length() > 0) { int referenceAlleleLength = REF.length(); int minClipLength = Integer.MAX_VALUE; for (int i = 0; i < alts.length; i++) { int alternativeAlleleLength = alts[i].length(); //what does clipLength represent? int clipLength = 0; for (int j = 0; j < Math.min(alternativeAlleleLength, referenceAlleleLength); j++) { //this is based on the assumption that all characters are ASCII characters if (REF.charAt(referenceAlleleLength - j - 1) != alts[i].byteAt(alternativeAlleleLength - j - 1)) { clipLength = j; break; } clipLength = j + 1; } minClipLength = Math.min(clipLength, minClipLength); } /* apparently this code block is part of normalization. is this working properly, though? e.g. it converts CGTG,CG => GT,"" what this is doing is clip off tailing characters shared by both REF and ALT. make sure length after subtracting clip is nonnegative */ if (minClipLength > 0) { REF = REF.substring(0, Math.max(0, referenceAlleleLength - minClipLength)); for (int i = 0; i < alts.length; i++) { alts[i].setSeq(new FlexSeq(alts[i].getSeq().substring(0, Math.max(0, alts[i].length() - minClipLength)))); } } } byte[] refs = new byte[REF.length()]; for (int i = 0; i < REF.length(); i++) { refs[i] = (byte) REF.charAt(i); } /*return new Variant(chr, pos, refs.length, refs, alts, genotypeArray, isGenotypePhased, variantId, FILTER, deletedReference, random); */ return new Variant.Builder().chr(chr).pos(pos).referenceAlleleLength(refs.length). ref(refs).alts(alts).phase(genotypeArray).isPhased(isGenotypePhased). varId(variantId).filter(FILTER).refDeleted(deletedReference). randomNumberGenerator(random).build(); } else { // breakend log.warn("breakend is not handled directly now: " + line); return null; } } public Variant parseLine() { /* TODO: line reading should be handled in a loop calling */ String line = this.line; readLine(); if (line == null || line.length() == 0) { log.info("blank line"); return null; } Variant variant = null; try { variant = processLine(line); } catch (Exception e) { //TODO: right now just be lazy, die on any error log.fatal(e.getMessage() + "\n" + line); e.printStackTrace(); System.exit(255); } if (variant == null && !line.startsWith(" log.warn("Returned null variant for line " + line); } return variant; } /** * convert ALT field to Alt[] array * AT,ATG => .. * <DUP>,<DUP> => .. * * @param ALT * @return */ public Alt[] string2Alt(String ALT){ String[] altsString = ALT.split(","); Alt[] alts = new Alt[altsString.length]; for (int i = 0; i < alts.length; i++) { alts[i] = Alt.altFactory(altsString[i]); } return alts; } }
package com.ray3k.skincomposer.data; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.List; import com.badlogic.gdx.scenes.scene2d.ui.ProgressBar; import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane; import com.badlogic.gdx.scenes.scene2d.ui.SelectBox; import com.badlogic.gdx.scenes.scene2d.ui.Skin.TintedDrawable; import com.badlogic.gdx.scenes.scene2d.ui.Slider; import com.badlogic.gdx.scenes.scene2d.ui.SplitPane; import com.badlogic.gdx.scenes.scene2d.ui.TextTooltip; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.JsonReader; import com.badlogic.gdx.utils.JsonValue; import com.badlogic.gdx.utils.JsonWriter; import com.badlogic.gdx.utils.JsonWriter.OutputType; import com.badlogic.gdx.utils.OrderedMap; import com.badlogic.gdx.utils.reflect.ClassReflection; import com.badlogic.gdx.utils.reflect.ReflectionException; import com.ray3k.skincomposer.Main; import com.ray3k.skincomposer.data.CustomProperty.PropertyType; import com.ray3k.skincomposer.dialog.DialogFactory; import java.io.StringWriter; public class JsonData implements Json.Serializable { private Array<ColorData> colors; private Array<FontData> fonts; private OrderedMap<Class, Array<StyleData>> classStyleMap; private Array<CustomClass> customClasses; private Main main; public JsonData() { colors = new Array<>(); fonts = new Array<>(); initializeClassStyleMap(); customClasses = new Array<>(); } public void setMain(Main main) { this.main = main; } public void clear() { colors.clear(); fonts.clear(); initializeClassStyleMap(); customClasses.clear(); } public Array<String> readFile(FileHandle fileHandle) throws Exception { Array<String> warnings = new Array<>(); main.getProjectData().setChangesSaved(false); //read drawables from texture atlas file FileHandle atlasHandle = fileHandle.sibling(fileHandle.nameWithoutExtension() + ".atlas"); if (atlasHandle.exists()) { main.getProjectData().getAtlasData().readAtlas(atlasHandle); } else { warnings.add("[RED]ERROR:[] Atlas file [BLACK]" + atlasHandle.name() + "[] does not exist."); return warnings; } //folder for critical files to be copied to FileHandle saveFile = main.getProjectData().getSaveFile(); FileHandle targetDirectory; if (saveFile != null) { targetDirectory = saveFile.sibling(saveFile.nameWithoutExtension() + "_data"); } else { targetDirectory = Gdx.files.local("temp/" + main.getProjectData().getId() + "_data"); } //read json file and create styles JsonReader reader = new JsonReader(); JsonValue val = reader.parse(fileHandle); for (JsonValue child : val.iterator()) { //fonts if (child.name().equals(BitmapFont.class.getName())) { for (JsonValue font : child.iterator()) { if (font.get("file") != null) { FileHandle fontFile = fileHandle.sibling(font.getString("file")); if (!fontFile.exists()) { warnings.add("[RED]ERROR:[] Font file [BLACK]" + fontFile.name() + "[] does not exist."); return warnings; } FileHandle fontCopy = targetDirectory.child(font.getString("file")); if (!fontCopy.parent().equals(fontFile.parent())) { fontFile.copyTo(fontCopy); } FontData fontData = new FontData(font.name(), fontCopy); //delete fonts with the same name for (FontData originalData : new Array<>(fonts)) { if (originalData.getName().equals(fontData.getName())) { fonts.removeValue(originalData, true); } } fonts.add(fontData); BitmapFont.BitmapFontData bitmapFontData = new BitmapFont.BitmapFontData(fontCopy, false); for (String path : bitmapFontData.imagePaths) { FileHandle file = new FileHandle(path); main.getProjectData().getAtlasData().getDrawable(file.nameWithoutExtension()).visible = false; } } } } //colors else if (child.name().equals(Color.class.getName())) { for (JsonValue color : child.iterator()) { ColorData colorData = new ColorData(color.name, new Color(color.getFloat("r", 0.0f), color.getFloat("g", 0.0f), color.getFloat("b", 0.0f), color.getFloat("a", 0.0f))); //delete colors with the same name for (ColorData originalData : new Array<>(colors)) { if (originalData.getName().equals(colorData.getName())) { colors.removeValue(originalData, true); } } colors.add(colorData); } } //tinted drawables else if (child.name().equals(TintedDrawable.class.getName())) { for (JsonValue tintedDrawable : child.iterator()) { DrawableData drawableData = new DrawableData(main.getProjectData().getAtlasData().getDrawable(tintedDrawable.getString("name")).file); drawableData.name = tintedDrawable.name; if (!tintedDrawable.get("color").isString()) { drawableData.tint = new Color(tintedDrawable.get("color").getFloat("r", 0.0f), tintedDrawable.get("color").getFloat("g", 0.0f), tintedDrawable.get("color").getFloat("b", 0.0f), tintedDrawable.get("color").getFloat("a", 0.0f)); } else { drawableData.tintName = tintedDrawable.getString("color"); } //todo:test overwriting a base drawable that is depended on by another tint //delete drawables with the same name for (DrawableData originalData : new Array<>(main.getProjectData().getAtlasData().getDrawables())) { if (originalData.name.equals(drawableData.name)) { main.getProjectData().getAtlasData().getDrawables().removeValue(originalData, true); } } main.getProjectData().getAtlasData().getDrawables().add(drawableData); } } //styles else { int classIndex = 0; if (testClassString(child.name)) { Class matchClass = ClassReflection.forName(child.name); for (Class clazz : Main.STYLE_CLASSES) { if (clazz.equals(matchClass)) { break; } else { classIndex++; } } Class clazz = Main.BASIC_CLASSES[classIndex]; for (JsonValue style : child.iterator()) { StyleData data = newStyle(clazz, style.name); for (JsonValue property : style.iterator()) { StyleProperty styleProperty = data.properties.get(property.name); if (styleProperty.type.equals(Float.TYPE)) { styleProperty.value = (double) property.asFloat(); } else if (styleProperty.type.equals(Color.class)) { if (property.isString()) { styleProperty.value = property.asString(); } else { Gdx.app.error(getClass().getName(), "Can't import JSON files that do not use predefined colors."); warnings.add("Property [BLACK]" + styleProperty.name + "[] value cleared for [BLACK]" + clazz.getSimpleName() + ": " + data.name + "[] (Unsupported color definition)"); } } else { if (property.isString()) { styleProperty.value = property.asString(); } else { Gdx.app.error(getClass().getName(), "Can't import JSON files that do not use String names for field values."); warnings.add("Property [BLACK]" + styleProperty.name + "[] value cleared for [BLACK]" + clazz.getSimpleName() + ": " + data.name + "[] (Unsupported propety value)"); } } } } } else { //custom classes CustomClass customClass = new CustomClass(child.name, child.name.replaceFirst(".*(\\.|\\$)", "")); customClass.setMain(main); CustomClass existingClass = getCustomClass(customClass.getDisplayName()); if (existingClass != null) { customClasses.removeValue(existingClass, true); } customClasses.add(customClass); for (JsonValue style : child.iterator()) { CustomStyle customStyle = new CustomStyle(style.name); customStyle.setParentClass(customClass); customStyle.setMain(main); CustomStyle existingStyle = customClass.getStyle(style.name); if (existingStyle != null) { customClass.getStyles().removeValue(existingStyle, true); } if (customStyle.getName().equals("default")) { customStyle.setDeletable(false); } customClass.getStyles().add(customStyle); for (JsonValue property : style.iterator()) { CustomProperty customProperty = new CustomProperty(); customProperty.setName(property.name); customProperty.setParentStyle(customStyle); customProperty.setMain(main); CustomProperty existingProperty = customStyle.getProperty(property.name); if (existingProperty != null) { customStyle.getProperties().removeValue(existingProperty, true); } if (property.isNumber()) { customProperty.setType(PropertyType.NUMBER); customProperty.setValue(property.asDouble()); } else if (property.isString()) { customProperty.setType(PropertyType.TEXT); customProperty.setValue(property.asString()); } else if (property.isBoolean()) { customProperty.setType(PropertyType.BOOL); customProperty.setValue(property.asBoolean()); } else if (property.isObject()) { customProperty.setType(PropertyType.RAW_TEXT); customProperty.setValue(property.toJson(OutputType.minimal)); } else if (property.isArray()) { customProperty.setType(PropertyType.RAW_TEXT); customProperty.setValue(property.toJson(OutputType.minimal)); } else { customProperty = null; } if (customProperty != null) { customStyle.getProperties().add(customProperty); //add to template style as necessary if (customClass.getTemplateStyle().getProperty(customProperty.getName()) == null) { CustomProperty dupeProperty = customProperty.copy(); dupeProperty.setValue(null); customClass.getTemplateStyle().getProperties().add(dupeProperty); } } } } //ensure default style has all the template styles. for (CustomStyle style : customClass.getStyles()) { if (style.getName().equals("default")) { for (CustomProperty templateProperty : customClass.getTemplateStyle().getProperties()) { boolean hasProperty = false; for (CustomProperty customProperty : style.getProperties()) { if (customProperty.getName().equals(templateProperty.getName())) { hasProperty = true; break; } } if (!hasProperty) { style.getProperties().add(templateProperty.copy()); } } break; } } } } } return warnings; } public void checkForPropertyConsistency() { for (Class clazz : classStyleMap.keys()) { for (StyleData styleData : classStyleMap.get(clazz)) { for (StyleProperty property : styleData.properties.values()) { if (property.value != null) { boolean keep = false; if (property.type == Color.class) { for (ColorData color : colors) { if (property.value.equals(color.getName())) { keep = true; break; } } } else if (property.type == BitmapFont.class) { for (FontData font : fonts) { if (property.value.equals(font.getName())) { keep = true; break; } } } else if (property.type == Drawable.class) { for (DrawableData drawable : main.getAtlasData().getDrawables()) { if (property.value.equals(drawable.name)) { keep = true; break; } } } else { keep = true; } if (!keep) { property.value = null; } } } } } for (CustomClass customClass : customClasses) { for (CustomStyle customStyle: customClass.getStyles()) { for (CustomProperty customProperty : customStyle.getProperties()) { if (customProperty.getValue() != null) { boolean keep = false; if (null == customProperty.getType()) { keep = true; } else switch (customProperty.getType()) { case COLOR: for (ColorData color : colors) { if (customProperty.getValue().equals(color.getName())) { keep = true; break; } } break; case DRAWABLE: for (DrawableData drawable : main.getAtlasData().getDrawables()) { if (customProperty.getValue().equals(drawable.name)) { keep = true; break; } } break; case FONT: for (FontData font : fonts) { if (customProperty.getValue().equals(font.getName())) { keep = true; break; } } break; default: keep = true; break; } if (!keep) { customProperty.setValue(null); } } } } } } public CustomClass getCustomClass(String name) { for (CustomClass customClass : customClasses) { if (customClass.getDisplayName().equals(name)) { return customClass; } } return null; } private boolean testClassString(String fullyQualifiedName) { boolean returnValue = false; for (Class clazz : Main.STYLE_CLASSES) { if (fullyQualifiedName.equals(clazz.getName())) { returnValue = true; break; } } return returnValue; } public Array<String> writeFile(FileHandle fileHandle) { Array<String> warnings = new Array<>(); StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.setOutputType(OutputType.minimal); Json json = new Json(); json.setWriter(jsonWriter); json.writeObjectStart(); //fonts if (fonts.size > 0) { json.writeObjectStart(BitmapFont.class.getName()); for (FontData font : fonts) { json.writeObjectStart(font.getName()); json.writeValue("file", font.file.name()); json.writeObjectEnd(); } json.writeObjectEnd(); } //colors if (colors.size > 0) { json.writeObjectStart(Color.class.getName()); for (ColorData color : colors) { json.writeObjectStart(color.getName()); json.writeValue("r", color.color.r); json.writeValue("g", color.color.g); json.writeValue("b", color.color.b); json.writeValue("a", color.color.a); json.writeObjectEnd(); } json.writeObjectEnd(); } //tinted drawables Array<DrawableData> tintedDrawables = new Array<>(); for (DrawableData drawable : main.getProjectData().getAtlasData().getDrawables()) { if (drawable.tint != null || drawable.tintName != null) { tintedDrawables.add(drawable); } } if (tintedDrawables.size > 0) { json.writeObjectStart(TintedDrawable.class.getName()); for (DrawableData drawable : tintedDrawables) { json.writeObjectStart(drawable.name); json.writeValue("name", DrawableData.proper(drawable.file.name())); if (drawable.tint != null) { json.writeObjectStart("color"); json.writeValue("r", drawable.tint.r); json.writeValue("g", drawable.tint.g); json.writeValue("b", drawable.tint.b); json.writeValue("a", drawable.tint.a); json.writeObjectEnd(); } else if (drawable.tintName != null) { json.writeValue("color", drawable.tintName); } json.writeObjectEnd(); } json.writeObjectEnd(); } //styles Array<Array<StyleData>> valuesArray = classStyleMap.values().toArray(); for (int i = 0; i < Main.STYLE_CLASSES.length; i++) { Class clazz = Main.STYLE_CLASSES[i]; Array<StyleData> styles = valuesArray.get(i); //check if any style has the mandatory fields necessary to write boolean hasMandatoryStyles = false; for (StyleData style : styles) { if (style.hasMandatoryFields() && ! style.hasAllNullFields()) { hasMandatoryStyles = true; break; } } if (hasMandatoryStyles) { json.writeObjectStart(clazz.getName()); for (StyleData style : styles) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { json.writeObjectStart(style.name); for (StyleProperty property : style.properties.values()) { //if not optional, null, or zero if (!property.optional || property.value != null && !(property.value instanceof Number && MathUtils.isZero((float) (double) property.value))) { json.writeValue(property.name, property.value); } } json.writeObjectEnd(); } else { if (style.hasAllNullFields()) { warnings.add("Did not export style [BLACK]" + style.name + "[] for class [BLACK]" + clazz.getSimpleName() + " (All fields null)"); } else if (!style.hasMandatoryFields()) { warnings.add("Did not export style [BLACK]" + style.name + "[] for class [BLACK]" + clazz.getSimpleName() + " (All fields null)"); } } } json.writeObjectEnd(); } else { warnings.add("Did not export class [BLACK]" + clazz.getSimpleName() + "[] (No valid styles)"); } } //custom classes for (CustomClass customClass : customClasses) { if (customClassHasFields(customClass)) { json.writeObjectStart(customClass.getFullyQualifiedName()); for (CustomStyle customStyle : customClass.getStyles()) { if (customStyleHasFields(customStyle)) { json.writeObjectStart(customStyle.getName()); for (CustomProperty customProperty : customStyle.getProperties()) { //only write value if it is valid if (customPropertyIsNotNull(customProperty)) { if (customProperty.getType().equals(CustomProperty.PropertyType.RAW_TEXT)) { try { json.getWriter().json(customProperty.getName(), (String)customProperty.getValue()); } catch (Exception e) { DialogFactory.showDialogErrorStatic("Error writing custom property.", "Error writing custom property " + customProperty.getName() + " for custom class " + customClass.getDisplayName() + "."); } } else { json.writeValue(customProperty.getName(), customProperty.getValue()); } } } json.writeObjectEnd(); } else { warnings.add("Did not export custom style [BLACK]" + customStyle.getName() + "[] for class [BLACK]" + customClass.getDisplayName() + "[] (All fields null)"); } } json.writeObjectEnd(); } else { warnings.add("Did not export custom class [BLACK]" + customClass.getDisplayName() + "[] (No valid styles)"); } } json.writeObjectEnd(); fileHandle.writeString(json.prettyPrint(stringWriter.toString()), false); return warnings; } private boolean customPropertyIsNotNull(CustomProperty customProperty) { boolean returnValue = false; if (customProperty.getValue() instanceof Float && customProperty.getType() == PropertyType.NUMBER || customProperty.getValue() instanceof Double && customProperty.getType() == PropertyType.NUMBER || customProperty.getValue() instanceof Boolean && customProperty.getType() == PropertyType.BOOL) { returnValue = true; } else if (customProperty.getValue() instanceof String && !((String) customProperty.getValue()).equals("")) { if (null != customProperty.getType()) switch (customProperty.getType()) { case TEXT: case RAW_TEXT: returnValue = true; break; case COLOR: for (ColorData data : getColors()) { if (data.getName().equals(customProperty.getValue())) { returnValue = true; break; } } break; case DRAWABLE: for (DrawableData data : main.getAtlasData().getDrawables()) { if (data.name.equals(customProperty.getValue())) { returnValue = true; break; } } break; case FONT: for (FontData data : getFonts()) { if (data.getName().equals(customProperty.getValue())) { returnValue = true; break; } } break; } } return returnValue; } private boolean customStyleHasFields(CustomStyle customStyle) { boolean returnValue = false; for (CustomProperty customProperty : customStyle.getProperties()) { if (customPropertyIsNotNull(customProperty)) { returnValue = true; break; } } return returnValue; } private boolean customClassHasFields(CustomClass customClass) { for (CustomStyle style : customClass.getStyles()) { if (customStyleHasFields(style)) { return true; } } return false; } public Array<ColorData> getColors() { return colors; } public ColorData getColorByName(String tintName) { ColorData returnValue = null; for (ColorData color : colors) { if (color.getName().equals(tintName)) { returnValue = color; break; } } return returnValue; } public Array<FontData> getFonts() { return fonts; } public OrderedMap<Class, Array<StyleData>> getClassStyleMap() { return classStyleMap; } private void initializeClassStyleMap() { classStyleMap = new OrderedMap(); for (Class clazz : Main.BASIC_CLASSES) { Array<StyleData> array = new Array<>(); classStyleMap.put(clazz, array); if (clazz.equals(Slider.class) || clazz.equals(ProgressBar.class) || clazz.equals(SplitPane.class)) { StyleData data = new StyleData(clazz, "default-horizontal", main); data.jsonData = this; data.deletable = false; array.add(data); data = new StyleData(clazz, "default-vertical", main); data.jsonData = this; data.deletable = false; array.add(data); } else { StyleData data = new StyleData(clazz, "default", main); data.jsonData = this; data.deletable = false; array.add(data); } } } @Override public void write(Json json) { json.writeValue("colors", colors); json.writeValue("fonts", fonts); json.writeValue("classStyleMap", classStyleMap); json.writeValue("customClasses", customClasses, Array.class, CustomClass.class); } @Override public void read(Json json, JsonValue jsonData) { try { colors = json.readValue("colors", Array.class, jsonData); fonts = json.readValue("fonts", Array.class, jsonData); classStyleMap = new OrderedMap<>(); for (JsonValue data : jsonData.get("classStyleMap").iterator()) { classStyleMap.put(ClassReflection.forName(data.name), json.readValue(Array.class, data)); } for (Array<StyleData> styleDatas : classStyleMap.values()) { for (StyleData styleData : styleDatas) { styleData.jsonData = this; } } customClasses = json.readValue("customClasses", Array.class, CustomClass.class, new Array<>(), jsonData); for (CustomClass customClass : customClasses) { customClass.setMain(main); } } catch (ReflectionException e) { Gdx.app.log(getClass().getName(), "Error parsing json data during file read", e); main.getDialogFactory().showDialogError("Error while reading file...", "Error while attempting to read save file.\nPlease ensure that file is not corrupted.\n\nOpen error log?"); } } /** * Creates a new StyleData object if one with the same name currently does not exist. If it does exist * it is returned and the properties are wiped. ClassName and deletable flag is retained. * @param className * @param styleName * @return */ public StyleData newStyle(Class className, String styleName) { Array<StyleData> styles = getClassStyleMap().get(className); StyleData data = null; for (StyleData tempStyle : styles) { if (tempStyle.name.equals(styleName)) { data = tempStyle; data.resetProperties(); } } if (data == null) { data = new StyleData(className, styleName, main); data.jsonData = this; styles.add(data); } return data; } public StyleData copyStyle(StyleData original, String styleName) { Array<StyleData> styles = getClassStyleMap().get(original.clazz); StyleData data = new StyleData(original, styleName, main); data.jsonData = this; styles.add(data); return data; } public void deleteStyle(StyleData styleData) { Array<StyleData> styles = getClassStyleMap().get(styleData.clazz); styles.removeValue(styleData, true); //reset any properties pointing to this style to the default style if (styleData.clazz.equals(Label.class)) { for (StyleData data : getClassStyleMap().get(TextTooltip.class)) { StyleProperty property = data.properties.get("label"); if (property != null && property.value.equals(styleData.name)) { property.value = "default"; } } } else if (styleData.clazz.equals(List.class)) { for (StyleData data : getClassStyleMap().get(SelectBox.class)) { StyleProperty property = data.properties.get("listStyle"); if (property != null && property.value.equals(styleData.name)) { property.value = "default"; } } } else if (styleData.clazz.equals(ScrollPane.class)) { for (StyleData data : getClassStyleMap().get(SelectBox.class)) { StyleProperty property = data.properties.get("scrollStyle"); if (property != null && property.value.equals(styleData.name)) { property.value = "default"; } } } } public void set(JsonData jsonData) { colors.clear(); colors.addAll(jsonData.colors); fonts.clear(); fonts.addAll(jsonData.fonts); classStyleMap.clear(); classStyleMap.putAll(jsonData.classStyleMap); customClasses.clear(); customClasses.addAll(jsonData.customClasses); } public Array<CustomClass> getCustomClasses() { return customClasses; } }
package guitests; import static org.junit.Assert.*; import org.junit.Test; import guitests.guihandles.TaskCardHandle; import seedu.testplanner.testutil.TestTask; //@@author A0139102U public class UnpinCommandTest extends DailyPlannerGuiTest { @Test public void unpin() { TestTask taskToUnpin = td.CS2103_Project; commandBox.runCommand("pin 1"); assertUnpinSuccess("unpin 1", taskToUnpin); } private void assertUnpinSuccess(String command, TestTask taskToUnpin) { commandBox.runCommand(command); // confirm there is only 1 task remaining in the pinned list assertEquals(pinnedListPanel.getNumberOfPeople(), 1); } }
package com.conveyal.gtfs.loader; import com.conveyal.gtfs.error.NewGTFSError; import com.conveyal.gtfs.error.SQLErrorStorage; import com.conveyal.gtfs.loader.conditions.AgencyHasMultipleRowsCheck; import com.conveyal.gtfs.loader.conditions.ConditionalRequirement; import com.conveyal.gtfs.loader.conditions.FieldInRangeCheck; import com.conveyal.gtfs.loader.conditions.FieldIsEmptyCheck; import com.conveyal.gtfs.loader.conditions.FieldNotEmptyAndMatchesValueCheck; import com.conveyal.gtfs.loader.conditions.ForeignRefExistsCheck; import com.conveyal.gtfs.loader.conditions.ReferenceFieldShouldBeProvidedCheck; import com.conveyal.gtfs.model.Agency; import com.conveyal.gtfs.model.Attribution; import com.conveyal.gtfs.model.Calendar; import com.conveyal.gtfs.model.CalendarDate; import com.conveyal.gtfs.model.Entity; import com.conveyal.gtfs.model.FareAttribute; import com.conveyal.gtfs.model.FareRule; import com.conveyal.gtfs.model.FeedInfo; import com.conveyal.gtfs.model.Frequency; import com.conveyal.gtfs.model.Pattern; import com.conveyal.gtfs.model.PatternStop; import com.conveyal.gtfs.model.Route; import com.conveyal.gtfs.model.ScheduleException; import com.conveyal.gtfs.model.ShapePoint; import com.conveyal.gtfs.model.Stop; import com.conveyal.gtfs.model.StopTime; import com.conveyal.gtfs.model.Transfer; import com.conveyal.gtfs.model.Translation; import com.conveyal.gtfs.model.Trip; import com.conveyal.gtfs.storage.StorageException; import com.csvreader.CsvReader; import org.apache.commons.io.input.BOMInputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import static com.conveyal.gtfs.error.NewGTFSErrorType.DUPLICATE_HEADER; import static com.conveyal.gtfs.error.NewGTFSErrorType.TABLE_IN_SUBDIRECTORY; import static com.conveyal.gtfs.loader.JdbcGtfsLoader.sanitize; import static com.conveyal.gtfs.loader.Requirement.EDITOR; import static com.conveyal.gtfs.loader.Requirement.EXTENSION; import static com.conveyal.gtfs.loader.Requirement.OPTIONAL; import static com.conveyal.gtfs.loader.Requirement.REQUIRED; import static com.conveyal.gtfs.loader.Requirement.UNKNOWN; /** * This groups a table name with a description of the fields in the table. * It can be normative (expressing the specification for a CSV table in GTFS) * or descriptive (providing the schema of an RDBMS table). * * TODO associate Table with EntityPopulator (combine read and write sides) */ public class Table { private static final Logger LOG = LoggerFactory.getLogger(Table.class); public final String name; final Class<? extends Entity> entityClass; final Requirement required; public final Field[] fields; /** Determines whether cascading delete is restricted. Defaults to false (i.e., cascade delete is allowed) */ private boolean cascadeDeleteRestricted = false; /** An update to the parent table will trigger an update to this table if parent has nested entities. */ private Table parentTable; /** When snapshotting a table for editor use, this indicates whether a primary key constraint should be added to ID. */ private boolean usePrimaryKey = false; /** Indicates whether the table has unique key field. */ public boolean hasUniqueKeyField = true; /** * Indicates whether the table has a compound key that must be used in conjunction with the key field to determine * table uniqueness(e.g., transfers#to_stop_id). * */ private boolean compoundKey; public Table (String name, Class<? extends Entity> entityClass, Requirement required, Field... fields) { // TODO: verify table name is OK for use in constructing dynamic SQL queries this.name = name; this.entityClass = entityClass; this.required = required; this.fields = fields; } public static final Table AGENCY = new Table("agency", Agency.class, REQUIRED, new StringField("agency_id", OPTIONAL).requireConditions( // If there is more than one agency, the agency_id must be provided // https://developers.google.com/transit/gtfs/reference#agencytxt new AgencyHasMultipleRowsCheck() ).hasForeignReferences(), new StringField("agency_name", REQUIRED), new URLField("agency_url", REQUIRED), new StringField("agency_timezone", REQUIRED), // FIXME new field type for time zones? new StringField("agency_lang", OPTIONAL), // FIXME new field type for languages? new StringField("agency_phone", OPTIONAL), new URLField("agency_branding_url", OPTIONAL), new URLField("agency_fare_url", OPTIONAL), new StringField("agency_email", OPTIONAL) // FIXME new field type for emails? ).restrictDelete().addPrimaryKey(); // The GTFS spec says this table is required, but in practice it is not required if calendar_dates is present. public static final Table CALENDAR = new Table("calendar", Calendar.class, OPTIONAL, new StringField("service_id", REQUIRED), new IntegerField("monday", REQUIRED, 0, 1), new IntegerField("tuesday", REQUIRED, 0, 1), new IntegerField("wednesday", REQUIRED, 0, 1), new IntegerField("thursday", REQUIRED, 0, 1), new IntegerField("friday", REQUIRED, 0, 1), new IntegerField("saturday", REQUIRED, 0, 1), new IntegerField("sunday", REQUIRED, 0, 1), new DateField("start_date", REQUIRED), new DateField("end_date", REQUIRED), // Editor-specific field new StringField("description", EDITOR) ).restrictDelete().addPrimaryKey(); public static final Table SCHEDULE_EXCEPTIONS = new Table("schedule_exceptions", ScheduleException.class, EDITOR, new StringField("name", REQUIRED), // FIXME: This makes name the key field... // FIXME: Change to DateListField new DateListField("dates", REQUIRED), new ShortField("exemplar", REQUIRED, 9), new StringListField("custom_schedule", OPTIONAL).isReferenceTo(CALENDAR), new StringListField("added_service", OPTIONAL).isReferenceTo(CALENDAR), new StringListField("removed_service", OPTIONAL).isReferenceTo(CALENDAR) ); public static final Table CALENDAR_DATES = new Table("calendar_dates", CalendarDate.class, OPTIONAL, new StringField("service_id", REQUIRED).isReferenceTo(CALENDAR), new DateField("date", REQUIRED), new IntegerField("exception_type", REQUIRED, 1, 2) ).keyFieldIsNotUnique(); public static final Table FARE_ATTRIBUTES = new Table("fare_attributes", FareAttribute.class, OPTIONAL, new StringField("fare_id", REQUIRED), new DoubleField("price", REQUIRED, 0.0, Double.MAX_VALUE, 2), new CurrencyField("currency_type", REQUIRED), new ShortField("payment_method", REQUIRED, 1), new ShortField("transfers", REQUIRED, 2).permitEmptyValue(), new StringField("agency_id", OPTIONAL).requireConditions( // If there is more than one agency, this agency_id is required. // https://developers.google.com/transit/gtfs/reference#fare_attributestxt new ReferenceFieldShouldBeProvidedCheck("agency_id") ), new IntegerField("transfer_duration", OPTIONAL) ).addPrimaryKey(); // FIXME: Should we add some constraint on number of rows that this table has? Perhaps this is a GTFS editor specific // feature. public static final Table FEED_INFO = new Table("feed_info", FeedInfo.class, OPTIONAL, new StringField("feed_publisher_name", REQUIRED), // feed_id is not the first field because that would label it as the key field, which we do not want because the // key field cannot be optional. feed_id is not part of the GTFS spec, but is required by OTP to associate static GTFS with GTFS-rt feeds. new StringField("feed_id", OPTIONAL), new URLField("feed_publisher_url", REQUIRED), new LanguageField("feed_lang", REQUIRED), new DateField("feed_start_date", OPTIONAL), new DateField("feed_end_date", OPTIONAL), new StringField("feed_version", OPTIONAL), // Editor-specific field that represents default route values for use in editing. new ColorField("default_route_color", EDITOR), // FIXME: Should the route type max value be equivalent to GTFS spec's max? new IntegerField("default_route_type", EDITOR, 999), new LanguageField("default_lang", OPTIONAL), new StringField("feed_contact_email", OPTIONAL), new URLField("feed_contact_url", OPTIONAL) ).keyFieldIsNotUnique(); public static final Table ROUTES = new Table("routes", Route.class, REQUIRED, new StringField("route_id", REQUIRED), new StringField("agency_id", OPTIONAL).isReferenceTo(AGENCY).requireConditions( // If there is more than one agency, this agency_id is required. // https://developers.google.com/transit/gtfs/reference#routestxt new ReferenceFieldShouldBeProvidedCheck("agency_id") ), new StringField("route_short_name", OPTIONAL), // one of short or long must be provided new StringField("route_long_name", OPTIONAL), new StringField("route_desc", OPTIONAL), // Max route type according to the GTFS spec is 7; however, there is a GTFS proposal that could see this new IntegerField("route_type", REQUIRED, 1800), new URLField("route_url", OPTIONAL), new URLField("route_branding_url", OPTIONAL), new ColorField("route_color", OPTIONAL), // really this is an int in hex notation new ColorField("route_text_color", OPTIONAL), // Editor fields below. new ShortField("publicly_visible", EDITOR, 1), // wheelchair_accessible is an exemplar field applied to all trips on a route. new ShortField("wheelchair_accessible", EDITOR, 2).permitEmptyValue(), new IntegerField("route_sort_order", OPTIONAL, 0, Integer.MAX_VALUE), // Status values are In progress (0), Pending approval (1), and Approved (2). new ShortField("status", EDITOR, 2), new ShortField("continuous_pickup", OPTIONAL,3), new ShortField("continuous_drop_off", OPTIONAL,3) ).addPrimaryKey(); public static final Table SHAPES = new Table("shapes", ShapePoint.class, OPTIONAL, new StringField("shape_id", REQUIRED), new IntegerField("shape_pt_sequence", REQUIRED), new DoubleField("shape_pt_lat", REQUIRED, -80, 80, 6), new DoubleField("shape_pt_lon", REQUIRED, -180, 180, 6), new DoubleField("shape_dist_traveled", OPTIONAL, 0, Double.POSITIVE_INFINITY, -1), // Editor-specific field that represents a shape point's behavior in UI. // 0 - regular shape point // 1 - user-designated anchor point (handle with which the user can manipulate shape) // 2 - stop-projected point (dictates the value of shape_dist_traveled for a pattern stop) new ShortField("point_type", EDITOR, 2) ); public static final Table PATTERNS = new Table("patterns", Pattern.class, OPTIONAL, new StringField("pattern_id", REQUIRED), new StringField("route_id", REQUIRED).isReferenceTo(ROUTES), new StringField("name", OPTIONAL), // Editor-specific fields. // direction_id and shape_id are exemplar fields applied to all trips for a pattern. new ShortField("direction_id", EDITOR, 1), new ShortField("use_frequency", EDITOR, 1), new StringField("shape_id", EDITOR).isReferenceTo(SHAPES) ).addPrimaryKey(); public static final Table STOPS = new Table("stops", Stop.class, REQUIRED, new StringField("stop_id", REQUIRED), new StringField("stop_code", OPTIONAL), // The actual conditions that will be acted upon are within the location_type field. new StringField("stop_name", OPTIONAL).requireConditions(), new StringField("stop_desc", OPTIONAL), // The actual conditions that will be acted upon are within the location_type field. new DoubleField("stop_lat", OPTIONAL, -80, 80, 6).requireConditions(), // The actual conditions that will be acted upon are within the location_type field. new DoubleField("stop_lon", OPTIONAL, -180, 180, 6).requireConditions(), new StringField("zone_id", OPTIONAL).hasForeignReferences(), new URLField("stop_url", OPTIONAL), new ShortField("location_type", OPTIONAL, 4).requireConditions( // If the location type is defined and within range, the dependent fields are required. // https://developers.google.com/transit/gtfs/reference#stopstxt new FieldInRangeCheck(0, 2, "stop_name"), new FieldInRangeCheck(0, 2, "stop_lat"), new FieldInRangeCheck(0, 2, "stop_lon"), new FieldInRangeCheck(2, 4, "parent_station") ), // The actual conditions that will be acted upon are within the location_type field. new StringField("parent_station", OPTIONAL).requireConditions(), new StringField("stop_timezone", OPTIONAL), new ShortField("wheelchair_boarding", OPTIONAL, 2), new StringField("platform_code", OPTIONAL) ) .restrictDelete() .addPrimaryKey(); // GTFS reference: https://developers.google.com/transit/gtfs/reference#fare_rulestxt public static final Table FARE_RULES = new Table("fare_rules", FareRule.class, OPTIONAL, new StringField("fare_id", REQUIRED).isReferenceTo(FARE_ATTRIBUTES), new StringField("route_id", OPTIONAL).isReferenceTo(ROUTES), new StringField("origin_id", OPTIONAL).requireConditions( // If the origin_id is defined, its value must exist as a zone_id in stops.txt. new ForeignRefExistsCheck("zone_id", "fare_rules") ), new StringField("destination_id", OPTIONAL).requireConditions( // If the destination_id is defined, its value must exist as a zone_id in stops.txt. new ForeignRefExistsCheck("zone_id", "fare_rules") ), new StringField("contains_id", OPTIONAL).requireConditions( // If the contains_id is defined, its value must exist as a zone_id in stops.txt. new ForeignRefExistsCheck("zone_id", "fare_rules") ) ) .withParentTable(FARE_ATTRIBUTES) .addPrimaryKey().keyFieldIsNotUnique(); public static final Table PATTERN_STOP = new Table("pattern_stops", PatternStop.class, OPTIONAL, new StringField("pattern_id", REQUIRED).isReferenceTo(PATTERNS), new IntegerField("stop_sequence", REQUIRED, 0, Integer.MAX_VALUE), // FIXME: Do we need an index on stop_id? new StringField("stop_id", REQUIRED).isReferenceTo(STOPS), // Editor-specific fields new IntegerField("default_travel_time", EDITOR,0, Integer.MAX_VALUE), new IntegerField("default_dwell_time", EDITOR, 0, Integer.MAX_VALUE), new IntegerField("drop_off_type", EDITOR, 2), new IntegerField("pickup_type", EDITOR, 2), new DoubleField("shape_dist_traveled", EDITOR, 0, Double.POSITIVE_INFINITY, -1), new ShortField("timepoint", EDITOR, 1) ).withParentTable(PATTERNS); public static final Table TRANSFERS = new Table("transfers", Transfer.class, OPTIONAL, // FIXME: Do we need an index on from_ and to_stop_id new StringField("from_stop_id", REQUIRED).isReferenceTo(STOPS), new StringField("to_stop_id", REQUIRED).isReferenceTo(STOPS), new ShortField("transfer_type", REQUIRED, 3), new StringField("min_transfer_time", OPTIONAL)) .addPrimaryKey() .keyFieldIsNotUnique() .hasCompoundKey(); public static final Table TRIPS = new Table("trips", Trip.class, REQUIRED, new StringField("trip_id", REQUIRED), new StringField("route_id", REQUIRED).isReferenceTo(ROUTES).indexThisColumn(), // FIXME: Should this also optionally reference CALENDAR_DATES? // FIXME: Do we need an index on service_id new StringField("service_id", REQUIRED).isReferenceTo(CALENDAR), new StringField("trip_headsign", OPTIONAL), new StringField("trip_short_name", OPTIONAL), new ShortField("direction_id", OPTIONAL, 1), new StringField("block_id", OPTIONAL), new StringField("shape_id", OPTIONAL).isReferenceTo(SHAPES), new ShortField("wheelchair_accessible", OPTIONAL, 2), new ShortField("bikes_allowed", OPTIONAL, 2), // Editor-specific fields below. new StringField("pattern_id", EDITOR).isReferenceTo(PATTERNS) ).addPrimaryKey(); // Must come after TRIPS and STOPS table to which it has references public static final Table STOP_TIMES = new Table("stop_times", StopTime.class, REQUIRED, new StringField("trip_id", REQUIRED).isReferenceTo(TRIPS), new IntegerField("stop_sequence", REQUIRED, 0, Integer.MAX_VALUE), // FIXME: Do we need an index on stop_id new StringField("stop_id", REQUIRED).isReferenceTo(STOPS), // .indexThisColumn(), // TODO verify that we have a special check for arrival and departure times first and last stop_time in a trip, which are required new TimeField("arrival_time", OPTIONAL), new TimeField("departure_time", OPTIONAL), new StringField("stop_headsign", OPTIONAL), new ShortField("pickup_type", OPTIONAL, 3), new ShortField("drop_off_type", OPTIONAL, 3), new ShortField("continuous_pickup", OPTIONAL, 3), new ShortField("continuous_drop_off", OPTIONAL, 3), new DoubleField("shape_dist_traveled", OPTIONAL, 0, Double.POSITIVE_INFINITY, 2), new ShortField("timepoint", OPTIONAL, 1), new IntegerField("fare_units_traveled", EXTENSION) // OpenOV NL extension ).withParentTable(TRIPS); // Must come after TRIPS table to which it has a reference public static final Table FREQUENCIES = new Table("frequencies", Frequency.class, OPTIONAL, new StringField("trip_id", REQUIRED).isReferenceTo(TRIPS), new TimeField("start_time", REQUIRED), new TimeField("end_time", REQUIRED), // Set max headway seconds to the equivalent of 6 hours. This should leave space for any very long headways // (e.g., a ferry running exact times at a 4 hour headway), but will catch cases where milliseconds were // exported accidentally. new IntegerField("headway_secs", REQUIRED, 20, 60*60*6), new IntegerField("exact_times", OPTIONAL, 1)) .withParentTable(TRIPS) .keyFieldIsNotUnique(); // GTFS reference: https://developers.google.com/transit/gtfs/reference#attributionstxt public static final Table TRANSLATIONS = new Table("translations", Translation.class, OPTIONAL, new StringField("table_name", REQUIRED), new StringField("field_name", REQUIRED), new LanguageField("language", REQUIRED), new StringField("translation", REQUIRED), new StringField("record_id", OPTIONAL).requireConditions( // If the field_value is empty the record_id is required. new FieldIsEmptyCheck("field_value") ), new StringField("record_sub_id", OPTIONAL).requireConditions( // If the record_id is not empty and the value is stop_times the record_sub_id is required. new FieldNotEmptyAndMatchesValueCheck("record_id", "stop_times") ), new StringField("field_value", OPTIONAL).requireConditions( // If the record_id is empty the field_value is required. new FieldIsEmptyCheck("record_id") )) .keyFieldIsNotUnique(); public static final Table ATTRIBUTIONS = new Table("attributions", Attribution.class, OPTIONAL, new StringField("attribution_id", OPTIONAL), new StringField("agency_id", OPTIONAL).isReferenceTo(AGENCY), new LanguageField("route_id", OPTIONAL).isReferenceTo(ROUTES), new StringField("trip_id", OPTIONAL).isReferenceTo(TRIPS), new StringField("organization_name", REQUIRED), new ShortField("is_producer", OPTIONAL, 1), new ShortField("is_operator", OPTIONAL, 1), new ShortField("is_authority", OPTIONAL, 1), new URLField("attribution_url", OPTIONAL), new StringField("attribution_email", OPTIONAL), new StringField("attribution_phone", OPTIONAL)); /** List of tables in order needed for checking referential integrity during load stage. */ public static final Table[] tablesInOrder = { AGENCY, CALENDAR, SCHEDULE_EXCEPTIONS, CALENDAR_DATES, FARE_ATTRIBUTES, FEED_INFO, ROUTES, PATTERNS, SHAPES, STOPS, FARE_RULES, PATTERN_STOP, TRANSFERS, TRIPS, STOP_TIMES, FREQUENCIES, TRANSLATIONS, ATTRIBUTIONS }; /** * Fluent method that restricts deletion of an entity in this table if there are references to it elsewhere. For * example, a calendar that has trips referencing it must not be deleted. */ public Table restrictDelete () { this.cascadeDeleteRestricted = true; return this; } /** * Fluent method to de-set the hasUniqueKeyField flag for tables which the first field should not be considered a * primary key. */ public Table keyFieldIsNotUnique() { this.hasUniqueKeyField = false; return this; } /** Fluent method to set whether the table has a compound key, e.g., transfers#to_stop_id. */ public Table hasCompoundKey() { this.compoundKey = true; return this; } /** * Fluent method that indicates that the integer ID field should be made a primary key. This should generally only * be used for tables that would ever need to be queried on the unique integer ID (which represents row number for * tables directly after csv load). For example, we may need to query for a stop or route by unique ID in order to * update or delete it. (Whereas querying for a specific stop time vs. a set of stop times would rarely if ever be * needed.) */ public Table addPrimaryKey () { this.usePrimaryKey = true; return this; } /** * Registers the table with a parent table. When updates are made to the parent table, updates to child entities * nested in the JSON string will be made. For example, pattern stops and shape points use this method to point to * the pattern table as their parent. Currently, an update to either of these child tables must be made by way of * a pattern update with nested array pattern_stops and/or shapes. This is due in part to the historical editor * data structure in mapdb which allowed for storing a list of objects as a table field. It also (TBD) may be useful * for ensuring data integrity and avoiding potentially risky partial updates. FIXME This needs further investigation. * * FIXME: Perhaps this logic should be removed from the Table class and explicitly stated in the editor/writer * classes. */ private Table withParentTable(Table parentTable) { this.parentTable = parentTable; return this; } /** * Get only those fields included in the official GTFS specification for this table or used by the editor. */ public List<Field> editorFields() { List<Field> editorFields = new ArrayList<>(); for (Field f : fields) if (f.requirement == REQUIRED || f.requirement == OPTIONAL || f.requirement == EDITOR) { editorFields.add(f); } return editorFields; } /** * Get only those fields marked as required in the official GTFS specification for this table. */ public List<Field> requiredFields () { // Filter out fields not used in editor (i.e., extension fields). List<Field> requiredFields = new ArrayList<>(); for (Field f : fields) if (f.requirement == REQUIRED) requiredFields.add(f); return requiredFields; } /** * Get only those fields included in the official GTFS specification for this table, i.e., filter out fields used * in the editor or extensions. */ public List<Field> specFields () { List<Field> specFields = new ArrayList<>(); for (Field f : fields) if (f.requirement == REQUIRED || f.requirement == OPTIONAL) specFields.add(f); return specFields; } public boolean isCascadeDeleteRestricted() { return cascadeDeleteRestricted; } public boolean createSqlTable(Connection connection) { return createSqlTable(connection, null, false, null); } public boolean createSqlTable(Connection connection, boolean makeIdSerial) { return createSqlTable(connection, null, makeIdSerial, null); } public boolean createSqlTable(Connection connection, String namespace, boolean makeIdSerial) { return createSqlTable(connection, namespace, makeIdSerial, null); } /** * Create an SQL table with all the fields specified by this table object, * plus an integer CSV line number field in the first position. */ public boolean createSqlTable (Connection connection, String namespace, boolean makeIdSerial, String[] primaryKeyFields) { // Optionally join namespace and name to create full table name if namespace is not null (i.e., table object is // a spec table). String tableName = namespace != null ? String.join(".", namespace, name) : name; String fieldDeclarations = Arrays.stream(fields) .map(Field::getSqlDeclaration) .collect(Collectors.joining(", ")); if (primaryKeyFields != null) { fieldDeclarations += String.format(", primary key (%s)", String.join(", ", primaryKeyFields)); } String dropSql = String.format("drop table if exists %s", tableName); // Adding the unlogged keyword gives about 12 percent speedup on loading, but is non-standard. String idFieldType = makeIdSerial ? "serial" : "bigint"; String createSql = String.format("create table %s (id %s not null, %s)", tableName, idFieldType, fieldDeclarations); try { Statement statement = connection.createStatement(); LOG.info(dropSql); statement.execute(dropSql); LOG.info(createSql); return statement.execute(createSql); } catch (Exception ex) { throw new StorageException(ex); } } /** * Create an SQL table that will insert a value into all the fields specified by this table object, * plus an integer CSV line number field in the first position. */ public String generateInsertSql () { return generateInsertSql(null, false); } public String generateInsertSql (boolean setDefaultId) { return generateInsertSql(null, setDefaultId); } /** * Create SQL string for use in insert statement. Note, this filters table's fields to only those used in editor. */ public String generateInsertSql (String namespace, boolean setDefaultId) { String tableName = namespace == null ? name : String.join(".", namespace, name); String joinedFieldNames = commaSeparatedNames(editorFields()); String idValue = setDefaultId ? "DEFAULT" : "?"; return String.format( "insert into %s (id, %s) values (%s, %s)", tableName, joinedFieldNames, idValue, String.join(", ", Collections.nCopies(editorFields().size(), "?")) ); } /** * In GTFS feeds, all files are supposed to be in the root of the zip file, but feed producers often put them * in a subdirectory. This function will search subdirectories if the entry is not found in the root. * It records an error if the entry is in a subdirectory (as long as errorStorage is not null). * It then creates a CSV reader for that table if it's found. */ public CsvReader getCsvReader(ZipFile zipFile, SQLErrorStorage sqlErrorStorage) { final String tableFileName = this.name + ".txt"; ZipEntry entry = zipFile.getEntry(tableFileName); if (entry == null) { // Table was not found, check if it is in a subdirectory. Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry e = entries.nextElement(); if (e.getName().endsWith(tableFileName)) { entry = e; if (sqlErrorStorage != null) sqlErrorStorage.storeError(NewGTFSError.forTable(this, TABLE_IN_SUBDIRECTORY)); break; } } } if (entry == null) return null; try { InputStream zipInputStream = zipFile.getInputStream(entry); // Skip any byte order mark that may be present. Files must be UTF-8, // but the GTFS spec says that "files that include the UTF byte order mark are acceptable". InputStream bomInputStream = new BOMInputStream(zipInputStream); CsvReader csvReader = new CsvReader(bomInputStream, ',', Charset.forName("UTF8")); // Don't skip empty records (this is set to true by default on CsvReader. We want to check for empty records // during table load, so that they are logged as validation issues (WRONG_NUMBER_OF_FIELDS). csvReader.setSkipEmptyRecords(false); csvReader.readHeaders(); return csvReader; } catch (IOException e) { LOG.error("Exception while opening zip entry: {}", e); e.printStackTrace(); return null; } } /** * Join a list of fields with a comma + space separator. */ public static String commaSeparatedNames(List<Field> fieldsToJoin) { return commaSeparatedNames(fieldsToJoin, null, false); } /** * Prepend a prefix string to each field and join them with a comma + space separator. * Also, if an export to GTFS is being performed, certain fields need a translation from the database format to the * GTFS format. Otherwise, the fields are assumed to be asked in order to do a database-to-database export and so * the verbatim values of the fields are needed. */ public static String commaSeparatedNames(List<Field> fieldsToJoin, String prefix, boolean csvOutput) { return fieldsToJoin.stream() // NOTE: This previously only prefixed fields that were foreign refs or key fields. However, this // caused an issue where shared fields were ambiguously referenced in a select query (specifically, // wheelchair_accessible in routes and trips). So this filter has been removed. .map(f -> f.getColumnExpression(prefix, csvOutput)) .collect(Collectors.joining(", ")); } // FIXME: Add table method that sets a field parameter based on field name and string value? // public void setParameterByName (PreparedStatement preparedStatement, String fieldName, String value) { // Field field = getFieldForName(fieldName); // int editorFieldIndex = editorFields().indexOf(field); // field.setParameter(preparedStatement, editorFieldIndex, value); /** * Create SQL string for use in update statement. Note, this filters table's fields to only those used in editor. */ public String generateUpdateSql (String namespace, int id) { // Collect field names for string joining from JsonObject. String joinedFieldNames = editorFields().stream() // If updating, add suffix for use in set clause .map(field -> field.name + " = ?") .collect(Collectors.joining(", ")); String tableName = namespace == null ? name : String.join(".", namespace, name); return String.format("update %s set %s where id = %d", tableName, joinedFieldNames, id); } /** * Generate select all SQL string. The minimum requirement parameter is used to determine which fields ought to be * included in the select statement. For example, if "OPTIONAL" is passed in, both optional and required fields * are included in the select. If "EDITOR" is the minimum requirement, editor, optional, and required fields will * all be included. */ public String generateSelectSql (String namespace, Requirement minimumRequirement) { String fieldsString; String tableName = String.join(".", namespace, name); String fieldPrefix = tableName + "."; if (minimumRequirement.equals(EDITOR)) { fieldsString = commaSeparatedNames(editorFields(), fieldPrefix, true); } else if (minimumRequirement.equals(OPTIONAL)) { fieldsString = commaSeparatedNames(specFields(), fieldPrefix, true); } else if (minimumRequirement.equals(REQUIRED)) { fieldsString = commaSeparatedNames(requiredFields(), fieldPrefix, true); } else fieldsString = "*"; return String.format("select %s from %s", fieldsString, tableName); } /** * Shorthand wrapper for calling {@link #generateSelectSql(String, Requirement)}. Note: this does not prefix field * names with the namespace, so cannot serve as a replacement for {@link #generateSelectAllExistingFieldsSql}. */ public String generateSelectAllSql (String namespace) { return generateSelectSql(namespace, Requirement.PROPRIETARY); } /** * Generate a select statement from the columns that actually exist in the database table. This method is intended * to be used when exporting to a GTFS and eventually generates the select all with each individual field and * applicable transformations listed out. */ public String generateSelectAllExistingFieldsSql(Connection connection, String namespace) throws SQLException { // select all columns from table // FIXME This is postgres-specific and needs to be made generic for non-postgres databases. PreparedStatement statement = connection.prepareStatement( "SELECT column_name FROM information_schema.columns WHERE table_schema = ? AND table_name = ?" ); statement.setString(1, namespace); statement.setString(2, name); ResultSet result = statement.executeQuery(); // get result and add fields that are defined in this table List<Field> existingFields = new ArrayList<>(); while (result.next()) { String columnName = result.getString(1); existingFields.add(getFieldForName(columnName)); } String tableName = String.join(".", namespace, name); String fieldPrefix = tableName + "."; return String.format( "select %s from %s", commaSeparatedNames(existingFields, fieldPrefix, true), tableName ); } public String generateJoinSql (Table joinTable, String namespace, String fieldName, boolean prefixTableName) { return generateJoinSql(null, joinTable, null, namespace, fieldName, prefixTableName); } public String generateJoinSql (String optionalSelect, Table joinTable, String namespace) { return generateJoinSql(optionalSelect, joinTable, null, namespace, null, true); } public String generateJoinSql (Table joinTable, String namespace) { return generateJoinSql(null, joinTable, null, namespace, null, true); } /** * Constructs a join clause to use in conjunction with {@link #generateJoinSql}. By default the join type is "INNER * JOIN" and the join field is whatever the table instance's key field is. Both of those defaults can be overridden * with the other overloaded methods. * @param optionalSelect optional select query to pre-select the join table * @param joinTable the Table to join with * @param joinType type of join (e.g., INNER JOIN, OUTER LEFT JOIN, etc.) * @param namespace feedId (or schema prefix) * @param fieldName the field to join on (default's to key field) * @param prefixTableName whether to prefix this table's name with the schema (helpful if this join follows a * previous join that renamed the table by dropping the schema/namespace * @return a fully formed join clause that can be appended to a select statement */ public String generateJoinSql (String optionalSelect, Table joinTable, String joinType, String namespace, String fieldName, boolean prefixTableName) { if (fieldName == null) { // Default to key field if field name is not specified fieldName = getKeyFieldName(); } if (joinType == null) { // Default to INNER JOIN if no join type provided joinType = "INNER JOIN"; } String joinTableQuery; String joinTableName; if (optionalSelect != null) { // If a pre-select query is provided for the join table, the join table name must not contain the namespace // prefix. joinTableName = joinTable.name; joinTableQuery = String.format("(%s) %s", optionalSelect, joinTableName); } else { // Otherwise, set both the join "query" and the table name to the standard "namespace.table_name" joinTableQuery = joinTableName = String.format("%s.%s", namespace, joinTable.name); } // If prefix table name is set to false, skip prefixing the table name. String tableName = prefixTableName ? String.format("%s.%s", namespace, this.name) :this.name; // Construct the join clause. A sample might appear like: // "INNER JOIN schema.join_table ON schema.this_table.field_name = schema.join_table.field_name" // OR if optionalSelect is specified // "INNER JOIN (select * from schema.join_table where x = 'y') join_table ON schema.this_table.field_name = join_table.field_name" return String.format("%s %s ON %s.%s = %s.%s", joinType, joinTableQuery, tableName, fieldName, joinTableName, fieldName); } public String generateDeleteSql (String namespace) { return generateDeleteSql(namespace, null); } /** * Generate delete SQL string. */ public String generateDeleteSql (String namespace, String fieldName) { String whereField = fieldName == null ? "id" : fieldName; return String.format("delete from %s where %s = ?", String.join(".", namespace, name), whereField); } /** * @param name a column name from the header of a CSV file * @return the Field object from this table with the given name. If there is no such field defined, create * a new Field object for this name. */ public Field getFieldForName(String name) { int index = getFieldIndex(name); if (index >= 0) return fields[index]; LOG.warn("Unrecognized header {}. Treating it as a proprietary string field.", name); return new StringField(name, UNKNOWN); } /** * Gets the key field for the table. Calling this on a table that has no key field is meaningless. WARNING: this * MUST be called on a spec table (i.e., one of the constant tables defined in this class). Otherwise, it * could return a non-key field. * * FIXME: Should this return null if hasUniqueKeyField is false? Not sure what might break if we change this... */ public String getKeyFieldName () { // FIXME: If the table is constructed from fields found in a GTFS file, the first field is not guaranteed to be // the key field. return fields[0].name; } /** * Returns field name that defines order for grouped entities or that defines the compound key field (e.g., * transfers#to_stop_id). WARNING: this field must be in the 1st position (base zero) of the fields array; hence, * this MUST be called on a spec table (i.e., one of the constant tables defined in this class). Otherwise, it could * return null even if the table has an order field defined. */ public String getOrderFieldName () { String name = fields[1].name; if (name.contains("_sequence") || compoundKey) return name; else return null; } /** * Gets index fields for the spec table. WARNING: this MUST be called on a spec table (i.e., one of the constant * tables defined in this class). Otherwise, it could return fields that should not be indexed. * @return */ public String getIndexFields() { String orderFieldName = getOrderFieldName(); if (orderFieldName == null) return getKeyFieldName(); else return String.join(",", getKeyFieldName(), orderFieldName); } public Class<? extends Entity> getEntityClass() { return entityClass; } /** * Finds the index of the field for this table given a string name. * @return the index of the field or -1 if no match is found */ public int getFieldIndex (String name) { return Field.getFieldIndex(fields, name); } /** * Whether a field with the provided name exists in the table's list of fields. */ public boolean hasField (String name) { return getFieldIndex(name) != -1; } public boolean isRequired () { return required == REQUIRED; } /** * Checks whether the table is part of the GTFS specification, i.e., it is not an internal table used for the editor * (e.g., Patterns or PatternStops). */ public boolean isSpecTable() { return required == REQUIRED || required == OPTIONAL; } /** * Create indexes for table using shouldBeIndexed(), key field, and/or sequence field. WARNING: this MUST be called * on a spec table (i.e., one of the constant tables defined in this class). Otherwise, the getIndexFields method * could return fields that should not be indexed. * FIXME: add foreign reference indexes? */ public void createIndexes(Connection connection, String namespace) throws SQLException { if ("agency".equals(name) || "feed_info".equals(name)) { // Skip indexing for the small tables that have so few records that indexes are unlikely to // improve query performance or that are unlikely to be joined to other tables. NOTE: other tables could be // added here in the future as needed. LOG.info("Skipping indexes for {} table", name); return; } LOG.info("Indexing {}...", name); String tableName; if (namespace == null) { throw new IllegalStateException("Schema namespace must be provided!"); } else { // Construct table name with prefixed namespace (and account for whether it already ends in a period). tableName = namespace.endsWith(".") ? namespace + name : String.join(".", namespace, name); } // We determine which columns should be indexed based on field order in the GTFS spec model table. // Not sure that's a good idea, this could use some abstraction. TODO getIndexColumns() on each table. String indexColumns = getIndexFields(); // TODO verify referential integrity and uniqueness of keys // TODO create primary key and fall back on plain index (consider not null & unique constraints) // TODO use line number as primary key // Note: SQLITE requires specifying a name for indexes. String indexName = String.join("_", tableName.replace(".", "_"), "idx"); String indexSql = String.format("create index %s on %s (%s)", indexName, tableName, indexColumns); //String indexSql = String.format("alter table %s add primary key (%s)", tableName, indexColumns); LOG.info(indexSql); connection.createStatement().execute(indexSql); // TODO add foreign key constraints, and recover recording errors as needed. // More indexing // TODO integrate with the above indexing code, iterating over a List<String> of index column expressions for (Field field : fields) { if (field.shouldBeIndexed()) { Statement statement = connection.createStatement(); String fieldIndex = String.join("_", tableName.replace(".", "_"), field.name, "idx"); String sql = String.format("create index %s on %s (%s)", fieldIndex, tableName, field.name); LOG.info(sql); statement.execute(sql); } } } /** * Creates a SQL table from the table to clone. This uses the SQL syntax "create table x as y" not only copies the * table structure, but also the data from the original table. Creating table indexes is not handled by this method. * * Note: the stop_times table is a special case that will optionally normalize the stop_sequence values to be * zero-based and incrementing. * * @param connection SQL connection * @param tableToClone table name to clone (in the dot notation: namespace.gtfs_table) * @param normalizeStopTimes whether to normalize stop times (set stop_sequence values to be zero-based and * incrementing) */ public boolean createSqlTableFrom(Connection connection, String tableToClone, boolean normalizeStopTimes) { long startTime = System.currentTimeMillis(); try { Statement statement = connection.createStatement(); // Drop target table to avoid a conflict. String dropSql = String.format("drop table if exists %s", name); LOG.info(dropSql); statement.execute(dropSql); if (tableToClone.endsWith("stop_times") && normalizeStopTimes) { normalizeAndCloneStopTimes(statement, name, tableToClone); } else { // Adding the unlogged keyword gives about 12 percent speedup on loading, but is non-standard. // FIXME: Which create table operation is more efficient? String createTableAsSql = String.format("create table %s as table %s", name, tableToClone); // Create table in the image of the table we're copying (indexes are not included). LOG.info(createTableAsSql); statement.execute(createTableAsSql); } applyAutoIncrementingSequence(statement); // FIXME: Is there a need to add primary key constraint here? if (usePrimaryKey) { // Add primary key to ID column for any tables that require it. String addPrimaryKeySql = String.format("ALTER TABLE %s ADD PRIMARY KEY (id)", name); LOG.info(addPrimaryKeySql); statement.execute(addPrimaryKeySql); } return true; } catch (SQLException ex) { LOG.error("Error cloning table {}: {}", name, ex.getSQLState()); LOG.error("details: ", ex); try { connection.rollback(); // It is likely that if cloning the table fails, the reason was that the table did not already exist. // Try to create the table here from scratch. // FIXME: Maybe we should check that the reason the clone failed was that the table already exists. createSqlTable(connection, true); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } finally { LOG.info("Cloned table {} as {} in {} ms", tableToClone, name, System.currentTimeMillis() - startTime); } } /** * Normalize stop sequences for stop times table so that sequences are all zero-based and increment by one. This ensures that sequence values for stop_times and pattern_stops are not initially out of sync for feeds imported into the editor. NOTE: This happens here instead of as part of post-processing because it's much faster overall to perform this as an INSERT vs. an UPDATE. It also needs to be done before creating table indexes. There may be some messiness here as far as using the column metadata to perform the SELECT query with the correct column names, but it is about an order of magnitude faster than the UPDATE approach. For example, with the Bronx bus feed, the UPDATE approach took 53 seconds on an un-normalized table (i.e., snapshotting a table from a direct GTFS load), but it only takes about 8 seconds with the INSERT approach. Additionally, this INSERT approach seems to dramatically cut down on the time needed for indexing large tables. */ private void normalizeAndCloneStopTimes(Statement statement, String name, String tableToClone) throws SQLException { // Create table with matching columns first and then insert all rows with a special select query that // normalizes the stop sequences before inserting. // "Create table like" can optionally include indexes, but we want to avoid creating the indexes beforehand // because this will slow down our massive insert for stop times. String createTableLikeSql = String.format("create table %s (like %s)", name, tableToClone); LOG.info(createTableLikeSql); statement.execute(createTableLikeSql); long normalizeStartTime = System.currentTimeMillis(); LOG.info("Normalizing stop sequences"); // First get the column names (to account for any non-standard fields that may be present) List<String> columns = new ArrayList<>(); ResultSet resultSet = statement.executeQuery(String.format("select * from %s limit 1", tableToClone)); ResultSetMetaData metadata = resultSet.getMetaData(); int nColumns = metadata.getColumnCount(); for (int i = 1; i <= nColumns; i++) { columns.add(metadata.getColumnName(i)); } // Replace stop sequence column with the normalized sequence values. columns.set(columns.indexOf("stop_sequence"), "-1 + row_number() over (partition by trip_id order by stop_sequence) as stop_sequence"); String insertAllSql = String.format("insert into %s (select %s from %s)", name, String.join(", ", columns), tableToClone); LOG.info(insertAllSql); statement.execute(insertAllSql); LOG.info("Normalized stop times sequences in {} ms", System.currentTimeMillis() - normalizeStartTime); } private void applyAutoIncrementingSequence(Statement statement) throws SQLException { String selectMaxSql = String.format("SELECT MAX(id) + 1 FROM %s", name); int maxID = 0; LOG.info(selectMaxSql); statement.execute(selectMaxSql); ResultSet maxIdResult = statement.getResultSet(); if (maxIdResult.next()) { maxID = maxIdResult.getInt(1); } // Set default max ID to 1 (the start value cannot be less than MINVALUE 1) // FIXME: Skip sequence creation if maxID = 1? if (maxID < 1) { maxID = 1; } String sequenceName = name + "_id_seq"; String createSequenceSql = String.format("CREATE SEQUENCE %s START WITH %d", sequenceName, maxID); LOG.info(createSequenceSql); statement.execute(createSequenceSql); String alterColumnNextSql = String.format("ALTER TABLE %s ALTER COLUMN id SET DEFAULT nextval('%s')", name, sequenceName); LOG.info(alterColumnNextSql); statement.execute(alterColumnNextSql); String alterColumnNotNullSql = String.format("ALTER TABLE %s ALTER COLUMN id SET NOT NULL", name); LOG.info(alterColumnNotNullSql); statement.execute(alterColumnNotNullSql); } public Table getParentTable() { return parentTable; } /** * For an array of field headers, returns the matching set of {@link Field}s for a {@link Table}. If errorStorage is * not null, errors related to unexpected or duplicate header names will be stored. */ public Field[] getFieldsFromFieldHeaders(String[] headers, SQLErrorStorage errorStorage) { Field[] fields = new Field[headers.length]; Set<String> fieldsSeen = new HashSet<>(); for (int h = 0; h < headers.length; h++) { String header = sanitize(headers[h], errorStorage); if (fieldsSeen.contains(header) || "id".equals(header)) { // FIXME: add separate error for tables containing ID field. if (errorStorage != null) errorStorage.storeError(NewGTFSError.forTable(this, DUPLICATE_HEADER).setBadValue(header)); fields[h] = null; } else { fields[h] = getFieldForName(header); fieldsSeen.add(header); } } return fields; } /** * Returns the index of the key field within the array of fields provided for a given table. * @param fields array of fields (intended to be derived from the headers of a csv text file) */ public int getKeyFieldIndex(Field[] fields) { String keyField = getKeyFieldName(); return Field.getFieldIndex(fields, keyField); } public boolean hasConditionalRequirements() { return !getConditionalRequirements().isEmpty(); } public Map<Field, ConditionalRequirement[]> getConditionalRequirements() { Map<Field, ConditionalRequirement[]> fieldsWithConditions = new HashMap<>(); for (Field field : fields) { if (field.isConditionallyRequired()) { fieldsWithConditions.put(field, field.conditions); } } return fieldsWithConditions; } }
package com.testa3d.taprhythm; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.Screen; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.scenes.scene2d.Action; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.utils.viewport.FitViewport; import java.math.BigDecimal; import java.text.DecimalFormat; import java.util.Random; import static com.badlogic.gdx.scenes.scene2d.actions.Actions.delay; import static com.badlogic.gdx.scenes.scene2d.actions.Actions.run; import static com.badlogic.gdx.scenes.scene2d.actions.Actions.sequence; public class MainMenuScreen implements Screen { final taprhythm game; private static final class ScoreText extends Actor { String text = ""; BitmapFont font = new BitmapFont(Gdx.files.internal("m_plus_1p.fnt")); @Override public void draw(Batch batch, float parentAlpha) { super.draw(batch, parentAlpha); font.draw(batch, text, getX(), getY()); } } private ScoreText scoreText; private ScoreText dot; private float score; private String one = "0"; private String two = "0"; private String three = "0"; private String four = "0"; private String five = "0"; OrthographicCamera camera; private double dtokuten; private String escore; private Stage stage; private Image im1; private Image im2; private Image im3; private Image im4; private Image im5; private Sound roll; int onrandom = 0; Random rnd = new Random(); public MainMenuScreen(final taprhythm game) { this.game = game; escore =""; stage = new Stage(new FitViewport(1920,1080)); im1 = new Image(new Texture(Gdx.files.internal("blue"+one+".png"))); im2 = new Image(new Texture(Gdx.files.internal("blue"+two+".png"))); im3 = new Image(new Texture(Gdx.files.internal("red"+three+".png"))); im4 = new Image(new Texture(Gdx.files.internal("red"+four+".png"))); im5 = new Image(new Texture(Gdx.files.internal("red"+five+".png"))); im1.setPosition(stage.getWidth() * 0.1f,stage.getHeight() / 2); im2.setPosition(stage.getWidth() * 0.25f,stage.getHeight() / 2); im3.setPosition(stage.getWidth() * 0.55f,stage.getHeight() / 2); im4.setPosition(stage.getWidth() * 0.65f,stage.getHeight() / 2); im5.setPosition(stage.getWidth() * 0.7f,stage.getHeight() / 2); stage.addActor(im1); stage.addActor(im2); stage.addActor(im3); stage.addActor(im4); stage.addActor(im5); scoreText = new ScoreText(); scoreText.text = "Your Score is ..."; scoreText.setPosition(150, stage.getHeight() - 40); stage.addActor(scoreText); dot = new ScoreText(); dot.text = "."; dot.setPosition(stage.getWidth() * 0.31f,stage.getHeight() / 2+42); stage.addActor(dot); } public void settokuten(){ DecimalFormat exFormat1 = new DecimalFormat("00.000"); escore = exFormat1.format(dtokuten); escore = escore.replace(".", ""); Gdx.app.log("TapRhythm:MainMenuScore",escore); one = escore.substring(0,1); two = escore.substring(1,2); three = escore.substring(2,3); four = escore.substring(3,4); five = escore.substring(4,5); Gdx.app.log("TapRhythm:one",one); Gdx.app.log("TapRhythm:two",two); Gdx.app.log("TapRhythm:three",three); Gdx.app.log("TapRhythm:four",four); Gdx.app.log("TapRhythm:five",five); } @Override public void render(float delta) { Gdx.gl.glClearColor(255 / 255.f, 255 / 255.f, 255 / 255.f, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); if(onrandom == 5){ one = String.valueOf(rnd.nextInt(10)); two = String.valueOf(rnd.nextInt(10)); three = String.valueOf(rnd.nextInt(10)); four = String.valueOf(rnd.nextInt(10)); five = String.valueOf(rnd.nextInt(10)); } if(onrandom == 4){ one = String.valueOf(rnd.nextInt(10)); two = String.valueOf(rnd.nextInt(10)); three = String.valueOf(rnd.nextInt(10)); four = String.valueOf(rnd.nextInt(10)); // five = String.valueOf(rnd.nextInt(10)); } if(onrandom == 3){ one = String.valueOf(rnd.nextInt(10)); two = String.valueOf(rnd.nextInt(10)); three = String.valueOf(rnd.nextInt(10)); // four = String.valueOf(rnd.nextInt(10)); // five = String.valueOf(rnd.nextInt(10)); } if(onrandom == 2){ one = String.valueOf(rnd.nextInt(10)); two = String.valueOf(rnd.nextInt(10)); // three = String.valueOf(rnd.nextInt(10)); // four = String.valueOf(rnd.nextInt(10)); // five = String.valueOf(rnd.nextInt(10)); } im1.remove(); im2.remove(); im3.remove(); im4.remove(); im5.remove(); im1 = new Image(new Texture(Gdx.files.internal("blue"+one+".png"))); im2 = new Image(new Texture(Gdx.files.internal("blue"+two+".png"))); im3 = new Image(new Texture(Gdx.files.internal("red"+three+".png"))); im4 = new Image(new Texture(Gdx.files.internal("red"+four+".png"))); im5 = new Image(new Texture(Gdx.files.internal("red"+five+".png"))); im1.setPosition(stage.getWidth() * 0.1f,stage.getHeight() / 2); im2.setPosition(stage.getWidth() * 0.2f,stage.getHeight() / 2); im3.setPosition(stage.getWidth() * 0.35f,stage.getHeight() / 2); im4.setPosition(stage.getWidth() * 0.45f,stage.getHeight() / 2); im5.setPosition(stage.getWidth() * 0.55f,stage.getHeight() / 2); stage.addActor(im1); stage.addActor(im2); stage.addActor(im3); stage.addActor(im4); stage.addActor(im5); stage.act(Gdx.graphics.getDeltaTime()); // render(delta time) stage.draw(); } @Override public void resize(int width, int height) { } public void setGscore(float gscore){ score = gscore; } @Override public void pause() { } @Override public void resume() { } @Override public void show() { roll = Gdx.audio.newSound(Gdx.files.internal("roll.ogg")); dtokuten = score; onrandom = 5; roll.play(); stage.addAction(randomend); } private final Action randomend = sequence( delay(2), run(new Runnable() { @Override public void run() { onrandom = 4; settokuten(); } }), delay(0.5f), run(new Runnable() { @Override public void run() { onrandom = 3; settokuten(); } }), delay(0.5f), run(new Runnable() { @Override public void run() { onrandom = 2; settokuten(); } }), delay(1.8f), run(new Runnable() { @Override public void run() { onrandom = 1; settokuten(); } })); @Override public void hide() { } @Override public void dispose() { } }
package org.cactoos.set; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Joined; import org.hamcrest.Matcher; import org.hamcrest.core.AllOf; import org.hamcrest.core.IsCollectionContaining; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasSize; /** * Test case for {@link SetOf}. * @since 0.49.2 * @checkstyle MagicNumber (500 line) * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") public final class SetOfTest { @Test public void behaveAsSetWithOriginalDuplicationsInTheTail() { new Assertion<>( "Must keep unique numbers", new SetOf<>(1, 2, 2), new AllOf<>( new IterableOf<Matcher<? super SetOf<Integer>>>( new HasSize(2), new IsCollectionContaining<>(new IsEqual<>(1)), new IsCollectionContaining<>(new IsEqual<>(2)) ) ) ).affirm(); } @Test public void behaveAsSetWithOriginalDuplicationsInTheHead() { new Assertion<>( "Must keep unique numbers", new SetOf<>(1, 1, 2, 3), new AllOf<>( new IterableOf<Matcher<? super SetOf<Integer>>>( new HasSize(3), new IsCollectionContaining<>(new IsEqual<>(1)), new IsCollectionContaining<>(new IsEqual<>(2)), new IsCollectionContaining<>(new IsEqual<>(3)) ) ) ).affirm(); } @Test public void behaveAsSetWithOriginalDuplicationsInTheMiddle() { new Assertion<>( "Must keep unique numbers", new SetOf<>(1, 2, 2, 3), new AllOf<>( new IterableOf<Matcher<? super SetOf<Integer>>>( new HasSize(3), new IsCollectionContaining<>(new IsEqual<>(1)), new IsCollectionContaining<>(new IsEqual<>(2)), new IsCollectionContaining<>(new IsEqual<>(3)) ) ) ).affirm(); } @Test public void behaveAsSetWithOriginalMergedCollectionsWithDuplicates() { new Assertion<>( "Must keep unique string literals", new SetOf<String>( new Joined<String>( new IterableOf<>("cc", "ff"), new IterableOf<>("aa", "bb", "cc", "dd") ) ), new AllOf<>( new IterableOf<Matcher<? super SetOf<String>>>( new HasSize(5), new IsCollectionContaining<>(new IsEqual<>("aa")), new IsCollectionContaining<>(new IsEqual<>("bb")), new IsCollectionContaining<>(new IsEqual<>("cc")), new IsCollectionContaining<>(new IsEqual<>("dd")), new IsCollectionContaining<>(new IsEqual<>("ff")) ) ) ).affirm(); } }
package com.dnmaze.dncli.patch; import com.dnmaze.dncli.command.CommandPatch; import com.dnmaze.dncli.util.OsUtil; import lombok.Cleanup; import lombok.SneakyThrows; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Objects; public class Patcher implements Runnable { private static final int BUFSIZE = 8192; private static final int MAX_REDIRECTS = System.getenv("MAX_REDIRECTS") == null ? 10 : Integer.parseInt(System.getenv("MAX_REDIRECTS")); private final CommandPatch args; public Patcher(CommandPatch args) { this.args = args; } @SneakyThrows @Override public void run() { File outputDir = args.getOutput(); Objects.requireNonNull(outputDir, "Output directory cannot be null"); outputDir = outputDir.getAbsoluteFile(); int baseVersion = args.getBaseVersion(); int endVersion = args.getEndVersion(); int version = baseVersion; if (endVersion < baseVersion) { throw new RuntimeException("the end version must be at least equal to the end version."); } HttpURLConnection.setFollowRedirects(false); while (version < endVersion) { int nextVersion = version + 1; String strVersion = getPatchString(nextVersion); URL patchUrl = new URL(args.getUrl(), strVersion + "/Patch" + strVersion + ".pak"); String url = patchUrl.toString(); File output = new File(outputDir, "Patch" + strVersion + ".pak"); if (download(patchUrl, output, 0)) { log(url + " -> " + output.getPath()); } else { break; } version = nextVersion; } int diff = version - baseVersion; if (diff != 0) { log(""); } log("Downloaded " + diff + " patch(es)."); log("Ended at version " + version); File versionFile = args.getVersionFile(); if (versionFile != null) { log(""); createVersionFile(versionFile.getAbsoluteFile(), version); } } private boolean download(URL url, File destination, int redirectCount) throws IOException { if (redirectCount >= MAX_REDIRECTS) { throw new IOException("Too many redirects (" + MAX_REDIRECTS + ")"); } @Cleanup("disconnect") HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setInstanceFollowRedirects(false); conn.connect(); if (conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM || conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) { String redirectUrl = conn.getHeaderField("Location"); // follow redirect return redirectUrl.endsWith(destination.getName()) && download(new URL(redirectUrl), destination, redirectCount + 1); } if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { return false; } // if not force overwrite, check with user if can overwrite. if (!args.isForce() && !OsUtil.confirmOverwrite(destination)) { return true; } File parentDir = destination.getParentFile(); if (!parentDir.exists() && !parentDir.mkdirs()) { throw new IOException("Could not create " + parentDir.getPath()); } try (InputStream input = conn.getInputStream()) { try (OutputStream output = new FileOutputStream(destination)) { byte[] buffer = new byte[BUFSIZE]; int read; while ((read = input.read(buffer)) != -1) { output.write(buffer, 0, read); } } } return true; } private void createVersionFile(File file, int version) throws IOException { File parentDir = file.getParentFile(); if (!parentDir.exists() && !parentDir.mkdirs()) { throw new IOException("Could not create directory " + parentDir.getPath()); } // if not force overwrite, check with user if can overwrite. if (!args.isForce() && !OsUtil.confirmOverwrite(file)) { return; } try (FileOutputStream output = new FileOutputStream(file)) { output.write(("" + version).getBytes(StandardCharsets.UTF_8)); log("Created version file " + file.getPath()); } } private String getPatchString(int version) { return ("" + (100000000 + version)).substring(1); } private void log(String message) { if (!args.isQuiet()) { System.out.println(message); } } }
package tech.tablesaw; import tech.tablesaw.api.BooleanColumn; import tech.tablesaw.api.CategoryColumn; import tech.tablesaw.api.DateColumn; import tech.tablesaw.api.ShortColumn; import tech.tablesaw.api.Table; import tech.tablesaw.reducing.CrossTab; import tech.tablesaw.util.Selection; import static tech.tablesaw.api.QueryHelper.*; import static tech.tablesaw.reducing.NumericReduceUtils.range; /** * Example code for: * Learning Data Science with Java and Tablesaw * */ public class Example1 { public static void main(String[] args) throws Exception { // create our table from a flat file: Table table1 = Table.read().csv("data/BushApproval.csv"); // return the name of the table out("Table name: " + table1.name()); // return the table's shape out(table1.shape()); // display the table structure: out(table1.structure().print()); // We can peak at a few rows: out("First three rows:"); out(table1.first(3).print()); // List the column names out("Column names: " + table1.columnNames()); // Get the approval column. ShortColumn approval = table1.shortColumn("approval"); // Column Operation Examples // Operations like count(), and min() produce a single value for a column of data. out("Minimum approval rating: " + approval.min()); // Other operations return a new column. // Method dayOfYear() applied to a DateColumn returns a ShortColumn containing the day of the year from 1 to 366 DateColumn date = table1.dateColumn("date"); ShortColumn dayOfYear = date.dayOfYear(); out(dayOfYear.summary().print()); // Show the first 10 elements of the column out(dayOfYear.first(10).print()); // As a rule, column-returning methods come in two flavors: Some take a scalar value as an input. // This adds four days to every element. out(date.plusDays(4)); // Others take a column as an argument. They process the two columns in order, computing a new value for each // row and returning it as a column // Boolean results // Boolean operations like isMonday() return a Selection object. Selections can be used to filter tables Selection selection = date.isMonday(); // To get a boolean column if you want it. You simply pass the Selection and the original column length to a BooleanColumn constructor, along with a name for the new column. BooleanColumn monday = new BooleanColumn("monday?", selection, date.size()); out(monday.summary().print()); //Querying //NOTE: we need a static import of QueryHelper for this section. See the imports above Table highRatings = table1.selectWhere(column("approval").isGreaterThan(80)); highRatings.setName("Approval ratings over 80%"); out(highRatings.print()); Table Q3 = table1.selectWhere(date.isInQ3()); Q3.setName("3rd Quarter ratings"); out(Q3.print()); // Sorting // Sort on column names in ascending order highRatings = highRatings.sortOn("who", "approval"); out(highRatings.first(10).print()); // Sort on column names in descending order highRatings = highRatings.sortDescendingOn("who", "approval"); out(highRatings.first(10).print()); // to a column name to indicate a descending sort on that column highRatings = highRatings.sortOn("who", "-approval"); out(highRatings.first(10).print()); // Summarizing Table summary = table1.summarize("approval", range).by("who"); out(summary.print()); CategoryColumn month = date.month(); table1.addColumn(month); CategoryColumn who = table1.categoryColumn("who"); Table xtab = CrossTab.xTabCount(table1, month, who); out(xtab.print()); out(CrossTab.tablePercents(xtab).print()); } private static void out(Object str) { System.out.println(String.valueOf(str)); System.out.println(""); } }
package org.mariadb.jdbc; import org.junit.Assert; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; import java.sql.*; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class DateTest extends BaseTest { /** * Initialization. * @throws SQLException exception */ @BeforeClass() public static void initClass() throws SQLException { createTable("dtest", "d date"); createTable("date_test2", "id int not null primary key auto_increment, d_from datetime ,d_to datetime"); createTable("timetest", "t time"); createTable("timetest2", "t time"); createTable("timestampzerotest", "ts timestamp, dt datetime, dd date"); createTable("dtest", "d datetime"); createTable("dtest2", "d date"); createTable("dtest3", "d date"); createTable("dtest4", "d time"); createTable("date_test3", " x date"); createTable("date_test4", "x date"); createTable("timestampAsDate", "ts timestamp(6), dt datetime(6), dd date"); } @Test public void dateTestLegacy() throws SQLException { dateTest(true); } @Test public void dateTestWithoutLegacy() throws SQLException { dateTest(false); } /** * Date testing. * @param useLegacy use legacy client side timezone or server side timezone. * @throws SQLException exception */ public void dateTest(boolean useLegacy) throws SQLException { Assume.assumeFalse(sharedIsRewrite()); Connection connection = null; try { connection = setConnection("&useLegacyDatetimeCode=" + useLegacy + "&serverTimezone=+5:00&maximizeMysqlCompatibility=false&useServerPrepStmts=true"); setSessionTimeZone(connection, "+5:00"); createTable("date_test", "id int not null primary key auto_increment, d_test date,dt_test datetime, " + "t_test time"); Statement stmt = connection.createStatement(); Date date = Date.valueOf("2009-01-17"); Timestamp timestamp = Timestamp.valueOf("2009-01-17 15:41:01"); Time time = Time.valueOf("23:59:59"); PreparedStatement ps = connection.prepareStatement("insert into date_test (d_test, dt_test, t_test) " + "values (?,?,?)"); ps.setDate(1, date); ps.setTimestamp(2, timestamp); ps.setTime(3, time); ps.executeUpdate(); ResultSet rs = stmt.executeQuery("select d_test, dt_test, t_test from date_test"); assertEquals(true, rs.next()); Date date2 = rs.getDate(1); Date date3 = rs.getDate("d_test"); Time time2 = rs.getTime(3); assertEquals(date.toString(), date2.toString()); assertEquals(date.toString(), date3.toString()); assertEquals(time.toString(), time2.toString()); Time time3 = rs.getTime("t_test"); assertEquals(time.toString(), time3.toString()); Timestamp timestamp2 = rs.getTimestamp(2); assertEquals(timestamp.toString(), timestamp2.toString()); Timestamp timestamp3 = rs.getTimestamp("dt_test"); assertEquals(timestamp.toString(), timestamp3.toString()); } finally { connection.close(); } } @Test public void dateRangeTest() throws SQLException { PreparedStatement ps = sharedConnection.prepareStatement("insert into date_test2 (id, d_from, d_to) values " + "(1, ?,?)"); Timestamp timestamp1 = Timestamp.valueOf("2009-01-17 15:41:01"); Timestamp timestamp2 = Timestamp.valueOf("2015-01-17 15:41:01"); ps.setTimestamp(1, timestamp1); ps.setTimestamp(2, timestamp2); ps.executeUpdate(); PreparedStatement ps1 = sharedConnection.prepareStatement("select d_from, d_to from date_test2 " + "where d_from <= ? and d_to >= ?"); Timestamp timestamp3 = Timestamp.valueOf("2014-01-17 15:41:01"); ps1.setTimestamp(1, timestamp3); ps1.setTimestamp(2, timestamp3); ResultSet rs = ps1.executeQuery(); assertEquals(true, rs.next()); Timestamp ts1 = rs.getTimestamp(1); Timestamp ts2 = rs.getTimestamp(2); assertEquals(ts1.toString(), timestamp1.toString()); assertEquals(ts2.toString(), timestamp2.toString()); } @Test(expected = SQLException.class) public void dateTest2() throws SQLException { Statement stmt = sharedConnection.createStatement(); ResultSet rs = stmt.executeQuery("select 1"); rs.next(); rs.getDate(1); } @Test(expected = SQLException.class) public void dateTest3() throws SQLException { Statement stmt = sharedConnection.createStatement(); ResultSet rs = stmt.executeQuery("select 1 as a"); rs.next(); rs.getDate("a"); } @Test(expected = SQLException.class) public void timeTest3() throws SQLException { Statement stmt = sharedConnection.createStatement(); ResultSet rs = stmt.executeQuery("select 'aaa' as a"); rs.next(); rs.getTimestamp("a"); } @Test public void yearTest() throws SQLException { Assume.assumeTrue(isMariadbServer()); createTable("yeartest", "y1 year, y2 year(2)"); sharedConnection.createStatement().execute("insert into yeartest values (null, null), (1901, 70), (0, 0), " + "(2155, 69)"); Statement stmt = sharedConnection.createStatement(); ResultSet rs = stmt.executeQuery("select * from yeartest"); Date[] data1 = new Date[]{null, Date.valueOf("1901-01-01"), Date.valueOf("0000-01-01"), Date.valueOf("2155-01-01")}; Date[] data2 = new Date[]{null, Date.valueOf("1970-01-01"), Date.valueOf("2000-01-01"), Date.valueOf("2069-01-01")}; checkDateResult(data1, data2, rs); //CONJ-282 PreparedStatement preparedStatement = sharedConnection.prepareStatement("SELECT * FROM yeartest"); rs = preparedStatement.executeQuery(); checkDateResult(data1, data2, rs); } private void checkDateResult(Date[] data1, Date[] data2, ResultSet rs) throws SQLException { int count = 0; while (rs.next()) { assertEquals(data1[count], rs.getObject(1)); assertEquals(data2[count], rs.getObject(2)); assertEquals(data1[count], rs.getDate(1)); assertEquals(data2[count], rs.getDate(2)); count++; } } @Test public void timeTestLegacy() throws SQLException { Connection connection = null; try { connection = setConnection("&useLegacyDatetimeCode=true&serverTimezone=+05:00"); setSessionTimeZone(connection, "+05:00"); connection.createStatement().execute("insert into timetest values (null), ('-838:59:59'), ('00:00:00'), " + "('838:59:59')"); Time[] data = new Time[]{null, Time.valueOf("-838:59:59"), Time.valueOf("00:00:00"), Time.valueOf("838:59:59")}; Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("select * from timetest"); testTime(rs, data); PreparedStatement pstmt = connection.prepareStatement("select * from timetest"); testTime(pstmt.executeQuery(), data); rs = stmt.executeQuery("select '11:11:11'"); testTime11(rs); PreparedStatement pstmt2 = connection.prepareStatement("select TIME('11:11:11') "); testTime11(pstmt2.executeQuery()); } finally { connection.close(); } } @Test public void timeTest() throws SQLException { Connection connection = null; try { connection = setConnection("&useLegacyDatetimeCode=false&serverTimezone=+5:00"); setSessionTimeZone(connection, "+5:00"); connection.createStatement().execute("insert into timetest2 values (null), ('00:00:00'), ('23:59:59')"); Time[] data = new Time[]{null, Time.valueOf("00:00:00"), Time.valueOf("23:59:59")}; Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("select * from timetest2"); testTime(rs, data); PreparedStatement pstmt = connection.prepareStatement("select * from timetest2"); testTime(pstmt.executeQuery(), data); rs = stmt.executeQuery("select '11:11:11'"); testTime11(rs); PreparedStatement pstmt2 = connection.prepareStatement("select TIME('11:11:11') "); testTime11(pstmt2.executeQuery()); } finally { if (connection != null) { connection.close(); } } } private void testTime(ResultSet rs, Time[] data) throws SQLException { int count = 0; while (rs.next()) { Time t1 = data[count]; Time t2 = (Time) rs.getObject(1); assertEquals(t1, t2); count++; } rs.close(); } private void testTime11(ResultSet rs) throws SQLException { rs.next(); Calendar cal = Calendar.getInstance(); assertEquals("11:11:11", rs.getTime(1, cal).toString()); rs.close(); } @Test public void timestampZeroTest() throws SQLException { Assume.assumeTrue(isMariadbServer()); String timestampZero = "0000-00-00 00:00:00"; String dateZero = "0000-00-00"; sharedConnection.createStatement().execute("insert into timestampzerotest values ('" + timestampZero + "', '" + timestampZero + "', '" + dateZero + "')"); Statement stmt = sharedConnection.createStatement(); ResultSet rs = stmt.executeQuery("select * from timestampzerotest"); Timestamp ts = null; Timestamp datetime = null; Date date = null; while (rs.next()) { assertEquals(null, rs.getObject(1)); ts = rs.getTimestamp(1); assertEquals(rs.wasNull(), true); datetime = rs.getTimestamp(2); assertEquals(rs.wasNull(), true); date = rs.getDate(3); assertEquals(rs.wasNull(), true); } rs.close(); assertEquals(ts, null); assertEquals(datetime, null); assertEquals(date, null); } @Test public void timestampAsDate() throws SQLException { Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(Calendar.YEAR, 1970); cal2.set(Calendar.MONTH, 0); cal2.set(Calendar.DAY_OF_YEAR, 1); Calendar cal3 = Calendar.getInstance(); cal3.set(Calendar.HOUR_OF_DAY, 0); cal3.set(Calendar.MINUTE, 0); cal3.set(Calendar.SECOND, 0); cal3.set(Calendar.MILLISECOND, 0); cal3.set(Calendar.YEAR, 1970); cal3.set(Calendar.MONTH, 0); cal3.set(Calendar.DAY_OF_YEAR, 1); Timestamp currentTimeStamp = new Timestamp(System.currentTimeMillis()); PreparedStatement preparedStatement1 = sharedConnection.prepareStatement("/*CLIENT*/ insert into timestampAsDate values (?, ?, ?)"); preparedStatement1.setTimestamp(1, currentTimeStamp); preparedStatement1.setTimestamp(2, currentTimeStamp); preparedStatement1.setDate(3, new Date(currentTimeStamp.getTime())); preparedStatement1.addBatch(); preparedStatement1.execute(); Date dateWithoutTime = new Date(cal.getTimeInMillis()); Time zeroTime = new Time(cal3.getTimeInMillis()); ResultSet rs = sharedConnection.createStatement().executeQuery("select * from timestampAsDate"); checkResult(rs, currentTimeStamp, cal, dateWithoutTime, zeroTime); PreparedStatement pstmt = sharedConnection.prepareStatement("select * from timestampAsDate where 1 = ?"); pstmt.setInt(1,1); pstmt.addBatch(); rs = pstmt.executeQuery(); checkResult(rs, currentTimeStamp, cal, dateWithoutTime, zeroTime); } private void checkResult(ResultSet rs, Timestamp currentTimeStamp, Calendar cal, Date dateWithoutTime, Time zeroTime) throws SQLException { if (rs.next()) { Assert.assertEquals(rs.getTimestamp(1), currentTimeStamp); Assert.assertEquals(rs.getTimestamp(2), currentTimeStamp); Assert.assertEquals(rs.getTimestamp(3), new Timestamp(cal.getTimeInMillis())); Assert.assertEquals(rs.getDate(1), new Date(currentTimeStamp.getTime())); Assert.assertEquals(rs.getDate(2), new Date(currentTimeStamp.getTime())); Assert.assertEquals(rs.getDate(3), dateWithoutTime); Assert.assertEquals(rs.getTime(1), new Time(currentTimeStamp.getTime())); Assert.assertEquals(rs.getTime(2), new Time(currentTimeStamp.getTime())); Assert.assertEquals(rs.getTime(3), zeroTime); } else { fail("Must have a result"); } rs.close(); } @Test public void javaUtilDateInPreparedStatementAsTimeStamp() throws Exception { java.util.Date currentDate = Calendar.getInstance(TimeZone.getDefault()).getTime(); PreparedStatement ps = sharedConnection.prepareStatement("insert into dtest values(?)"); ps.setObject(1, currentDate, Types.TIMESTAMP); ps.executeUpdate(); ResultSet rs = sharedConnection.createStatement().executeQuery("select * from dtest"); rs.next(); /* Check that time is correct, up to seconds precision */ Assert.assertTrue(Math.abs((currentDate.getTime() - rs.getTimestamp(1).getTime())) <= 1000); } @Test public void nullTimestampTest() throws SQLException { PreparedStatement ps = sharedConnection.prepareStatement("insert into dtest2 values(null)"); ps.executeUpdate(); ResultSet rs = sharedConnection.createStatement().executeQuery("select * from dtest2 where d is null"); rs.next(); Calendar cal = new GregorianCalendar(); assertEquals(null, rs.getTimestamp(1, cal)); } @SuppressWarnings("deprecation") @Test public void javaUtilDateInPreparedStatementAsDate() throws Exception { java.util.Date currentDate = Calendar.getInstance(TimeZone.getDefault()).getTime(); PreparedStatement ps = sharedConnection.prepareStatement("insert into dtest3 values(?)"); ps.setObject(1, currentDate, Types.DATE); ps.executeUpdate(); ResultSet rs = sharedConnection.createStatement().executeQuery("select * from dtest3"); rs.next(); /* Check that time is correct, up to seconds precision */ assertEquals(currentDate.getYear(), rs.getDate(1).getYear()); assertEquals(currentDate.getMonth(), rs.getDate(1).getMonth()); assertEquals(currentDate.getDay(), rs.getDate(1).getDay()); } @SuppressWarnings("deprecation") @Test public void javaUtilDateInPreparedStatementAsTime() throws Exception { java.util.Date currentDate = Calendar.getInstance(TimeZone.getDefault()).getTime(); PreparedStatement ps = sharedConnection.prepareStatement("insert into dtest4 values(?)"); ps.setObject(1, currentDate, Types.TIME); ps.executeUpdate(); ResultSet rs = sharedConnection.createStatement().executeQuery("select * from dtest4"); rs.next(); Calendar calendar = Calendar.getInstance(); calendar.setTime(currentDate); calendar.set(Calendar.YEAR, 1970); calendar.set(Calendar.MONTH, 0); calendar.set(Calendar.DAY_OF_MONTH, 1); /* Check that time is correct, up to seconds precision */ Assert.assertTrue(Math.abs(calendar.getTimeInMillis() - rs.getTime(1).getTime()) <= 1000); } @Test public void serverTimezone() throws Exception { TimeZone tz = TimeZone.getDefault(); Connection connection = null; try { connection = setConnection("&serverTimezone=+5:00"); setSessionTimeZone(connection, "+5:00"); java.util.Date now = new java.util.Date(); TimeZone canadaTimeZone = TimeZone.getTimeZone("GMT+5:00"); long clientOffset = tz.getOffset(now.getTime()); long serverOffset = canadaTimeZone.getOffset(System.currentTimeMillis()); long totalOffset = serverOffset - clientOffset; PreparedStatement ps = connection.prepareStatement("select now()"); ResultSet rs = ps.executeQuery(); rs.next(); Timestamp ts = rs.getTimestamp(1); long differenceToServer = ts.getTime() - now.getTime(); long diff = Math.abs(differenceToServer - totalOffset); /* query take less than a second but taking in account server and client time second diff ... */ assertTrue(diff < 5000); ps = connection.prepareStatement("select utc_timestamp(), ?"); ps.setObject(1, now); rs = ps.executeQuery(); rs.next(); ts = rs.getTimestamp(1); Timestamp ts2 = rs.getTimestamp(2); long diff2 = Math.abs(ts.getTime() - ts2.getTime()) - clientOffset; assertTrue(diff2 < 5000); /* query take less than a second */ } finally { connection.close(); } } /** * Conj-107. * * @throws SQLException exception */ @Test public void timestampMillisecondsTest() throws SQLException { Statement statement = sharedConnection.createStatement(); boolean isMariadbServer = isMariadbServer(); if (isMariadbServer) { createTable("tt", "id decimal(10), create_time datetime(6)"); statement.execute("INSERT INTO tt (id, create_time) VALUES (1,'2013-07-18 13:44:22.123456')"); } else { createTable("tt", "id decimal(10), create_time datetime"); statement.execute("INSERT INTO tt (id, create_time) VALUES (1,'2013-07-18 13:44:22')"); } PreparedStatement ps = sharedConnection.prepareStatement("insert into tt (id, create_time) values (?,?)"); ps.setInt(1, 2); Timestamp writeTs = new Timestamp(1273017612999L); Timestamp writeTsWithoutMilliSec = new Timestamp(1273017612999L); ps.setTimestamp(2, writeTs); ps.execute(); ResultSet rs = statement.executeQuery("SELECT * FROM tt"); assertTrue(rs.next()); if (isMariadbServer) { assertTrue("2013-07-18 13:44:22.123456".equals(rs.getString(2))); } else { assertTrue("2013-07-18 13:44:22.0".equals(rs.getString(2))); } assertTrue(rs.next()); Timestamp readTs = rs.getTimestamp(2); if (isMariadbServer) { assertEquals(writeTs, readTs); } else { assertEquals(writeTs, writeTsWithoutMilliSec); } } @Test public void dateTestWhenServerDifference() throws Throwable { Connection connection = null; try { connection = setConnection("&serverTimezone=UTC"); PreparedStatement pst = connection.prepareStatement("insert into date_test3 values (?)"); Date date = Date.valueOf("2013-02-01"); pst.setDate(1, date); pst.execute(); pst = connection.prepareStatement("select x from date_test3 WHERE x = ?"); pst.setDate(1, date); ResultSet rs = pst.executeQuery(); rs.next(); Date dd = rs.getDate(1); assertEquals(dd, date); } finally { connection.close(); } } @Test public void dateTestWhenServerDifferenceClient() throws Throwable { Connection connection = null; try { connection = setConnection("&serverTimezone=UTC"); PreparedStatement pst = connection.prepareStatement("/*CLIENT*/insert into date_test4 values (?)"); Date date = Date.valueOf("2013-02-01"); pst.setDate(1, date); pst.execute(); pst = connection.prepareStatement("/*CLIENT*/ select x from date_test4 WHERE x = ?"); pst.setDate(1, date); ResultSet rs = pst.executeQuery(); rs.next(); Date dd = rs.getDate(1); assertEquals(dd, date); } finally { connection.close(); } } /** * Conj-267 : null pointer exception getting zero date. */ @Test public void nullDateString() throws Throwable { createTable("date_test5", "x date"); Statement stmt = sharedConnection.createStatement(); try { stmt.execute("INSERT INTO date_test5 (x) VALUES ('0000-00-00')"); PreparedStatement pst = sharedConnection.prepareStatement("SELECT * FROM date_test5 WHERE 1 = ?"); pst.setInt(1, 1); ResultSet rs = pst.executeQuery(); Assert.assertTrue(rs.next()); if (sharedUsePrepare()) { Assert.assertNull(rs.getString(1)); Assert.assertNull(rs.getDate(1)); } else { Assert.assertEquals("0000-00-00", rs.getString(1)); Assert.assertNull(rs.getDate(1)); } } catch (SQLDataException sqldataException) { //'0000-00-00' doesn't work anymore on mysql 5.7. } } /** * Conj-317 : null pointer exception on getDate on null timestamp. */ @Test public void nullDateFromTimestamp() throws Throwable { createTable("nulltimestamp", "ts timestamp(6) NULL "); Statement stmt = sharedConnection.createStatement(); try { stmt.execute("INSERT INTO nulltimestamp (ts) VALUES ('0000-00-00'), (null)"); PreparedStatement pst = sharedConnection.prepareStatement("SELECT * FROM nulltimestamp WHERE 1 = ?"); pst.setInt(1, 1); ResultSet rs = pst.executeQuery(); Assert.assertTrue(rs.next()); Assert.assertNull(rs.getString(1)); Assert.assertNull(rs.getDate(1)); Assert.assertNull(rs.getTimestamp(1)); Assert.assertNull(rs.getTime(1)); Assert.assertTrue(rs.next()); Assert.assertNull(rs.getString(1)); Assert.assertNull(rs.getDate(1)); Assert.assertNull(rs.getTimestamp(1)); Assert.assertNull(rs.getTime(1)); } catch (SQLDataException sqldataException) { //'0000-00-00' doesn't work anymore on mysql 5.7. } } /** * CONJ-388 : getString on a '0000-00-00 00:00:00' must not return null. * * @throws SQLException if exception occur */ @Test public void getZeroDateString() throws SQLException { createTable("zeroTimestamp", "ts timestamp NULL "); try (Statement statement = sharedConnection.createStatement()) { statement.execute("INSERT INTO zeroTimestamp values ('0000-00-00 00:00:00')"); try (PreparedStatement preparedStatement = sharedConnection.prepareStatement("SELECT * from zeroTimestamp")) { ResultSet resultSet = preparedStatement.executeQuery(); Assert.assertTrue(resultSet.next()); Assert.assertEquals(null, resultSet.getDate(1)); Assert.assertEquals(null, resultSet.getString(1)); } ResultSet resultSet = statement.executeQuery("SELECT * from zeroTimestamp"); Assert.assertTrue(resultSet.next()); Assert.assertEquals(null, resultSet.getDate(1)); Assert.assertTrue(resultSet.getString(1).contains("0000-00-00 00:00:00")); } } }
package com.emc.rest.smart; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.ClientRequest; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.filter.ClientFilter; import org.apache.http.HttpHost; import org.apache.http.client.utils.URIUtils; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; public class SmartFilter extends ClientFilter { public static final String BYPASS_LOAD_BALANCER = "com.emc.rest.smart.bypassLoadBalancer"; private SmartConfig smartConfig; public SmartFilter(SmartConfig smartConfig) { this.smartConfig = smartConfig; } @Override public ClientResponse handle(ClientRequest request) throws ClientHandlerException { // check for bypass flag Boolean bypass = (Boolean) request.getProperties().get(BYPASS_LOAD_BALANCER); if (bypass != null && bypass) { return getNext().handle(request); } // get highest ranked host for next request Host host = smartConfig.getLoadBalancer().getTopHost(request.getProperties()); // replace the host in the request URI uri = request.getURI(); try { uri = URIUtils.rewriteURI(uri, new HttpHost(host.getName(), uri.getPort(), uri.getScheme())); } catch (URISyntaxException e) { throw new RuntimeException("load-balanced host generated invalid URI", e); } request.setURI(uri); // track requests stats for LB ranking host.connectionOpened(); // not really, but we can't (cleanly) intercept any lower than this try { // call to delegate ClientResponse response = getNext().handle(request); // capture request stats if (response.getStatus() >= 500 && response.getStatus() != 501) { // except for 501 (not implemented), all 50x responses are considered server errors host.callComplete(true); } else { host.callComplete(false); } // wrap the input stream so we can capture the actual connection close response.setEntityInputStream(new WrappedInputStream(response.getEntityInputStream(), host)); return response; } catch (RuntimeException e) { // capture requests stats (error) host.callComplete(true); host.connectionClosed(); throw e; } } /** * captures closure in host statistics */ protected class WrappedInputStream extends FilterInputStream { private Host host; private boolean closed = false; public WrappedInputStream(InputStream in, Host host) { super(in); this.host = host; } @Override public void close() throws IOException { synchronized (this) { if (!closed) { host.connectionClosed(); // capture closure closed = true; } } super.close(); } } }
package forklift.consumer; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import forklift.Forklift; import forklift.classloader.RunAsClassLoader; import forklift.connectors.ConnectorException; import forklift.connectors.ForkliftMessage; import forklift.consumer.parser.KeyValueParser; import forklift.decorators.Config; import forklift.decorators.Headers; import forklift.decorators.MultiThreaded; import forklift.decorators.On; import forklift.decorators.OnMessage; import forklift.decorators.OnValidate; import forklift.decorators.Ons; import forklift.decorators.Order; import forklift.decorators.Queue; import forklift.decorators.Response; import forklift.decorators.Topic; import forklift.message.Header; import forklift.producers.ForkliftProducerI; import forklift.properties.PropertiesManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import javax.inject.Inject; public class Consumer { static ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule()) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); private Logger log; private static AtomicInteger id = new AtomicInteger(1); private final ClassLoader classLoader; private final Forklift forklift; private final Map<Class, Map<Class<?>, List<Field>>> injectFields; private final Class<?> msgHandler; private final List<Method> onMessage; private final List<Method> onValidate; private final List<Method> onResponse; private final Map<String, List<MessageRunnable>> orderQueue; private final Map<ProcessStep, List<Method>> onProcessStep; private Constructor<?> constructor; private Annotation[][] constructorAnnotations; private String name; private Queue queue; private Topic topic; private List<ConsumerService> services; private Method orderMethod; // If a queue can process multiple messages at a time we // use a thread pool to manage how much cpu load the queue can // take. These are reinstantiated anytime the consumer is asked // to listen for messages. private BlockingQueue<Runnable> blockQueue; private ThreadPoolExecutor threadPool; private java.util.function.Consumer<Consumer> outOfMessages; private AtomicBoolean running = new AtomicBoolean(false); public Consumer(Class<?> msgHandler, Forklift forklift) { this(msgHandler, forklift, null); } public Consumer(Class<?> msgHandler, Forklift forklift, ClassLoader classLoader) { this(msgHandler, forklift, classLoader, false); } public Consumer(Class<?> msgHandler, Forklift forklift, ClassLoader classLoader, Queue q) { this(msgHandler, forklift, classLoader, true); this.queue = q; if (this.queue == null) throw new IllegalArgumentException("Msg Handler must handle a queue."); this.name = queue.value() + ":" + id.getAndIncrement(); log = LoggerFactory.getLogger(this.name); } public Consumer(Class<?> msgHandler, Forklift forklift, ClassLoader classLoader, Topic t) { this(msgHandler, forklift, classLoader, true); this.topic = t; if (this.topic == null) throw new IllegalArgumentException("Msg Handler must handle a topic."); this.name = topic.value() + ":" + id.getAndIncrement(); log = LoggerFactory.getLogger(this.name); } @SuppressWarnings("unchecked") private Consumer(Class<?> msgHandler, Forklift forklift, ClassLoader classLoader, boolean preinit) { this.classLoader = classLoader; this.forklift = forklift; this.msgHandler = msgHandler; if (!preinit && queue == null && topic == null) { this.queue = msgHandler.getAnnotation(Queue.class); this.topic = msgHandler.getAnnotation(Topic.class); if (this.queue != null && this.topic != null) throw new IllegalArgumentException("Msg Handler cannot consume a queue and topic"); if (this.queue != null && !forklift.getConnector().supportsQueue()) throw new RuntimeException("@Queue is not supported by the current connector"); if (this.topic != null && !forklift.getConnector().supportsTopic()) throw new RuntimeException("@Topic is not supported by the current connector"); if (this.queue != null) this.name = queue.value() + ":" + id.getAndIncrement(); else if (this.topic != null) this.name = topic.value() + ":" + id.getAndIncrement(); else throw new IllegalArgumentException("Msg Handler must handle a queue or topic."); } log = LoggerFactory.getLogger(Consumer.class); // Look for all methods that need to be called when a // message is received. onMessage = new ArrayList<>(); onValidate = new ArrayList<>(); onResponse = new ArrayList<>(); onProcessStep = new HashMap<>(); Arrays.stream(ProcessStep.values()).forEach(step -> onProcessStep.put(step, new ArrayList<>())); for (Method m : msgHandler.getDeclaredMethods()) { if (m.isAnnotationPresent(OnMessage.class)) onMessage.add(m); else if (m.isAnnotationPresent(OnValidate.class)) onValidate.add(m); else if (m.isAnnotationPresent(Response.class)) { if (!forklift.getConnector().supportsResponse()) throw new RuntimeException("@Response is not supported by the current connector"); onResponse.add(m); } else if (m.isAnnotationPresent(Order.class)) { if (!forklift.getConnector().supportsOrder()) throw new RuntimeException("@Order is not supported by the current connector"); orderMethod = m; } else if (m.isAnnotationPresent(On.class) || m.isAnnotationPresent(Ons.class)) Arrays.stream(m.getAnnotationsByType(On.class)) .map(on -> on.value()) .distinct() .forEach(x -> onProcessStep.get(x).add(m)); } if (orderMethod != null) orderQueue = new HashMap<>(); else orderQueue = null; injectFields = new HashMap<>(); injectFields.put(Config.class, new HashMap<>()); injectFields.put(javax.inject.Inject.class, new HashMap<>()); injectFields.put(forklift.decorators.Message.class, new HashMap<>()); injectFields.put(forklift.decorators.Headers.class, new HashMap<>()); injectFields.put(forklift.decorators.Properties.class, new HashMap<>()); injectFields.put(forklift.decorators.Producer.class, new HashMap<>()); for (Field f : msgHandler.getDeclaredFields()) { injectFields.keySet().forEach(type -> { if (f.isAnnotationPresent(type)) { f.setAccessible(true); // Init the list if (injectFields.get(type).get(f.getType()) == null) injectFields.get(type).put(f.getType(), new ArrayList<>()); injectFields.get(type).get(f.getType()).add(f); } }); } configureConstructorInjection(); } /** * Creates a JMS consumer and begins listening for messages. * If the JMS consumer dies, this method will attempt to * get a new JMS consumer. */ public void listen() { final ForkliftConsumerI consumer; try { if (topic != null) consumer = forklift.getConnector().getTopic(topic.value()); else if (queue != null) consumer = forklift.getConnector().getQueue(queue.value()); else throw new RuntimeException("No queue/topic specified"); // Init the thread pools if the msg handler is multi threaded. If the msg handler is single threaded // it'll just run in the current thread to prevent any message read ahead that would be performed. if (msgHandler.isAnnotationPresent(MultiThreaded.class)) { final MultiThreaded multiThreaded = msgHandler.getAnnotation(MultiThreaded.class); log.info("Creating thread pool of {}", multiThreaded.value()); blockQueue = new ArrayBlockingQueue<>(multiThreaded.value() * 100 + 100); threadPool = new ThreadPoolExecutor( multiThreaded.value(), multiThreaded.value(), 5L, TimeUnit.MINUTES, blockQueue); threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); } else { blockQueue = null; threadPool = null; } messageLoop(consumer); // Always cleanup the consumer. if (consumer != null) consumer.close(); } catch (ConnectorException e) { log.debug("", e); } } public String getName() { return name; } public void messageLoop(ForkliftConsumerI consumer) { try { running.set(true); while (running.get()) { ForkliftMessage consumerMsg; while ((consumerMsg = consumer.receive(2500)) != null && running.get()) { try { final List<Closeable> closeMe = new ArrayList<>(); final Object handler = constructMessageHandlerInstance(consumerMsg, closeMe); final ForkliftMessage msg = consumerMsg; RunAsClassLoader.run(classLoader, () -> { closeMe.addAll(inject(msg, handler)); }); // Create the runner that will ultimately run the handler. final MessageRunnable runner = new MessageRunnable(this, msg, classLoader, handler, onMessage, onValidate, onResponse, onProcessStep, closeMe); // If the message is ordered we need to store messages that cannot currently be processed, and retry them periodically. if (orderQueue != null) { final String id = (String)orderMethod.invoke(handler); // Reuse the close functionality to hook the process to trigger the next message execution. closeMe.add(new Closeable() { @Override public void close() throws IOException { synchronized (orderQueue) { final List<MessageRunnable> msgs = orderQueue.get(id); msgs.remove(runner); final Optional<MessageRunnable> optRunner = msgs.stream().findFirst(); if (optRunner.isPresent()) { // Execute the message. if (threadPool != null) threadPool.execute(optRunner.get()); else optRunner.get().run(); } else { orderQueue.remove(id); } } } }); synchronized (orderQueue) { // If the message is not the first with a given identifier we'll assume that // another message is currently being processed and we'll be called later. if (orderQueue.containsKey(id)) { orderQueue.get(id).add(runner); // Let the next message get processed since this one needs to wait. continue; } final List<MessageRunnable> list = new ArrayList<>(); list.add(runner); orderQueue.put(id, list); } } // Execute the message. if (threadPool != null) threadPool.execute(runner); else runner.run(); } catch (Exception e) { // If this error occurs we had a massive problem with the conusmer class setup. log.error("Consumer couldn't be used.", e); // In this instance just stop the consumer. Someone needs to fix their shit! running.set(false); } } if (outOfMessages != null) outOfMessages.accept(this); } // Shutdown the pool, but let actively executing work finish. if (threadPool != null) { log.info("Shutting down thread pool - active {}", threadPool.getActiveCount()); threadPool.shutdown(); threadPool.awaitTermination(60, TimeUnit.SECONDS); blockQueue.clear(); } } catch (ConnectorException e) { running.set(false); log.error("JMS Error in message loop: ", e); } catch (InterruptedException ignored) { // thrown by threadpool.awaitterm } finally { try { consumer.close(); } catch (Exception e) { log.error("Error in message loop shutdown:", e); } } } public void shutdown() { log.info("Consumer shutting down"); running.set(false); } public void setOutOfMessages(java.util.function.Consumer<Consumer> outOfMessages) { this.outOfMessages = outOfMessages; } private final void configureConstructorInjection() { Constructor<?>[] constructors = msgHandler.getDeclaredConstructors(); List<Constructor> injectableConstructors = Arrays.stream(constructors).filter(constructor -> constructor.isAnnotationPresent(Inject.class)).collect(Collectors.toList()); if (injectableConstructors.size() > 0) { this.constructor = injectableConstructors.get(0); this.constructorAnnotations = this.constructor.getParameterAnnotations(); if (injectableConstructors.size() > 1) { log.error("Multiple constructors annotated with Inject. Using first injectable constructor found"); } } } /** * Inject the data from a forklift message into an instance of the msgHandler class. * * @param msg containing data * @param instance an instance of the msgHandler class. */ public List<Closeable> inject(ForkliftMessage msg, final Object instance) { // Keep any closable resources around so the injection utilizer can cleanup. final List<Closeable> closeMe = new ArrayList<>(); // Inject the forklift msg injectFields.keySet().stream().forEach(decorator -> { final Map<Class<?>, List<Field>> fields = injectFields.get(decorator); fields.keySet().stream().forEach(clazz -> { fields.get(clazz).forEach(field -> { log.trace("Inject target> Field: ({}) Decorator: ({})", field, decorator); try { Object value = getInjectableValue(field.getAnnotation(decorator), field.getName(), clazz, msg); if (value instanceof ForkliftProducerI) { closeMe.add((ForkliftProducerI)value); } if (value != null) { field.set(instance, value); } } catch (JsonMappingException | JsonParseException e) { log.warn("Unable to parse json for injection.", e); } catch (Exception e) { log.error("Error injecting data into Msg Handler", e); e.printStackTrace(); throw new RuntimeException("Error injecting data into Msg Handler"); } }); }); }); return closeMe; } private Object constructMessageHandlerInstance(ForkliftMessage forkliftMessage, List<Closeable> closeables) throws IllegalAccessException, InvocationTargetException, InstantiationException, IOException { Object instance = null; if (this.constructor != null) { Object[] constructorParameters = buildConstructorParameters(forkliftMessage, closeables); instance = this.constructor.newInstance(constructorParameters); } else { instance = msgHandler.newInstance(); } return instance; } private Object[] buildConstructorParameters(ForkliftMessage forkliftMessage, List<Closeable> closeables) throws IOException { Object[] parameters = new Object[constructorAnnotations.length]; int index = 0; for (Annotation[] parameterAnnotations : constructorAnnotations) { Annotation injectable = null; for (Annotation parameterAnnotation : parameterAnnotations) { if (injectFields.containsKey(parameterAnnotation.annotationType())) { injectable = parameterAnnotation; break; } } Parameter p = constructor.getParameters()[index]; Object value = getInjectableValue(injectable, null, p.getType(), forkliftMessage); parameters[index] = value; if (value != null && value instanceof ForkliftProducerI) { closeables.add((ForkliftProducerI)value); } index++; } return parameters; } private Object getInjectableValue(Annotation decorator, String mappedName, Class<?> mappedClass, ForkliftMessage msg) throws IOException { Object value = null; if (decorator == null || decorator.annotationType() == javax.inject.Inject.class) { if (this.services != null) { // Try to resolve the class from any available BeanResolvers. for (ConsumerService s : this.services) { try { final Object o = s.resolve(mappedClass, null); if (o != null) { value = o; break; } } catch (Exception e) { log.debug("", e); } } } } else if (decorator.annotationType() == forklift.decorators.Message.class && msg.getMsg() != null) { if (mappedClass == ForkliftMessage.class) { value = msg; } else if (mappedClass == String.class) { value = msg.getMsg(); } else if (mappedClass == Map.class && !msg.getMsg().startsWith("{")) { value = KeyValueParser.parse(msg.getMsg()); // We assume that the map is <String, String>. } else { // Attempt to parse a json value = mapper.readValue(msg.getMsg(), mappedClass); } } else if (decorator.annotationType() == Config.class) { if (mappedClass == Properties.class) { String confName = ((Config)decorator).value(); if (confName.equals("")) { confName = mappedName; } final Properties config = PropertiesManager.get(confName); if (config == null) { log.warn("Attempt to inject field failed because resource file {} was not found", ((Config)decorator).value()); } else { value = config; } } else { final Properties config = PropertiesManager.get(((Config)decorator).value()); if (config == null) { log.warn("Attempt to inject field failed because resource file {} was not found", ((Config)decorator).value()); } String key = ((Config)decorator).field(); if (key.equals("")) { key = mappedName; } value = config.get(key); } } else if (decorator.annotationType() == Headers.class) { final Map<Header, Object> headers = msg.getHeaders(); if (mappedClass == Map.class) { value = headers; } else { final Header key = ((Headers)decorator).value(); if (headers == null) { log.warn("Attempt to inject {} from headers, but headers are null", key); } else if (!key.getHeaderType().equals(mappedClass)) { log.warn("Injecting field {} failed because it is not type {}", mappedName, key.getHeaderType()); } else { value = headers.get(key); } } } else if (decorator.annotationType() == forklift.decorators.Properties.class) { Map<String, String> properties = msg.getProperties(); if (mappedClass == Map.class) { value = msg.getProperties(); } else if (properties != null) { String key = ((forklift.decorators.Properties)decorator).value(); if (key.equals("")) { key = mappedName; } if (properties == null) { log.warn("Attempt to inject field {} from properties, but properties is null", key); } else { value = properties.get(key); } } } else if (decorator.annotationType() == forklift.decorators.Producer.class) { if (mappedClass == ForkliftProducerI.class) { forklift.decorators.Producer producer = (forklift.decorators.Producer)decorator; final ForkliftProducerI p; if (producer.queue().length() > 0) p = forklift.getConnector().getQueueProducer(producer.queue()); else if (producer.topic().length() > 0) p = forklift.getConnector().getTopicProducer(producer.topic()); else p = null; value = p; } } return value; } public Class<?> getMsgHandler() { return msgHandler; } /** * Creates an instance of the MessageHandler class utilized by this constructor. Constructor and Field level injection is performed using both the * passed in msg and any Services {@link #addServices(ConsumerService...) added} to this consumer. * * @param msg */ public Object getMsgHandlerInstance(ForkliftMessage msg) { Object instance = null; try { instance = this.constructMessageHandlerInstance(msg, new ArrayList<>()); inject(msg, instance); } catch (JsonMappingException | JsonParseException e) { log.warn("Unable to parse json for injection.", e); } catch (Exception e) { log.error("Error injecting data into Msg Handler", e); e.printStackTrace(); throw new RuntimeException("Error injecting data into Msg Handler Constructor"); } return instance; } public Queue getQueue() { return queue; } public Topic getTopic() { return topic; } public Forklift getForklift() { return forklift; } public void addServices(ConsumerService... services) { if (this.services == null) this.services = new ArrayList<>(); for (ConsumerService s : services) this.services.add(s); } public void setServices(List<ConsumerService> services) { this.services = services; } }
package org.opennars.core; import org.junit.Test; import org.junit.experimental.ParallelComputer; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.RunWith; import org.junit.runner.notification.Failure; import org.junit.runners.Parameterized; import org.opennars.io.events.TextOutputHandler; import org.opennars.main.Nar; import org.opennars.main.MiscFlags; import org.opennars.storage.Memory; import org.opennars.util.io.ExampleFileInput; import org.opennars.util.test.OutputCondition; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.text.ParseException; import java.util.*; import static org.junit.Assert.assertTrue; @RunWith(Parameterized.class) public class NALTest { static { Memory.randomNumber.setSeed(1); MiscFlags.DEBUG = false; MiscFlags.TEST = true; } final int minCycles = 1550; //TODO reduce this to one or zero to avoid wasting any extra time during tests static public boolean showOutput = false; static public boolean showSuccess = false; static public final boolean showFail = true; static public final boolean showReport = true; static public final boolean requireSuccess = true; static public final int similarsToSave = 5; protected static final Map<String, String> examples = new HashMap(); //path -> script data public static final Map<String, Boolean> tests = new HashMap(); public static final Map<String, Double> scores = new HashMap(); final String scriptPath; public static String getExample(final String path) { try { String existing = examples.get(path); if (existing!=null) return existing; existing = ExampleFileInput.load(path); examples.put(path, existing); return existing; } catch (final IOException e) { throw new IllegalStateException("Could not load path", e); } } public Nar newNAR() throws IOException, InstantiationException, InvocationTargetException, NoSuchMethodException, ParserConfigurationException, IllegalAccessException, SAXException, ClassNotFoundException, ParseException { return new Nar(); } @Parameterized.Parameters public static Collection params() { final String[] directories = new String[] { "/nal/single_step/", "/nal/multi_step/", "/nal/application/" }; final Map<String, Object> et = ExampleFileInput.getUnitTests(directories); final Collection t = et.values(); for (final String x : et.keySet()) addTest(x); return t; } public static void addTest(String name) { name = name.substring(3, name.indexOf(".nal")); tests.put(name, true); } public static double runTests(final Class c) { tests.clear(); scores.clear(); final Result result = JUnitCore.runClasses(new ParallelComputer(true, true), c); for (final Failure f : result.getFailures()) { final String test = f.getMessage().substring(f.getMessage().indexOf("/nal/single_step") + 8, f.getMessage().indexOf(".nal")); tests.put(test, false); } final int[] levelSuccess = new int[10]; final int[] levelTotals = new int[10]; for (final Map.Entry<String, Boolean> e : tests.entrySet()) { final String name = e.getKey(); int level = 0; level = Integer.parseInt(name.split("\\.")[0]); levelTotals[level]++; if (e.getValue()) { levelSuccess[level]++; } } double totalScore = 0; for (final Double d : scores.values()) totalScore += d; if (showReport) { int totalSucceeded = 0, total = 0; for (int i = 0; i < 9; i++) { final float rate = (levelTotals[i] > 0) ? ((float)levelSuccess[i]) / levelTotals[i] : 0; final String prefix = (i > 0) ? ("NAL" + i) : "Other"; System.out.println(prefix + ": " + (rate*100.0) + "% (" + levelSuccess[i] + "/" + levelTotals[i] + ")" ); totalSucceeded += levelSuccess[i]; total += levelTotals[i]; } System.out.println(totalSucceeded + " / " + total); System.out.println("Score: " + totalScore); } return totalScore; } public static void main(final String[] args) { runTests(NALTest.class); } public NALTest(final String scriptPath) { this.scriptPath = scriptPath; } protected double testNAL(final String path) throws IOException, InstantiationException, InvocationTargetException, NoSuchMethodException, ParserConfigurationException, IllegalAccessException, SAXException, ClassNotFoundException, ParseException { Memory.resetStatic(); Nar n = newNAR(); final String example = getExample(path); if (showOutput) { System.out.println(example); System.out.println(); } final List<OutputCondition> extractedExpects = OutputCondition.getConditions(n, example, similarsToSave); final List<OutputCondition> expects = new ArrayList<>(extractedExpects); if (showOutput) { new TextOutputHandler(n, System.out); } n.addInputFile(path); n.cycles(minCycles); if (showOutput) { System.err.flush(); System.out.flush(); } boolean success = expects.size() > 0; for (final OutputCondition e: expects) { if (!e.succeeded) success = false; } double score = Double.POSITIVE_INFINITY; if (success) { long lastSuccess = -1; for (final OutputCondition e: expects) { if (e.getTrueTime()!=-1) { if (lastSuccess < e.getTrueTime()) lastSuccess = e.getTrueTime(); } } if (lastSuccess!=-1) { //score = 1.0 + 1.0 / (1+lastSuccess); score = lastSuccess; scores.put(path, score); } } else { scores.put(path, Double.POSITIVE_INFINITY); } //System.out.println(lastSuccess + " , " + path + " \t excess cycles=" + (n.time() - lastSuccess) + " end=" + n.time()); if ((!success & showFail) || (success && showSuccess)) { System.err.println('\n' + path + " @" + n.time()); for (final OutputCondition e: expects) { System.err.println(" " + e); } } if (requireSuccess) assertTrue(path, success); return score; } @Test public void test() throws IOException, InstantiationException, InvocationTargetException, NoSuchMethodException, ParserConfigurationException, IllegalAccessException, SAXException, ClassNotFoundException, ParseException { testNAL(scriptPath); } }
package com.fishercoder.solutions; import java.util.ArrayList; import java.util.HashSet; import java.util.List; public class _212 { public static class Solution1 { public List<String> findWords(char[][] board, String[] words) { TrieNode root = buildTrie(words); List<String> result = new ArrayList(); for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { dfs(root, board, i, j, result); } } return result; } private void dfs(TrieNode root, char[][] board, int i, int j, List<String> result) { char c = board[i][j]; if (c == '#' || root.children[c - 'a'] == null) { return; } if (root.children[c - 'a'].word != null) { result.add(root.children[c - 'a'].word); root.children[c - 'a'].word = null;//de-duplicate } board[i][j] = '#';//mark it as visited to avoid cycles if (i > 0) { dfs(root.children[c - 'a'], board, i - 1, j, result); } if (j > 0) { dfs(root.children[c - 'a'], board, i, j - 1, result); } if (i + 1 < board.length) { dfs(root.children[c - 'a'], board, i + 1, j, result); } if (j + 1 < board[0].length) { dfs(root.children[c - 'a'], board, i, j + 1, result); } board[i][j] = c; } private TrieNode root; class TrieNode { String word; TrieNode[] children = new TrieNode[26]; } private TrieNode buildTrie(String[] words) { TrieNode root = new TrieNode(); for (String word : words) { char[] chars = word.toCharArray(); TrieNode temp = root; for (char c : chars) { if (temp.children[c - 'a'] == null) { temp.children[c - 'a'] = new TrieNode(); } temp = temp.children[c - 'a']; } temp.word = word; } return root; } } public static class Solution2 { public List<String> findWords (char[][] board, String[] words) { List<String> result = new ArrayList(); HashSet<String> set = new HashSet(); for (String word : words) { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (board[i][j] == word.charAt(0) && search(board, i, j, 0, word)) { set.add(word); } } } } result = new ArrayList<>(set); return result; } private boolean search(char[][] board, int i, int j, int count, String word) { if (count == word.length()) { return true; } if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != word.charAt(count)) { return false; } char temp = board[i][j]; board[i][j] = ' '; boolean foundWord = search(board, i + 1, j, count + 1, word) || search(board, i - 1, j, count + 1, word) || search(board, i, j + 1, count + 1, word) || search(board, i, j - 1, count + 1, word); board[i][j] = temp; return foundWord; } } }
package hudson.model; import hudson.EnvVars; import hudson.Functions; import hudson.Launcher; import hudson.Util; import hudson.matrix.MatrixConfiguration; import hudson.model.Fingerprint.BuildPtr; import hudson.model.Fingerprint.RangeSet; import hudson.model.listeners.SCMListener; import hudson.scm.CVSChangeLogParser; import hudson.scm.ChangeLogParser; import hudson.scm.ChangeLogSet; import hudson.scm.ChangeLogSet.Entry; import hudson.scm.SCM; import hudson.scm.NullChangeLogParser; import hudson.tasks.BuildStep; import hudson.tasks.BuildWrapper; import hudson.tasks.Builder; import hudson.tasks.Fingerprinter.FingerprintAction; import hudson.tasks.Publisher; import hudson.tasks.test.AbstractTestResultAction; import hudson.util.AdaptedIterator; import hudson.util.Iterators; import hudson.util.VariableResolver; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.export.Exported; import org.xml.sax.SAXException; import javax.servlet.ServletException; import java.io.File; import java.io.IOException; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * Base implementation of {@link Run}s that build software. * * For now this is primarily the common part of {@link Build} and MavenBuild. * * @author Kohsuke Kawaguchi * @see AbstractProject */ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Run<P,R> implements Queue.Executable { /** * Name of the slave this project was built on. * Null or "" if built by the master. (null happens when we read old record that didn't have this information.) */ private String builtOn; /** * Version of Hudson that built this. */ private String hudsonVersion; /** * SCM used for this build. * Maybe null, for historical reason, in which case CVS is assumed. */ private ChangeLogParser scm; /** * Changes in this build. */ private volatile transient ChangeLogSet<? extends Entry> changeSet; private volatile Set<String> culprits; protected transient List<Environment> buildEnvironments; protected AbstractBuild(P job) throws IOException { super(job); } protected AbstractBuild(P job, Calendar timestamp) { super(job, timestamp); } protected AbstractBuild(P project, File buildDir) throws IOException { super(project, buildDir); } public final P getProject() { return getParent(); } /** * Returns a {@link Slave} on which this build was done. * * @return * null, for example if the slave that this build run no logner exists. */ public Node getBuiltOn() { if(builtOn==null || builtOn.equals("")) return Hudson.getInstance(); else return Hudson.getInstance().getNode(builtOn); } /** * Returns the name of the slave it was built on, or null if it was the master. */ @Exported(name="builtOn") public String getBuiltOnStr() { return builtOn; } /** * Used to render the side panel "Back to project" link. * * <p> * In a rare situation where a build can be reached from multiple paths, * returning different URLs from this method based on situations might * be desirable. * * <p> * If you override this method, you'll most likely also want to override * {@link #getDisplayName()}. */ public String getUpUrl() { return Functions.getNearestAncestorUrl(Stapler.getCurrentRequest(),getParent())+'/'; } /** * List of users who committed a change since the last non-broken build till now. * * <p> * This list at least always include people who made changes in this build, but * if the previous build was a failure it also includes the culprit list from there. * * @return * can be empty but never null. */ @Exported public Set<User> getCulprits() { if(culprits==null) { Set<User> r = new HashSet<User>(); R p = getPreviousBuild(); if(p !=null && isBuilding() && p.getResult().isWorseThan(Result.UNSTABLE)) { // we are still building, so this is just the current latest information, // but we seems to be failing so far, so inherit culprits from the previous build. // isBuilding() check is to avoid recursion when loading data from old Hudson, which doesn't record // this information r.addAll(p.getCulprits()); } for( Entry e : getChangeSet() ) r.add(e.getAuthor()); return r; } return new AbstractSet<User>() { public Iterator<User> iterator() { return new AdaptedIterator<String,User>(culprits.iterator()) { protected User adapt(String id) { return User.get(id); } }; } public int size() { return culprits.size(); } }; } /** * Returns true if this user has made a commit to this build. * * @since 1.191 */ public boolean hasParticipant(User user) { for (ChangeLogSet.Entry e : getChangeSet()) if(e.getAuthor()==user) return true; return false; } /** * Gets the version of Hudson that was used to build this job. * * @since 1.246 */ public String getHudsonVersion() { return hudsonVersion; } protected abstract class AbstractRunner implements Runner { /** * Since configuration can be changed while a build is in progress, * create a launcher once and stick to it for the entire build duration. */ protected Launcher launcher; /** * Returns the current {@link Node} on which we are buildling. */ protected final Node getCurrentNode() { return Executor.currentExecutor().getOwner().getNode(); } public Result run(BuildListener listener) throws Exception { Node node = getCurrentNode(); assert builtOn==null; builtOn = node.getNodeName(); hudsonVersion = Hudson.VERSION; launcher = createLauncher(listener); if(!Hudson.getInstance().getNodes().isEmpty()) listener.getLogger().println(Messages.AbstractBuild_BuildingRemotely(node.getNodeName())); node.getFileSystemProvisioner().prepareWorkspace(AbstractBuild.this,project.getWorkspace(),listener); if(checkout(listener)) return Result.FAILURE; if(!preBuild(listener,project.getProperties())) return Result.FAILURE; Result result = doRun(listener); // kill run-away processes that are left // use multiple environment variables so that people can escape this massacre by overriding an environment // variable for some processes launcher.kill(getCharacteristicEnvVars()); // this is ugly, but for historical reason, if non-null value is returned // it should become the final result. if(result==null) result = getResult(); if(result==null) result = Result.SUCCESS; if(result.isBetterOrEqualTo(Result.UNSTABLE)) createSymLink(listener,"lastSuccessful"); if(result.isBetterOrEqualTo(Result.SUCCESS)) createSymLink(listener,"lastStable"); return result; } /** * Creates a {@link Launcher} that this build will use. This can be overridden by derived types * to decorate the resulting {@link Launcher}. * * @param listener * Always non-null. Connected to the main build output. */ protected Launcher createLauncher(BuildListener listener) throws IOException, InterruptedException { return getCurrentNode().createLauncher(listener); } private void createSymLink(BuildListener listener, String name) throws InterruptedException { Util.createSymlink(getProject().getBuildDir(),"builds/"+getId(),"../"+name,listener); } private boolean checkout(BuildListener listener) throws Exception { // for historical reasons, null in the scm field means CVS, so we need to explicitly set this to something // in case check out fails and leaves a broken changelog.xml behind. AbstractBuild.this.scm = new NullChangeLogParser(); if(!project.checkout(AbstractBuild.this,launcher,listener,new File(getRootDir(),"changelog.xml"))) return true; SCM scm = project.getScm(); AbstractBuild.this.scm = scm.createChangeLogParser(); AbstractBuild.this.changeSet = AbstractBuild.this.calcChangeSet(); for (SCMListener l : Hudson.getInstance().getSCMListeners()) l.onChangeLogParsed(AbstractBuild.this,listener,changeSet); return false; } /** * The portion of a build that is specific to a subclass of {@link AbstractBuild} * goes here. * * @return * null to continue the build normally (that means the doRun method * itself run successfully) * Return a non-null value to abort the build right there with the specified result code. */ protected abstract Result doRun(BuildListener listener) throws Exception, RunnerAbortedException; /** * @see #post(BuildListener) */ protected abstract void post2(BuildListener listener) throws Exception; public final void post(BuildListener listener) throws Exception { try { post2(listener); } finally { // update the culprit list HashSet<String> r = new HashSet<String>(); for (User u : getCulprits()) r.add(u.getId()); culprits = r; } } public void cleanUp(BuildListener listener) throws Exception { // default is no-op } protected final void performAllBuildStep(BuildListener listener, Map<?,? extends BuildStep> buildSteps, boolean phase) throws InterruptedException, IOException { performAllBuildStep(listener,buildSteps.values(),phase); } /** * Runs all the given build steps, even if one of them fail. * * @param phase * true for the post build processing, and false for the final "run after finished" execution. */ protected final void performAllBuildStep(BuildListener listener, Iterable<? extends BuildStep> buildSteps, boolean phase) throws InterruptedException, IOException { for( BuildStep bs : buildSteps ) { if( (bs instanceof Publisher && ((Publisher)bs).needsToRunAfterFinalized()) ^ phase) bs.perform(AbstractBuild.this, launcher, listener); } } protected final boolean preBuild(BuildListener listener,Map<?,? extends BuildStep> steps) { return preBuild(listener,steps.values()); } protected final boolean preBuild(BuildListener listener,Collection<? extends BuildStep> steps) { return preBuild(listener,(Iterable<? extends BuildStep>)steps); } protected final boolean preBuild(BuildListener listener,Iterable<? extends BuildStep> steps) { for( BuildStep bs : steps ) if(!bs.prebuild(AbstractBuild.this,listener)) return false; return true; } } /** * Gets the changes incorporated into this build. * * @return never null. */ @Exported public ChangeLogSet<? extends Entry> getChangeSet() { if(scm==null) scm = new CVSChangeLogParser(); if(changeSet==null) // cached value changeSet = calcChangeSet(); return changeSet; } /** * Returns true if the changelog is already computed. */ public boolean hasChangeSetComputed() { File changelogFile = new File(getRootDir(), "changelog.xml"); return changelogFile.exists(); } private ChangeLogSet<? extends Entry> calcChangeSet() { File changelogFile = new File(getRootDir(), "changelog.xml"); if(!changelogFile.exists()) return ChangeLogSet.createEmpty(this); try { return scm.parse(this,changelogFile); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return ChangeLogSet.createEmpty(this); } @Override public EnvVars getEnvironment() throws IOException, InterruptedException { EnvVars env = super.getEnvironment(); env.put("WORKSPACE", getProject().getWorkspace().getRemote()); // servlet container may have set CLASSPATH in its launch script, // so don't let that inherit to the new child process. env.put("CLASSPATH",""); JDK jdk = project.getJDK(); if(jdk != null) { Computer computer = Computer.currentComputer(); if (computer != null) { // just in case were not in a build jdk = jdk.forNode(computer.getNode()); } jdk.buildEnvVars(env); } project.getScm().buildEnvVars(this,env); if(buildEnvironments!=null) for (Environment e : buildEnvironments) e.buildEnvVars(env); ParametersAction parameters = getAction(ParametersAction.class); if (parameters != null) parameters.buildEnvVars(this,env); EnvVars.resolve(env); return env; } public Calendar due() { return getTimestamp(); } /** * Provides additional variables and their values to {@link Builder}s. * * <p> * This mechanism is used by {@link MatrixConfiguration} to pass * the configuration values to the current build. It is up to * {@link Builder}s to decide whether it wants to recognize the values * or how to use them. * * <p> * This also includes build parameters if a build is parameterized. * * @return * The returned map is mutable so that subtypes can put more values. */ public Map<String,String> getBuildVariables() { Map<String,String> r = new HashMap<String, String>(); ParametersAction parameters = getAction(ParametersAction.class); if(parameters!=null) { // this is a rather round about way of doing this... for (ParameterValue p : parameters) { String v = p.createVariableResolver(this).resolve(p.getName()); if(v!=null) r.put(p.getName(),v); } } return r; } /** * Creates {@link VariableResolver} backed by {@link #getBuildVariables()}. */ public final VariableResolver<String> getBuildVariableResolver() { return new VariableResolver.ByMap<String>(getBuildVariables()); } /** * Gets {@link AbstractTestResultAction} associated with this build if any. */ public AbstractTestResultAction getTestResultAction() { return getAction(AbstractTestResultAction.class); } /** * Invoked by {@link Executor} to performs a build. */ public abstract void run(); // fingerprint related stuff @Override public String getWhyKeepLog() { // if any of the downstream project is configured with 'keep dependency component', // we need to keep this log OUTER: for (AbstractProject<?,?> p : getParent().getDownstreamProjects()) { if(!p.isKeepDependencies()) continue; AbstractBuild<?,?> fb = p.getFirstBuild(); if(fb==null) continue; // no active record // is there any active build that depends on us? for(int i : getDownstreamRelationship(p).listNumbersReverse()) { // TODO: this is essentially a "find intersection between two sparse sequences" // and we should be able to do much better. if(i<fb.getNumber()) continue OUTER; // all the other records are younger than the first record, so pointless to search. AbstractBuild<?,?> b = p.getBuildByNumber(i); if(b!=null) return Messages.AbstractBuild_KeptBecause(b); } } return super.getWhyKeepLog(); } /** * Gets the dependency relationship from this build (as the source) * and that project (as the sink.) * * @return * range of build numbers that represent which downstream builds are using this build. * The range will be empty if no build of that project matches this, but it'll never be null. */ public RangeSet getDownstreamRelationship(AbstractProject that) { RangeSet rs = new RangeSet(); FingerprintAction f = getAction(FingerprintAction.class); if(f==null) return rs; // look for fingerprints that point to this build as the source, and merge them all for (Fingerprint e : f.getFingerprints().values()) { BuildPtr o = e.getOriginal(); if(o!=null && o.is(this)) rs.add(e.getRangeSet(that)); } return rs; } /** * Works like {@link #getDownstreamRelationship(AbstractProject)} but returns * the actual build objects, in ascending order. * @since 1.150 */ public Iterable<AbstractBuild<?,?>> getDownstreamBuilds(final AbstractProject<?,?> that) { final Iterable<Integer> nums = getDownstreamRelationship(that).listNumbers(); return new Iterable<AbstractBuild<?, ?>>() { public Iterator<AbstractBuild<?, ?>> iterator() { return new Iterators.FilterIterator<AbstractBuild<?,?>>( new AdaptedIterator<Integer,AbstractBuild<?,?>>(nums) { protected AbstractBuild<?, ?> adapt(Integer item) { return that.getBuildByNumber(item); } }) { protected boolean filter(AbstractBuild<?,?> build) { return build!=null; } }; } }; } /** * Gets the dependency relationship from this build (as the sink) * and that project (as the source.) * * @return * Build number of the upstream build that feed into this build, * or -1 if no record is available. */ public int getUpstreamRelationship(AbstractProject that) { FingerprintAction f = getAction(FingerprintAction.class); if(f==null) return -1; int n = -1; // look for fingerprints that point to the given project as the source, and merge them all for (Fingerprint e : f.getFingerprints().values()) { BuildPtr o = e.getOriginal(); if(o!=null && o.belongsTo(that)) n = Math.max(n,o.getNumber()); } return n; } /** * Works like {@link #getUpstreamRelationship(AbstractProject)} but returns the * actual build object. * * @return * null if no such upstream build was found, or it was found but the * build record is already lost. */ public AbstractBuild<?,?> getUpstreamRelationshipBuild(AbstractProject<?,?> that) { int n = getUpstreamRelationship(that); if(n==-1) return null; return that.getBuildByNumber(n); } /** * Gets the downstream builds of this build, which are the builds of the * downstream projects that use artifacts of this build. * * @return * For each project with fingerprinting enabled, returns the range * of builds (which can be empty if no build uses the artifact from this build.) */ public Map<AbstractProject,RangeSet> getDownstreamBuilds() { Map<AbstractProject,RangeSet> r = new HashMap<AbstractProject,RangeSet>(); for (AbstractProject p : getParent().getDownstreamProjects()) { if(p.isFingerprintConfigured()) r.put(p,getDownstreamRelationship(p)); } return r; } /** * Gets the upstream builds of this build, which are the builds of the * upstream projects whose artifacts feed into this build. * * @see #getTransitiveUpstreamBuilds() */ public Map<AbstractProject,Integer> getUpstreamBuilds() { return _getUpstreamBuilds(getParent().getUpstreamProjects()); } /** * Works like {@link #getUpstreamBuilds()} but also includes all the transitive * dependencies as well. */ public Map<AbstractProject,Integer> getTransitiveUpstreamBuilds() { return _getUpstreamBuilds(getParent().getTransitiveUpstreamProjects()); } private Map<AbstractProject, Integer> _getUpstreamBuilds(Collection<AbstractProject> projects) { Map<AbstractProject,Integer> r = new HashMap<AbstractProject,Integer>(); for (AbstractProject p : projects) { int n = getUpstreamRelationship(p); if(n>=0) r.put(p,n); } return r; } /** * Gets the changes in the dependency between the given build and this build. */ public Map<AbstractProject,DependencyChange> getDependencyChanges(AbstractBuild from) { if(from==null) return Collections.emptyMap(); // make it easy to call this from views FingerprintAction n = this.getAction(FingerprintAction.class); FingerprintAction o = from.getAction(FingerprintAction.class); if(n==null || o==null) return Collections.emptyMap(); Map<AbstractProject,Integer> ndep = n.getDependencies(); Map<AbstractProject,Integer> odep = o.getDependencies(); Map<AbstractProject,DependencyChange> r = new HashMap<AbstractProject,DependencyChange>(); for (Map.Entry<AbstractProject,Integer> entry : odep.entrySet()) { AbstractProject p = entry.getKey(); Integer oldNumber = entry.getValue(); Integer newNumber = ndep.get(p); if(newNumber!=null && oldNumber.compareTo(newNumber)<0) { r.put(p,new DependencyChange(p,oldNumber,newNumber)); } } return r; } /** * Represents a change in the dependency. */ public static final class DependencyChange { /** * The dependency project. */ public final AbstractProject project; /** * Version of the dependency project used in the previous build. */ public final int fromId; /** * {@link Build} object for {@link #fromId}. Can be null if the log is gone. */ public final AbstractBuild from; /** * Version of the dependency project used in this build. */ public final int toId; public final AbstractBuild to; public DependencyChange(AbstractProject<?,?> project, int fromId, int toId) { this.project = project; this.fromId = fromId; this.toId = toId; this.from = project.getBuildByNumber(fromId); this.to = project.getBuildByNumber(toId); } /** * Gets the {@link AbstractBuild} objects (fromId,toId]. * <p> * This method returns all such available builds in the ascending order * of IDs, but due to log rotations, some builds may be already unavailable. */ public List<AbstractBuild> getBuilds() { List<AbstractBuild> r = new ArrayList<AbstractBuild>(); AbstractBuild<?,?> b = (AbstractBuild)project.getNearestBuild(fromId); if(b!=null && b.getNumber()==fromId) b = b.getNextBuild(); // fromId exclusive while(b!=null && b.getNumber()<=toId) { r.add(b); b = b.getNextBuild(); } return r; } } // web methods /** * Stops this build if it's still going. * * If we use this/executor/stop URL, it causes 404 if the build is already killed, * as {@link #getExecutor()} returns null. */ public synchronized void doStop( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { Executor e = getExecutor(); if(e!=null) e.doStop(req,rsp); else // nothing is building rsp.forwardToPreviousPage(req); } }
package sg.ncl; import org.apache.commons.lang3.RandomStringUtils; import org.json.JSONObject; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.ResultActions; import org.springframework.web.client.RestOperations; import org.springframework.web.client.RestTemplate; import org.springframework.web.context.WebApplicationContext; import sg.ncl.domain.NodeType; import sg.ncl.domain.UserType; import sg.ncl.testbed_interface.User2; import javax.inject.Inject; import javax.servlet.http.HttpSession; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; import static org.mockito.Mockito.when; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withBadRequest; import static org.springframework.test.web.client.response.MockRestResponseCreators.withServerError; import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; /** * @author Te Ye */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = WebApplication.class) @WebAppConfiguration public class MainControllerTest { @Rule public MockitoRule mockito = MockitoJUnit.rule(); @Rule public ExpectedException exception = ExpectedException.none(); // @Bean // RestTemplate restTemplate() { // return Mockito.mock(RestTemplate.class); private MockMvc mockMvc; // private RestTemplate restTemplate; private MockRestServiceServer mockServer; @Inject private RestOperations restOperations; @Inject private ConnectionProperties properties; @Inject private WebApplicationContext webApplicationContext; @Mock private WebProperties webProperties; @Mock private HttpSession session; @Before public void setUp() throws Exception { // restTemplate = Mockito.mock(RestTemplate.class); mockServer = MockRestServiceServer.createServer((RestTemplate) restOperations); mockMvc = webAppContextSetup(webApplicationContext).build(); } // Test before login HTML pages @Test public void testIndexPage() throws Exception { // ensure page can load <head>, navigation, <body>, <footer> mockMvc.perform(get("/")) .andExpect(status().isOk()) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("navbar-header"))) .andExpect(content().string(containsString("NATIONAL CYBERSECURITY R&amp;D LAB"))) .andExpect(content().string(containsString("Features"))) .andExpect(content().string(containsString("Focus on your"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testOverviewPage() throws Exception { mockMvc.perform(get("/overview")) .andExpect(status().isOk()) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("navbar-header"))) .andExpect(content().string(containsString("id=\"joinUs\""))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testCommunityPage() throws Exception { mockMvc.perform(get("/community")) .andExpect(status().isOk()) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("navbar-header"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testAboutPage() throws Exception { mockMvc.perform(get("/about")) .andExpect(status().isOk()) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("navbar-header"))) .andExpect(content().string(containsString("id=\"about-us\""))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testEventPage() throws Exception { mockMvc.perform(get("/event")) .andExpect(status().isOk()) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("navbar-header"))) .andExpect(content().string(containsString("div id=\"portfolioSlider\""))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testPlanPage() throws Exception { mockMvc.perform(get("/plan")) .andExpect(status().isOk()) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("navbar-header"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } // page is taken out as of 22/9/2016 @Ignore public void testFuturePlanPage() throws Exception { mockMvc.perform(get("/futureplan")) .andExpect(status().isOk()) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("navbar-header"))) .andExpect(content().string(containsString("a href=\"/futureplan/download\""))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testPricingPage() throws Exception { mockMvc.perform(get("/pricing")) .andExpect(status().isOk()) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("navbar-header"))) .andExpect(content().string(containsString("Pricing"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testResourcesPage() throws Exception { mockMvc.perform(get("/resources")) .andExpect(status().isOk()) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("navbar-header"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testResearchPage() throws Exception { mockMvc.perform(get("/research")) .andExpect(status().isOk()) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("navbar-header"))) .andExpect(content().string(containsString("Research"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testContactUsPage() throws Exception { // calendar page display BEFORE login mockMvc.perform(get("/contactus")) .andExpect(status().isOk()) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("navbar-header"))) .andExpect(content().string(containsString("Contact Us"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testGetLoginPage() throws Exception { mockMvc.perform(get("/login")) .andExpect(status().isOk()) .andExpect(view().name("login")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/login"))) //.andExpect(content().string(containsString("/signup2"))) .andExpect(content().string(containsString("form method=\"post\" action=\"/login\""))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testPostLoginPageInvalidUserPassword() throws Exception { mockServer.expect(requestTo(properties.getSioAuthUrl())) .andExpect(method(HttpMethod.POST)) .andRespond(withBadRequest().body("{\"error\":\"sg.ncl.service.authentication.exceptions.InvalidCredentialsException\"}").contentType(MediaType.APPLICATION_JSON)); ResultActions perform = mockMvc.perform( post("/login") .param("loginEmail", "123456789@nus.edu.sg") .param("loginPassword", "123456789") ); perform .andExpect(view().name("login")); perform .andExpect(model().attributeExists("loginForm")); } /* @Test public void testGetSignUpPage() throws Exception { mockMvc.perform(get("/signup2")) .andExpect(status().isOk()) .andExpect(view().name("signup2")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/login"))) .andExpect(content().string(containsString("/signup2"))) .andExpect(content().string(containsString("form action=\"/signup2\" method=\"post\" role=\"form\""))) .andExpect(content().string(containsString("footer id=\"footer\""))) .andExpect(model().attributeExists("signUpMergedForm")); } */ @Test public void testRedirectNotFoundNotLoggedOn() throws Exception { mockMvc.perform(get("/notfound")) .andExpect(redirectedUrl("/")); } @Test public void testRedirectNotFoundLoggedOn() throws Exception { final String id = RandomStringUtils.randomAlphabetic(10); mockMvc.perform(get("/notfound").sessionAttr("id", id)) .andExpect(redirectedUrl("/dashboard")); } @Test public void testCareerPage() throws Exception { mockMvc.perform(get("/career")) .andExpect(status().isOk()) .andExpect(view().name("career")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/plan"))) .andExpect(content().string(containsString("/research"))) .andExpect(content().string(containsString("/pricing"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/contactus"))) .andExpect(content().string(containsString("/event"))) .andExpect(content().string(containsString("/about"))) //.andExpect(content().string(containsString("/signup2"))) .andExpect(content().string(containsString("/login"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testTutorialsUseNodePage() throws Exception { mockMvc.perform(get("/tutorials/usenode")) .andExpect(status().isOk()) .andExpect(view().name("usenode")) .andExpect(content().string(containsString("How to Access your Experiment Node"))) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/plan"))) .andExpect(content().string(containsString("/research"))) .andExpect(content().string(containsString("/pricing"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/contactus"))) .andExpect(content().string(containsString("/event"))) .andExpect(content().string(containsString("/about"))) //.andExpect(content().string(containsString("/signup2"))) .andExpect(content().string(containsString("/login"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testTutorialsUseSSHPage() throws Exception { mockMvc.perform(get("/tutorials/usessh")) .andExpect(status().isOk()) .andExpect(view().name("usessh")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/plan"))) .andExpect(content().string(containsString("/research"))) .andExpect(content().string(containsString("/pricing"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/contactus"))) .andExpect(content().string(containsString("/event"))) .andExpect(content().string(containsString("/about"))) //.andExpect(content().string(containsString("/signup2"))) .andExpect(content().string(containsString("/login"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testTutorialsUseScpPage() throws Exception { mockMvc.perform(get("/tutorials/usescp")) .andExpect(status().isOk()) .andExpect(view().name("usescp")) .andExpect(content().string(containsString("Open the SSH terminal on your system go to the directory where the file to be uploaded is located."))) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/plan"))) .andExpect(content().string(containsString("/research"))) .andExpect(content().string(containsString("/pricing"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/contactus"))) .andExpect(content().string(containsString("/event"))) .andExpect(content().string(containsString("/about"))) //.andExpect(content().string(containsString("/signup2"))) .andExpect(content().string(containsString("/login"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testTutorialsUseGui() throws Exception { mockMvc.perform(get("/tutorials/usegui")) .andExpect(status().isOk()) .andExpect(view().name("usegui")) .andExpect(content().string(containsString("Install deskstop and VNC server using the following commands"))) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/plan"))) .andExpect(content().string(containsString("/research"))) .andExpect(content().string(containsString("/pricing"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/contactus"))) .andExpect(content().string(containsString("/event"))) .andExpect(content().string(containsString("/about"))) //.andExpect(content().string(containsString("/signup2"))) .andExpect(content().string(containsString("/login"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testTutorialsManagerResource() throws Exception { mockMvc.perform(get("/tutorials/manageresource")) .andExpect(status().isOk()) .andExpect(view().name("manageresource")) .andExpect(content().string(containsString("To set the quota for resources, enter a monetary value for \"Budget\""))) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/plan"))) .andExpect(content().string(containsString("/research"))) .andExpect(content().string(containsString("/pricing"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/contactus"))) .andExpect(content().string(containsString("/event"))) .andExpect(content().string(containsString("/about"))) //.andExpect(content().string(containsString("/signup2"))) .andExpect(content().string(containsString("/login"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testTutorialsTestbedInfo() throws Exception { mockMvc.perform(get("/tutorials/testbedinfo")) .andExpect(status().isOk()) .andExpect(view().name("testbedinfo")) .andExpect(content().string(containsString("View Testbed Info"))) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/plan"))) .andExpect(content().string(containsString("/research"))) .andExpect(content().string(containsString("/pricing"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/contactus"))) .andExpect(content().string(containsString("/event"))) .andExpect(content().string(containsString("/about"))) //.andExpect(content().string(containsString("/signup2"))) .andExpect(content().string(containsString("/login"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testTutorialsCreateCustom() throws Exception { mockMvc.perform(get("/tutorials/createcustom")) .andExpect(status().isOk()) .andExpect(view().name("createcustom")) .andExpect(content().string(containsString("How to Save an Image for an Experiment Node"))) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/plan"))) .andExpect(content().string(containsString("/research"))) .andExpect(content().string(containsString("/pricing"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/contactus"))) .andExpect(content().string(containsString("/event"))) .andExpect(content().string(containsString("/about"))) //.andExpect(content().string(containsString("/signup2"))) .andExpect(content().string(containsString("/login"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testErrorOpenStack() throws Exception { mockMvc.perform(get("/error_openstack")) .andExpect(status().isOk()) .andExpect(view().name("error_openstack")) .andExpect(content().string(containsString("Currently, we are in the process of integrating OpenStack with our systems"))) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/teams"))) .andExpect(content().string(containsString("/experiments"))) .andExpect(content().string(containsString("/data"))) .andExpect(content().string(containsString("/admin"))) .andExpect(content().string(containsString("/admin/experiments"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/approve_new_user"))) .andExpect(content().string(containsString("/account_settings"))) .andExpect(content().string(containsString("/logout"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testAccessExperiment() throws Exception { mockMvc.perform(get("/accessexperiment")) .andExpect(status().isOk()) .andExpect(view().name("accessexperiment")) .andExpect(content().string(containsString("Go to dashboard page and take note of the username under Info!: Use your username: XXX to access the experiments' nodes."))) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/plan"))) .andExpect(content().string(containsString("/research"))) .andExpect(content().string(containsString("/pricing"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/contactus"))) .andExpect(content().string(containsString("/event"))) .andExpect(content().string(containsString("/about"))) //.andExpect(content().string(containsString("/signup2"))) .andExpect(content().string(containsString("/login"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testResource2() throws Exception { mockMvc.perform(get("/resource2")) .andExpect(status().isOk()) .andExpect(view().name("resource2")) .andExpect(content().string(containsString("Vulnerability Environments"))) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/teams"))) .andExpect(content().string(containsString("/experiments"))) .andExpect(content().string(containsString("/data"))) .andExpect(content().string(containsString("/admin"))) .andExpect(content().string(containsString("/admin/experiments"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/approve_new_user"))) .andExpect(content().string(containsString("/account_settings"))) .andExpect(content().string(containsString("/logout"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } // Test after login HTML pages // FIXME: ignore for now as dashboard page invoke two other rest calls @Ignore @Test public void testGetDashboardPage() throws Exception { final String id = RandomStringUtils.randomAlphabetic(10); mockServer.expect(requestTo(properties.getDeterUid(id))) .andExpect(method(HttpMethod.GET)) .andRespond(withSuccess(id, MediaType.APPLICATION_JSON)); mockMvc.perform(get("/dashboard").sessionAttr("id", id)) .andExpect(status().isOk()) .andExpect(view().name("dashboard")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/teams"))) .andExpect(content().string(containsString("/experiments"))) .andExpect(content().string(containsString("/calendar1"))) .andExpect(content().string(containsString("/approve_new_user"))) .andExpect(content().string(containsString("/account_settings"))) .andExpect(content().string(containsString("/logout"))) .andExpect(content().string(containsString("Dashboard"))) .andExpect(content().string(containsString("footer id=\"footer\""))) .andExpect(model().attribute("deterUid", is(id))); } // FIXME: ignore for now as dashboard page invoke two other rest calls @Ignore @Test public void testGetDashboardPageWithAdmin() throws Exception { final String id = RandomStringUtils.randomAlphabetic(10); mockServer.expect(requestTo(properties.getDeterUid(id))) .andExpect(method(HttpMethod.GET)) .andRespond(withSuccess(id, MediaType.APPLICATION_JSON)); mockMvc.perform(get("/dashboard").sessionAttr("id", id).sessionAttr("roles", UserType.ADMIN.toString())) .andExpect(status().isOk()) .andExpect(view().name("dashboard")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/teams"))) .andExpect(content().string(containsString("/experiments"))) .andExpect(content().string(containsString("/admin"))) .andExpect(content().string(containsString("/calendar1"))) .andExpect(content().string(containsString("/approve_new_user"))) .andExpect(content().string(containsString("/account_settings"))) .andExpect(content().string(containsString("/logout"))) .andExpect(content().string(containsString("Dashboard"))) .andExpect(content().string(containsString("footer id=\"footer\""))) .andExpect(model().attribute("deterUid", is(id))); } @Test public void getUserProfileTest() throws Exception { JSONObject predefinedUserJson = Util.createUserJson(); String predefinedJsonStr = predefinedUserJson.toString(); when(webProperties.getSessionJwtToken()).thenReturn("token"); // uri must be equal to that defined in MainController mockServer.expect(requestTo(properties.getSioUsersUrl() + "null")) .andExpect(method(HttpMethod.GET)) .andRespond(withSuccess(predefinedJsonStr, MediaType.APPLICATION_JSON)); MvcResult result = mockMvc.perform(get("/account_settings").sessionAttr(webProperties.getSessionJwtToken(), "1234")) .andExpect(status().isOk()) .andExpect(view().name("account_settings")) .andExpect(model().attribute("editUser", hasProperty("id", is(predefinedUserJson.getString("id"))))) .andReturn(); } @Test public void updateUserProfileTest() throws Exception { // TODO to be completed // update the phone to test main json // update the lastname to test user details json // update the address2 to test address json JSONObject predefinedUserJson = Util.createUserJson(); final User2 user2 = Util.getUser(); final String id = RandomStringUtils.randomAlphabetic(10); String predefinedJsonStr = predefinedUserJson.toString(); when(webProperties.getSessionUserAccount()).thenReturn("originalAccountDetails"); when(webProperties.getSessionJwtToken()).thenReturn("token"); when(webProperties.getSessionUserId()).thenReturn("id"); when(session.getAttribute(webProperties.getSessionUserAccount())).thenReturn(user2); when(session.getAttribute(webProperties.getSessionUserId())).thenReturn(id); mockServer.expect(requestTo(properties.getSioUsersUrl() + id)) .andExpect(method(HttpMethod.PUT)) .andRespond(withSuccess(predefinedJsonStr, MediaType.APPLICATION_JSON)); MvcResult result = mockMvc.perform( post("/account_settings").sessionAttr(webProperties.getSessionUserAccount(), user2).sessionAttr(webProperties.getSessionJwtToken(), "1234").sessionAttr(webProperties.getSessionUserId(), id) .param("email", "apple@nus.edu.sg") .param("password", "password") .param("confirmPassword", "confirmPassword") .param("firstName", "apple") .param("lastName", "edited") .param("phone", "12345678") .param("jobTitle", "research") .param("institution", "national university") .param("institutionAbbreviation", "nus") .param("institutionWeb", "") .param("address1", "address1") .param("address2", "edited") .param("country", "singapore") .param("city", "sg") .param("province", "west") .param("postalCode", "123456")) .andExpect(redirectedUrl("/account_settings")) .andReturn(); } @Test public void testGetJoinTeamPageFromTeamPage() throws Exception { mockMvc.perform(get("/teams/join_team")) .andExpect(status().isOk()) .andExpect(view().name("team_page_join_team")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/teams"))) .andExpect(content().string(containsString("/experiments"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/approve_new_user"))) .andExpect(content().string(containsString("/approve_new_user"))) .andExpect(content().string(containsString("/account_settings"))) .andExpect(content().string(containsString("/logout"))) .andExpect(content().string(containsString("method=\"post\" action=\"/teams/join_team\""))) .andExpect(content().string(containsString("footer id=\"footer\""))) .andExpect(model().attribute("teamPageJoinTeamForm", hasProperty("teamName"))); } @Test public void testGetApplyNewTeamPageFromTeamPage() throws Exception { mockMvc.perform(get("/teams/apply_team")) .andExpect(status().isOk()) .andExpect(view().name("team_page_apply_team")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/teams"))) .andExpect(content().string(containsString("/experiments"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/approve_new_user"))) .andExpect(content().string(containsString("/approve_new_user"))) .andExpect(content().string(containsString("/account_settings"))) .andExpect(content().string(containsString("/logout"))) .andExpect(content().string(containsString("method=\"post\" action=\"/teams/apply_team\""))) .andExpect(content().string(containsString("footer id=\"footer\""))) .andExpect(model().attribute("teamPageApplyTeamForm", hasProperty("teamName"))); } @Test public void testResetPasswordEnterEmail() throws Exception { mockMvc.perform( get("/password_reset_email")) .andExpect(view().name("password_reset_email")) .andExpect(model().attributeExists("passwordResetRequestForm")); } @Test public void testResetPasswordRequestUsernameNotFound() throws Exception { mockServer.expect(requestTo(properties.getPasswordResetRequestURI())) .andExpect(method(HttpMethod.POST)) .andRespond(withStatus(HttpStatus.NOT_FOUND)); ResultActions perform = mockMvc.perform( post("/password_reset_request") .param("email", "123456@nus.edu.sg")) .andExpect(status().isOk()) .andExpect(model().attribute("passwordResetRequestForm", hasProperty("errMsg", is("Email not registered. Please use a different email address.")))) .andExpect(view().name("password_reset_email")); } @Test public void testResetPasswordRequestGood() throws Exception { mockServer.expect(requestTo(properties.getPasswordResetRequestURI())) .andExpect(method(HttpMethod.POST)) .andRespond(withStatus(HttpStatus.ACCEPTED)); mockMvc.perform( post("/password_reset_request") .param("email", "123456@nus.edu.sg")) .andExpect(status().isOk()) .andExpect(view().name("password_reset_email_sent")); } @Test public void testResetPasswordNewPassword() throws Exception { mockMvc.perform( get("/passwordReset?key=12345678")) // .param("key", "12345678")) .andExpect(status().isOk()) .andExpect(view().name("password_reset_new_password")) .andExpect(model().attributeExists("passwordResetForm")); } @Test public void testResetPasswordGood() throws Exception { mockServer.expect(requestTo(properties.getPasswordResetURI())) .andExpect(method(HttpMethod.PUT)) .andRespond(withStatus(HttpStatus.OK)); mockMvc.perform( post("/password_reset") .param("password1", "password1") .param("password2", "password1") .sessionAttr("key", "12345678")) .andExpect(status().isOk()) .andExpect(view().name("password_reset_success")); } @Test public void testResetPasswordRequestTimeout() throws Exception { mockServer.expect(requestTo(properties.getPasswordResetURI())) .andExpect(method(HttpMethod.PUT)) .andRespond(withBadRequest().body("{\"error\":\"sg.ncl.service.authentication.exceptions.PasswordResetRequestTimeoutException\"}").contentType(MediaType.APPLICATION_JSON)); mockMvc.perform( post("/password_reset") .param("password1", "password1") .param("password2", "password1") .sessionAttr("key", "12345678")) .andExpect(status().isOk()) .andExpect(view().name("password_reset_new_password")) .andExpect(model().attribute("passwordResetForm", hasProperty("errMsg", is("Password reset request timed out. Please request a new reset email.")))); } @Test public void testResetPasswordUnknownRequest() throws Exception { mockServer.expect(requestTo(properties.getPasswordResetURI())) .andExpect(method(HttpMethod.PUT)) .andRespond(withStatus(HttpStatus.NOT_FOUND).body("{\"error\":\"sg.ncl.service.authentication.exceptions.PasswordResetRequestNotFoundException\"}").contentType(MediaType.APPLICATION_JSON)); mockMvc.perform( post("/password_reset") .param("password1", "password1") .param("password2", "password1") .sessionAttr("key", "12345678")) .andExpect(status().isOk()) .andExpect(view().name("password_reset_new_password")) .andExpect(model().attribute("passwordResetForm", hasProperty("errMsg", is("Invalid password reset request. Please request a new reset email.")))); } @Test public void testResetPasswordServerError() throws Exception { mockServer.expect(requestTo(properties.getPasswordResetURI())) .andExpect(method(HttpMethod.PUT)) .andRespond(withServerError().body("{\"error\":\"sg.ncl.service.authentication.exceptions.AdapterConnectionException\"}").contentType(MediaType.APPLICATION_JSON)); mockMvc.perform( post("/password_reset") .param("password1", "password1") .param("password2", "password1") .param("key", "12345678")) .andExpect(status().isOk()) .andExpect(view().name("password_reset_new_password")) .andExpect(model().attribute("passwordResetForm", hasProperty("errMsg", is("Server-side error. Please contact support@ncl.sg")))); } @Test public void testTutorialsCreateAccountNoLogin() throws Exception { mockMvc.perform(get("/tutorials/createaccount")) .andExpect(status().isOk()) .andExpect(view().name("createaccount")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/plan"))) .andExpect(content().string(containsString("/research"))) .andExpect(content().string(containsString("/pricing"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/contactus"))) .andExpect(content().string(containsString("/event"))) .andExpect(content().string(containsString("/about"))) //.andExpect(content().string(containsString("/signup2"))) .andExpect(content().string(containsString("/login"))) .andExpect(content().string(containsString("Fill in all required information here. ALL fields are required."))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testTutorialsCreateAccountLogin() throws Exception { mockMvc.perform(get("/tutorials/createaccount").sessionAttr("id", "id")) .andExpect(status().isOk()) .andExpect(view().name("createaccount")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/teams"))) .andExpect(content().string(containsString("/experiments"))) .andExpect(content().string(containsString("/data"))) .andExpect(content().string(containsString("/admin"))) .andExpect(content().string(containsString("/admin/experiments"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/approve_new_user"))) .andExpect(content().string(containsString("/account_settings"))) .andExpect(content().string(containsString("/logout"))) .andExpect(content().string(containsString("Fill in all required information here. ALL fields are required."))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testTutorialsCreateExperimentNoLogin() throws Exception { mockMvc.perform(get("/tutorials/createexperiment")) .andExpect(status().isOk()) .andExpect(view().name("createexperiment")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/plan"))) .andExpect(content().string(containsString("/research"))) .andExpect(content().string(containsString("/pricing"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/contactus"))) .andExpect(content().string(containsString("/event"))) .andExpect(content().string(containsString("/about"))) //.andExpect(content().string(containsString("/signup2"))) .andExpect(content().string(containsString("/login"))) .andExpect(content().string(containsString("After logging in, click on “Experiment” on the navigation bar at the top"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testTutorialsCreateExperimentLogin() throws Exception { mockMvc.perform(get("/tutorials/createexperiment").sessionAttr("id", "id")) .andExpect(status().isOk()) .andExpect(view().name("createexperiment")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/teams"))) .andExpect(content().string(containsString("/experiments"))) .andExpect(content().string(containsString("/data"))) .andExpect(content().string(containsString("/admin"))) .andExpect(content().string(containsString("/admin/experiments"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/approve_new_user"))) .andExpect(content().string(containsString("/account_settings"))) .andExpect(content().string(containsString("/logout"))) .andExpect(content().string(containsString("After logging in, click on “Experiment” on the navigation bar at the top"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testTutorialsLoadImageNoLogin() throws Exception { mockMvc.perform(get("/tutorials/loadimage")) .andExpect(status().isOk()) .andExpect(view().name("loadimage")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/plan"))) .andExpect(content().string(containsString("/research"))) .andExpect(content().string(containsString("/pricing"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/contactus"))) .andExpect(content().string(containsString("/event"))) .andExpect(content().string(containsString("/about"))) //.andExpect(content().string(containsString("/signup2"))) .andExpect(content().string(containsString("/login"))) .andExpect(content().string(containsString("At the Teams page, under the section “Your teams’ saved operating system images”, pick an image that you have saved previously."))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testTutorialsLoadImageLogin() throws Exception { mockMvc.perform(get("/tutorials/loadimage").sessionAttr("id", "id")) .andExpect(status().isOk()) .andExpect(view().name("loadimage")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/teams"))) .andExpect(content().string(containsString("/experiments"))) .andExpect(content().string(containsString("/data"))) .andExpect(content().string(containsString("/admin"))) .andExpect(content().string(containsString("/admin/experiments"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/approve_new_user"))) .andExpect(content().string(containsString("/account_settings"))) .andExpect(content().string(containsString("/logout"))) .andExpect(content().string(containsString("At the Teams page, under the section “Your teams’ saved operating system images”, pick an image that you have saved previously."))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testTutorialsSaveImageNoLogin() throws Exception { mockMvc.perform(get("/tutorials/saveimage")) .andExpect(status().isOk()) .andExpect(view().name("saveimage")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/plan"))) .andExpect(content().string(containsString("/research"))) .andExpect(content().string(containsString("/pricing"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/contactus"))) .andExpect(content().string(containsString("/event"))) .andExpect(content().string(containsString("/about"))) //.andExpect(content().string(containsString("/signup2"))) .andExpect(content().string(containsString("/login"))) .andExpect(content().string(containsString("Click on “View” under Details to see more details about the started experiment"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testTutorialsSaveImageLogin() throws Exception { mockMvc.perform(get("/tutorials/saveimage").sessionAttr("id", "id")) .andExpect(status().isOk()) .andExpect(view().name("saveimage")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/teams"))) .andExpect(content().string(containsString("/experiments"))) .andExpect(content().string(containsString("/data"))) .andExpect(content().string(containsString("/admin"))) .andExpect(content().string(containsString("/admin/experiments"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/approve_new_user"))) .andExpect(content().string(containsString("/account_settings"))) .andExpect(content().string(containsString("/logout"))) .andExpect(content().string(containsString("Click on “View” under Details to see more details about the started experiment"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testTutorialsApplyTeamNoLogin() throws Exception { mockMvc.perform(get("/tutorials/applyteam")) .andExpect(status().isOk()) .andExpect(view().name("applyteam")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/plan"))) .andExpect(content().string(containsString("/research"))) .andExpect(content().string(containsString("/pricing"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/contactus"))) .andExpect(content().string(containsString("/event"))) .andExpect(content().string(containsString("/about"))) //.andExpect(content().string(containsString("/signup2"))) .andExpect(content().string(containsString("/login"))) .andExpect(content().string(containsString("Go to team dashboard and click the apply a team button."))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testTutorialsApplyTeamLogin() throws Exception { mockMvc.perform(get("/tutorials/applyteam").sessionAttr("id", "id")) .andExpect(status().isOk()) .andExpect(view().name("applyteam")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/teams"))) .andExpect(content().string(containsString("/experiments"))) .andExpect(content().string(containsString("/data"))) .andExpect(content().string(containsString("/admin"))) .andExpect(content().string(containsString("/admin/experiments"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/approve_new_user"))) .andExpect(content().string(containsString("/account_settings"))) .andExpect(content().string(containsString("/logout"))) .andExpect(content().string(containsString("Go to team dashboard and click the apply a team button."))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testTutorialsJoinTeamNoLogin() throws Exception { mockMvc.perform(get("/tutorials/jointeam")) .andExpect(status().isOk()) .andExpect(view().name("jointeam")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/plan"))) .andExpect(content().string(containsString("/research"))) .andExpect(content().string(containsString("/pricing"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/contactus"))) .andExpect(content().string(containsString("/event"))) .andExpect(content().string(containsString("/about"))) //.andExpect(content().string(containsString("/signup2"))) .andExpect(content().string(containsString("/login"))) .andExpect(content().string(containsString("Go to team dashboard and click the join a team button."))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testTutorialsJoinTeamLogin() throws Exception { mockMvc.perform(get("/tutorials/jointeam").sessionAttr("id", "id")) .andExpect(status().isOk()) .andExpect(view().name("jointeam")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/teams"))) .andExpect(content().string(containsString("/experiments"))) .andExpect(content().string(containsString("/data"))) .andExpect(content().string(containsString("/admin"))) .andExpect(content().string(containsString("/admin/experiments"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/approve_new_user"))) .andExpect(content().string(containsString("/account_settings"))) .andExpect(content().string(containsString("/logout"))) .andExpect(content().string(containsString("Go to team dashboard and click the join a team button."))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testTutorialsNoLogin() throws Exception { mockMvc.perform(get("/tutorials")) .andExpect(status().isOk()) .andExpect(view().name("tutorials")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/plan"))) .andExpect(content().string(containsString("/research"))) .andExpect(content().string(containsString("/pricing"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/contactus"))) .andExpect(content().string(containsString("/event"))) .andExpect(content().string(containsString("/about"))) //.andExpect(content().string(containsString("/signup2"))) .andExpect(content().string(containsString("/login"))) .andExpect(content().string(containsString("How to Create an Account"))) .andExpect(content().string(containsString("How to Apply a Team"))) .andExpect(content().string(containsString("How to Join a Team"))) .andExpect(content().string(containsString("How to Create an Experiment"))) .andExpect(content().string(containsString("How to Use your Experiment Node"))) .andExpect(content().string(containsString("How to Create Custom Image"))) .andExpect(content().string(containsString("How to Provision Software Defined Network (SDN) Experiments in NCL Testbed"))) .andExpect(content().string(containsString("How to Manage Team Resources"))) .andExpect(content().string(containsString("How to Get Information about NCL Testbed"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testTutorialsLogin() throws Exception { mockMvc.perform(get("/tutorials").sessionAttr("id", "id")) .andExpect(status().isOk()) .andExpect(view().name("tutorials")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/teams"))) .andExpect(content().string(containsString("/experiments"))) .andExpect(content().string(containsString("/data"))) .andExpect(content().string(containsString("/admin"))) .andExpect(content().string(containsString("/admin/experiments"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/approve_new_user"))) .andExpect(content().string(containsString("/account_settings"))) .andExpect(content().string(containsString("/logout"))) .andExpect(content().string(containsString("How to Create an Account"))) .andExpect(content().string(containsString("How to Apply a Team"))) .andExpect(content().string(containsString("How to Join a Team"))) .andExpect(content().string(containsString("How to Create an Experiment"))) .andExpect(content().string(containsString("How to Use your Experiment Node"))) .andExpect(content().string(containsString("How to Create Custom Image"))) .andExpect(content().string(containsString("How to Provision Software Defined Network (SDN) Experiments in NCL Testbed"))) .andExpect(content().string(containsString("How to Manage Team Resources"))) .andExpect(content().string(containsString("How to Get Information about NCL Testbed"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testTestbedInformationNoLogin() throws Exception { // mock three REST calls // mockServer order is important here, the web service first invokes the get global image follow by get total nodes, get testbed stats JSONObject predefinedResultJson = new JSONObject(); predefinedResultJson.put(NodeType.TOTAL.name(), "99"); JSONObject predefinedResultJson2 = new JSONObject(); predefinedResultJson2.put("images", "{\"imageA\": {\"osname\": \"Linux\", \"description\": \"image description\"}}"); JSONObject predefinedResultJson3 = new JSONObject(); predefinedResultJson3.put("users", "10"); predefinedResultJson3.put("experiments", "20"); mockServer.expect(requestTo(properties.getGlobalImages())) .andExpect(method(HttpMethod.GET)) .andRespond(withSuccess(predefinedResultJson2.toString(), MediaType.APPLICATION_JSON)); mockServer.expect(requestTo(properties.getNodes(NodeType.TOTAL))) .andExpect(method(HttpMethod.GET)) .andRespond(withSuccess(predefinedResultJson.toString(), MediaType.APPLICATION_JSON)); mockServer.expect(requestTo(properties.getTestbedStats())) .andExpect(method(HttpMethod.GET)) .andRespond(withSuccess(predefinedResultJson3.toString(), MediaType.APPLICATION_JSON)); mockMvc.perform(get("/testbedInformation")) .andExpect(status().isOk()) .andExpect(view().name("testbed_information")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/plan"))) .andExpect(content().string(containsString("/research"))) .andExpect(content().string(containsString("/pricing"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/contactus"))) .andExpect(content().string(containsString("/event"))) .andExpect(content().string(containsString("/about"))) //.andExpect(content().string(containsString("/signup2"))) .andExpect(content().string(containsString("/login"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } @Test public void testTestbedInformationLogin() throws Exception { // mock three REST calls // mockServer order is important here, the web service first invokes the get global image follow by get total nodes, testbed stats JSONObject predefinedResultJson = new JSONObject(); predefinedResultJson.put(NodeType.TOTAL.name(), "99"); JSONObject predefinedResultJson2 = new JSONObject(); predefinedResultJson2.put("images", "{\"imageA\": {\"osname\": \"Linux\", \"description\": \"image description\"}}"); JSONObject predefinedResultJson3 = new JSONObject(); predefinedResultJson3.put("users", "10"); predefinedResultJson3.put("experiments", "20"); mockServer.expect(requestTo(properties.getGlobalImages())) .andExpect(method(HttpMethod.GET)) .andRespond(withSuccess(predefinedResultJson2.toString(), MediaType.APPLICATION_JSON)); mockServer.expect(requestTo(properties.getNodes(NodeType.TOTAL))) .andExpect(method(HttpMethod.GET)) .andRespond(withSuccess(predefinedResultJson.toString(), MediaType.APPLICATION_JSON)); mockServer.expect(requestTo(properties.getTestbedStats())) .andExpect(method(HttpMethod.GET)) .andRespond(withSuccess(predefinedResultJson3.toString(), MediaType.APPLICATION_JSON)); mockMvc.perform(get("/testbedInformation").sessionAttr("id", "id")) .andExpect(status().isOk()) .andExpect(view().name("testbed_information")) .andExpect(content().string(containsString("main.css"))) .andExpect(content().string(containsString("main.js"))) .andExpect(content().string(containsString("/teams"))) .andExpect(content().string(containsString("/experiments"))) .andExpect(content().string(containsString("/data"))) .andExpect(content().string(containsString("/admin"))) .andExpect(content().string(containsString("/admin/experiments"))) .andExpect(content().string(containsString("/tutorials"))) .andExpect(content().string(containsString("/resources"))) .andExpect(content().string(containsString("/testbedInformation"))) .andExpect(content().string(containsString("/calendar"))) .andExpect(content().string(containsString("/approve_new_user"))) .andExpect(content().string(containsString("/account_settings"))) .andExpect(content().string(containsString("/logout"))) .andExpect(content().string(containsString("footer id=\"footer\""))); } }
package com.fishercoder.solutions; import java.util.HashMap; import java.util.List; import java.util.Map; public class _554 { public static class Solution1 { public int leastBricks(List<List<Integer>> wall) { Map<Integer, Integer> map = new HashMap(); for (List<Integer> row : wall) { int sum = 0; for (int i = 0; i < row.size() - 1; i++) { //NOTE: i < row.size()-1 sum += row.get(i); if (map.containsKey(sum)) { map.put(sum, map.get(sum) + 1); } else { map.put(sum, 1); } } } int result = wall.size(); for (int key : map.keySet()) { result = Math.min(result, wall.size() - map.get(key)); } return result; } } }
/** * * @author Carlos F. Meneses * carlosfmeneses@gmail.com * 05/13/2016 * * R&D TableView, TableColumn and TableCell classes. */ package tableviewdemo; import javafx.application.Application; import javafx.beans.property.SimpleStringProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableColumn.CellEditEvent; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.stage.Stage; import javafx.util.Callback; public class TableViewDemo extends Application { private final TableView<Person> table = new TableView<>(); private final ObservableList<Person> data = FXCollections.observableArrayList( new Person("Apple", "(800)692–7753", "apple.com"), new Person("Google", "(800)877-2981", "google.com"), new Person("Facebook", "(888)275-2174 ", "facebook.com")); final HBox hb = new HBox(); public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) { Scene scene = new Scene(new Group()); stage.setTitle("Table View Demo"); stage.setWidth(450); stage.setHeight(550); final Label label = new Label("Customers"); label.setFont(new Font("Arial", 20)); table.setEditable(true); Callback<TableColumn, TableCell> cellFactory; cellFactory = (TableColumn p) -> new EditingCell(); TableColumn companyCol = new TableColumn("Company"); companyCol.setMinWidth(100); companyCol.setCellValueFactory( new PropertyValueFactory<>("companyName")); companyCol.setCellFactory(cellFactory); companyCol.setOnEditCommit( new EventHandler<CellEditEvent<Person, String>>() { @Override public void handle(CellEditEvent<Person, String> t) { ((Person) t.getTableView().getItems().get( t.getTablePosition().getRow()) ).setCompanyName(t.getNewValue()); } } ); TableColumn phoneCol = new TableColumn("Phone"); phoneCol.setMinWidth(150); phoneCol.setCellValueFactory( new PropertyValueFactory<>("phoneNumber")); phoneCol.setCellFactory(cellFactory); phoneCol.setOnEditCommit( new EventHandler<CellEditEvent<Person, String>>() { @Override public void handle(CellEditEvent<Person, String> t) { ((Person) t.getTableView().getItems().get( t.getTablePosition().getRow()) ).setPhoneNumber(t.getNewValue()); } } ); TableColumn websiteCol = new TableColumn("Website"); websiteCol.setMinWidth(150); websiteCol.setCellValueFactory( new PropertyValueFactory<>("website")); websiteCol.setCellFactory(cellFactory); websiteCol.setOnEditCommit( new EventHandler<CellEditEvent<Person, String>>() { @Override public void handle(CellEditEvent<Person, String> t) { ((Person) t.getTableView().getItems().get( t.getTablePosition().getRow()) ).setWebsite(t.getNewValue()); } } ); table.setItems(data); table.getColumns().addAll(companyCol, phoneCol, websiteCol); final TextField addFirstName = new TextField(); addFirstName.setPromptText("First Name"); addFirstName.setMaxWidth(companyCol.getPrefWidth()); final TextField addLastName = new TextField(); addLastName.setMaxWidth(phoneCol.getPrefWidth()); addLastName.setPromptText("Last Name"); final TextField addEmail = new TextField(); addEmail.setMaxWidth(websiteCol.getPrefWidth()); addEmail.setPromptText("Email"); final Button addButton = new Button("Add"); addButton.setOnAction((ActionEvent e) -> { data.add(new Person( addFirstName.getText(), addLastName.getText(), addEmail.getText())); addFirstName.clear(); addLastName.clear(); addEmail.clear(); }); hb.getChildren().addAll(addFirstName, addLastName, addEmail, addButton); hb.setSpacing(3); final VBox vbox = new VBox(); vbox.setSpacing(5); vbox.setPadding(new Insets(10, 0, 0, 10)); vbox.getChildren().addAll(label, table, hb); ((Group) scene.getRoot()).getChildren().addAll(vbox); stage.setScene(scene); stage.show(); } public static class Person { private final SimpleStringProperty companyName; private final SimpleStringProperty phoneNumber; private final SimpleStringProperty website; private Person(String cName, String pNumber, String wSite) { this.companyName = new SimpleStringProperty(cName); this.phoneNumber = new SimpleStringProperty(pNumber); this.website = new SimpleStringProperty(wSite); } public String getCompanyName() { return companyName.get(); } public void setCompanyName(String cName) { companyName.set(cName); } public String getPhoneNumber() { return phoneNumber.get(); } public void setPhoneNumber(String pNumber) { phoneNumber.set(pNumber); } public String getWebsite() { return website.get(); } public void setWebsite(String wSite) { website.set(wSite); } } class EditingCell extends TableCell<Person, String> { private TextField textField; public EditingCell() { } @Override public void startEdit() { if (!isEmpty()) { super.startEdit(); createTextField(); setText(null); setGraphic(textField); textField.selectAll(); } } @Override public void cancelEdit() { super.cancelEdit(); setText((String) getItem()); setGraphic(null); } @Override public void updateItem(String item, boolean empty) { super.updateItem(item, empty); if (empty) { setText(null); setGraphic(null); } else { if (isEditing()) { if (textField != null) { textField.setText(getString()); } setText(null); setGraphic(textField); } else { setText(getString()); setGraphic(null); } } } private void createTextField() { textField = new TextField(getString()); textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2); textField.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean arg1, Boolean arg2) -> { if (!arg2) { commitEdit(textField.getText()); } }); } private String getString() { return getItem() == null ? "" : getItem(); } } }
package unit; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import bio.terra.cli.serialization.userfacing.resource.UFAiNotebook; import bio.terra.cli.service.utils.HttpUtils; import bio.terra.workspace.model.AccessScope; import bio.terra.workspace.model.CloningInstructionsEnum; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import harness.TestCommand; import harness.baseclasses.SingleWorkspaceUnit; import java.io.IOException; import java.time.Duration; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import org.hamcrest.CoreMatchers; import org.hamcrest.Matchers; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; /** Tests for the `terra resource` commands that handle controlled AI notebooks. */ @Tag("unit") public class AiNotebookControlled extends SingleWorkspaceUnit { @Disabled // TODO (PF-928): this test is failing when the delete times out @DisplayName("list and describe reflect creating and deleting a controlled notebook") void listDescribeReflectCreateDelete() throws IOException { workspaceCreator.login(); // `terra workspace set --id=$id` TestCommand.runCommandExpectSuccess("workspace", "set", "--id=" + getWorkspaceId()); // `terra resource create ai-notebook --name=$name` String name = "listDescribeReflectCreateDelete"; UFAiNotebook createdNotebook = TestCommand.runAndParseCommandExpectSuccess( UFAiNotebook.class, "resource", "create", "ai-notebook", "--name=" + name); // check that the name and notebook name match assertEquals(name, createdNotebook.name, "create output matches name"); // ai notebooks are always private assertEquals( AccessScope.PRIVATE_ACCESS, createdNotebook.accessScope, "create output matches access"); assertEquals( workspaceCreator.email.toLowerCase(), createdNotebook.privateUserName.toLowerCase(), "create output matches private user name"); // TODO (PF-616): check the private user roles once WSM returns them // check that the notebook is in the list UFAiNotebook matchedResource = listOneNotebookResourceWithName(name); assertEquals(name, matchedResource.name, "list output matches name"); // `terra resource describe --name=$name --format=json` UFAiNotebook describeResource = TestCommand.runAndParseCommandExpectSuccess( UFAiNotebook.class, "resource", "describe", "--name=" + name); // check that the name matches and the instance id is populated assertEquals(name, describeResource.name, "describe resource output matches name"); assertNotNull(describeResource.instanceName, "describe resource output includes instance name"); // ai notebooks are always private assertEquals( AccessScope.PRIVATE_ACCESS, describeResource.accessScope, "describe output matches access"); assertEquals( workspaceCreator.email.toLowerCase(), describeResource.privateUserName.toLowerCase(), "describe output matches private user name"); // TODO (PF-616): check the private user roles once WSM returns them // `terra notebook delete --name=$name` TestCommand.Result cmd = TestCommand.runCommand("resource", "delete", "--name=" + name, "--quiet"); assertTrue( cmd.exitCode == 0 || (cmd.exitCode == 1 && cmd.stdErr.contains( "CLI timed out waiting for the job to complete. It's still running on the server.")), "delete either succeeds or times out"); // confirm it no longer appears in the resources list List<UFAiNotebook> listedNotebooks = listNotebookResourcesWithName(name); assertThat( "deleted notebook no longer appears in the resources list", listedNotebooks, Matchers.empty()); } @Test @DisplayName("resolve and check-access for a controlled notebook") void resolveAndCheckAccess() throws IOException { workspaceCreator.login(); // `terra workspace set --id=$id` TestCommand.runCommandExpectSuccess("workspace", "set", "--id=" + getWorkspaceId()); // `terra resource create ai-notebook --name=$name` String name = "resolveAndCheckAccess"; UFAiNotebook createdNotebook = TestCommand.runAndParseCommandExpectSuccess( UFAiNotebook.class, "resource", "create", "ai-notebook", "--name=" + name); // `terra resource resolve --name=$name --format=json` String resolved = TestCommand.runAndParseCommandExpectSuccess( String.class, "resource", "resolve", "--name=" + name); assertEquals(createdNotebook.instanceName, resolved, "resolve returns the instance name"); // `terra resource check-access --name=$name` String stdErr = TestCommand.runCommandExpectExitCode(1, "resource", "check-access", "--name=" + name); assertThat( "check-access error is because ai notebooks are controlled resources", stdErr, CoreMatchers.containsString("Checking access is intended for REFERENCED resources only")); } @Test @DisplayName("override the default location and instance id") void overrideLocationAndInstanceId() throws IOException { workspaceCreator.login(); // `terra workspace set --id=$id` TestCommand.runCommandExpectSuccess("workspace", "set", "--id=" + getWorkspaceId()); // `terra resource create ai-notebook --name=$name // --cloning=$cloning --description=$description // --location=$location --instance-id=$instanceId` String name = "overrideLocationAndInstanceId"; CloningInstructionsEnum cloning = CloningInstructionsEnum.REFERENCE; String description = "\"override default location and instance id\""; String location = "us-central1-b"; String instanceId = "a" + UUID.randomUUID().toString(); // instance id must start with a letter UFAiNotebook createdNotebook = TestCommand.runAndParseCommandExpectSuccess( UFAiNotebook.class, "resource", "create", "ai-notebook", "--name=" + name, "--cloning=" + cloning, "--description=" + description, "--location=" + location, "--instance-id=" + instanceId); // check that the properties match assertEquals(name, createdNotebook.name, "create output matches name"); assertEquals(cloning, createdNotebook.cloningInstructions, "create output matches cloning"); assertEquals(description, createdNotebook.description, "create output matches description"); assertEquals(location, createdNotebook.location, "create output matches location"); assertEquals(instanceId, createdNotebook.instanceId, "create output matches instance id"); // ai notebooks are always private assertEquals( AccessScope.PRIVATE_ACCESS, createdNotebook.accessScope, "create output matches access"); assertEquals( workspaceCreator.email.toLowerCase(), createdNotebook.privateUserName.toLowerCase(), "create output matches private user name"); // TODO (PF-616): check the private user roles once WSM returns them // `terra resource describe --name=$name --format=json` UFAiNotebook describeResource = TestCommand.runAndParseCommandExpectSuccess( UFAiNotebook.class, "resource", "describe", "--name=" + name); // check that the properties match assertEquals(name, describeResource.name, "describe resource output matches name"); assertEquals(cloning, describeResource.cloningInstructions, "describe output matches cloning"); assertEquals(description, describeResource.description, "describe output matches description"); assertEquals(location, describeResource.location, "describe resource output matches location"); assertEquals( instanceId, describeResource.instanceId, "describe resource output matches instance id"); // ai notebooks are always private assertEquals( AccessScope.PRIVATE_ACCESS, describeResource.accessScope, "describe output matches access"); assertEquals( workspaceCreator.email.toLowerCase(), describeResource.privateUserName.toLowerCase(), "describe output matches private user name"); // TODO (PF-616): check the private user roles once WSM returns them } @Test // NOTE: This test takes ~10 minutes to run. @DisplayName("start, stop a notebook and poll until they complete") void startStop() throws IOException, InterruptedException { workspaceCreator.login(); // `terra workspace set --id=$id` TestCommand.runCommandExpectSuccess("workspace", "set", "--id=" + getWorkspaceId()); // `terra resource create ai-notebook --name=$name` String name = "startStop"; TestCommand.runCommandExpectSuccess("resource", "create", "ai-notebook", "--name=" + name); assertNotebookState(name, "PROVISIONING"); pollDescribeForNotebookState(name, "ACTIVE"); // `terra notebook start --name=$name` TestCommand.runCommandExpectSuccess("notebook", "start", "--name=" + name); assertNotebookState(name, "ACTIVE"); // `terra notebook stop --name=$name` TestCommand.runCommandExpectSuccess("notebook", "stop", "--name=" + name); assertNotebookState(name, "STOPPED"); // `terra notebook start --name=$name` TestCommand.runCommandExpectSuccess("notebook", "start", "--name=" + name); assertNotebookState(name, "ACTIVE"); } /** * Helper method to poll `terra resources describe` until the notebook state equals that * specified. Uses the current workspace. */ static void pollDescribeForNotebookState(String resourceName, String notebookState) throws InterruptedException, JsonProcessingException { pollDescribeForNotebookState(resourceName, notebookState, null); } /** * Helper method to poll `terra resources describe` until the notebook state equals that * specified. Filters on the specified workspace id; Uses the current workspace if null. */ static void pollDescribeForNotebookState( String resourceName, String notebookState, UUID workspaceId) throws InterruptedException, JsonProcessingException { HttpUtils.pollWithRetries( () -> workspaceId == null ? TestCommand.runAndParseCommandExpectSuccess( UFAiNotebook.class, "resource", "describe", "--name=" + resourceName) : TestCommand.runAndParseCommandExpectSuccess( UFAiNotebook.class, "resource", "describe", "--name=" + resourceName, "--workspace=" + workspaceId), (result) -> notebookState.equals(result.state), (ex) -> false, // no retries 2 * 20, // up to 20 minutes Duration.ofSeconds(30)); // every 30 seconds assertNotebookState(resourceName, notebookState, workspaceId); } /** * Helper method to call `terra resource describe` and assert that the notebook state matches that * given. Uses the current workspace. */ private static void assertNotebookState(String resourceName, String notebookState) throws JsonProcessingException { assertNotebookState(resourceName, notebookState, null); } /** * Helper method to call `terra resource describe` and assert that the notebook state matches that * given. Filters on the specified workspace id; Uses the current workspace if null. */ static void assertNotebookState(String resourceName, String notebookState, UUID workspaceId) throws JsonProcessingException { UFAiNotebook describeNotebook = workspaceId == null ? TestCommand.runAndParseCommandExpectSuccess( UFAiNotebook.class, "resource", "describe", "--name=" + resourceName) : TestCommand.runAndParseCommandExpectSuccess( UFAiNotebook.class, "resource", "describe", "--name=" + resourceName, "--workspace=" + workspaceId); assertEquals(notebookState, describeNotebook.state, "notebook state matches"); if (!notebookState.equals("PROVISIONING")) { assertNotNull(describeNotebook.proxyUri, "proxy url is populated"); } } /** * Helper method to call `terra resources list` and expect one resource with this name. Uses the * current workspace. */ static UFAiNotebook listOneNotebookResourceWithName(String resourceName) throws JsonProcessingException { return listOneNotebookResourceWithName(resourceName, null); } /** * Helper method to call `terra resources list` and expect one resource with this name. Filters on * the specified workspace id; Uses the current workspace if null. */ static UFAiNotebook listOneNotebookResourceWithName(String resourceName, UUID workspaceId) throws JsonProcessingException { List<UFAiNotebook> matchedResources = listNotebookResourcesWithName(resourceName, workspaceId); assertEquals(1, matchedResources.size(), "found exactly one resource with this name"); return matchedResources.get(0); } /** * Helper method to call `terra resources list` and filter the results on the specified resource * name. Uses the current workspace. */ static List<UFAiNotebook> listNotebookResourcesWithName(String resourceName) throws JsonProcessingException { return listNotebookResourcesWithName(resourceName, null); } /** * Helper method to call `terra resources list` and filter the results on the specified resource * name. Filters on the specified workspace id; Uses the current workspace if null. */ static List<UFAiNotebook> listNotebookResourcesWithName(String resourceName, UUID workspaceId) throws JsonProcessingException { // `terra resources list --type=AI_NOTEBOOK --format=json` List<UFAiNotebook> listedResources = workspaceId == null ? TestCommand.runAndParseCommandExpectSuccess( new TypeReference<>() {}, "resource", "list", "--type=AI_NOTEBOOK") : TestCommand.runAndParseCommandExpectSuccess( new TypeReference<>() {}, "resource", "list", "--type=AI_NOTEBOOK", "--workspace=" + workspaceId); // find the matching notebook in the list return listedResources.stream() .filter(resource -> resource.name.equals(resourceName)) .collect(Collectors.toList()); } }
package com.fishercoder.solutions; import com.fishercoder.common.classes.TreeNode; public class _979 { public static class Solution1 { int moves = 0; public int distributeCoins(TreeNode root) { dfs(root); return moves; } int dfs(TreeNode root) { if (root == null) { return 0; } int left = dfs(root.left); int right = dfs(root.right); moves += Math.abs(left) + Math.abs(right); return root.val + left + right - 1; } } }
package com.oracle.graal.hotspot.sparc; import static com.oracle.graal.lir.LIRInstruction.OperandFlag.*; import static com.oracle.graal.sparc.SPARC.*; import static com.oracle.graal.api.code.ValueUtil.*; import com.oracle.graal.api.code.*; import com.oracle.graal.api.meta.*; import com.oracle.graal.asm.sparc.*; import com.oracle.graal.asm.sparc.SPARCAssembler.*; import com.oracle.graal.lir.*; import com.oracle.graal.lir.asm.*; import com.oracle.graal.lir.sparc.*; /** * Patch the return address of the current frame. */ @Opcode("PATCH_RETURN") final class SPARCHotSpotPatchReturnAddressOp extends SPARCLIRInstruction { @Use(REG) AllocatableValue address; SPARCHotSpotPatchReturnAddressOp(AllocatableValue address) { this.address = address; } @Override public void emitCode(CompilationResultBuilder crb, SPARCMacroAssembler masm) { // FIXME This is non-trivial. On SPARC we need to flush all register windows first before we // can patch the return address (see: frame::patch_pc). // new Flushw().emit(masm); // int frameSize = crb.frameMap.frameSize(); // new SPARCAssembler.Ldx(new SPARCAddress(o7, 1), g3).emit(masm); // new Setx(8 * 15 - 1, g4, false).emit(masm); Register addrRegister = asLongReg(address); // new SPARCAssembler.Ldx(new SPARCAddress(o7, 1), g3).emit(masm); new Sub(addrRegister, Return.PC_RETURN_OFFSET, i7).emit(masm); // new Save(sp, -3000, sp).emit(masm); // new Flushw().emit(masm); // new Stx(g4, new SPARCAddress(fp, o7.number * crb.target.wordSize)).emit(masm); // new Restore(g0, g0, g0).emit(masm); // new Flushw().emit(masm); // new Ldx(new SPARCAddress(g0, 0x123), g0).emit(masm); } }
/* * $Id$ * $URL$ */ package org.subethamail.core.post; import javax.ejb.Local; import org.subethamail.entity.EmailAddress; import org.subethamail.entity.MailingList; import org.subethamail.entity.Person; import org.subethamail.entity.SubscriptionHold; /** * Sends outbound email with a variety of templates. * * @author Jeff Schnitzer */ @Local public interface PostOffice { public static final String JNDI_NAME = "subetha/PostOffice/local"; /** * Notifies the user that they are now the pround owner of a * bouncing new baby mailing list. */ public void sendOwnerNewMailingList(EmailAddress address, MailingList list); /** * Sends a special token that will subscribe a user to a list. * * @param list which mailing list we are subscribing to. */ public void sendConfirmSubscribeToken(MailingList list, String email, String token); /** * Informs the user that they are now subscribed to a mailing list. * * @param deliverTo might be null in the case of disabled delivery, in * which case a random email address of the person gets the notice. */ public void sendSubscribed(MailingList list, Person who, EmailAddress deliverTo); /** * In the case of a forgotten password, this sends a piece of email to the * specified member with the password. * @param list is the context of the request, defined by which * website we are visiting. */ public void sendPassword(EmailAddress addy, MailingList list); /** * Sends a token to the address which will merge that address (and * any account that may exist at that address) into the person. */ public void sendAddEmailToken(Person me, String email, String token); /** * Notifies user that their subscription is held pending approval. */ public void sendYourSubscriptionHeldNotice(SubscriptionHold hold); /** * Notifies the moderator that someone wants to subscribe and needs approval (or not). */ public void sendModeratorSubscriptionHeldNotice(Person person, SubscriptionHold hold); /** * Sends mail to the address letting the person know that their message is * waiting for approval. */ public void sendPosterMailHoldNotice(String posterEmail, MailingList toList, String holdMsg); }
package com.github.davidmoten.ar; import java.io.IOException; import java.io.InputStream; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.UnsupportedAudioFileException; public class Audio { // public byte[] readBytes(InputStream is) { // AudioInputStream in = AudioSystem.getAudioInputStream(is); // byte[] data = new byte[in.available()]; // in.read(data); // in.close(); // return data; // Create a global buffer size private static final int EXTERNAL_BUFFER_SIZE = 1024; public static void play(InputStream is) { // Load the Audio Input Stream from the file AudioInputStream audioInputStream = null; try { audioInputStream = AudioSystem.getAudioInputStream(is); } catch (Exception e) { e.printStackTrace(); System.exit(1); } // Get Audio Format information AudioFormat audioFormat = audioInputStream.getFormat(); // Handle opening the line SourceDataLine line = null; DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); try { line = (SourceDataLine) AudioSystem.getLine(info); line.open(audioFormat); } catch (LineUnavailableException e) { e.printStackTrace(); System.exit(1); } catch (Exception e) { e.printStackTrace(); System.exit(1); } // Start playing the sound line.start(); // Write the sound to an array of bytes int nBytesRead = 0; byte[] abData = new byte[EXTERNAL_BUFFER_SIZE]; while (nBytesRead != -1) { try { nBytesRead = audioInputStream.read(abData, 0, abData.length); } catch (IOException e) { e.printStackTrace(); } if (nBytesRead >= 0) { line.write(abData, 0, nBytesRead); } } // close the line line.drain(); line.close(); } public static void read(InputStream is) { // Load the Audio Input Stream from the file AudioInputStream audioInputStream = null; try { audioInputStream = AudioSystem.getAudioInputStream(is); } catch (UnsupportedAudioFileException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } // Get Audio Format information AudioFormat audioFormat = audioInputStream.getFormat(); printAudioDetails(audioInputStream, audioFormat); // Write the sound to an array of bytes int nBytesRead = 0; byte[] abData = new byte[8192]; while (nBytesRead != -1) { try { nBytesRead = audioInputStream.read(abData, 0, abData.length); } catch (IOException e) { throw new RuntimeException(e); } if (nBytesRead > 0) { // Determine the original Endian encoding format boolean isBigEndian = audioFormat.isBigEndian(); int n = nBytesRead / 2; // this array is the value of the signal at time i*h Complex x[] = new Complex[n]; // convert each pair of byte values from the byte array to an // Endian value for (int i = 0; i < n * 2; i += 2) { int b1 = abData[i]; int b2 = abData[i + 1]; if (b1 < 0) b1 += 0x100; if (b2 < 0) b2 += 0x100; int value; // Store the data based on the original Endian encoding // format if (!isBigEndian) value = (b1 << 8) + b2; else value = b1 + (b2 << 8); x[i / 2] = new Complex(value, 0); } } } } private static void printAudioDetails(AudioInputStream audioInputStream, AudioFormat audioFormat) { // Calculate the sample rate float sample_rate = audioFormat.getSampleRate(); System.out.println("sample rate = " + sample_rate); // Calculate the length in seconds of the sample float T = audioInputStream.getFrameLength() / audioFormat.getFrameRate(); System.out .println("T = " + T + " (length of sampled sound in seconds)"); // Calculate the number of equidistant points in time int num = (int) (T * sample_rate) / 2; System.out.println("n = " + num + " (number of equidistant points)"); // Calculate the time interval at each equidistant point float h = (T / num); System.out.println("h = " + h + " (length of each time interval in seconds)"); } }
package com.github.pagehelper; import java.io.Serializable; import java.util.Collection; import java.util.List; @SuppressWarnings({"rawtypes", "unchecked"}) public class PageInfo<T> implements Serializable { private static final long serialVersionUID = 1L; private int pageNum; private int pageSize; private int size; //startRowendRow //"startRowendRow size" private int startRow; private int endRow; private long total; private int pages; private List<T> list; private int prePage; private int nextPage; private boolean isFirstPage = false; private boolean isLastPage = false; private boolean hasPreviousPage = false; private boolean hasNextPage = false; private int navigatePages; private int[] navigatepageNums; private int navigateFirstPage; private int navigateLastPage; public PageInfo() { } /** * Page * * @param list */ public PageInfo(List<T> list) { this(list, 8); } /** * Page * * @param list page * @param navigatePages */ public PageInfo(List<T> list, int navigatePages) { if (list instanceof Page) { Page page = (Page) list; this.pageNum = page.getPageNum(); this.pageSize = page.getPageSize(); this.pages = page.getPages(); this.list = page; this.size = page.size(); this.total = page.getTotal(); //>startRow+1 if (this.size == 0) { this.startRow = 0; this.endRow = 0; } else { this.startRow = page.getStartRow() + 1; //endRow this.endRow = this.startRow - 1 + this.size; } } else if (list instanceof Collection) { this.pageNum = 1; this.pageSize = list.size(); this.pages = this.pageSize > 0 ? 1 : 0; this.list = list; this.size = list.size(); this.total = list.size(); this.startRow = 0; this.endRow = list.size() > 0 ? list.size() - 1 : 0; } if (list instanceof Collection) { this.navigatePages = navigatePages; calcNavigatepageNums(); calcPage(); judgePageBoudary(); } } private void calcNavigatepageNums() { if (pages <= navigatePages) { navigatepageNums = new int[pages]; for (int i = 0; i < pages; i++) { navigatepageNums[i] = i + 1; } } else { navigatepageNums = new int[navigatePages]; int startNum = pageNum - navigatePages / 2; int endNum = pageNum + navigatePages / 2; if (startNum < 1) { startNum = 1; //(navigatePages for (int i = 0; i < navigatePages; i++) { navigatepageNums[i] = startNum++; } } else if (endNum > pages) { endNum = pages; //navigatePages for (int i = navigatePages - 1; i >= 0; i navigatepageNums[i] = endNum } } else { for (int i = 0; i < navigatePages; i++) { navigatepageNums[i] = startNum++; } } } } private void calcPage() { if (navigatepageNums != null && navigatepageNums.length > 0) { navigateFirstPage = navigatepageNums[0]; navigateLastPage = navigatepageNums[navigatepageNums.length - 1]; if (pageNum > 1) { prePage = pageNum - 1; } if (pageNum < pages) { nextPage = pageNum + 1; } } } private void judgePageBoudary() { isFirstPage = pageNum == 1; isLastPage = pageNum == pages || pages == 0;; hasPreviousPage = pageNum > 1; hasNextPage = pageNum < pages; } public int getPageNum() { return pageNum; } public void setPageNum(int pageNum) { this.pageNum = pageNum; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public int getStartRow() { return startRow; } public void setStartRow(int startRow) { this.startRow = startRow; } public int getEndRow() { return endRow; } public void setEndRow(int endRow) { this.endRow = endRow; } public long getTotal() { return total; } public void setTotal(long total) { this.total = total; } public int getPages() { return pages; } public void setPages(int pages) { this.pages = pages; } public List<T> getList() { return list; } public void setList(List<T> list) { this.list = list; } @Deprecated // firstPage1, , public int getFirstPage() { return navigateFirstPage; } @Deprecated public void setFirstPage(int firstPage) { this.navigateFirstPage = firstPage; } public int getPrePage() { return prePage; } public void setPrePage(int prePage) { this.prePage = prePage; } public int getNextPage() { return nextPage; } public void setNextPage(int nextPage) { this.nextPage = nextPage; } @Deprecated // getPages(), , . public int getLastPage() { return navigateLastPage; } @Deprecated public void setLastPage(int lastPage) { this.navigateLastPage = lastPage; } public boolean isIsFirstPage() { return isFirstPage; } public void setIsFirstPage(boolean isFirstPage) { this.isFirstPage = isFirstPage; } public boolean isIsLastPage() { return isLastPage; } public void setIsLastPage(boolean isLastPage) { this.isLastPage = isLastPage; } public boolean isHasPreviousPage() { return hasPreviousPage; } public void setHasPreviousPage(boolean hasPreviousPage) { this.hasPreviousPage = hasPreviousPage; } public boolean isHasNextPage() { return hasNextPage; } public void setHasNextPage(boolean hasNextPage) { this.hasNextPage = hasNextPage; } public int getNavigatePages() { return navigatePages; } public void setNavigatePages(int navigatePages) { this.navigatePages = navigatePages; } public int[] getNavigatepageNums() { return navigatepageNums; } public void setNavigatepageNums(int[] navigatepageNums) { this.navigatepageNums = navigatepageNums; } public int getNavigateFirstPage() { return navigateFirstPage; } public int getNavigateLastPage() { return navigateLastPage; } public void setNavigateFirstPage(int navigateFirstPage) { this.navigateFirstPage = navigateFirstPage; } public void setNavigateLastPage(int navigateLastPage) { this.navigateLastPage = navigateLastPage; } @Override public String toString() { final StringBuffer sb = new StringBuffer("PageInfo{"); sb.append("pageNum=").append(pageNum); sb.append(", pageSize=").append(pageSize); sb.append(", size=").append(size); sb.append(", startRow=").append(startRow); sb.append(", endRow=").append(endRow); sb.append(", total=").append(total); sb.append(", pages=").append(pages); sb.append(", list=").append(list); sb.append(", prePage=").append(prePage); sb.append(", nextPage=").append(nextPage); sb.append(", isFirstPage=").append(isFirstPage); sb.append(", isLastPage=").append(isLastPage); sb.append(", hasPreviousPage=").append(hasPreviousPage); sb.append(", hasNextPage=").append(hasNextPage); sb.append(", navigatePages=").append(navigatePages); sb.append(", navigateFirstPage").append(navigateFirstPage); sb.append(", navigateLastPage").append(navigateLastPage); sb.append(", navigatepageNums="); if (navigatepageNums == null) sb.append("null"); else { sb.append('['); for (int i = 0; i < navigatepageNums.length; ++i) sb.append(i == 0 ? "" : ", ").append(navigatepageNums[i]); sb.append(']'); } sb.append('}'); return sb.toString(); } }
package properties.rovers; import static structure.impl.other.Quantification.EXISTS; import static structure.impl.other.Quantification.FORALL; import structure.intf.Assignment; import structure.intf.Binding; import structure.intf.Guard; import structure.intf.QEA; import creation.QEABuilder; /* * External * - ExactlyOneSuccess * - IncreasingCommand * - NestedCommand * - AcknowledgeCommand * - ExistsSatellite * - ExistsLeader * - MessageHashCorrect * * Internal * - GrantCancel * - ResourceLifecycle * - ReleaseResource * - RespectConflicts * - RespectPriorities * */ public class RoverCaseStudy { public static QEA makeGrantCancelSingleSwitch() { QEABuilder q = new QEABuilder("GrantCancelSingleSwitch"); int GRANT = 1; int CANCEL = 2; int T1 = 1; int T2 = 2; int R = -1; q.addQuantification(FORALL, R); q.addTransition(1, GRANT, new int[] { R, T1 }, 2); q.addTransition(2, GRANT, new int[] { R, T2 }, 3); q.startTransition(2); q.eventName(CANCEL); q.addVarArg(R); q.addVarArg(T2); q.addGuard(Guard.isEqual(T1, T2)); q.endTransition(1); q.addFinalStates(1, 2); QEA qea = q.make(); qea.record_event_name("grant", 1); qea.record_event_name("cancel", 2); return qea; } public static QEA makeGrantCancelSingle() { // Figure A.25 (2) QEABuilder q = new QEABuilder("GrantCancelSingle"); int GRANT = 1; int CANCEL = 2; int T1 = 1; int T2 = 2; int R = -1; q.addQuantification(FORALL, R); q.addTransition(1, GRANT, new int[] { T1, R }, 2); // TODO In the thesis, the parameters are: (-, R) q.addTransition(2, GRANT, new int[] { T2, R }, 3); q.startTransition(2); q.eventName(CANCEL); q.addVarArg(T2); q.addVarArg(R); q.addGuard(Guard.isEqual(T1, T2)); q.endTransition(1); q.addFinalStates(1, 2); QEA qea = q.make(); qea.record_event_name("grant", 1); qea.record_event_name("cancel", 2); return qea; } public static QEA makeGrantCancelDouble() { // Figure A.25 (1) QEABuilder q = new QEABuilder("GrantCancelDouble"); int GRANT = 1; int CANCEL = 2; int R = -1; int T = -2; int TT = 1; q.addQuantification(FORALL, R); q.addQuantification(FORALL, T); q.addTransition(1, GRANT, new int[] { T, R }, 2); // TODO In the thesis, the parameters are: (-, R) q.addTransition(2, GRANT, new int[] { TT, R }, 3); q.addTransition(2, CANCEL, new int[] { T, R }, 1); q.addFinalStates(1, 2); QEA qea = q.make(); qea.record_event_name("grant", 1); qea.record_event_name("cancel", 2); return qea; } public static QEA makeResourceLifecycle() { // Figure A.26 QEABuilder q = new QEABuilder("ResourceLifecycle"); int REQUEST = 1; int GRANT = 2; int DENY = 3; int RESCIND = 4; int CANCEL = 5; int R = -1; q.addQuantification(FORALL, R); int[] r = new int[] { R }; q.addTransition(1, REQUEST, r, 2); q.addTransition(2, DENY, r, 1); q.addTransition(2, GRANT, r, 3); q.addTransition(3, RESCIND, r, 3); q.addTransition(3, CANCEL, r, 1); q.addFinalStates(1, 2); QEA qea = q.make(); qea.record_event_name("request", 1); qea.record_event_name("grant", 2); qea.record_event_name("deny", 3); qea.record_event_name("rescind", 4); qea.record_event_name("cancel", 5); return qea; } public static QEA makeReleaseResource() { // Figure A.27 QEABuilder q = new QEABuilder("ReleaseResource"); int SCHEDULE = 1; int GRANT = 2; int CANCEL = 3; int FINISH = 4; int T = -1; int C = -2; int R = -3; q.addQuantification(FORALL, T); q.addQuantification(FORALL, C); q.addQuantification(FORALL, R); q.addTransition(1, SCHEDULE, new int[] { T, C }, 2); q.addTransition(2, GRANT, new int[] { T, R }, 3); q.addTransition(3, CANCEL, new int[] { T, R }, 2); q.addTransition(3, FINISH, new int[] { C }, 4); q.addFinalStates(1, 2); q.setSkipStates(1, 2, 3, 4); QEA qea = q.make(); qea.record_event_name("schedule", 1); qea.record_event_name("grant", 2); qea.record_event_name("cancel", 3); qea.record_event_name("finish", 4); return qea; } public static QEA makeRespectConflictsDouble() { // Figure A.28 QEABuilder q = new QEABuilder("RespectConflictsDouble"); // Events int CONFLICT = 1; int GRANT = 2; int CANCEL = 3; // Quantified variables int R1 = -1; int R2 = -2; q.addQuantification(FORALL, R1); q.addQuantification(FORALL, R2); q.addTransition(1, CONFLICT, new int[] { R1, R2 }, 2); q.addTransition(1, CONFLICT, new int[] { R2, R1 }, 2); q.addTransition(2, GRANT, new int[] { R1 }, 3); q.addTransition(3, CANCEL, new int[] { R1 }, 2); q.addTransition(3, GRANT, new int[] { R2 }, 4); q.addFinalStates(1, 2, 3); q.setSkipStates(1, 2, 3, 4); QEA qea = q.make(); qea.record_event_name("conflict", 1); qea.record_event_name("grant", 2); qea.record_event_name("cancel", 3); return qea; } public static QEA makeRespectConflictsSingle() { // Figure A.29 QEABuilder q = new QEABuilder("RespectConflictsSingle"); // Events int CONFLICT = 1; int GRANT = 2; int CANCEL = 3; // Quantified variable int R1 = -1; // Free variables int R2 = 1; int RS = 2; q.addQuantification(FORALL, R1); q.startTransition(1); q.eventName(CONFLICT); q.addVarArg(R1); q.addVarArg(R2); q.addAssignment(Assignment.createSetFromElement(RS, R2)); q.endTransition(2); q.startTransition(2); q.eventName(CONFLICT); q.addVarArg(R1); q.addVarArg(R2); q.addAssignment(Assignment.addElementToSet(RS, R2)); q.endTransition(2); q.addTransition(2, GRANT, new int[] { R1 }, 3); q.addTransition(3, CANCEL, new int[] { R1 }, 2); q.startTransition(3); q.eventName(GRANT); q.addVarArg(R2); q.addGuard(Guard.setContainsElement(R2, RS)); q.endTransition(4); // Manual skip states for state 3 q.addTransition(3, CONFLICT, new int[] { R1, R2 }, 3); q.startTransition(3); q.eventName(GRANT); q.addVarArg(R2); q.addGuard(Guard.setNotContainsElement(R2, RS)); q.endTransition(3); // Final and skip states q.addFinalStates(1, 2, 3); q.setSkipStates(1, 2, 4); QEA qea = q.make(); qea.record_event_name("conflict", 1); qea.record_event_name("grant", 2); qea.record_event_name("cancel", 3); return qea; } public static QEA makeRespectPriorities() { // Figure A.30 QEABuilder q = new QEABuilder("RespectPriorities"); // Events int GRANT = 1; int CANCEL = 2; int PRIORITY = 3; int REQUEST = 4; int RESCIND = 5; int DENY = 6; // Quantified variables int R1 = -1; int R2 = -2; // Free variables int R3 = 1; int RS = 2; int G = 3; q.addQuantification(FORALL, R1); q.addQuantification(FORALL, R2); q.startTransition(1); q.eventName(PRIORITY); q.addVarArg(R3); q.addVarArg(R2); q.addAssignment(Assignment.addElementToSet(RS, R3)); q.endTransition(1); q.addTransition(1, PRIORITY, new int[] { R2, R1 }, 2); q.startTransition(2); q.eventName(PRIORITY); q.addVarArg(R3); q.addVarArg(R2); q.addAssignment(Assignment.addElementToSet(RS, R3)); q.endTransition(2); q.startTransition(2); q.eventName(GRANT); q.addVarArg(R3); q.addGuard(Guard.setContainsElement(R3, RS)); q.addAssignment(Assignment.addElementToSet(G, R3)); q.endTransition(3); q.addTransition(2, GRANT, new int[] { R1 }, 5); q.addTransition(2, GRANT, new int[] { R2 }, 10); q.startTransition(3); q.eventName(CANCEL); q.addVarArg(R3); q.addGuard(Guard.setContainsOnlyElement(R3, G)); q.addAssignment(Assignment.removeElementFromSet(G, R3)); q.endTransition(2); q.startTransition(3); q.eventName(GRANT); q.addVarArg(R3); q.addGuard(Guard.setContainsElement(R3, RS)); q.addAssignment(Assignment.addElementToSet(G, R3)); q.endTransition(3); q.startTransition(3); q.eventName(CANCEL); q.addVarArg(R3); q.addGuard(Guard.setContainsMoreThanElement(R3, G)); q.addAssignment(Assignment.removeElementFromSet(G, R3)); q.endTransition(3); q.addTransition(3, REQUEST, new int[] { R2 }, 4); q.addTransition(4, DENY, new int[] { R2 }, 3); q.addTransition(5, CANCEL, new int[] { R1 }, 2); q.addTransition(5, REQUEST, new int[] { R2 }, 6); q.startTransition(5); q.eventName(GRANT); q.addVarArg(R3); q.addGuard(Guard.setContainsElement(R3, RS)); q.addAssignment(Assignment.addElementToSet(G, R3)); q.endTransition(8); q.addTransition(6, RESCIND, new int[] { R1 }, 7); q.addTransition(7, CANCEL, new int[] { R1 }, 2); q.startTransition(8); q.eventName(CANCEL); q.addVarArg(R3); q.addGuard(Guard.setContainsOnlyElement(R3, G)); q.addAssignment(Assignment.removeElementFromSet(G, R3)); q.endTransition(5); q.startTransition(8); q.eventName(GRANT); q.addVarArg(R3); q.addGuard(Guard.setContainsElement(R3, RS)); q.addAssignment(Assignment.addElementToSet(G, R3)); q.endTransition(8); q.startTransition(8); q.eventName(CANCEL); q.addVarArg(R3); q.addGuard(Guard.setContainsMoreThanElement(R3, G)); q.addAssignment(Assignment.removeElementFromSet(G, R3)); q.endTransition(8); q.addTransition(8, REQUEST, new int[] { R2 }, 9); q.addTransition(9, DENY, new int[] { R2 }, 8); q.addTransition(10, CANCEL, new int[] { R2 }, 2); q.startTransition(10); q.eventName(GRANT); q.addVarArg(R3); q.addGuard(Guard.setNotContainsElement(R3, RS)); q.endTransition(10); q.startTransition(10); q.eventName(CANCEL); q.addVarArg(R3); q.addGuard(Guard.setNotContainsElement(R3, RS)); q.endTransition(10); q.addFinalStates(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); QEA qea = q.make(); qea.record_event_name("grant", 1); qea.record_event_name("cancel", 2); qea.record_event_name("priority", 3); qea.record_event_name("request", 4); qea.record_event_name("rescind", 5); qea.record_event_name("deny", 6); return qea; } public static QEA makeExactlyOnceSuccess() { // Figure A.31 QEABuilder q = new QEABuilder("ExactlyOnceSuccess"); // Events int COM = 1; int SUC = 2; int FAIL = 3; // Quantified variable int C = -1; q.addQuantification(FORALL, C); q.addTransition(1, COM, new int[] { C }, 2); q.addTransition(2, SUC, new int[] { C }, 3); q.addTransition(2, FAIL, new int[] { C }, 4); q.addFinalStates(1, 2, 3); QEA qea = q.make(); qea.record_event_name("com", 1); qea.record_event_name("suc", 2); qea.record_event_name("fail", 3); return qea; } public static QEA makeIncreasingIdentifiers() { // Figure A.32 QEABuilder q = new QEABuilder("IncreasingIdentifiers"); // Event int COM = 1; // Free variables int C1 = 1; int C2 = 2; q.addTransition(1, COM, new int[] { C1 }, 2); q.startTransition(2); q.eventName(COM); q.addVarArg(C2); q.addGuard(Guard.isGreaterThan(C2, C1)); q.addAssignment(Assignment.store(C1, C2)); q.endTransition(2); q.addFinalStates(1, 2); QEA qea = q.make(); qea.record_event_name("com", 1); return qea; } public static QEA makeCommandAcknowledgements() { // Figure A.33 QEABuilder q = new QEABuilder("CommandAcknowledgements"); // Events int SET_ACK_TIMEOUT = 1; int COM = 2; int ACK = 3; // Quantified variable int C = -1; // Free variables final int M = 1; final int N1 = 2; final int P1 = 3; final int T1 = 4; final int N2 = 5; final int P2 = 6; final int T2 = 7; q.addQuantification(FORALL, C); q.addTransition(1, SET_ACK_TIMEOUT, new int[] { M }, 2); q.addTransition(2, COM, new int[] { C, N1, P1, T1 }, 3); q.startTransition(3); q.eventName(ACK); q.addVarArg(C); q.addVarArg(T2); q.addGuard(Guard.isLessThan(T2, M)); q.endTransition(4); q.startTransition(3); q.eventName(COM); q.addVarArg(N2); q.addVarArg(P2); q.addVarArg(T2); q.addGuard(new Guard("SpecificGuard") { @Override public boolean usesQvars() { return false; } @Override public boolean check(Binding binding, int qvar, Object firstQval) { return check(binding); } @Override public boolean check(Binding binding) { int n1 = binding.getForcedAsInteger(N1); int n2 = binding.getForcedAsInteger(N2); int p1 = binding.getForcedAsInteger(P1); int p2 = binding.getForcedAsInteger(P2); int t1 = binding.getForcedAsInteger(T1); int t2 = binding.getForcedAsInteger(T2); int m = binding.getForcedAsInteger(M); return n1 == n2 && p1 == p2 && (t2 - t1 < 2 * m); } }); q.endTransition(4); // Manual skip states for state 3 q.addTransition(3, SET_ACK_TIMEOUT, new int[] { M }, 3); q.startTransition(3); q.eventName(ACK); q.addVarArg(C); q.addVarArg(T2); q.addGuard(Guard.isGreaterThanOrEqualTo(T2, M)); q.endTransition(3); q.startTransition(3); q.eventName(COM); q.addVarArg(N2); q.addVarArg(P2); q.addVarArg(T2); q.addGuard(new Guard("SpecificInverseGuard") { @Override public boolean usesQvars() { return false; } @Override public boolean check(Binding binding, int qvar, Object firstQval) { return check(binding); } @Override public boolean check(Binding binding) { int n1 = binding.getForcedAsInteger(N1); int n2 = binding.getForcedAsInteger(N2); int p1 = binding.getForcedAsInteger(P1); int p2 = binding.getForcedAsInteger(P2); int t1 = binding.getForcedAsInteger(T1); int t2 = binding.getForcedAsInteger(T2); int m = binding.getForcedAsInteger(M); return !(n1 == n2 && p1 == p2 && (t2 - t1 < 2 * m)); } }); q.endTransition(3); // Final and skip states q.addFinalStates(1, 2, 4); q.setSkipStates(1, 2, 4); QEA qea = q.make(); qea.record_event_name("set_ack_timeout", 1); qea.record_event_name("com", 2); qea.record_event_name("ack", 3); return qea; } public static QEA makeExistsSatelliteDouble() { // Figure A.34 QEABuilder q = new QEABuilder("ExistsSatelliteDouble"); // Events int PING = 1; int ACK = 2; // Quantified variables int R = -1; int S = -2; q.addQuantification(FORALL, R); q.addQuantification(EXISTS, S); q.addTransition(1, PING, new int[] { R, S }, 2); q.addTransition(2, ACK, new int[] { S, R }, 3); q.addFinalStates(3); q.setSkipStates(1, 2, 3); QEA qea = q.make(); qea.record_event_name("ping", 1); qea.record_event_name("ack", 2); return qea; } public static QEA makeExistsSatelliteSingle() { // Figure A.35 QEABuilder q = new QEABuilder("ExistsSatelliteSingle"); // Events int PING = 1; int ACK = 2; // Quantified variable int r = -1; // Free variables int s = 1; int S = 2; q.addQuantification(FORALL, r); q.startTransition(1); q.eventName(PING); q.addVarArg(r); q.addVarArg(s); q.addAssignment(Assignment.createSetFromElement(S, s)); q.endTransition(2); q.startTransition(2); q.eventName(PING); q.addVarArg(r); q.addVarArg(s); q.addAssignment(Assignment.addElementToSet(S, s)); q.endTransition(2); q.startTransition(2); q.eventName(ACK); q.addVarArg(s); q.addVarArg(r); q.addGuard(Guard.setContainsElement(s, S)); q.endTransition(3); // Manual skip states for state 2 q.startTransition(2); q.eventName(ACK); q.addVarArg(s); q.addVarArg(r); q.addGuard(Guard.setNotContainsElement(s, S)); q.endTransition(2); // Final and skip states q.addFinalStates(1, 3); q.setSkipStates(1, 3); QEA qea = q.make(); qea.record_event_name("ping", 1); qea.record_event_name("ack", 2); return qea; } public static QEA makeExistsLeader() { // Figure A.36 QEABuilder q = new QEABuilder("ExistsLeader"); // Events int PING = 1; int ACK = 2; // Quantified variables int R1 = -1; int R2 = -2; q.addQuantification(EXISTS, R1); q.addQuantification(FORALL, R2); q.addTransition(1, PING, new int[] { R1, R2 }, 2); q.addTransition(2, ACK, new int[] { R2, R1 }, 3); q.addFinalStates(3); q.setSkipStates(1, 2, 3); QEA qea = q.make(); qea.record_event_name("ping", 1); qea.record_event_name("ack", 2); return qea; } }
package com.github.wovnio.wovnjava; import java.io.InputStream; import java.io.OutputStream; import java.io.ByteArrayOutputStream; import java.io.UnsupportedEncodingException; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.net.MalformedURLException; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import java.util.LinkedHashMap; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.xml.bind.DatatypeConverter; import net.arnx.jsonic.JSON; class Api { private final int READ_BUFFER_SIZE = 8196; private final Settings settings; private final Headers headers; private final String responseEncoding = "UTF-8"; // always response is UTF8 Api(Settings settings, Headers headers) { this.settings = settings; this.headers = headers; } String translate(String lang, String html) throws ApiException { HttpURLConnection con = null; try { URL url = getApiUrl(lang, html); con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(settings.connectTimeout); con.setReadTimeout(settings.readTimeout); return translate(lang, html, con); } catch (UnsupportedEncodingException e) { Logger.log.error("Api url", e); throw new ApiException("encoding"); } catch (IOException e) { Logger.log.error("Api url", e); throw new ApiException("io"); } catch (NoSuchAlgorithmException e) { Logger.log.error("Api url", e); throw new ApiException("algorithm"); } finally { if (con != null) { con.disconnect(); } } } String translate(String lang, String html, HttpURLConnection con) throws ApiException { OutputStream out = null; try { ByteArrayOutputStream body = gzipStream(getApiBody(lang, html).getBytes()); con.setDoOutput(true); con.setRequestProperty("Accept-Encoding", "gzip"); con.setRequestProperty("Content-Type", "application/octet-stream"); con.setRequestProperty("Content-Length", String.valueOf(body.size())); con.setRequestMethod("POST"); out = con.getOutputStream(); body.writeTo(out); out.close(); out = null; int status = con.getResponseCode(); if (status == HttpURLConnection.HTTP_OK) { InputStream input = con.getInputStream(); if ("gzip".equals(con.getContentEncoding())) { input = new GZIPInputStream(input); } return extractHtml(input); } else { throw new ApiException("status_" + String.valueOf(status)); } } catch (UnsupportedEncodingException e) { Logger.log.error("Api url", e); throw new ApiException("encoding"); } catch (IOException e) { Logger.log.error("Api url", e); throw new ApiException("io"); } finally { if (out != null) { try { out.close(); } catch (IOException e) { Logger.log.error("Api close", e); } } } } private ByteArrayOutputStream gzipStream(byte[] input) throws IOException, UnsupportedEncodingException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); GZIPOutputStream gz = new GZIPOutputStream(buffer); try { gz.write(input); } finally { gz.close(); } return buffer; } private String extractHtml(InputStream input) throws ApiException, IOException, UnsupportedEncodingException { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[READ_BUFFER_SIZE]; int len = 0; while ((len = input.read(buffer)) > 0) { out.write(buffer, 0, len); } input.close(); String json = out.toString(responseEncoding); LinkedHashMap<String, String> dict = JSON.decode(json); String html = dict.get("body"); if (html == null) { Logger.log.error("Unknown json format " + json); throw new ApiException("unknown_json_format"); } return html; } private String getApiBody(String lang, String body) throws UnsupportedEncodingException { StringBuilder sb = new StringBuilder(); appendKeyValue(sb, "url=", headers.url); appendKeyValue(sb, "&token=", settings.projectToken); appendKeyValue(sb, "&lang_code=", lang); appendKeyValue(sb, "&url_pattern=", settings.urlPattern); appendKeyValue(sb, "&body=", body); return sb.toString(); } private URL getApiUrl(String lang, String body) throws UnsupportedEncodingException, NoSuchAlgorithmException, MalformedURLException { StringBuilder sb = new StringBuilder(); sb.append(settings.apiUrl); sb.append("translation?cache_key="); appendValue(sb, "(token="); appendValue(sb, settings.projectToken); appendValue(sb, "&settings_hash="); appendValue(sb, settings.hash()); appendValue(sb, "&body_hash="); appendValue(sb, hash(body.getBytes())); appendValue(sb, "&path="); appendValue(sb, headers.pathName); appendValue(sb, "&lang="); appendValue(sb, lang); appendValue(sb, "&version="); appendValue(sb, settings.version); appendValue(sb, ")"); return new URL(sb.toString()); } private String hash(byte[] item) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(item); byte[] digest = md.digest(); return DatatypeConverter.printHexBinary(digest).toUpperCase(); } private void appendKeyValue(StringBuilder sb, String key, String value) throws UnsupportedEncodingException { sb.append(key); appendValue(sb, value); } private void appendValue(StringBuilder sb, String value) throws UnsupportedEncodingException { sb.append(URLEncoder.encode(value, "UTF-8")); } }
package org.eclipse.persistence.internal.jpa.deployment; import java.util.*; import java.net.URL; import java.net.URLClassLoader; import java.lang.instrument.*; import java.lang.reflect.Constructor; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.ProtectionDomain; import org.eclipse.persistence.logging.AbstractSessionLog; import org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider; import org.eclipse.persistence.internal.security.PrivilegedAccessHelper; import org.eclipse.persistence.internal.security.PrivilegedGetConstructorFor; import org.eclipse.persistence.internal.security.PrivilegedInvokeConstructor; import org.eclipse.persistence.config.PersistenceUnitProperties; import org.eclipse.persistence.exceptions.*; import org.eclipse.persistence.logging.SessionLog; import javax.persistence.PersistenceException; import javax.persistence.spi.ClassTransformer; import javax.persistence.spi.PersistenceUnitInfo; /** * INTERNAL: * * JavaSECMPInitializer is used to bootstrap the deployment of EntityBeans in EJB 3.0 * when deployed in a non-managed setting * * It is called internally by our Provider * * @see org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider */ public class JavaSECMPInitializer extends JPAInitializer { // Used when byte code enhancing public static Instrumentation globalInstrumentation; // Adding this flag because globalInstrumentation could be set to null after weaving is done. protected static boolean usesAgent; // Adding this flag to know that within a JEE container so weaving should be enabled without an agent for non managed persistence units. protected static boolean isInContainer; // Indicates whether has been initialized - that could be done only once. protected static boolean isInitialized; protected static JavaSECMPInitializer initializer; // Used as a lock in getJavaSECMPInitializer. Don't substitute for Boolean.TRUE. protected static Boolean initializationLock = new Boolean(true); public static boolean isInContainer() { return isInContainer; } public static void setIsInContainer(boolean isInContainer) { JavaSECMPInitializer.isInContainer = isInContainer; } /** * Get the singleton entityContainer. */ public static JavaSECMPInitializer getJavaSECMPInitializer() { return getJavaSECMPInitializer(Thread.currentThread().getContextClassLoader(), null, false); } public static JavaSECMPInitializer getJavaSECMPInitializer(ClassLoader classLoader) { return getJavaSECMPInitializer(classLoader, null, false); } public static JavaSECMPInitializer getJavaSECMPInitializerFromAgent() { return getJavaSECMPInitializer(Thread.currentThread().getContextClassLoader(), null, true); } public static JavaSECMPInitializer getJavaSECMPInitializerFromMain(Map m) { return getJavaSECMPInitializer(Thread.currentThread().getContextClassLoader(), m, false); } public static JavaSECMPInitializer getJavaSECMPInitializer(ClassLoader classLoader, Map m, boolean fromAgent) { if(!isInitialized) { if(globalInstrumentation != null) { synchronized(initializationLock) { if(!isInitialized) { initializeTopLinkLoggingFile(); if(fromAgent) { AbstractSessionLog.getLog().log(SessionLog.FINER, SessionLog.WEAVER, "cmp_init_initialize_from_agent", (Object[])null); } usesAgent = true; initializer = new JavaSECMPInitializer(classLoader); initializer.initialize(m != null ? m : new HashMap(0)); // all the transformers have been added to instrumentation, don't need it any more. globalInstrumentation = null; } } } isInitialized = true; } if(initializer != null && initializer.getInitializationClassLoader() == classLoader) { return initializer; } else { // when agent is not used initializer does not need to be initialized. return new JavaSECMPInitializer(classLoader); } } /** * User should not instantiate JavaSECMPInitializer. */ protected JavaSECMPInitializer() { super(); } protected JavaSECMPInitializer(ClassLoader loader) { super(); this.initializationClassloader = loader; } /** * Check whether weaving is possible and update the properties and variable as appropriate * @param properties The list of properties to check for weaving and update if weaving is not needed */ public void checkWeaving(Map properties){ String weaving = EntityManagerFactoryProvider.getConfigPropertyAsString(PersistenceUnitProperties.WEAVING, properties, null); // Check usesAgent instead of globalInstrumentation!=null because globalInstrumentation is set to null after initialization, // but we still have to keep weaving so that the resulting projects correspond to the woven (during initialization) classes. if (!usesAgent && !isInContainer) { if (weaving == null) { properties.put(PersistenceUnitProperties.WEAVING, "false"); weaving = "false"; } else if (weaving.equalsIgnoreCase("true")) { throw new PersistenceException(EntityManagerSetupException.wrongWeavingPropertyValue()); } } if ((weaving != null) && ((weaving.equalsIgnoreCase("false")) || (weaving.equalsIgnoreCase("static")))){ shouldCreateInternalLoader = false; } } /** * Create a temporary class loader that can be used to inspect classes and then * thrown away. This allows classes to be introspected prior to loading them * with application's main class loader enabling weaving. */ protected ClassLoader createTempLoader(Collection col) { return createTempLoader(col, true); } protected ClassLoader createTempLoader(Collection col, boolean shouldOverrideLoadClassForCollectionMembers) { if (!shouldCreateInternalLoader) { return Thread.currentThread().getContextClassLoader(); } ClassLoader currentLoader = Thread.currentThread().getContextClassLoader(); if (!(currentLoader instanceof URLClassLoader)) { //we can't create a TempEntityLoader so just use the current one //shouldn't be a problem (and should only occur) in JavaSE return currentLoader; } URL[] urlPath = ((URLClassLoader)currentLoader).getURLs(); ClassLoader tempLoader = null; if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) { try { Class[] argsClasses = new Class[] { URL[].class, ClassLoader.class, Collection.class, boolean.class }; Object[] args = new Object[] { urlPath, currentLoader, col, shouldOverrideLoadClassForCollectionMembers }; Constructor classLoaderConstructor = (Constructor) AccessController.doPrivileged(new PrivilegedGetConstructorFor(TempEntityLoader.class, argsClasses, true)); tempLoader = (ClassLoader) AccessController.doPrivileged(new PrivilegedInvokeConstructor(classLoaderConstructor, args)); } catch (PrivilegedActionException privilegedException) { throw new PersistenceException(EntityManagerSetupException.failedToInstantiateTemporaryClassLoader(privilegedException)); } } else { tempLoader = new TempEntityLoader(urlPath, currentLoader, col, shouldOverrideLoadClassForCollectionMembers); } AbstractSessionLog.getLog().log(SessionLog.FINER, SessionLog.WEAVER, "cmp_init_tempLoader_created", tempLoader); AbstractSessionLog.getLog().log(SessionLog.FINER, SessionLog.WEAVER, "cmp_init_shouldOverrideLoadClassForCollectionMembers", Boolean.valueOf(shouldOverrideLoadClassForCollectionMembers)); return tempLoader; } /** * INTERNAL: * Should be called only by the agent. (when weaving classes) * If succeeded return true, false otherwise. */ protected static void initializeFromAgent(Instrumentation instrumentation) throws Exception { // Squirrel away the instrumentation for later globalInstrumentation = instrumentation; getJavaSECMPInitializerFromAgent(); } /** * Usually JavaSECMPInitializer is initialized from agent during premain * to ensure that the classes to be weaved haven't been loaded before initialization. * However, in this case initialization can't be debugged. * In order to be able to debug initialization specify * in java options -javaagent with parameter "main": (note: a separate eclipselink-agent.jar is no longer required) * -javaagent:c:\trunk\eclipselink.jar=main * that causes instrumentation to be cached during premain and postpones initialization until main. * With initialization done in main (during the first createEntityManagerFactory call) * there's a danger of the classes to be weaved being already loaded. * In that situation initializeFromMain should be called before any classes are loaded. * The sure-to-work method would be to create a new runnable class with a main method * consisting of just two lines: calling initializeFromMain * followed by reflective call to the main method of the original runnable class. * The same could be achieved by calling PersistenceProvider.createEntityManagerFactory method instead * of JavaSECMPInitializer.initializeFromMain method, * however initializeFromMain might be more convenient because it * doesn't require a persistence unit name. * The method doesn't do anything if JavaSECMPInitializer has been already initialized. * @param m - a map containing the set of properties to instantiate with. */ public static void initializeFromMain(Map m) { getJavaSECMPInitializerFromMain(m); } /** * The version of initializeFromMain that passes an empty map. */ public static void initializeFromMain() { initializeFromMain(new HashMap()); } /** * Register a transformer. In this case, we use the instrumentation to add a transformer for the * JavaSE environment * @param transformer * @param persistenceUnitInfo */ public void registerTransformer(final ClassTransformer transformer, PersistenceUnitInfo persistenceUnitInfo, Map properties){ if ((transformer != null) && (globalInstrumentation != null)) { AbstractSessionLog.getLog().log(SessionLog.FINER, SessionLog.WEAVER, "cmp_init_register_transformer", persistenceUnitInfo.getPersistenceUnitName()); globalInstrumentation.addTransformer(new ClassFileTransformer() { // adapt ClassTransformer to ClassFileTransformer interface public byte[] transform( ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { return transformer.transform(loader, className, classBeingRedefined, protectionDomain, classfileBuffer); } }); } else if (transformer == null) { AbstractSessionLog.getLog().log(SessionLog.FINER, SessionLog.WEAVER, "cmp_init_transformer_is_null", null, true); } else if (globalInstrumentation == null) { AbstractSessionLog.getLog().log(SessionLog.FINER, SessionLog.WEAVER, "cmp_init_globalInstrumentation_is_null", null, true); } } /** * Indicates whether puName uniquely defines the persistence unit. * usesAgent means that it is a stand alone SE case. * Otherwise it could be an application server case where different persistence units * may have the same name: that could happen if they are loaded by different classloaders; * the common case is the same persistence unit jar deployed in several applications. */ public boolean isPersistenceUnitUniquelyDefinedByName() { return usesAgent; } /** * Indicates whether initialization has already occurred. */ public static boolean isInitialized() { return isInitialized; } /** * Indicates whether Java agent and globalInstrumentation was used. */ public static boolean usesAgent() { return usesAgent; } /** * Indicates whether initialPuInfos and initialEmSetupImpls are used. */ @Override protected boolean keepAllPredeployedPersistenceUnits() { return usesAgent; } /** * This class loader is provided at initialization time to allow us to temporarily load * domain classes so we can examine them for annotations. After they are loaded we will throw this * class loader away. Transformers can then be registered on the real class loader to allow * weaving to occur. * * It selectively loads classes based on the list of classnames it is instantiated with. Classes * not on that list are allowed to be loaded by the parent. */ public static class TempEntityLoader extends URLClassLoader { Collection classNames; boolean shouldOverrideLoadClassForCollectionMembers; //added to resolved gf #589 - without this, the orm.xml url would be returned twice public Enumeration<URL> getResources(String name) throws java.io.IOException { return this.getParent().getResources(name); } public TempEntityLoader(URL[] urls, ClassLoader parent, Collection classNames, boolean shouldOverrideLoadClassForCollectionMembers) { super(urls, parent); this.classNames = classNames; this.shouldOverrideLoadClassForCollectionMembers = shouldOverrideLoadClassForCollectionMembers; } public TempEntityLoader(URL[] urls, ClassLoader parent, Collection classNames) { this(urls, parent, classNames, true); } // Indicates if the classLoad should be overridden for the passed className. // Returns true in case the class should NOT be loaded by parent classLoader. protected boolean shouldOverrideLoadClass(String name) { if (shouldOverrideLoadClassForCollectionMembers) { // Override classLoad if the name is in collection return (classNames != null) && classNames.contains(name); } else { // Directly opposite: Override classLoad if the name is NOT in collection. // Forced to check for java. and javax. packages here, because even if the class // has been loaded by parent loader we would load it again // (see comment in loadClass) return !name.startsWith("java.") && !name.startsWith("javax.") && ((classNames == null) || !classNames.contains(name)); } } protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { if (shouldOverrideLoadClass(name)) { // First, check if the class has already been loaded. // Note that the check only for classes loaded by this loader, // it doesn't return true if the class has been loaded by parent loader // (forced to live with that because findLoadedClass method defined as final protected: // neither can override it nor call it on the parent loader) Class c = findLoadedClass(name); if (c == null) { c = findClass(name); } if (resolve) { resolveClass(c); } return c; } else { return super.loadClass(name, resolve); } } } }
package com.jcabi.log; /** * Actual implementation of {@link TextDecolorant} * used in {@link MultiColorLayout}. * @author Mihai Andronache (amihaiemil@gmail.com) * @version $Id$ */ public final class RtTextDecolorant implements TextDecolorant { /** * Name of the property that is used to disable log coloring. */ private static final String COLORING_PROPERY = "com.jcabi.log.coloring"; @Override public boolean isColoringEnabled() { return !"false".equals( System.getProperty(RtTextDecolorant.COLORING_PROPERY) ); } }
package com.ociweb.gl.impl; import com.ociweb.gl.api.*; import com.ociweb.gl.api.transducer.HTTPResponseListenerTransducer; import com.ociweb.gl.api.transducer.PubSubListenerTransducer; import com.ociweb.gl.api.transducer.RestListenerTransducer; import com.ociweb.gl.api.transducer.StateChangeListenerTransducer; import com.ociweb.gl.impl.http.client.HTTPClientConfigImpl; import com.ociweb.gl.impl.http.server.HTTPResponseListenerBase; import com.ociweb.gl.impl.mqtt.MQTTConfigImpl; import com.ociweb.gl.impl.schema.*; import com.ociweb.gl.impl.stage.*; import com.ociweb.gl.impl.telemetry.TelemetryConfigImpl; import com.ociweb.json.JSONExtractorImpl; import com.ociweb.json.JSONExtractorCompleted; import com.ociweb.pronghorn.network.ClientCoordinator; import com.ociweb.pronghorn.network.HTTPServerConfig; import com.ociweb.pronghorn.network.HTTPServerConfigImpl; import com.ociweb.pronghorn.network.NetGraphBuilder; import com.ociweb.pronghorn.network.TLSCertificates; import com.ociweb.pronghorn.network.config.*; import com.ociweb.pronghorn.network.http.CompositePath; import com.ociweb.pronghorn.network.http.HTTP1xRouterStageConfig; import com.ociweb.pronghorn.network.http.HTTPClientRequestStage; import com.ociweb.pronghorn.network.schema.*; import com.ociweb.pronghorn.pipe.*; import com.ociweb.pronghorn.pipe.util.hash.IntHashTable; import com.ociweb.pronghorn.stage.PronghornStage; import com.ociweb.pronghorn.stage.PronghornStageProcessor; import com.ociweb.pronghorn.stage.file.FileGraphBuilder; import com.ociweb.pronghorn.stage.file.NoiseProducer; import com.ociweb.pronghorn.stage.file.schema.*; import com.ociweb.pronghorn.stage.route.ReplicatorStage; import com.ociweb.pronghorn.stage.scheduling.GraphManager; import com.ociweb.pronghorn.stage.scheduling.StageScheduler; import com.ociweb.pronghorn.struct.StructBuilder; import com.ociweb.pronghorn.struct.StructRegistry; import com.ociweb.pronghorn.util.*; import com.ociweb.json.decode.JSONExtractor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.security.SecureRandom; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantLock; public class BuilderImpl implements Builder { private static final int MIN_CYCLE_RATE = 1; //cycle rate can not be zero protected static final int MINIMUM_TLS_BLOB_SIZE = 1<<15; protected long timeTriggerRate; protected long timeTriggerStart; private Runnable cleanShutdownRunnable; private Runnable dirtyShutdownRunnable; int subscriptionPipeIdx = 0; //this implementation is dependent upon graphManager returning the pipes in the order created! final IntHashTable subscriptionPipeLookup = new IntHashTable(10);//NOTE: this is a maximum of 1024 listeners private Blocker channelBlocker; public final GraphManager gm; public final ArgumentParser args; private int threadLimit = -1; private boolean threadLimitHard = false; private boolean hasPrivateTopicsChecked = false; private boolean isAllPrivateTopics = false; private static final int DEFAULT_LENGTH = 16; protected static final long MS_TO_NS = 1_000_000; private static final Logger logger = LoggerFactory.getLogger(BuilderImpl.class); public final PipeConfigManager pcm = new PipeConfigManager(); public Enum<?> beginningState; private int parallelismTracks = 1;//default is one private static final int BehaviorMask = 1<<31;//high bit on //all non shutdown listening reactors will be shutdown only after the listeners have finished. public AtomicInteger liveShutdownListeners = new AtomicInteger(); public AtomicInteger totalLiveReactors = new AtomicInteger(); public AtomicBoolean shutdownRequsted = new AtomicBoolean(false); public boolean shutdownIsComplete = false; public Runnable lastCall; //TODO: group these into an object for ReactiveListenerStage to use... ///Pipes for initial startup declared subscriptions. (Not part of graph) //TODO: should be zero unless startup is used. private final int maxStartupSubs = 256; //TODO: make a way to adjust this outside??? private final int maxTopicLengh = 128; private Pipe<MessagePubSub> tempPipeOfStartupSubscriptions; public int netResponsePipeIdxCounter = 0;//this implementation is dependent upon graphManager returning the pipes in the order created! private final boolean enableAutoPrivateTopicDiscovery = true; private long defaultSleepRateNS = 5_000;// should normally be between 900 and 20_000; private final int shutdownTimeoutInSeconds = 1; protected ReentrantLock devicePinConfigurationLock = new ReentrantLock(); private MQTTConfigImpl mqtt = null; private HTTPServerConfigImpl server = null; private TelemetryConfigImpl telemetry = null; private HTTPClientConfigImpl client = null; private ClientCoordinator ccm; protected int IDX_MSG = -1; protected int IDX_NET = -1; private StageScheduler scheduler; //These topics are enforced so that they only go from one producer to a single consumer //No runtime subscriptions can pick them up //They do not go though the public router //private topics never share a pipe so the topic is not sent on the pipe only the payload //private topics are very performant and much more secure than pub/sub. //private topics have their own private pipe and can not be "imitated" by public messages //WARNING: private topics do not obey traffic cops and allow for immediate communications. //private String[] privateTopics = null; ///gather and store the server module pipes private ArrayList<Pipe<HTTPRequestSchema>>[][] collectedHTTPRequestPipes; private ArrayList<Pipe<ServerResponseSchema>>[] collectedServerResponsePipes; //support for REST modules and routing public final HTTPSpecification<HTTPContentTypeDefaults, HTTPRevisionDefaults, HTTPVerbDefaults, HTTPHeaderDefaults> httpSpec = HTTPSpecification.defaultSpec(); private HTTP1xRouterStageConfig<HTTPContentTypeDefaults, HTTPRevisionDefaults, HTTPVerbDefaults, HTTPHeaderDefaults> routerConfig; public void usePrivateTopicsExclusively() { if (hasPrivateTopicsChecked) { throw new UnsupportedOperationException("Must set in declare configuration section before startup"); } isAllPrivateTopics = true; } /** * * @return false */ public boolean isAllPrivateTopics() { hasPrivateTopicsChecked = true; return isAllPrivateTopics; } public final ReactiveOperators operators; private final Set<String> behaviorNames = new HashSet<String>(); /** * a method to validate fullName and add it to behaviorNames * @param behaviorName String arg used in behaviorNames * @param trackId int arg used with fullName if arg >= 0 * @return behaviorName + trackId */ //will throw if a duplicate stage name is detected. public String validateUniqueName(String behaviorName, int trackId) { String fullName = behaviorName; //confirm stage name is not found.. if (behaviorNames.contains(behaviorName)) { throw new UnsupportedOperationException("Duplicate name detected: "+behaviorName); } if (trackId>=0) { fullName = behaviorName+"."+trackId; //additional check for name+"."+trackId if (behaviorNames.contains(fullName)) { throw new UnsupportedOperationException("Duplicate name detected: "+fullName); } //add the name+"."+name behaviorNames.add(fullName);//never add the root since we are watching that no one else did. } else { //add the stage name behaviorNames.add(behaviorName); } return fullName; } //TODO: replace with add only general int to Object hash table? private IntHashTable netPipeLookup = new IntHashTable(7);//Initial default size /** * a method that doubles IntHashTable if necessary and logs warning if !IntHashTable.setItem(netPipeLookup, uniqueId, pipeIdx) * @param uniqueId int arg to specify id * @param pipeIdx int arg to specify index */ public void registerHTTPClientId(final int uniqueId, int pipeIdx) { if (0==uniqueId) { throw new UnsupportedOperationException("Zero can not be used as the uniqueId"); } if ( (IntHashTable.count(netPipeLookup)<<1) >= IntHashTable.size(netPipeLookup) ) { //must grow first since we are adding many entries netPipeLookup = IntHashTable.doubleSize(netPipeLookup); } //TODO: netPipeLookup is the entry point for JSON extraction?? // we need to store extractor so its done when we do the lookup. boolean addedItem = IntHashTable.setItem(netPipeLookup, uniqueId, pipeIdx); if (!addedItem) { logger.warn("The route {} has already been assigned to a listener and can not be assigned to another.\n" + "Check that each HTTP Client consumer does not share an Id with any other.",uniqueId); } } /** * A method to look up the client pipes http * @param routeId route to be looked for in pipe * @return IntHashTable.getItem(netPipeLookup, routeId) */ public int lookupHTTPClientPipe(int routeId) { return IntHashTable.getItem(netPipeLookup, routeId); } public boolean hasHTTPClientPipe(int routeId) { return IntHashTable.hasItem(netPipeLookup, routeId); } /** * * @return index message */ public int pubSubIndex() { return IDX_MSG; } /** * * @return net index */ public int netIndex() { return IDX_NET; } /** * * @param count int arg used to set count in MsgCommandChannel.publishGo * @param gcc MsgCommandChannel<?> */ public void releasePubSubTraffic(int count, MsgCommandChannel<?> gcc) { //TODO: non descriptive arg name gcc?? MsgCommandChannel.publishGo(count, IDX_MSG, gcc); } /** * * @return ccm */ public ClientCoordinator getClientCoordinator() { return ccm; } @Override public HTTPServerConfig useHTTP1xServer(int bindPort) { if (server != null) { throw new RuntimeException("Server already enabled"); } return server = new HTTPServerConfigImpl(bindPort, pcm, gm.recordTypeData); } public final HTTPServerConfig getHTTPServerConfig() { return this.server; } /** * * @param b Behavior arg used in System.identityHashCode * @return Behavior Mask */ public int behaviorId(Behavior b) { return BehaviorMask | System.identityHashCode(b); } public final HTTP1xRouterStageConfig<HTTPContentTypeDefaults, HTTPRevisionDefaults, HTTPVerbDefaults, HTTPHeaderDefaults> routerConfig() { if (null==routerConfig) { routerConfig = new HTTP1xRouterStageConfig<HTTPContentTypeDefaults, HTTPRevisionDefaults, HTTPVerbDefaults, HTTPHeaderDefaults>( httpSpec, server.connectionStruct()); } return routerConfig; } /** * A method to append pipe mapping and group ids when invoked by builder * @param pipe Pipe<HTTPRequestSchema> arg used for routerConfig().appendPipeIdMappingForIncludedGroupIds * @param parallelId int arg used for routerConfig().appendPipeIdMappingForIncludedGroupIds * @param groupIds int arg used for routerConfig().appendPipeIdMappingForIncludedGroupIds * @return routerConfig().appendPipeIdMappingForIncludedGroupIds(pipe, parallelId, collectedHTTPRequestPipes, groupIds) */ public final boolean appendPipeMappingIncludingGroupIds(Pipe<HTTPRequestSchema> pipe, int parallelId, int ... groupIds) { lazyCreatePipeLookupMatrix(); return routerConfig().appendPipeIdMappingForIncludedGroupIds(pipe, parallelId, collectedHTTPRequestPipes, groupIds); } /** * A method to append pipe mapping but not including group ids when invoked by builder * @param pipe Pipe<HTTPRequestSchema> arg used for routerConfig().appendPipeIdMappingForExcludedGroupIds * @param parallelId int arg used for routerConfig().appendPipeIdMappingForExcludedGroupIds * @param groupIds int arg used for routerConfig().appendPipeIdMappingForExcludedGroupIds * @return routerConfig().appendPipeIdMappingForExcludedGroupIds(pipe, parallelId, collectedHTTPRequestPipes, groupIds) */ public final boolean appendPipeMappingExcludingGroupIds(Pipe<HTTPRequestSchema> pipe, int parallelId, int ... groupIds) { lazyCreatePipeLookupMatrix(); return routerConfig().appendPipeIdMappingForExcludedGroupIds(pipe, parallelId, collectedHTTPRequestPipes, groupIds); } /** * * @param pipe Pipe<HTTPRequestSchema> arg used for routerConfig().appendPipeIdMappingForAllGroupIds * @param parallelId int arg used for routerConfig().appendPipeIdMappingForAllGroupIds * @return routerConfig().appendPipeIdMappingForAllGroupIds(pipe, parallelId, collectedHTTPRequestPipes) */ public final boolean appendPipeMappingAllGroupIds(Pipe<HTTPRequestSchema> pipe, int parallelId) { lazyCreatePipeLookupMatrix(); return routerConfig().appendPipeIdMappingForAllGroupIds(pipe, parallelId, collectedHTTPRequestPipes); } /** * * @return collectedHTTPRequestPipes */ final ArrayList<Pipe<HTTPRequestSchema>>[][] targetPipeMapping() { lazyCreatePipeLookupMatrix(); return collectedHTTPRequestPipes; } /** * * @param r int arg used as index in collectedHTTPRequestPipes array * @param p int arg used as index in collectedHTTPRequestPipes array * @return null!= collectedHTTPRequestPipes ? collectedHTTPRequestPipes[r][p] : new ArrayList<Pipe<HTTPRequestSchema>>() */ public final ArrayList<Pipe<HTTPRequestSchema>> buildFromRequestArray(int r, int p) { assert(null== collectedHTTPRequestPipes || r< collectedHTTPRequestPipes.length); assert(null== collectedHTTPRequestPipes || p< collectedHTTPRequestPipes[r].length) : "p "+p+" vs "+ collectedHTTPRequestPipes[r].length; return null!= collectedHTTPRequestPipes ? collectedHTTPRequestPipes[r][p] : new ArrayList<Pipe<HTTPRequestSchema>>(); } private void lazyCreatePipeLookupMatrix() { if (null== collectedHTTPRequestPipes) { int parallelism = parallelTracks(); int routesCount = routerConfig().totalPathsCount(); assert(parallelism>=1); assert(routesCount>-1); //for catch all route since we have no specific routes. if (routesCount==0) { routesCount = 1; } collectedHTTPRequestPipes = (ArrayList<Pipe<HTTPRequestSchema>>[][]) new ArrayList[parallelism][routesCount]; int p = parallelism; while (--p>=0) { int r = routesCount; while (--r>=0) { collectedHTTPRequestPipes[p][r] = new ArrayList(); } } } } /** * * @param netResponse arg used for collectedServerResponse * @param parallelInstanceId int arg used for collectedServerResponse */ public final void recordPipeMapping(Pipe<ServerResponseSchema> netResponse, int parallelInstanceId) { if (null == collectedServerResponsePipes) { int parallelism = parallelTracks(); collectedServerResponsePipes = (ArrayList<Pipe<ServerResponseSchema>>[]) new ArrayList[parallelism]; int p = parallelism; while (--p>=0) { collectedServerResponsePipes[p] = new ArrayList(); } } collectedServerResponsePipes[parallelInstanceId].add(netResponse); } /** * * @param r int arg used in collectedServerResponsePipes * @return (Pipe<ServerResponseSchema>[]) list.toArray(new Pipe[list.size()]) */ public final Pipe<ServerResponseSchema>[] buildToOrderArray(int r) { if (null==collectedServerResponsePipes || collectedServerResponsePipes.length==0) { return new Pipe[0]; } else { ArrayList<Pipe<ServerResponseSchema>> list = collectedServerResponsePipes[r]; return (Pipe<ServerResponseSchema>[]) list.toArray(new Pipe[list.size()]); } } /** * * @param config * @param parallelInstanceId int arg used for recordPipeMapping * @return pipe */ public final Pipe<ServerResponseSchema> newNetResponsePipe(PipeConfig<ServerResponseSchema> config, int parallelInstanceId) { Pipe<ServerResponseSchema> pipe = new Pipe<ServerResponseSchema>(config) { @SuppressWarnings("unchecked") @Override protected DataOutputBlobWriter<ServerResponseSchema> createNewBlobWriter() { return new NetResponseWriter(this); } }; recordPipeMapping(pipe, parallelInstanceId); return pipe; } public BuilderImpl(GraphManager gm, String[] args) { this.operators = ReactiveListenerStage.reactiveOperators(); this.gm = gm; this.getTempPipeOfStartupSubscriptions().initBuffers(); this.args = new ArgumentParser(args); int requestQueue = 4; this.pcm.addConfig(new PipeConfig<NetPayloadSchema>(NetPayloadSchema.instance, requestQueue, MINIMUM_TLS_BLOB_SIZE)); int maxMessagesQueue = 8; int maxMessageSize = 256; this.pcm.addConfig(new PipeConfig<MessageSubscription>(MessageSubscription.instance, maxMessagesQueue, maxMessageSize)); this.pcm.addConfig(new PipeConfig<TrafficReleaseSchema>(TrafficReleaseSchema.instance, DEFAULT_LENGTH)); this.pcm.addConfig(new PipeConfig<TrafficAckSchema>(TrafficAckSchema.instance, DEFAULT_LENGTH)); int defaultCommandChannelLength = 16; int defaultCommandChannelHTTPMaxPayload = 1<<14; //must be at least 32K for TLS support this.pcm.addConfig(new PipeConfig<NetResponseSchema>(NetResponseSchema.instance, defaultCommandChannelLength, defaultCommandChannelHTTPMaxPayload)); //for MQTT ingress int maxMQTTMessagesQueue = 8; int maxMQTTMessageSize = 1024; this.pcm.addConfig(new PipeConfig(IngressMessages.instance, maxMQTTMessagesQueue, maxMQTTMessageSize)); } public final <E extends Enum<E>> boolean isValidState(E state) { if (null!=beginningState) { return beginningState.getClass()==state.getClass(); } return false; } public final <E extends Enum<E>> Builder startStateMachineWith(E state) { beginningState = state; return this; } /** * * @param rateInMS Rate in milliseconds to trigger events. * * @return this */ public final Builder setTimerPulseRate(long rateInMS) { timeTriggerRate = rateInMS; timeTriggerStart = System.currentTimeMillis()+rateInMS; return this; } /** * * @param trigger {@link TimeTrigger} to use for controlling trigger rate. * * @return this */ public final Builder setTimerPulseRate(TimeTrigger trigger) { long period = trigger.getRate(); timeTriggerRate = period; long now = System.currentTimeMillis(); long soFar = (now % period); timeTriggerStart = (now - soFar) + period; return this; } @Override public final HTTPClientConfig useNetClient() { return useNetClient(TLSCertificates.defaultCerts); } @Override public final HTTPClientConfig useInsecureNetClient() { return useNetClient((TLSCertificates) null); } @Override public HTTPClientConfigImpl useNetClient(TLSCertificates certificates) { if (client != null) throw new RuntimeException("Client already enabled"); this.client = new HTTPClientConfigImpl(certificates); this.client.beginDeclarations(); return client; } /** * * @return this.client */ public final HTTPClientConfig getHTTPClientConfig() { return this.client; } /** * * @return timeTriggerRate */ public final long getTriggerRate() { return timeTriggerRate; } /** * * @return timeTriggerStart */ public final long getTriggerStart() { return timeTriggerStart; } /** * * @param gm {@link GraphManager} arg used in new ReactiveListenerStage * @param listener {@link Behavior} arg used in ReactiveListenerStage * @param inputPipes arg used in ReactiveListenerStage * @param outputPipes arg used in ReactiveListenerStage * @param consumers arg used in ReactiveListenerStage * @param parallelInstance int arg used in ReactiveListenerStage * @param nameId String arg used in ReactiveListenerStage * @return new reactive listener stage */ public <R extends ReactiveListenerStage> R createReactiveListener(GraphManager gm, Behavior listener, Pipe<?>[] inputPipes, Pipe<?>[] outputPipes, ArrayList<ReactiveManagerPipeConsumer> consumers, int parallelInstance, String nameId) { assert(null!=listener); return (R) new ReactiveListenerStage(gm, listener, inputPipes, outputPipes, consumers, this, parallelInstance, nameId); } @Deprecated public <G extends MsgCommandChannel> G newCommandChannel( int features, int parallelInstanceId, PipeConfigManager pcm ) { return (G) new GreenCommandChannel(gm, this, features, parallelInstanceId, pcm); } /** * * @param parallelInstanceId MsgCommandChannel arg used for GreenCommandChannel(gm, this, 0, parallelInstanceId, pcm) * @param pcm int arg used for GreenCommandChannel(gm, this, 0, parallelInstanceId, pcm) * @return new GreenCommandChannel(gm, this, 0, parallelInstanceId, pcm) */ public <G extends MsgCommandChannel> G newCommandChannel( int parallelInstanceId, PipeConfigManager pcm ) { return (G) new GreenCommandChannel(gm, this, 0, parallelInstanceId, pcm); } static final boolean debug = false; public void shutdown() { if (null!=ccm) { ccm.shutdown(); } //can be overridden by specific hardware impl if shutdown is supported. } protected void initChannelBlocker(int maxGoPipeId) { channelBlocker = new Blocker(maxGoPipeId+1); } protected final boolean useNetClient(Pipe<ClientHTTPRequestSchema>[] netRequestPipes) { return (netRequestPipes.length!=0); } protected final void createMessagePubSubStage( MsgRuntime<?,?> runtime, IntHashTable subscriptionPipeLookup, Pipe<IngressMessages>[] ingressMessagePipes, Pipe<MessagePubSub>[] messagePubSub, Pipe<TrafficReleaseSchema>[] masterMsggoOut, Pipe<TrafficAckSchema>[] masterMsgackIn, Pipe<MessageSubscription>[] subscriptionPipes) { new MessagePubSubTrafficStage(this.gm, runtime, subscriptionPipeLookup, this, ingressMessagePipes, messagePubSub, masterMsggoOut, masterMsgackIn, subscriptionPipes); } /** * * @param runtime final MsgRuntime arg used in createScheduler * @return createScheduler(runtime, null, null) */ public StageScheduler createScheduler(final MsgRuntime runtime) { return createScheduler(runtime, null, null); } /** * * @param runtime final MsgRuntime arg used to check if arg.builder.threadLimit > 0 * @param cleanRunnable final Runnable arg used with runtime.addCleanShutdownRunnable * @param dirtyRunnable final Runnable arg used with runtime.addDirtyShutdownRunnable * @return scheduler */ public StageScheduler createScheduler(final MsgRuntime runtime, final Runnable cleanRunnable, final Runnable dirtyRunnable) { final StageScheduler scheduler = runtime.builder.threadLimit>0 ? StageScheduler.defaultScheduler(gm, runtime.builder.threadLimit, runtime.builder.threadLimitHard) : StageScheduler.defaultScheduler(gm); runtime.addCleanShutdownRunnable(cleanRunnable); runtime.addDirtyShutdownRunnable(dirtyRunnable); return scheduler; } private final int getShutdownSeconds() { return shutdownTimeoutInSeconds; } protected final ChildClassScannerVisitor deepListener = new ChildClassScannerVisitor<ListenerTransducer>() { @Override public boolean visit(ListenerTransducer child, Object topParent, String name) { return false; } }; public final boolean isListeningToSubscription(Behavior listener) { //NOTE: we only call for scan if the listener is not already of this type return listener instanceof PubSubMethodListenerBase || listener instanceof StateChangeListenerBase<?> || !ChildClassScanner.visitUsedByClass(null, listener, deepListener, PubSubListenerTransducer.class) || !ChildClassScanner.visitUsedByClass(null, listener, deepListener, StateChangeListenerTransducer.class); } public final boolean isListeningToHTTPResponse(Object listener) { return listener instanceof HTTPResponseListenerBase || //will return false if HTTPResponseListenerBase was encountered !ChildClassScanner.visitUsedByClass(null, listener, deepListener, HTTPResponseListenerTransducer.class); } public final boolean isListeningHTTPRequest(Object listener) { return listener instanceof RestMethodListenerBase || //will return false if RestListenerBase was encountered !ChildClassScanner.visitUsedByClass(null, listener, deepListener, RestListenerTransducer.class); } /** * access to system time. This method is required so it can be monitored and simulated by unit tests. */ public long currentTimeMillis() { return System.currentTimeMillis(); } public final void blockChannelUntil(int channelId, long timeInMillis) { channelBlocker.until(channelId, timeInMillis); } public final boolean isChannelBlocked(int channelId) { if (null != channelBlocker) { return channelBlocker.isBlocked(channelId); } else { return false; } } public final long releaseChannelBlocks(long now) { if (null != channelBlocker) { channelBlocker.releaseBlocks(now); return channelBlocker.durationToNextRelease(now, -1); } else { return -1; //was not init so there are no possible blocked channels. } } public final long nanoTime() { return System.nanoTime(); } public final Enum[] getStates() { return null==beginningState? new Enum[0] : beginningState.getClass().getEnumConstants(); } public final void addStartupSubscription(CharSequence topic, int systemHash, int parallelInstance) { Pipe<MessagePubSub> pipe = getTempPipeOfStartupSubscriptions(); if (PipeWriter.tryWriteFragment(pipe, MessagePubSub.MSG_SUBSCRIBE_100)) { DataOutputBlobWriter<MessagePubSub> output = PipeWriter.outputStream(pipe); output.openField(); output.append(topic); //this is in a track and may need a suffix. if (parallelInstance>=0) { if (BuilderImpl.hasNoUnscopedTopics()) { //add suffix.. output.append('/'); Appendables.appendValue(output, parallelInstance); } else { if (BuilderImpl.notUnscoped(reader, output)) { //add suffix output.append('/'); Appendables.appendValue(output, parallelInstance); } } } output.closeHighLevelField(MessagePubSub.MSG_SUBSCRIBE_100_FIELD_TOPIC_1); //PipeWriter.writeUTF8(pipe, MessagePubSub.MSG_SUBSCRIBE_100_FIELD_TOPIC_1, topic); PipeWriter.writeInt(pipe, MessagePubSub.MSG_SUBSCRIBE_100_FIELD_SUBSCRIBERIDENTITYHASH_4, systemHash); PipeWriter.publishWrites(pipe); } else { throw new UnsupportedOperationException("Limited number of startup subscriptions "+maxStartupSubs+" encountered."); } } private final Pipe<MessagePubSub> getTempPipeOfStartupSubscriptions() { if (null==tempPipeOfStartupSubscriptions) { final PipeConfig<MessagePubSub> messagePubSubConfig = new PipeConfig<MessagePubSub>(MessagePubSub.instance, maxStartupSubs, maxTopicLengh); tempPipeOfStartupSubscriptions = new Pipe<MessagePubSub>(messagePubSubConfig); } return tempPipeOfStartupSubscriptions; } public final Pipe<MessagePubSub> consumeStartupSubscriptions() { Pipe<MessagePubSub> result = tempPipeOfStartupSubscriptions; tempPipeOfStartupSubscriptions = null;//no longer needed return result; } @Override public final void limitThreads(int threadLimit) { if (telemetry != null && threadLimit>0 && threadLimit<64) { //must ensure telemetry has the threads it needs. threadLimit+=2; } this.threadLimit = threadLimit; this.threadLimitHard = true; } @Override public void limitThreads() { this.threadLimit = idealThreadCount(); this.threadLimitHard = true; } private int idealThreadCount() { return Runtime.getRuntime().availableProcessors()*4; } @Override public final int parallelTracks() { return parallelismTracks; } @Override public final void parallelTracks(int trackCount) { assert(trackCount>0); parallelismTracks = trackCount; } private final TrieParserReader localReader = new TrieParserReader(true); @Override public long fieldId(int routeId, byte[] fieldName) { return TrieParserReader.query(localReader, this.routeExtractionParser(routeId), fieldName, 0, fieldName.length, Integer.MAX_VALUE); } @Override public final CompositePath defineRoute(JSONExtractorCompleted extractor, HTTPHeader ... headers) { return routerConfig().registerCompositeRoute(extractor, headers); } @Override public final CompositePath defineRoute(HTTPHeader ... headers) { return routerConfig().registerCompositeRoute(headers); } @Override public final JSONExtractor defineJSONSDecoder() { return new JSONExtractor(); } @Override public final JSONExtractor defineJSONSDecoder(boolean writeDot) { return new JSONExtractor(writeDot); } public final TrieParser routeExtractionParser(int route) { return routerConfig().extractionParser(route).getRuntimeParser(); } public final int routeExtractionParserIndexCount(int route) { return routerConfig().extractionParser(route).getIndexCount(); } public final Pipe<HTTPRequestSchema> newHTTPRequestPipe(PipeConfig<HTTPRequestSchema> restPipeConfig) { final boolean hasNoRoutes = (0==routerConfig().totalPathsCount()); Pipe<HTTPRequestSchema> pipe = new Pipe<HTTPRequestSchema>(restPipeConfig) { @SuppressWarnings("unchecked") @Override protected DataInputBlobReader<HTTPRequestSchema> createNewBlobReader() { return new HTTPRequestReader(this, hasNoRoutes, routerConfig()); } }; return pipe; } @Override public TelemetryConfig enableTelemetry() { return enableTelemetry(null, TelemetryConfig.defaultTelemetryPort); } @Override public TelemetryConfig enableTelemetry(int port) { return enableTelemetry(null, port); } @Override public TelemetryConfig enableTelemetry(String host) { return enableTelemetry(host, TelemetryConfig.defaultTelemetryPort); } @Override public TelemetryConfig enableTelemetry(String host, int port) { if (telemetry != null) { throw new RuntimeException("Telemetry already enabled"); } this.telemetry = new TelemetryConfigImpl(host, port); this.telemetry.beginDeclarations(); if (threadLimit>0 && threadLimit>0 && threadLimit<64) { //we must increase the thread limit to ensure telemetry is not started threadLimit += 2; } return this.telemetry; } public TelemetryConfig getTelemetryConfig() { return this.telemetry; } public final long getDefaultSleepRateNS() { return defaultSleepRateNS; } @Override public final void setDefaultRate(long ns) { //new Exception("setting new rate "+ns).printStackTrace(); defaultSleepRateNS = Math.max(ns, MIN_CYCLE_RATE); //protect against negative and zero } public void buildStages(MsgRuntime runtime) { IntHashTable subscriptionPipeLookup2 = MsgRuntime.getSubPipeLookup(runtime); GraphManager gm = MsgRuntime.getGraphManager(runtime); Pipe<NetResponseSchema>[] httpClientResponsePipes = GraphManager.allPipesOfTypeWithNoProducer(gm, NetResponseSchema.instance); Pipe<MessageSubscription>[] subscriptionPipes = GraphManager.allPipesOfTypeWithNoProducer(gm, MessageSubscription.instance); Pipe<TrafficOrderSchema>[] orderPipes = GraphManager.allPipesOfTypeWithNoConsumer(gm, TrafficOrderSchema.instance); Pipe<ClientHTTPRequestSchema>[] httpClientRequestPipes = GraphManager.allPipesOfTypeWithNoConsumer(gm, ClientHTTPRequestSchema.instance); Pipe<MessagePubSub>[] messagePubSub = GraphManager.allPipesOfTypeWithNoConsumer(gm, MessagePubSub.instance); Pipe<IngressMessages>[] ingressMessagePipes = GraphManager.allPipesOfTypeWithNoConsumer(gm, IngressMessages.instance); //TODO: no longer right now that we have no cops.. int commandChannelCount = orderPipes.length; int eventSchemas = 0; IDX_MSG = (IntHashTable.isEmpty(subscriptionPipeLookup2) && subscriptionPipes.length==0 && messagePubSub.length==0) ? -1 : eventSchemas++; IDX_NET = useNetClient(httpClientRequestPipes) ? eventSchemas++ : -1; long timeout = 240_000; //240 seconds so we have time to capture telemetry. int maxGoPipeId = 0; Pipe<TrafficReleaseSchema>[][] masterGoOut = new Pipe[eventSchemas][0]; Pipe<TrafficAckSchema>[][] masterAckIn = new Pipe[eventSchemas][0]; if (IDX_MSG >= 0) { masterGoOut[IDX_MSG] = new Pipe[messagePubSub.length]; masterAckIn[IDX_MSG] = new Pipe[messagePubSub.length]; } if (IDX_NET >= 0) { assert(httpClientResponsePipes.length>0); masterGoOut[IDX_NET] = new Pipe[httpClientResponsePipes.length]; masterAckIn[IDX_NET] = new Pipe[httpClientResponsePipes.length]; } int copGoAck = commandChannelCount; //logger.info("\ncommand channel count to be checked {}",copGoAck); while (--copGoAck>=0) { Pipe<TrafficReleaseSchema>[] goOut = new Pipe[eventSchemas]; Pipe<TrafficAckSchema>[] ackIn = new Pipe[eventSchemas]; //only setup the go and in pipes if the cop is used. if (null != orderPipes[copGoAck]) { //this only returns the features associated with this order pipe, eg only the ones needing a cop. final int features = getFeatures(gm, orderPipes[copGoAck]); if ((features&Behavior.DYNAMIC_MESSAGING) != 0) { maxGoPipeId = populateGoAckPipes(maxGoPipeId, masterGoOut, masterAckIn, goOut, ackIn, IDX_MSG); } if ((features&Behavior.NET_REQUESTER) != 0) { maxGoPipeId = populateGoAckPipes(maxGoPipeId, masterGoOut, masterAckIn, goOut, ackIn, IDX_NET); } logger.info("\nnew traffic cop for graph {}",gm.name); TrafficCopStage.newInstance(gm, timeout, orderPipes[copGoAck], ackIn, goOut, runtime, this); } else { logger.info("\noops get features skipped since no cops but needed for private topics"); } } initChannelBlocker(maxGoPipeId); buildHTTPClientGraph(runtime, httpClientResponsePipes, httpClientRequestPipes, masterGoOut, masterAckIn); //always create the pub sub and state management stage? //TODO: only create when subscriptionPipeLookup is not empty and subscriptionPipes has zero length. if (IDX_MSG<0) { logger.trace("saved some resources by not starting up the unused pub sub service."); } else { if (!isAllPrivateTopics) { //logger.info("builder created pub sub"); createMessagePubSubStage(runtime, subscriptionPipeLookup2, ingressMessagePipes, messagePubSub, masterGoOut[IDX_MSG], masterAckIn[IDX_MSG], subscriptionPipes); } } } public void buildHTTPClientGraph( MsgRuntime<?,?> runtime, Pipe<NetResponseSchema>[] netResponsePipes, Pipe<ClientHTTPRequestSchema>[] netRequestPipes, Pipe<TrafficReleaseSchema>[][] masterGoOut, Pipe<TrafficAckSchema>[][] masterAckIn) { //create the network client stages if (useNetClient(netRequestPipes)) { int tracks = Math.max(1, runtime.getBuilder().parallelTracks()); int maxPartialResponses = Math.max(2,ClientHostPortInstance.getSessionCount()); int maxClientConnections = 4*(maxPartialResponses*tracks); int connectionsInBits = (int)Math.ceil(Math.log(maxClientConnections)/Math.log(2)); int netResponseCount = 8; int responseQueue = 10; //must be adjusted together int outputsCount = 8; //Multipler per session for total connections ,count of pipes to channel writer int clientWriters = 1; //count of channel writer stages PipeConfig<NetPayloadSchema> clientNetRequestConfig = pcm.getConfig(NetPayloadSchema.class); //BUILD GRAPH ccm = new ClientCoordinator(connectionsInBits, maxPartialResponses, this.client.getCertificates(), gm.recordTypeData); Pipe<NetPayloadSchema>[] clientRequests = new Pipe[outputsCount]; int r = outputsCount; while (--r>=0) { clientRequests[r] = new Pipe<NetPayloadSchema>(clientNetRequestConfig); } if (isAllNull(masterGoOut[IDX_NET])) { //this one has much lower latency and should be used if possible new HTTPClientRequestStage(gm, ccm, netRequestPipes, clientRequests); } else { logger.info("Warning, the slower HTTP Client Request code was called. 2ms latency may be introduced."); //this may stay for as long as 2ms before returning due to timeout of //traffic logic, this is undesirable in some low latency cases. new HTTPClientRequestTrafficStage( gm, runtime, this, ccm, netRequestPipes, masterGoOut[IDX_NET], masterAckIn[IDX_NET], clientRequests); } int releaseCount = 1024; int responseUnwrapCount = 2; int clientWrapperCount = 2; NetGraphBuilder.buildHTTPClientGraph(gm, ccm, responseQueue, clientRequests, netResponsePipes, netResponseCount, releaseCount, responseUnwrapCount, clientWrapperCount, clientWriters); } } private boolean isAllNull(Pipe<?>[] pipes) { int p = pipes.length; while (--p>=0) { if (pipes[p]!=null) { return false; } } return true; } protected int populateGoAckPipes(int maxGoPipeId, Pipe<TrafficReleaseSchema>[][] masterGoOut, Pipe<TrafficAckSchema>[][] masterAckIn, Pipe<TrafficReleaseSchema>[] goOut, Pipe<TrafficAckSchema>[] ackIn, int p) { if (p>=0) { addToLastNonNull(masterGoOut[p], goOut[p] = new Pipe<TrafficReleaseSchema>(this.pcm.getConfig(TrafficReleaseSchema.class))); maxGoPipeId = Math.max(maxGoPipeId, goOut[p].id); addToLastNonNull(masterAckIn[p], ackIn[p] = new Pipe<TrafficAckSchema>(this.pcm.getConfig(TrafficAckSchema.class))); } return maxGoPipeId; } private <S extends MessageSchema<S>> void addToLastNonNull(Pipe<S>[] pipes, Pipe<S> pipe) { int i = pipes.length; while (--i>=0) { if (null == pipes[i]) { pipes[i] = pipe; return; } } } protected int getFeatures(GraphManager gm, Pipe<TrafficOrderSchema> orderPipe) { PronghornStage producer = GraphManager.getRingProducer(gm, orderPipe.id); assert(producer instanceof ReactiveProxyStage) : "TrafficOrderSchema must only come from Reactor stages but was "+producer.getClass().getSimpleName(); return ((ReactiveProxyStage)producer).getFeatures(orderPipe); } @Override public MQTTConfigImpl useMQTT(CharSequence host, int port, CharSequence clientId) { return useMQTT(host, port, clientId, MQTTConfigImpl.DEFAULT_MAX_MQTT_IN_FLIGHT, MQTTConfigImpl.DEFAULT_MAX__MQTT_MESSAGE); } @Override public MQTTConfigImpl useMQTT(CharSequence host, int port, CharSequence clientId, int maxInFlight) { return useMQTT(host, port, clientId, maxInFlight, MQTTConfigImpl.DEFAULT_MAX__MQTT_MESSAGE); } @Override public MQTTConfigImpl useMQTT(CharSequence host, int port, CharSequence clientId, int maxInFlight, int maxMessageLength) { ClientCoordinator.registerDomain(host); if (maxInFlight>(1<<15)) { throw new UnsupportedOperationException("Does not suppport more than "+(1<<15)+" in flight"); } if (maxMessageLength>(256*(1<<20))) { throw new UnsupportedOperationException("Specification does not support values larger than 256M"); } pcm.ensureSize(MessageSubscription.class, maxInFlight, maxMessageLength); //all these use a smaller rate to ensure MQTT can stay ahead of the internal message passing long rate = defaultSleepRateNS>200_000?defaultSleepRateNS/4:defaultSleepRateNS; MQTTConfigImpl mqttBridge = new MQTTConfigImpl(host, port, clientId, this, rate, (short)maxInFlight, maxMessageLength); mqtt = mqttBridge; mqttBridge.beginDeclarations(); return mqtt; } @Override public void useInsecureSerialStores(int instances, int largestBlock) { logger.warn("Non encrypted serial stores are in use. Please call useSerialStores with a passphrase to ensure data is encrypted."); int j = instances; while (--j>=0) { buildSerialStore(j, null, largestBlock); } } @Override public void useSerialStores(int instances, int largestBlock, String passphrase) { CharSequenceToUTF8 charSequenceToUTF8 = CharSequenceToUTF8Local.get(); SecureRandom sr = new SecureRandom(charSequenceToUTF8.convert(passphrase).asBytes()); charSequenceToUTF8.clear(); NoiseProducer noiseProducer = new NoiseProducer(sr); serialStoreReleaseAck = new Pipe[instances]; serialStoreReplay = new Pipe[instances]; serialStoreWriteAck = new Pipe[instances]; serialStoreRequestReplay = new Pipe[instances]; serialStoreWrite = new Pipe[instances]; int j = instances; while (--j>=0) { buildSerialStore(j, noiseProducer, largestBlock); } } @Override public void useSerialStores(int instances, int largestBlock, byte[] passphrase) { SecureRandom sr = new SecureRandom(passphrase); NoiseProducer noiseProducer = new NoiseProducer(sr); serialStoreReleaseAck = new Pipe[instances]; serialStoreReplay = new Pipe[instances]; serialStoreWriteAck = new Pipe[instances]; serialStoreRequestReplay = new Pipe[instances]; serialStoreWrite = new Pipe[instances]; for(int j=0; j<instances; j++) { buildSerialStore(j, noiseProducer, largestBlock); } } //holding these for build lookup public Pipe<PersistedBlobLoadReleaseSchema>[] serialStoreReleaseAck; public Pipe<PersistedBlobLoadConsumerSchema>[] serialStoreReplay; public Pipe<PersistedBlobLoadProducerSchema>[] serialStoreWriteAck; public Pipe<PersistedBlobStoreConsumerSchema>[] serialStoreRequestReplay; public Pipe<PersistedBlobStoreProducerSchema>[] serialStoreWrite; public Pipe<NetResponseSchema> buildNetResponsePipe() { Pipe<NetResponseSchema> netResponsePipe = new Pipe<NetResponseSchema>(pcm.getConfig(NetResponseSchema.class)) { @SuppressWarnings("unchecked") @Override protected DataInputBlobReader<NetResponseSchema> createNewBlobReader() { return new HTTPResponseReader(this, httpSpec); } }; return netResponsePipe; } private void buildSerialStore(int id, NoiseProducer noiseProducer, int largestBlock) { File targetDirectory = null; try { targetDirectory = new File(Files.createTempDirectory("serialStore"+id).toString()); } catch (IOException e) { throw new RuntimeException(e); } final short maxInFlightCount = 4; buildSerialStore(id, noiseProducer, largestBlock, targetDirectory, maxInFlightCount); } private void buildSerialStore(int id, NoiseProducer noiseProducer, int largestBlock, File targetDirectory, final short maxInFlightCount) { Pipe<PersistedBlobLoadReleaseSchema> fromStoreRelease = PersistedBlobLoadReleaseSchema.instance.newPipe(maxInFlightCount, 0); Pipe<PersistedBlobLoadConsumerSchema> fromStoreConsumer = PersistedBlobLoadConsumerSchema.instance.newPipe(maxInFlightCount, largestBlock); Pipe<PersistedBlobLoadProducerSchema> fromStoreProducer = PersistedBlobLoadProducerSchema.instance.newPipe(maxInFlightCount, 0); Pipe<PersistedBlobStoreConsumerSchema> toStoreConsumer = PersistedBlobStoreConsumerSchema.instance.newPipe(maxInFlightCount, 0); Pipe<PersistedBlobStoreProducerSchema> toStoreProducer = PersistedBlobStoreProducerSchema.instance.newPipe(maxInFlightCount, largestBlock); serialStoreReleaseAck[id] = fromStoreRelease; serialStoreReplay[id] = fromStoreConsumer; serialStoreWriteAck[id] = fromStoreProducer; serialStoreRequestReplay[id] = toStoreConsumer; serialStoreWrite[id] = toStoreProducer; //NOTE: the above pipes will dangle but will remain in the created order so that // they can be attached to the right command channels upon definition long rate=-1;//do not set so we will use the system default. String backgroundColor="cornsilk2"; PronghornStageProcessor proc = new PronghornStageProcessor() { @Override public void process(GraphManager gm, PronghornStage stage) { GraphManager.addNota(gm, GraphManager.SCHEDULE_RATE, rate, stage); GraphManager.addNota(gm, GraphManager.DOT_BACKGROUND, backgroundColor, stage); } }; FileGraphBuilder.buildSequentialReplayer(gm, fromStoreRelease, fromStoreConsumer, fromStoreProducer, toStoreConsumer, toStoreProducer, maxInFlightCount, largestBlock, targetDirectory, noiseProducer, proc); } //fields supporting private topics private final TrieParser privateTopicSource = new TrieParser(); private final TrieParser privateTopicTarget = new TrieParser(); private final List<List<PrivateTopic>> privateSourceTopics = new ArrayList<List<PrivateTopic>>(); private final List<List<PrivateTopic>> privateTargetTopics = new ArrayList<List<PrivateTopic>>(); private final TrieParserReader reader = new TrieParserReader(); private final List<String> dynamicTopicPublishers = new ArrayList<String>(); private final List<String> dynamicTopicSubscribers = new ArrayList<String>(); //TODO: MUST HAVE ARRAY OF TOPICS TO LOOK UP BY PIPE? public List<PrivateTopic> getPrivateTopicsFromSource(String source) { int sourceId = (int)TrieParserReader.query(reader, privateTopicSource, source); List<PrivateTopic> result = (sourceId<0) ? Collections.EMPTY_LIST : privateSourceTopics.get(sourceId); return result; } public List<PrivateTopic> getPrivateTopicsFromTarget(String target) { int targetId = (int)TrieParserReader.query(reader, privateTopicTarget, target); List<PrivateTopic> result = (targetId<0) ? Collections.EMPTY_LIST: privateTargetTopics.get(targetId); return result; } public static TrieParser unScopedTopics = null; //package protected static, all unscoped topics @Override public void defineUnScopedTopic(String topic) { if (null == unScopedTopics) { unScopedTopics = new TrieParser(); } unScopedTopics.setUTF8Value(topic, 1); } @Override public void definePrivateTopic(String topic, String source, String ... targets) { definePrivateTopic(10, 10000, topic, source, targets); } @Override public void definePrivateTopic(int queueLength, int maxMessageSize, String topic, String source, String ... targets) { if (targets.length<=1) { throw new UnsupportedOperationException("only call this with multiple targets"); } boolean hideTopics = false; PrivateTopic sourcePT = new PrivateTopic(topic, queueLength, maxMessageSize, hideTopics, this); List<PrivateTopic> localSourceTopics = null; int sourceId = (int)TrieParserReader.query(reader, privateTopicSource, source); if (sourceId<0) { localSourceTopics = new ArrayList<PrivateTopic>(); privateTopicSource.setUTF8Value(source, privateSourceTopics.size()); privateSourceTopics.add(localSourceTopics); } else { localSourceTopics = privateSourceTopics.get(sourceId); } localSourceTopics.add(sourcePT); int pt = parallelismTracks<1?1:parallelismTracks; while (--pt>=0) { Pipe<MessagePrivate> src = sourcePT.getPipe(pt); PipeConfig<MessagePrivate> trgtConfig = src.config().grow2x(); int t = targets.length; Pipe[] trgts = new Pipe[t]; PrivateTopic[] trgtTopics = new PrivateTopic[t]; while (--t>=0) { trgtTopics[t] = new PrivateTopic(topic, trgtConfig, this); trgts[t] = trgtTopics[t].getPipe(pt); List<PrivateTopic> localTargetTopics = null; int targetId = (int)TrieParserReader.query(reader, privateTopicTarget, targets[t]); if (targetId<0) { localTargetTopics = new ArrayList<PrivateTopic>(); privateTopicTarget.setUTF8Value( targets[t], privateTargetTopics.size()); privateTargetTopics.add(localTargetTopics); } else { localTargetTopics = privateTargetTopics.get(targetId); } localTargetTopics.add(trgtTopics[t]); } ReplicatorStage.newInstance(gm, src, trgts); } } //these are to stop some topics from becomming private. private ArrayList<String[]> publicTopics = new ArrayList<String[]>(); @Override public void definePublicTopics(String ... topics) { publicTopics.add(topics); } @Override public void definePrivateTopic(String topic, String source, String target) { definePrivateTopic(10, 10000, topic, source, target); } @Override public void definePrivateTopic(int queueLength, int maxMessageSize, String topic, String source, String target) { boolean hideTopics = false; PrivateTopic obj = new PrivateTopic(topic, queueLength, maxMessageSize, hideTopics, this); defPrivateTopic(source, target, obj); } void definePrivateTopic(PipeConfig<MessagePrivate> config, String topic, String source, String target) { boolean hideTopics = false; PrivateTopic obj = new PrivateTopic(topic, config, hideTopics, this); defPrivateTopic(source, target, obj); } private void defPrivateTopic(String source, String target, PrivateTopic obj) { List<PrivateTopic> localSourceTopics = null; int sourceId = (int)TrieParserReader.query(reader, privateTopicSource, source); if (sourceId<0) { localSourceTopics = new ArrayList<PrivateTopic>(); //logger.info("record source '{}'",source); privateTopicSource.setUTF8Value(source, privateSourceTopics.size()); privateSourceTopics.add(localSourceTopics); } else { localSourceTopics = privateSourceTopics.get(sourceId); } localSourceTopics.add(obj); List<PrivateTopic> localTargetTopics = null; int targetId = (int)TrieParserReader.query(reader, privateTopicTarget, target); if (targetId<0) { localTargetTopics = new ArrayList<PrivateTopic>(); //logger.info("record target '{}'",target); privateTopicTarget.setUTF8Value(target, privateTargetTopics.size()); privateTargetTopics.add(localTargetTopics); } else { localTargetTopics = privateTargetTopics.get(targetId); } localTargetTopics.add(obj); } @Override public void enableDynamicTopicPublish(String id) { dynamicTopicPublishers.add(id); } @Override public void enableDynamicTopicSubscription(String id) { dynamicTopicSubscribers.add(id); } @Override public String[] args() { return args.args(); } @Override public boolean hasArgument(String longName, String shortName) { return args.hasArgument(longName, shortName); } @Override public String getArgumentValue(String longName, String shortName, String defaultValue) { return args.getArgumentValue(longName, shortName, defaultValue); } @Override public Boolean getArgumentValue(String longName, String shortName, Boolean defaultValue) { return args.getArgumentValue(longName, shortName, defaultValue); } @Override public Character getArgumentValue(String longName, String shortName, Character defaultValue) { return args.getArgumentValue(longName, shortName, defaultValue); } @Override public Byte getArgumentValue(String longName, String shortName, Byte defaultValue) { return args.getArgumentValue(longName, shortName, defaultValue); } @Override public Short getArgumentValue(String longName, String shortName, Short defaultValue) { return args.getArgumentValue(longName, shortName, defaultValue); } @Override public Long getArgumentValue(String longName, String shortName, Long defaultValue) { return args.getArgumentValue(longName, shortName, defaultValue); } @Override public Integer getArgumentValue(String longName, String shortName, Integer defaultValue) { return args.getArgumentValue(longName, shortName, defaultValue); } @Override public <T extends Enum<T>> T getArgumentValue(String longName, String shortName, Class<T> c, T defaultValue) { return args.getArgumentValue(longName, shortName, c, defaultValue); } public void blockChannelDuration(long durationNanos, int pipeId) { final long durationMills = durationNanos/1_000_000; final long remaningNanos = durationNanos%1_000_000; if (remaningNanos>0) { try { long limit = System.nanoTime()+remaningNanos; Thread.sleep(0L, (int)remaningNanos); long dif; while ((dif = (limit-System.nanoTime()))>0) { if (dif>100) { Thread.yield(); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } } if (durationMills>0) { //now pull the current time and wait until ms have passed blockChannelUntil(pipeId, currentTimeMillis() + durationMills ); } } /** * Enables the child classes to modify which schemas are used. * For the pi this allows for using i2c instead of digital or analog in transducers. * * @param schema */ public MessageSchema schemaMapper(MessageSchema schema) { return schema; } public void finalizeDeclareConnections() { // two of these are recalculating the same local host address when host is null if (server != null) { server.finalizeDeclareConnections(); } if (client != null) { client.finalizeDeclareConnections(); } if (telemetry != null) { telemetry.finalizeDeclareConnections(); } } public static boolean notUnscoped(TrieParserReader reader, DataOutputBlobWriter<MessagePubSub> output){ return (-1 == output.startsWith(reader, BuilderImpl.unScopedTopics )); } public static boolean hasNoUnscopedTopics() { return null==BuilderImpl.unScopedTopics; } @Override public void setGlobalSLALatencyNS(long ns) { GraphManager.addDefaultNota(gm, GraphManager.SLA_LATENCY, ns); } @Override public long lookupFieldByName(int id, String name) { if ((id & StructRegistry.IS_STRUCT_BIT) == 0) { //this is a route so we must covert to struct id = routerConfig.getStructIdForRouteId(id); } return gm.recordTypeData.fieldLookup(name, id); } @Override public long lookupFieldByIdentity(int id, Object obj) { if ((id & StructRegistry.IS_STRUCT_BIT) == 0) { //this is a route so we must covert to struct id = routerConfig.getStructIdForRouteId(id); } return gm.recordTypeData.fieldLookupByIdentity(obj, id); } @Override public StructBuilder defineStruct() { return StructBuilder.newStruct(gm.recordTypeData); } @Override public StructBuilder extendStruct(StructBuilder template) { return StructBuilder.newStruct(gm.recordTypeData, template); } private ArrayList<ReactiveListenerStage> pendingReactiveStages = new ArrayList<ReactiveListenerStage>(); /** * Store the reactive listeners until they are all created. * The actual stages are created at once after they are all registered. * @param reactiveListenerStage */ public void pendingInit(ReactiveListenerStage<?> reactiveListenerStage) { pendingReactiveStages.add(reactiveListenerStage); } public void initAllPendingReactors() { if (null!=pendingReactiveStages) { if (enableAutoPrivateTopicDiscovery) { defineAutoDiscoveredPrivateTopcis();//must be done before the initRealStage call. } for(ReactiveListenerStage stage: pendingReactiveStages) { stage.initRealStage(); } pendingReactiveStages = null; } } /////////////Auto discovery of private topics //find topic matches where we have 1 channel producer and 1 behavior consumer private TrieParser possibleTopics = new TrieParser(); private int possiblePrivateTopicsCount = 0; private MsgCommandChannel[] possiblePrivateCmds = new MsgCommandChannel[16]; //ReactiveListenerStage private ArrayList[] possiblePrivateBehaviors = new ArrayList[16]; private int[] possiblePrivateTopicsProducerCount = new int[16]; private CharSequence[] possiblePrivateTopicsTopic = new CharSequence[16]; public void possiblePrivateTopicProducer(MsgCommandChannel<?> cmdChannel, String topic) { int id = (int)TrieParserReaderLocal.get().query(possibleTopics, topic); if (-1 == id) { growPossiblePrivateTopics(); possiblePrivateCmds[possiblePrivateTopicsCount] = cmdChannel; possiblePrivateTopicsTopic[possiblePrivateTopicsCount]=topic; possiblePrivateTopicsProducerCount[possiblePrivateTopicsCount]++; possibleTopics.setUTF8Value(topic, possiblePrivateTopicsCount++); } else { //only record once for same channel and topic pair if (cmdChannel != possiblePrivateCmds[id]) { possiblePrivateCmds[id] = cmdChannel; possiblePrivateTopicsProducerCount[id]++; } } } public void possiblePrivateTopicConsumer(ReactiveListenerStage listener, CharSequence topic) { int id = (int)TrieParserReaderLocal.get().query(possibleTopics, topic); if (-1 == id) { growPossiblePrivateTopics(); if (null==possiblePrivateBehaviors[possiblePrivateTopicsCount]) { possiblePrivateBehaviors[possiblePrivateTopicsCount] = new ArrayList(); } possiblePrivateBehaviors[possiblePrivateTopicsCount].add(listener); possiblePrivateTopicsTopic[possiblePrivateTopicsCount]=topic; //new Exception("added topic "+topic+" now consumers total "+possiblePrivateBehaviors[possiblePrivateTopicsCount].size()+" position "+possiblePrivateTopicsCount).printStackTrace();; possibleTopics.setUTF8Value(topic, possiblePrivateTopicsCount++); } else { if (null==possiblePrivateBehaviors[id]) { possiblePrivateBehaviors[id] = new ArrayList(); } possiblePrivateBehaviors[id].add(listener); } } private void growPossiblePrivateTopics() { if (possiblePrivateTopicsCount == possiblePrivateBehaviors.length) { //grow MsgCommandChannel[] newCmds = new MsgCommandChannel[possiblePrivateTopicsCount*2]; System.arraycopy(possiblePrivateCmds, 0, newCmds, 0, possiblePrivateTopicsCount); possiblePrivateCmds = newCmds; ArrayList[] newBeh = new ArrayList[possiblePrivateTopicsCount*2]; System.arraycopy(possiblePrivateBehaviors, 0, newBeh, 0, possiblePrivateTopicsCount); possiblePrivateBehaviors = newBeh; int[] newProducer = new int[possiblePrivateTopicsCount*2]; System.arraycopy(possiblePrivateTopicsProducerCount, 0, newProducer, 0, possiblePrivateTopicsCount); possiblePrivateTopicsProducerCount = newProducer; String[] newTopics = new String[possiblePrivateTopicsCount*2]; System.arraycopy(possiblePrivateTopicsTopic, 0, newTopics, 0, possiblePrivateTopicsCount); possiblePrivateTopicsTopic = newTopics; } } public void defineAutoDiscoveredPrivateTopcis() { //logger.info("possible private topics {} ",possiblePrivateTopicsCount); int actualPrivateTopicsFound = 0; int i = possiblePrivateTopicsCount; while (--i>=0) { String topic = possiblePrivateTopicsTopic[i].toString(); //logger.info("possible private topic {} {}->{}",topic, possiblePrivateTopicsProducerCount[i], null==possiblePrivateBehaviors[i] ? -1 :possiblePrivateBehaviors[i].size()); boolean madePrivate = false; String reasonSkipped = ""; final int consumers = (null==possiblePrivateBehaviors[i]) ? 0 : possiblePrivateBehaviors[i].size(); if (possiblePrivateTopicsProducerCount[i]==1) { if ((null!=possiblePrivateBehaviors[i]) && ((possiblePrivateBehaviors[i].size())>=1)) { //may be valid check that is is not on the list. if (!skipTopic(topic)) { MsgCommandChannel msgCommandChannel = possiblePrivateCmds[i]; String producerName = msgCommandChannel.behaviorName(); if (null!=producerName) { int j = possiblePrivateBehaviors[i].size(); if (j >= 1) { actualPrivateTopicsFound++; } while (--j>=0) { String consumerName = ((ReactiveListenerStage)(possiblePrivateBehaviors[i].get(j))).behaviorName(); if (null!=consumerName) { definePrivateTopic(msgCommandChannel.pcm.getConfig(MessagePrivate.class), topic, producerName, consumerName); madePrivate = true; } } } else { reasonSkipped = "Reason: Behavior had no name"; } } else { reasonSkipped = "Reason: Explicitly set as not to be private in behavior"; } } else { reasonSkipped = "Reason: Must have 1 or more consumers"; } } else { reasonSkipped = "Reason: Must have single producer"; } logger.info("MadePrivate: {} Topic: {} Producers: {} Consumers: {} {} ", madePrivate, topic, possiblePrivateTopicsProducerCount[i], consumers, reasonSkipped); } //hack test as we figure out what TODO: about this if (actualPrivateTopicsFound == possiblePrivateTopicsCount && (!messageRoutingRequired)) { isAllPrivateTopics = true; } } //iterate over single matches private boolean skipTopic(CharSequence topic) { boolean skipTopic = false; int w = publicTopics.size(); while (--w>=0) { if (isFoundInArray(topic, w)) { skipTopic = true; break; } } return skipTopic; } private boolean isFoundInArray(CharSequence topic, int w) { String[] s = publicTopics.get(w); int x = s.length; while (--x>=0) { if (isMatch(topic, s, x)) { return true; } } return false; } private boolean isMatch(CharSequence topic, String[] s, int x) { if (topic.length() == s[x].length()) { int z = topic.length(); while (--z >= 0) { if (topic.charAt(z) != s[x].charAt(z)) { return false; } } } else { return false; } return true; } public void populateListenerIdentityHash(Behavior listener) { //store this value for lookup later //logger.info("adding hash listener {} to pipe ",System.identityHashCode(listener)); if (!IntHashTable.setItem(subscriptionPipeLookup, System.identityHashCode(listener), subscriptionPipeIdx++)) { throw new RuntimeException("Could not find unique identityHashCode for "+listener.getClass().getCanonicalName()); } assert(!IntHashTable.isEmpty(subscriptionPipeLookup)); } public void populateListenerIdentityHash(int hash) { //store this value for lookup later //logger.info("adding hash listener {} to pipe ",System.identityHashCode(listener)); if (!IntHashTable.setItem(subscriptionPipeLookup, hash, subscriptionPipeIdx++)) { throw new RuntimeException("Could not find unique identityHashCode for "+hash); } assert(!IntHashTable.isEmpty(subscriptionPipeLookup)); } public IntHashTable getSubPipeLookup() { return subscriptionPipeLookup; } public void setCleanShutdownRunnable(Runnable cleanRunnable) { cleanShutdownRunnable = cleanRunnable; } public void setDirtyShutdownRunnable(Runnable dirtyRunnable) { dirtyShutdownRunnable = dirtyRunnable; } public void requestShutdown() { requestShutdown(3); } public void requestShutdown(int secondsTimeout) { if (ReactiveListenerStage.isShutdownRequested(this)) { return;//do not do again. } final Runnable lastCallClean = new Runnable() { @Override public void run() { //all the software has now stopped so shutdown the hardware now. shutdown(); if (null!=cleanShutdownRunnable) { cleanShutdownRunnable.run(); } } }; final Runnable lastCallDirty = new Runnable() { @Override public void run() { //all the software has now stopped so shutdown the hardware now. shutdown(); if (null!=dirtyShutdownRunnable) { dirtyShutdownRunnable.run(); } } }; //notify all the reactors to begin shutdown. ReactiveListenerStage.requestSystemShutdown(this, new Runnable() { @Override public void run() { logger.info("Scheduler {} shutdown ", scheduler.getClass().getSimpleName()); scheduler.shutdown(); scheduler.awaitTermination(secondsTimeout, TimeUnit.SECONDS, lastCallClean, lastCallDirty); } }); } public void setScheduler(StageScheduler s) { this.scheduler = s; } public StageScheduler getScheduler() { return this.scheduler; } private boolean messageRoutingRequired = false; public void messageRoutingRequired() { messageRoutingRequired = true; } public int lookupTargetPipe(ClientHostPortInstance session, Behavior listener) { int lookupHTTPClientPipe; if (hasHTTPClientPipe(session.sessionId)) { lookupHTTPClientPipe = lookupHTTPClientPipe(session.sessionId); } else { lookupHTTPClientPipe = lookupHTTPClientPipe(behaviorId(listener)); } return lookupHTTPClientPipe; } public void populatePrivateTopicPipeNames(byte[][] names) { int t = privateSourceTopics.size(); while (--t>=0) { List<PrivateTopic> local = privateSourceTopics.get(t); if (null!=local) { int l = local.size(); while (--l>=0) { local.get(l).populatePrivateTopicPipeNames(names); } } } } }
package org.languagetool.rules.en; import org.languagetool.Language; import org.languagetool.languagemodel.LanguageModel; import org.languagetool.rules.ngrams.ConfusionProbabilityRule; import org.languagetool.rules.Example; import java.util.Arrays; import java.util.List; import java.util.ResourceBundle; /** * @since 2.7 */ public class EnglishConfusionProbabilityRule extends ConfusionProbabilityRule { private static final List<String> EXCEPTIONS = Arrays.asList( // Use all-lowercase, matches will be case-insensitive. "your slack profile", "host to five", // "... is host to five classical music orchestras" "had I known", "is not exactly known", "live duet", "isn't known", "your move makes", "your move is", "he unchecked the", "thank you for the patience", "your patience regarding", "your fix", // fix = bug fix "your commit", "on point", "chapter one", "usb port", // The quote in this case in management means: "Know the competition and your software, and you will win.": "know the competition and", "know the competition or", "know your competition and", "know your competition or", "G Suite", "paste event", "need to know", "of you not", // "It would be wiser of you not to see him again." "of her element", "very grateful of you", "your use case", "he's", // vs. the's "he’s", "they're", "they’re", "your look is", // Really, your look is "have you known",// vs. "know" "have I known",// vs. "know" "had I known", "had you known", "his fluffy butt", "it's now better", // vs. no "it’s now better", // vs. no "it is now better", // vs. no "let us know below", "let us know in", "your kind of", "sneak peek", "the 4 of you", "your ride", "he most likely", "good cause", "big butt", "news debate", "verify you own", "ensure you own", "happy us!", "your pick up", "no but you", "no but we", "no but he", "no but I", "no but they", "no but she", "no but it", "he tracks", "which complains about", // vs complaints "do your work", // vs "you" "one many times", // vs "on" "let us know", "let me know", "this way the", "save you money", "way better", "so your plan", "the news man", "created us equally", ", their,", ", your,", ", its,", "us, humans,", "bring you happiness", "in a while", "confirm you own", "oh, god", "honey nut", "not now", "he proofs", "he needs", "1 thing", "way easier", "way faster", "way quicker", "way more", "way less", "way outside", "I now don't", "once your return is", "can we text", "believe in god", "on premise", "from poor to rich", "my GPU", "was your everything", "they mustnt", // different error "reply my email", "things god said", "let you text", "doubt in god", "in the news", "(news)", "fresh prince of", "good day bye", "it's us", "could be us being", // vs is "on twitter", // vs in "enjoy us being", // vs is "If your use of", // vs you "way too much", // vs was "way too early", // vs was "way too soon", // vs was "way too quick", // vs was "then,", // vs than "then?", // vs than "no it doesn", // vs know "no it isn", "no it wasn", "no it hasn", "no it can't", "no it won't", "no it wouldn", "no it couldn", "no it shouldn", "no that's not", // vs know "provided my country", "no i don't", "no i can't", "no i won't", "no i wasn", "no i haven", "no i wouldn", "no i couldn", "no i shouldn", "no you don't", "no you can't", "no you won't", "no you weren", "no you haven", "no you wouldn", "no you couldn", "no you shouldn", "for your recharge", // vs you "all you kids", // vs your "thanks for the patience", // vs patients "what to text", // vs do "is he famous for", // vs the "was he famous for", // the "really quiet at", // vs quit/quite "he programs", // vs the "scene 1", // vs seen "scene 2", "scene 3", "scene 4", "scene 5", "scene 6", "scene 7", "scene 8", "scene 9", "scene 10", "scene 11", "scene 12", "scene 13", "scene 14", "scene 15", "make a hire", "on the news", "brown plane", "news politics", "organic reach", "out bid", "message us in", "I picture us", "your and our", // vs you "house and pool", "your set up is", "your set up was", "because your pay is", "but your pay is", "the while block", // dev speech "updated my edge", // vs by "he haven", // vs the "is he naked", // vs the "these news sound", // vs new "those news sound", // vs new "(t)he", // vs the "[t]he", // vs the "the role at", // vs add "same false alarm", // vs some "why is he relevant", // vs the "then that would", // vs than "was he part of", // vs the "is he right now", // vs the "news site", "news website", "news organization", "news organisation", "scene in a movie", "mr.bean", // vs been "mr. bean", // vs been "your push notification" // vs you ); public EnglishConfusionProbabilityRule(ResourceBundle messages, LanguageModel languageModel, Language language) { this(messages, languageModel, language, 3); } public EnglishConfusionProbabilityRule(ResourceBundle messages, LanguageModel languageModel, Language language, int grams) { super(messages, languageModel, language, grams, EXCEPTIONS); addExamplePair(Example.wrong("I did not <marker>now</marker> where it came from."), Example.fixed("I did not <marker>know</marker> where it came from.")); } @Override protected boolean isException(String sentence, int startPos, int endPos) { if (startPos > 3) { String covered = sentence.substring(startPos-3, endPos); // the Google ngram data expands negated contractions like this: "Negations (n't) are normalized so // We don't deal with that yet (see GoogleStyleWordTokenizer), so ignore for now: if (covered.matches("['’`´‘]t .*")) { return true; } } return false; } }
package com.scylladb.jmx.api; import java.io.StringReader; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.function.BiFunction; import java.util.logging.Logger; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonReader; import javax.json.JsonReaderFactory; import javax.json.JsonString; import javax.management.openmbean.TabularData; import javax.management.openmbean.TabularDataSupport; import javax.ws.rs.ProcessingException; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import org.glassfish.jersey.client.ClientConfig; import com.scylladb.jmx.utils.SnapshotDetailsTabularData; public class APIClient { private Map<String, CacheEntry> cache = new HashMap<String, CacheEntry>(); private String getCacheKey(String key, MultivaluedMap<String, String> param, long duration) { if (duration <= 0) { return null; } if (param != null) { StringBuilder sb = new StringBuilder(key); sb.append("?"); for (String k : param.keySet()) { sb.append(k).append('=').append(param.get(k)).append('&'); } return sb.toString(); } return key; } private String getStringFromCache(String key, long duration) { if (key == null) { return null; } CacheEntry value = cache.get(key); return (value != null && value.valid(duration)) ? value.stringValue() : null; } private JsonObject getJsonObjectFromCache(String key, long duration) { if (key == null) { return null; } CacheEntry value = cache.get(key); return (value != null && value.valid(duration)) ? value.jsonObject() : null; } private JsonReaderFactory factory = Json.createReaderFactory(null); private static final Logger logger = Logger.getLogger(APIClient.class.getName()); private final APIConfig config; public APIClient(APIConfig config) { this.config = config; } private String getBaseUrl() { return config.getBaseUrl(); } public Invocation.Builder get(String path, MultivaluedMap<String, String> queryParams) { Client client = ClientBuilder.newClient(new ClientConfig()); WebTarget webTarget = client.target(getBaseUrl()).path(path); if (queryParams != null) { for (Entry<String, List<String>> qp : queryParams.entrySet()) { for (String e : qp.getValue()) { webTarget = webTarget.queryParam(qp.getKey(), e); } } } return webTarget.request(MediaType.APPLICATION_JSON); } public Invocation.Builder get(String path) { return get(path, null); } public Response post(String path, MultivaluedMap<String, String> queryParams) { return post(path, queryParams, null); } public Response post(String path, MultivaluedMap<String, String> queryParams, Object object, String type) { try { Response response = get(path, queryParams).post(Entity.entity(object, type)); if (response.getStatus() != Response.Status.OK.getStatusCode()) { throw getException("Scylla API server HTTP POST to URL '" + path + "' failed", response.readEntity(String.class)); } return response; } catch (ProcessingException e) { throw new IllegalStateException("Unable to connect to Scylla API server: " + e.getMessage()); } } public Response post(String path, MultivaluedMap<String, String> queryParams, Object object) { return post(path, queryParams, object, MediaType.TEXT_PLAIN); } public void post(String path) { post(path, null); } public IllegalStateException getException(String msg, String json) { JsonReader reader = factory.createReader(new StringReader(json)); JsonObject res = reader.readObject(); return new IllegalStateException(msg + ": " + res.getString("message")); } public String postGetVal(String path, MultivaluedMap<String, String> queryParams) { return post(path, queryParams).readEntity(String.class); } public int postInt(String path, MultivaluedMap<String, String> queryParams) { return Integer.parseInt(postGetVal(path, queryParams)); } public int postInt(String path) { return postInt(path, null); } public void delete(String path, MultivaluedMap<String, String> queryParams) { if (queryParams != null) { get(path, queryParams).delete(); return; } get(path).delete(); } public void delete(String path) { delete(path, null); } public String getRawValue(String string, MultivaluedMap<String, String> queryParams, long duration) { try { if (string.equals("")) { return ""; } String key = getCacheKey(string, queryParams, duration); String res = getStringFromCache(key, duration); if (res != null) { return res; } Response response = get(string, queryParams).get(Response.class); if (response.getStatus() != Response.Status.OK.getStatusCode()) { // TBD // We are currently not caching errors, // it should be reconsider. throw getException("Scylla API server HTTP GET to URL '" + string + "' failed", response.readEntity(String.class)); } res = response.readEntity(String.class); if (duration > 0) { cache.put(key, new CacheEntry(res)); } return res; } catch (ProcessingException e) { throw new IllegalStateException("Unable to connect to Scylla API server: " + e.getMessage()); } } public String getRawValue(String string, MultivaluedMap<String, String> queryParams) { return getRawValue(string, queryParams, 0); } public String getRawValue(String string, long duration) { return getRawValue(string, null, duration); } public String getRawValue(String string) { return getRawValue(string, null, 0); } public String getStringValue(String string, MultivaluedMap<String, String> queryParams) { return getRawValue(string, queryParams).replaceAll("^\"|\"$", ""); } public String getStringValue(String string, MultivaluedMap<String, String> queryParams, long duration) { return getRawValue(string, queryParams, duration).replaceAll("^\"|\"$", ""); } public String getStringValue(String string) { return getStringValue(string, null); } public JsonReader getReader(String string, MultivaluedMap<String, String> queryParams) { return factory.createReader(new StringReader(getRawValue(string, queryParams))); } public JsonReader getReader(String string) { return getReader(string, null); } public String[] getStringArrValue(String string) { List<String> val = getListStrValue(string); return val.toArray(new String[val.size()]); } public int getIntValue(String string, MultivaluedMap<String, String> queryParams) { return Integer.parseInt(getRawValue(string, queryParams)); } public int getIntValue(String string) { return getIntValue(string, null); } public static <T> BiFunction<APIClient, String, T> getReader(Class<T> type) { if (type == String.class) { return (c, s) -> type.cast(c.getRawValue(s)); } else if (type == Integer.class) { return (c, s) -> type.cast(c.getIntValue(s)); } else if (type == Double.class) { return (c, s) -> type.cast(c.getDoubleValue(s)); } else if (type == Long.class) { return (c, s) -> type.cast(c.getLongValue(s)); } throw new IllegalArgumentException(type.getName()); } public boolean getBooleanValue(String string) { return Boolean.parseBoolean(getRawValue(string)); } public double getDoubleValue(String string) { return Double.parseDouble(getRawValue(string)); } public List<String> getListStrValue(String string, MultivaluedMap<String, String> queryParams) { JsonReader reader = getReader(string, queryParams); JsonArray arr = reader.readArray(); List<String> res = new ArrayList<String>(arr.size()); for (int i = 0; i < arr.size(); i++) { res.add(arr.getString(i)); } reader.close(); return res; } public List<String> getListStrValue(String string) { return getListStrValue(string, null); } public static List<String> listStrFromJArr(JsonArray arr) { List<String> res = new ArrayList<String>(); for (int i = 0; i < arr.size(); i++) { res.add(arr.getString(i)); } return res; } public static Map<String, String> mapStrFromJArr(JsonArray arr) { Map<String, String> res = new HashMap<String, String>(); for (int i = 0; i < arr.size(); i++) { JsonObject obj = arr.getJsonObject(i); if (obj.containsKey("key") && obj.containsKey("value")) { res.put(obj.getString("key"), obj.getString("value")); } } return res; } public static String join(String[] arr, String joiner) { String res = ""; if (arr != null) { for (String name : arr) { if (name != null && !name.equals("")) { if (!res.equals("")) { res = res + ","; } res = res + name; } } } return res; } public static String join(String[] arr) { return join(arr, ","); } public static String mapToString(Map<String, String> mp, String pairJoin, String joiner) { String res = ""; if (mp != null) { for (String name : mp.keySet()) { if (!res.equals("")) { res = res + joiner; } res = res + name + pairJoin + mp.get(name); } } return res; } public static String mapToString(Map<String, String> mp) { return mapToString(mp, "=", ","); } public static boolean set_query_param(MultivaluedMap<String, String> queryParams, String key, String value) { if (queryParams != null && key != null && value != null && !value.equals("")) { queryParams.add(key, value); return true; } return false; } public static boolean set_bool_query_param(MultivaluedMap<String, String> queryParams, String key, boolean value) { if (queryParams != null && key != null && value) { queryParams.add(key, "true"); return true; } return false; } public Map<String, List<String>> getMapStringListStrValue(String string, MultivaluedMap<String, String> queryParams) { if (string.equals("")) { return null; } JsonReader reader = getReader(string, queryParams); JsonArray arr = reader.readArray(); Map<String, List<String>> map = new HashMap<String, List<String>>(); for (int i = 0; i < arr.size(); i++) { JsonObject obj = arr.getJsonObject(i); if (obj.containsKey("key") && obj.containsKey("value")) { map.put(obj.getString("key"), listStrFromJArr(obj.getJsonArray("value"))); } } reader.close(); return map; } public Map<String, List<String>> getMapStringListStrValue(String string) { return getMapStringListStrValue(string, null); } public Map<List<String>, List<String>> getMapListStrValue(String string, MultivaluedMap<String, String> queryParams) { if (string.equals("")) { return null; } JsonReader reader = getReader(string, queryParams); JsonArray arr = reader.readArray(); Map<List<String>, List<String>> map = new HashMap<List<String>, List<String>>(); for (int i = 0; i < arr.size(); i++) { JsonObject obj = arr.getJsonObject(i); if (obj.containsKey("key") && obj.containsKey("value")) { map.put(listStrFromJArr(obj.getJsonArray("key")), listStrFromJArr(obj.getJsonArray("value"))); } } reader.close(); return map; } public Map<List<String>, List<String>> getMapListStrValue(String string) { return getMapListStrValue(string, null); } public Set<String> getSetStringValue(String string, MultivaluedMap<String, String> queryParams) { JsonReader reader = getReader(string, queryParams); JsonArray arr = reader.readArray(); Set<String> res = new HashSet<String>(); for (int i = 0; i < arr.size(); i++) { res.add(arr.getString(i)); } reader.close(); return res; } public Set<String> getSetStringValue(String string) { return getSetStringValue(string, null); } public Map<String, String> getMapStrValue(String string, MultivaluedMap<String, String> queryParams) { if (string.equals("")) { return null; } JsonReader reader = getReader(string, queryParams); JsonArray arr = reader.readArray(); Map<String, String> map = new LinkedHashMap<String, String>(); for (int i = 0; i < arr.size(); i++) { JsonObject obj = arr.getJsonObject(i); if (obj.containsKey("key") && obj.containsKey("value")) { map.put(obj.getString("key"), obj.getString("value")); } } reader.close(); return map; } public Map<String, String> getMapStrValue(String string) { return getMapStrValue(string, null); } public Map<String, String> getReverseMapStrValue(String string, MultivaluedMap<String, String> queryParams) { if (string.equals("")) { return null; } JsonReader reader = getReader(string, queryParams); JsonArray arr = reader.readArray(); Map<String, String> map = new HashMap<String, String>(); for (int i = 0; i < arr.size(); i++) { JsonObject obj = arr.getJsonObject(i); if (obj.containsKey("key") && obj.containsKey("value")) { map.put(obj.getString("value"), obj.getString("key")); } } reader.close(); return map; } public Map<String, String> getReverseMapStrValue(String string) { return getReverseMapStrValue(string, null); } public List<InetAddress> getListInetAddressValue(String string, MultivaluedMap<String, String> queryParams) { List<String> vals = getListStrValue(string, queryParams); List<InetAddress> res = new ArrayList<InetAddress>(); for (String val : vals) { try { res.add(InetAddress.getByName(val)); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return res; } public List<InetAddress> getListInetAddressValue(String string) { return getListInetAddressValue(string, null); } public Map<String, TabularData> getMapStringTabularDataValue(String string) { // TODO Auto-generated method stub return null; } private TabularDataSupport getSnapshotData(String key, JsonArray arr) { TabularDataSupport data = new TabularDataSupport(SnapshotDetailsTabularData.TABULAR_TYPE); for (int i = 0; i < arr.size(); i++) { JsonObject obj = arr.getJsonObject(i); if (obj.containsKey("ks") && obj.containsKey("cf")) { SnapshotDetailsTabularData.from(key, obj.getString("ks"), obj.getString("cf"), obj.getInt("total"), obj.getInt("live"), data); } } return data; } public Map<String, TabularData> getMapStringSnapshotTabularDataValue(String string, MultivaluedMap<String, String> queryParams) { if (string.equals("")) { return null; } JsonReader reader = getReader(string, queryParams); JsonArray arr = reader.readArray(); Map<String, TabularData> map = new HashMap<>(); for (int i = 0; i < arr.size(); i++) { JsonObject obj = arr.getJsonObject(i); if (obj.containsKey("key") && obj.containsKey("value")) { String key = obj.getString("key"); map.put(key, getSnapshotData(key, obj.getJsonArray("value"))); } } reader.close(); return map; } public long getLongValue(String string) { return Long.parseLong(getRawValue(string)); } public Map<InetAddress, Float> getMapInetAddressFloatValue(String string, MultivaluedMap<String, String> queryParams) { Map<InetAddress, Float> res = new HashMap<InetAddress, Float>(); JsonReader reader = getReader(string, queryParams); JsonArray arr = reader.readArray(); JsonObject obj = null; for (int i = 0; i < arr.size(); i++) { try { obj = arr.getJsonObject(i); res.put(InetAddress.getByName(obj.getString("key")), Float.parseFloat(obj.getString("value"))); } catch (UnknownHostException e) { logger.warning("Bad formatted address " + obj.getString("key")); } } return res; } public Map<InetAddress, Float> getMapInetAddressFloatValue(String string) { return getMapInetAddressFloatValue(string, null); } public Map<String, Long> getMapStringLongValue(String string, MultivaluedMap<String, String> queryParams) { Map<String, Long> res = new HashMap<String, Long>(); JsonReader reader = getReader(string, queryParams); JsonArray arr = reader.readArray(); JsonObject obj = null; for (int i = 0; i < arr.size(); i++) { obj = arr.getJsonObject(i); res.put(obj.getString("key"), obj.getJsonNumber("value").longValue()); } return res; } public Map<String, Long> getMapStringLongValue(String string) { return getMapStringLongValue(string, null); } public long[] getLongArrValue(String string, MultivaluedMap<String, String> queryParams) { JsonReader reader = getReader(string, queryParams); JsonArray arr = reader.readArray(); long[] res = new long[arr.size()]; for (int i = 0; i < arr.size(); i++) { res[i] = arr.getJsonNumber(i).longValue(); } reader.close(); return res; } public long[] getLongArrValue(String string) { return getLongArrValue(string, null); } public Map<String, Integer> getMapStringIntegerValue(String string, MultivaluedMap<String, String> queryParams) { Map<String, Integer> res = new HashMap<String, Integer>(); JsonReader reader = getReader(string, queryParams); JsonArray arr = reader.readArray(); JsonObject obj = null; for (int i = 0; i < arr.size(); i++) { obj = arr.getJsonObject(i); res.put(obj.getString("key"), obj.getInt("value")); } return res; } public Map<String, Integer> getMapStringIntegerValue(String string) { return getMapStringIntegerValue(string, null); } public int[] getIntArrValue(String string, MultivaluedMap<String, String> queryParams) { JsonReader reader = getReader(string, queryParams); JsonArray arr = reader.readArray(); int[] res = new int[arr.size()]; for (int i = 0; i < arr.size(); i++) { res[i] = arr.getInt(i); } reader.close(); return res; } public int[] getIntArrValue(String string) { return getIntArrValue(string, null); } public Map<String, Long> getListMapStringLongValue(String string, MultivaluedMap<String, String> queryParams) { if (string.equals("")) { return null; } JsonReader reader = getReader(string, queryParams); JsonArray arr = reader.readArray(); Map<String, Long> map = new HashMap<String, Long>(); for (int i = 0; i < arr.size(); i++) { JsonObject obj = arr.getJsonObject(i); Iterator<String> it = obj.keySet().iterator(); String key = ""; long val = -1; while (it.hasNext()) { String k = it.next(); if (obj.get(k) instanceof JsonString) { key = obj.getString(k); } else { val = obj.getJsonNumber(k).longValue(); } } if (val > 0 && !key.equals("")) { map.put(key, val); } } reader.close(); return map; } public Map<String, Long> getListMapStringLongValue(String string) { return getListMapStringLongValue(string, null); } public JsonArray getJsonArray(String string, MultivaluedMap<String, String> queryParams) { if (string.equals("")) { return null; } JsonReader reader = getReader(string, queryParams); JsonArray res = reader.readArray(); reader.close(); return res; } public JsonArray getJsonArray(String string) { return getJsonArray(string, null); } public List<Map<String, String>> getListMapStrValue(String string, MultivaluedMap<String, String> queryParams) { JsonArray arr = getJsonArray(string, queryParams); List<Map<String, String>> res = new ArrayList<Map<String, String>>(); for (int i = 0; i < arr.size(); i++) { res.add(mapStrFromJArr(arr.getJsonArray(i))); } return res; } public List<Map<String, String>> getListMapStrValue(String string) { return getListMapStrValue(string, null); } public TabularData getCQLResult(String string) { // TODO Auto-generated method stub return null; } public JsonObject getJsonObj(String string, MultivaluedMap<String, String> queryParams, long duration) { if (string.equals("")) { return null; } String key = getCacheKey(string, queryParams, duration); JsonObject res = getJsonObjectFromCache(key, duration); if (res != null) { return res; } JsonReader reader = getReader(string, queryParams); res = reader.readObject(); reader.close(); if (duration > 0) { cache.put(key, new CacheEntry(res)); } return res; } public JsonObject getJsonObj(String string, MultivaluedMap<String, String> queryParams) { return getJsonObj(string, queryParams, 0); } public long[] getEstimatedHistogramAsLongArrValue(String string, MultivaluedMap<String, String> queryParams) { JsonObject obj = getJsonObj(string, queryParams); JsonArray arr = obj.getJsonArray("buckets"); if (arr == null) { return new long[0]; } long res[] = new long[arr.size()]; for (int i = 0; i < arr.size(); i++) { res[i] = arr.getJsonNumber(i).longValue(); } return res; } public long[] getEstimatedHistogramAsLongArrValue(String string) { return getEstimatedHistogramAsLongArrValue(string, null); } public Map<String, Double> getMapStringDouble(String string, MultivaluedMap<String, String> queryParams) { if (string.equals("")) { return null; } JsonReader reader = getReader(string, queryParams); JsonArray arr = reader.readArray(); Map<String, Double> map = new HashMap<String, Double>(); for (int i = 0; i < arr.size(); i++) { JsonObject obj = arr.getJsonObject(i); Iterator<String> it = obj.keySet().iterator(); String key = ""; double val = -1; while (it.hasNext()) { String k = it.next(); if (obj.get(k) instanceof JsonString) { key = obj.getString(k); } else { val = obj.getJsonNumber(k).doubleValue(); } } if (!key.equals("")) { map.put(key, val); } } reader.close(); return map; } public Map<String, Double> getMapStringDouble(String string) { return getMapStringDouble(string, null); } }
package com.shawn.dev; import java.util.regex.Pattern; public class SmoothExpression { public SmoothExpression(final Pattern pattern) { this.pattern = pattern; } public String getRegularExpression() { return this.pattern.pattern(); } public boolean matches(String target) { return pattern.matcher(target).matches(); } private final Pattern pattern; public static ExpressionBuilder regex() { return new ExpressionBuilder(); } public static class ExpressionBuilder { private StringBuilder prefix = new StringBuilder(); private StringBuilder patternContent = new StringBuilder(); private StringBuilder suffix = new StringBuilder(); private int modifiers = Pattern.MULTILINE; ExpressionBuilder() { } private ExpressionBuilder add(String content) { patternContent.append("(?:" + content + ")"); return this; } public ExpressionBuilder anything() { this.add("[\\s\\S]*"); return this; } public ExpressionBuilder anythingBut(String content) { this.add("[^" + content + "]*"); return this; } public ExpressionBuilder startOfLine() { this.add("^"); return this; } public ExpressionBuilder endOfLine() { this.add("$"); return this; } public ExpressionBuilder singleDigit() { this.add("\\d"); return this; } public ExpressionBuilder integerNumber() { this.add("\\d+"); return this; } public ExpressionBuilder floatNumber() { this.add(""); return this; } public ExpressionBuilder wordChar() { return this; } public ExpressionBuilder nonWordChar() { return this; } public ExpressionBuilder then(final String content) { this.add(content); return this; } public ExpressionBuilder capture() { patternContent.append("("); return this; } public ExpressionBuilder endCapture() { patternContent.append(")"); return this; } public ExpressionBuilder oneOrMore() { return this; } public ExpressionBuilder zeroOrMore() { return this; } public ExpressionBuilder maybe(final String content) { return this; } public ExpressionBuilder addModifier(final char pModifier) { switch (pModifier) { case 'd': modifiers |= Pattern.UNIX_LINES; break; case 'i': modifiers |= Pattern.CASE_INSENSITIVE; break; case 'x': modifiers |= Pattern.COMMENTS; break; case 'm': modifiers |= Pattern.MULTILINE; break; case 's': modifiers |= Pattern.DOTALL; break; case 'u': modifiers |= Pattern.UNICODE_CASE; break; case 'U': modifiers |= Pattern.UNICODE_CHARACTER_CLASS; break; default: break; } return this; } public ExpressionBuilder removeModifier(final char pModifier) { switch (pModifier) { case 'd': modifiers &= ~Pattern.UNIX_LINES; break; case 'i': modifiers &= ~Pattern.CASE_INSENSITIVE; break; case 'x': modifiers &= ~Pattern.COMMENTS; break; case 'm': modifiers &= ~Pattern.MULTILINE; break; case 's': modifiers &= ~Pattern.DOTALL; break; case 'u': modifiers &= ~Pattern.UNICODE_CASE; break; case 'U': modifiers &= ~Pattern.UNICODE_CHARACTER_CLASS; break; default: break; } return this; } public SmoothExpression build() { Pattern pattern = Pattern.compile( this.prefix.toString() + this.patternContent.toString() + this.suffix.toString(), modifiers); return new SmoothExpression(pattern); } } public static void main(String[] args) { SmoothExpression exp = SmoothExpression.regex().then("he").anything().anythingBut("o").build(); System.out.println(exp.getRegularExpression()); System.out.println(exp.matches("hello")); } }
package com.trinia.blocks; import net.minecraft.block.Block; import net.minecraft.block.BlockTorch; import net.minecraft.block.material.Material; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.item.Item; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fml.common.registry.GameRegistry; import com.trinia.Reference; import com.trinia.TriniaMod; import com.trinia.tileentity.TileEntityTriniaWorkBench; public class TriniaBlocks { //World gen Blocks Trinia World public static Block triniaCobblestone; public static Block triniaGrass; public static Block triniaDirt; public static Block triniaStone; public static Block triniaStoneBrick; public static Block triniaMossyStoneBrick; public static Block triniaChiseledStoneBrick; public static Block triniaCrackedStoneBrick; public static Block triniaMossyCobblestone; public static Block triniaGravel; public static Block steelOre; public static Block copperOre; public static Block silverOre; public static Block tinOre; public static Block redLeaves; public static Block greenLeaves; public static Block purpleLeaves; public static Block yellowLeaves; public static Block blueLeaves; public static Block FlowerStem; public static Block FlowerBlue; public static Block FlowerGreen; public static Block FlowerOrange; public static Block FlowerPink; public static Block FlowerPurple; public static Block FlowerRed; public static Block FlowerYellow; public static Block MagicalBed; public static Block CastingBench; public static Block triniaDeadGrass; //Trinia Blocks public static Block steelBlock; public static Block copperBlock; public static Block silverBlock; public static Block tinBlock; public static Block hardenedBucket; public static Block hardenedBucketLava; public static Block hardenedBucketSilver; public static Block hardenedBucketSteel; public static Block hardenedBucketTin; public static Block hardenedBucketCopper; public static Block cloud; public static Block bluecloud; public static Block goldenBrick; public static Block goldenDoor; public static Block goldenKeyHole; public static Block goldenPillar; //World Gen Blocks Medeival World public static Block adimiteOre; public static Block bridroneOre; public static Block orcaOre; public static Block orisoneOre; public static Block inomiteTorch; //public static Block rockWheel; public static void init() { //Trinia World Gen Blocks goldenBrick = new BlockTrinia(Material.rock).setUnlocalizedName("goldenBrick"); goldenDoor = new BlockTrinia(Material.rock).setUnlocalizedName("goldenDoor"); goldenKeyHole = new BlockTrinia(Material.rock).setUnlocalizedName("goldenKeyHole"); goldenPillar = new BlockTrinia(Material.rock).setUnlocalizedName("goldenPillar"); inomiteTorch = new BlockInomiteTorch().setLightLevel(1F).setUnlocalizedName("inomiteTorch"); triniaDeadGrass = new BlockTrinia(Material.rock).setUnlocalizedName("triniaDeadGrass"); inomiteTorch = new BlockInomiteTorch().setLightLevel(1F).setUnlocalizedName("inomiteTorch"); triniaCobblestone = new BlockTrinia(Material.rock).setUnlocalizedName("triniaCobblestone"); triniaGrass = new BlockTriniaGrass().setUnlocalizedName("triniaGrass"); triniaDirt = new BlockTriniaDirt().setUnlocalizedName("triniaDirt"); triniaStone = new BlockTriniaStone(Material.rock).setUnlocalizedName("triniaStone"); triniaStoneBrick = new BlockTrinia(Material.rock).setUnlocalizedName("triniaStoneBrick"); triniaMossyStoneBrick = new BlockTrinia(Material.rock).setUnlocalizedName("triniaMossyStoneBrick"); triniaChiseledStoneBrick = new BlockTrinia(Material.rock).setUnlocalizedName("triniaChiseledStoneBrick"); triniaCrackedStoneBrick = new BlockTrinia(Material.rock).setUnlocalizedName("triniaCrackedStoneBrick"); triniaMossyCobblestone = new BlockTrinia(Material.rock).setUnlocalizedName("triniaMossyCobblestone"); triniaGravel = new BlockTriniaGravel().setUnlocalizedName("triniaGravel"); redLeaves = new BlockTriniaLeavesBase(Material.leaves, true).setUnlocalizedName("redLeaves").setLightOpacity(0); greenLeaves = new BlockTriniaLeavesBase(Material.leaves, true).setUnlocalizedName("greenLeaves").setLightOpacity(0); blueLeaves = new BlockTriniaLeavesBase(Material.leaves, true).setUnlocalizedName("blueLeaves").setLightOpacity(0); yellowLeaves = new BlockTriniaLeavesBase(Material.leaves, true).setUnlocalizedName("yellowLeaves").setLightOpacity(0); purpleLeaves = new BlockTriniaLeavesBase(Material.leaves, true).setUnlocalizedName("purpleLeaves").setLightOpacity(0); steelOre = new BlockTrinia(Material.rock).setUnlocalizedName("steelOre"); copperOre = new BlockTrinia(Material.rock).setUnlocalizedName("copperOre"); silverOre = new BlockTrinia(Material.rock).setUnlocalizedName("silverOre"); tinOre = new BlockTrinia(Material.rock).setUnlocalizedName("tinOre"); FlowerStem = new BlockFlower(Material.plants).setUnlocalizedName("FlowerStem"); FlowerBlue = new BlockFlower(Material.plants).setUnlocalizedName("FlowerBlue"); FlowerGreen = new BlockFlower(Material.plants).setUnlocalizedName("FlowerGreen"); FlowerOrange = new BlockFlower(Material.plants).setUnlocalizedName("FlowerOrange"); FlowerPink = new BlockFlower(Material.plants).setUnlocalizedName("FlowerPink"); FlowerPurple = new BlockFlower(Material.plants).setUnlocalizedName("FlowerPurple"); FlowerRed = new BlockFlower(Material.plants).setUnlocalizedName("FlowerRed"); FlowerYellow = new BlockFlower(Material.plants).setUnlocalizedName("FlowerYellow"); adimiteOre = new BlockAdimiteOre().setUnlocalizedName("adimiteOre"); bridroneOre = new BlockTrinia(Material.rock).setUnlocalizedName("bridroneOre"); orcaOre = new BlockTrinia(Material.rock).setUnlocalizedName("orcaOre"); orisoneOre = new BlockTrinia(Material.rock).setUnlocalizedName("orisoneOre"); MagicalBed = new BlockMagicalBed().setUnlocalizedName("bed"); CastingBench = new BlockCastingBench(Material.iron).setUnlocalizedName("CastingBench"); cloud = new BlockCloud().setUnlocalizedName("cloud"); bluecloud = new BlockBlueCloud().setUnlocalizedName("bluecloud"); //Trinia Blocks steelBlock = new BlockTrinia(Material.rock).setUnlocalizedName("steelBlock"); copperBlock = new BlockTrinia(Material.rock).setUnlocalizedName("copperBlock"); silverBlock = new BlockTrinia(Material.rock).setUnlocalizedName("silverBlock"); tinBlock = new BlockTrinia(Material.rock).setUnlocalizedName("tinBlock"); hardenedBucket = new BlockHardenedBucket(Material.iron).setUnlocalizedName("hardenedBucket"); hardenedBucketLava = new BlockHardenedBucket(Material.iron).setUnlocalizedName("hardenedBucketLava"); hardenedBucketCopper = new BlockHardenedBucket(Material.iron).setUnlocalizedName("hardenedBucketCopper"); hardenedBucketSilver = new BlockHardenedBucket(Material.iron).setUnlocalizedName("hardenedBucketSilver"); hardenedBucketSteel = new BlockHardenedBucket(Material.iron).setUnlocalizedName("hardenedBucketSteel"); hardenedBucketTin = new BlockHardenedBucket(Material.iron).setUnlocalizedName("hardenedBucketTin"); } public static void register() { //Trinia World Gen Blocks GameRegistry.registerBlock(goldenBrick, goldenBrick.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(goldenDoor, goldenDoor.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(goldenKeyHole, goldenKeyHole.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(goldenPillar, goldenPillar.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(inomiteTorch, inomiteTorch.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(triniaDeadGrass, triniaDeadGrass.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(steelOre, steelOre.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(copperOre, copperOre.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(silverOre, silverOre.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(tinOre, tinOre.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(triniaCobblestone, triniaCobblestone.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(triniaGrass, triniaGrass.getUnlocalizedName().substring(5)).setHardness(0.6F).setStepSound(Block.soundTypeGrass).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(triniaDirt, triniaDirt.getUnlocalizedName().substring(5)).setHardness(0.6F).setStepSound(Block.soundTypeGrass).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(triniaStone, triniaStone.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(triniaStoneBrick, triniaStoneBrick.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(triniaMossyStoneBrick, triniaMossyStoneBrick.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(triniaChiseledStoneBrick, triniaChiseledStoneBrick.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(triniaCrackedStoneBrick, triniaCrackedStoneBrick.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(triniaMossyCobblestone, triniaMossyCobblestone.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(triniaGravel, triniaGravel.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeGravel).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(redLeaves, redLeaves.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(greenLeaves, greenLeaves.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(blueLeaves, blueLeaves.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(yellowLeaves, yellowLeaves.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(purpleLeaves, purpleLeaves.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(FlowerStem, FlowerStem.getUnlocalizedName().substring(5)).setHardness(0.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(FlowerBlue, FlowerBlue.getUnlocalizedName().substring(5)).setHardness(0.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(FlowerGreen, FlowerGreen.getUnlocalizedName().substring(5)).setHardness(0.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(FlowerOrange, FlowerOrange.getUnlocalizedName().substring(5)).setHardness(0.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(FlowerPink, FlowerPink.getUnlocalizedName().substring(5)).setHardness(0.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(FlowerPurple, FlowerPurple.getUnlocalizedName().substring(5)).setHardness(0.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(FlowerRed, FlowerRed.getUnlocalizedName().substring(5)).setHardness(0.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(FlowerYellow, FlowerYellow.getUnlocalizedName().substring(5)).setHardness(0.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(adimiteOre, adimiteOre.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(bridroneOre, bridroneOre.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(orcaOre, orcaOre.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(orisoneOre, orisoneOre.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(MagicalBed, MagicalBed.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone); GameRegistry.registerBlock(CastingBench, CastingBench.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(cloud, cloud.getUnlocalizedName().substring(5)).setHardness(0.5F).setResistance(1.0F).setStepSound(Block.soundTypeCloth).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(bluecloud, bluecloud.getUnlocalizedName().substring(5)).setHardness(0.5F).setResistance(1.0F).setStepSound(Block.soundTypeCloth).setCreativeTab(TriniaMod.TriniaMainTab); //Trinia Blocks GameRegistry.registerBlock(steelBlock, steelBlock.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(copperBlock, copperBlock.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(silverBlock, silverBlock.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(tinBlock, tinBlock.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab); GameRegistry.registerBlock(hardenedBucket, hardenedBucket.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab);; GameRegistry.registerBlock(hardenedBucketLava, hardenedBucketLava.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab);; GameRegistry.registerBlock(hardenedBucketCopper, hardenedBucketCopper.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab);; GameRegistry.registerBlock(hardenedBucketSilver, hardenedBucketSilver.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab);; GameRegistry.registerBlock(hardenedBucketSteel, hardenedBucketSteel.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab);; GameRegistry.registerBlock(hardenedBucketTin, hardenedBucketTin.getUnlocalizedName().substring(5)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundTypeStone).setCreativeTab(TriniaMod.TriniaMainTab);; } public static void registerTileEntitys() { GameRegistry.registerTileEntity(TileEntityTriniaWorkBench.class, "craftingTileEntity"); } public static void registerRenders() { RegisterRender(FlowerStem); RegisterRender(FlowerBlue); RegisterRender(FlowerGreen); RegisterRender(FlowerOrange); RegisterRender(FlowerPink); RegisterRender(FlowerPurple); RegisterRender(FlowerRed); RegisterRender(FlowerYellow); RegisterRender(CastingBench); RegisterRender(hardenedBucket); RegisterRender(hardenedBucketLava); RegisterRender(hardenedBucketCopper); RegisterRender(hardenedBucketSilver); RegisterRender(hardenedBucketSteel); RegisterRender(hardenedBucketTin); RegisterRender(cloud); RegisterRender(bluecloud); RegisterRender(goldenBrick); RegisterRender(goldenDoor); RegisterRender(goldenKeyHole); RegisterRender(goldenPillar); RegisterRender(inomiteTorch); RegisterRender(triniaDeadGrass); //Random RegisterRender(redLeaves); RegisterRender(greenLeaves); RegisterRender(blueLeaves); RegisterRender(yellowLeaves); RegisterRender(purpleLeaves); //worldgen RegisterRender(triniaCobblestone); RegisterRender(triniaGrass); RegisterRender(triniaDirt); RegisterRender(triniaStone); RegisterRender(triniaStoneBrick); RegisterRender(triniaMossyStoneBrick); RegisterRender(triniaChiseledStoneBrick); RegisterRender(triniaCrackedStoneBrick); RegisterRender(triniaMossyCobblestone); RegisterRender(triniaGravel); RegisterRender(MagicalBed); //Ores RegisterRender(steelOre); RegisterRender(copperOre); RegisterRender(silverOre); RegisterRender(tinOre); RegisterRender(adimiteOre); RegisterRender(bridroneOre); RegisterRender(orcaOre); RegisterRender(orisoneOre); //Ore Blocks RegisterRender(steelBlock); RegisterRender(copperBlock); RegisterRender(silverBlock); RegisterRender(tinBlock); } public static void RegisterRender(Block block) { Item item = Item.getItemFromBlock(block); Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(item, 0, new ModelResourceLocation(Reference.MOD_ID + ":" + item.getUnlocalizedName().substring(5), "inventory")); } }
package com.zimmerbell.repaper; import java.awt.Desktop; import java.awt.Graphics2D; import java.awt.MenuItem; import java.awt.PopupMenu; import java.awt.SystemTray; import java.awt.TrayIcon; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.awt.image.ConvolveOp; import java.awt.image.Kernel; import java.awt.image.RescaleOp; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.HashMap; import javax.imageio.ImageIO; import javax.swing.JOptionPane; import org.quartz.CronScheduleBuilder; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.JobKey; import org.quartz.ObjectAlreadyExistsException; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.Trigger; import org.quartz.TriggerBuilder; import org.quartz.impl.StdSchedulerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sun.jna.Native; import com.sun.jna.platform.win32.WinDef.UINT_PTR; import com.sun.jna.win32.StdCallLibrary; import com.sun.jna.win32.W32APIFunctionMapper; import com.sun.jna.win32.W32APITypeMapper; public class Repaper { public final static String HOME = System.getProperty("user.home") + File.separator + ".repaper"; public final static int GAUSS_RADIUS = 15; public final static float BRIGTHNESS = 0.5f; public final static File CURRENT_FILE = new File(HOME, "current.jpg"); public final static File CURRENT_FILE_ORIGINAL = new File(HOME, "current-original.jpg"); private static final Logger LOG = LoggerFactory.getLogger(Repaper.class); private static Repaper repaperInstance; private TrayIcon trayIcon; private Source source; private Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); private JobDetail updateJob = JobBuilder.newJob(UpdateJob.class).build(); public static void main(String[] args) throws Exception { repaperInstance = new Repaper(new MuzeiSource()); } public static Repaper getInstance(){ return repaperInstance; } public Repaper(Source source) throws Exception { this.source = source; initTray(); initScheduler(); } private void initScheduler() { Trigger trigger = TriggerBuilder.newTrigger() .startNow() .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(5, 0).withMisfireHandlingInstructionFireAndProceed()) .build(); try { scheduler.start(); scheduler.scheduleJob(updateJob, trigger); // trigger now scheduler.triggerJob(updateJob.getKey()); } catch (SchedulerException e) { logError(e); } } private void initTray() throws Exception { PopupMenu popup = new PopupMenu(); MenuItem mi; popup.add(mi = new MenuItem("Update")); mi.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { try { scheduler.triggerJob(updateJob.getKey()); } catch (SchedulerException e) { logError(e); } } }); popup.add(mi = new MenuItem("Show original")); mi.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { showOriginal(); } }); if(Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)){ popup.add(mi = new MenuItem("Details")); mi.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { try { Desktop.getDesktop().browse(new URI(source.getDetailsUri())); } catch (Exception e) { logError(e); } } }); } popup.addSeparator(); popup.add(mi = new MenuItem("Exit")); mi.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { exit(); } }); trayIcon = new TrayIcon(ImageIO.read(Repaper.class.getResourceAsStream("/icon_16.png")), null, popup); trayIcon.setImageAutoSize(true); trayIcon.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showOriginal(); } }); SystemTray.getSystemTray().add(trayIcon); } public void update(){ try { LOG.info("update"); BufferedImage image = ImageIO.read(new URL(source.getImageUri()).openStream()); CURRENT_FILE_ORIGINAL.getParentFile().mkdir(); ImageIO.write(image, "jpg", CURRENT_FILE_ORIGINAL); image = blur(image); image = darken(image); CURRENT_FILE.getParentFile().mkdirs(); ImageIO.write(image, "jpg", CURRENT_FILE); trayIcon.setToolTip("\"" + source.getTitle() + "\"\n by " + source.getBy()); setBackgroundImage(false); } catch (IOException e) { trayIcon.setToolTip(null); logError(e); } } private void showOriginal(){ try { JobKey jobKey = JobKey.jobKey("showJob"); //scheduler.interrupt(jobKey); scheduler.scheduleJob(JobBuilder.newJob(ShowJob.class).withIdentity(jobKey).build(), TriggerBuilder.newTrigger().build()); }catch(ObjectAlreadyExistsException e){ // do nothing } catch (SchedulerException e) { logError(e); } } public void setBackgroundImage(boolean original) throws IOException{ LOG.info("show " + (original ? " original" : "") + " image"); File file = original ? CURRENT_FILE_ORIGINAL : CURRENT_FILE; SPI.INSTANCE.SystemParametersInfo(new UINT_PTR(SPI.SPI_SETDESKWALLPAPER), new UINT_PTR(0), file.getCanonicalPath(), new UINT_PTR(SPI.SPIF_UPDATEINIFILE | SPI.SPIF_SENDWININICHANGE)); } private void exit() { try { scheduler.shutdown(); } catch (SchedulerException e) { logError(e); } System.exit(0); } public static void logError(Throwable e){ LOG.error(e.getMessage(), e); JOptionPane.showMessageDialog(null, e.getMessage()); } private BufferedImage blur(BufferedImage image) { // image = gauss(GAUSS_RADIUS).filter(image, null); image = getGaussianBlurFilter(Repaper.GAUSS_RADIUS, true).filter(image, null); image = getGaussianBlurFilter(Repaper.GAUSS_RADIUS, false).filter(image, null); // cropping black borders BufferedImage croppedImage = new BufferedImage(image.getWidth() - (2 * Repaper.GAUSS_RADIUS), image.getHeight() - (2 * Repaper.GAUSS_RADIUS), BufferedImage.TYPE_INT_RGB); Graphics2D g = croppedImage.createGraphics(); g.drawImage(image, 0, 0, croppedImage.getWidth(), croppedImage.getHeight(), Repaper.GAUSS_RADIUS, Repaper.GAUSS_RADIUS, croppedImage.getWidth() + Repaper.GAUSS_RADIUS, croppedImage.getHeight() + Repaper.GAUSS_RADIUS, null); image = croppedImage; return image; } @SuppressWarnings("unused") private static ConvolveOp gauss(final int radius) { double sigma = ((2 * radius) + 1) / 6.0; float[][] matrix = new float[(2 * radius) + 1][(2 * radius) + 1]; for (int x = 0; x <= radius; x++) { for (int y = 0; y <= radius; y++) { float d = (float) (1 / (2 * Math.PI * sigma * sigma) * Math.exp(-((x * x) + (y * y)) / (2 * sigma * sigma))); matrix[radius + x][radius + y] = d; matrix[radius + x][radius - y] = d; matrix[radius - x][radius + y] = d; matrix[radius - x][radius - y] = d; } } for (int x = 0; x < matrix.length; x++) { for (int y = 0; y < matrix[x].length; y++) { System.out.print((x - radius) + "," + (y - radius) + "=" + matrix[x][y]); System.out.print("\t"); } System.out.println(); } float[] data = new float[((2 * radius) + 1) * ((2 * radius) + 1)]; int d = 0; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { data[d++] = matrix[i][j]; } } return new ConvolveOp(new Kernel((2 * radius) + 1, (2 * radius) + 1, data)); } private BufferedImage darken(BufferedImage image) { return new RescaleOp(Repaper.BRIGTHNESS, 0, null).filter(image, null); } private static ConvolveOp getGaussianBlurFilter(int radius, boolean horizontal) { if (radius < 1) { throw new IllegalArgumentException("Radius must be >= 1"); } int size = radius * 2 + 1; float[] data = new float[size]; float sigma = radius / 3.0f; float twoSigmaSquare = 2.0f * sigma * sigma; float sigmaRoot = (float) Math.sqrt(twoSigmaSquare * Math.PI); float total = 0.0f; for (int i = -radius; i <= radius; i++) { float distance = i * i; int index = i + radius; data[index] = (float) Math.exp(-distance / twoSigmaSquare) / sigmaRoot; total += data[index]; } for (int i = 0; i < data.length; i++) { data[i] /= total; } Kernel kernel = null; if (horizontal) { kernel = new Kernel(size, 1, data); } else { kernel = new Kernel(1, size, data); } // return new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null); return new ConvolveOp(kernel); } public interface SPI extends StdCallLibrary { long SPI_SETDESKWALLPAPER = 20; long SPIF_UPDATEINIFILE = 0x01; long SPIF_SENDWININICHANGE = 0x02; SPI INSTANCE = (SPI) Native.loadLibrary("user32", SPI.class, new HashMap<Object, Object>() { private static final long serialVersionUID = 1L; { put(OPTION_TYPE_MAPPER, W32APITypeMapper.UNICODE); put(OPTION_FUNCTION_MAPPER, W32APIFunctionMapper.UNICODE); } }); boolean SystemParametersInfo(UINT_PTR uiAction, UINT_PTR uiParam, String pvParam, UINT_PTR fWinIni); } }
package de.iani.cubequest; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TreeMap; import de.iani.cubequest.events.QuestRenameEvent; import de.iani.cubequest.quests.ComplexQuest; import de.iani.cubequest.quests.Quest; public class QuestManager { private static QuestManager instance; private Map<String, HashSet<Quest>> questsByNames; private Map<Integer, Quest> questsByIds; private Map<Integer, HashSet<ComplexQuest>> waitingForQuest; public static QuestManager getInstance() { if (instance == null) { instance = new QuestManager(); } return instance; } private QuestManager() { questsByNames = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); questsByIds = new HashMap<>(); waitingForQuest = new HashMap<>(); } public void addQuest(Quest quest) { questsByIds.put(quest.getId(), quest); addByName(quest); HashSet<ComplexQuest> waiting = waitingForQuest.get(quest.getId()); if (waiting != null) { for (ComplexQuest cq: waiting.toArray(new ComplexQuest[0])) { cq.informQuestNowThere(quest); waiting.remove(cq); if (waiting.isEmpty()) { waitingForQuest.remove(quest.getId()); } } } } public void removeQuest(int id) { Quest quest = questsByIds.get(id); if (quest == null) { return; } questsByIds.remove(id); removeByName(quest); } public void removeQuest(Quest quest) { removeQuest(quest.getId()); } public void onQuestRenameEvent(QuestRenameEvent event) { removeByName(event.getQuest()); addByName(event.getQuest(), event.getNewName()); } public Quest getQuest(int id) { return questsByIds.get(id); } public Set<Quest> getQuests(String name) { if (questsByNames.get(name) == null) { return new HashSet<>(); } return Collections.unmodifiableSet(questsByNames.get(name)); } /** * @return alle Quests als unmodifiableCollection (live-Object der values der HashMap, keine Kopie) */ public Collection<Quest> getQuests() { return Collections.unmodifiableCollection(questsByIds.values()); } private void addByName(Quest quest) { addByName(quest, quest.getName()); } private void addByName(Quest quest, String name) { HashSet<Quest> hs = questsByNames.get(quest.getName()); if (hs == null) { hs = new HashSet<>(); questsByNames.put(quest.getName(), hs); } hs.add(quest); } private void removeByName(Quest quest) { HashSet<Quest> hs = questsByNames.get(quest.getName()); if (hs == null) { return; } hs.remove(quest); if (hs.isEmpty()) { questsByNames.remove(quest.getName()); } } public void registerWaitingForQuest(ComplexQuest waiting, int waitingForId) { HashSet<ComplexQuest> hs = waitingForQuest.get(waitingForId); if (hs == null) { hs = new HashSet<>(); waitingForQuest.put(waitingForId, hs); } hs.add(waiting); } }
package ev3dev.sensors.ev3; import ev3dev.sensors.BaseSensor; import ev3dev.sensors.GenericMode; import ev3dev.utils.Sysfs; import lejos.hardware.port.Port; import lejos.hardware.sensor.SensorMode; public class EV3IRSensor extends BaseSensor { private static final String LEGO_EV3_IR = "lego-ev3-ir"; public static float MIN_RANGE = 5f; public static float MAX_RANGE = 100f; private static final String MODE_DISTANCE = "IR-PROX"; private static final String MODE_SEEK = "IR-SEEK"; private static final String MODE_REMOTE = "IR-REMOTE"; public final static int IR_CHANNELS = 4; public EV3IRSensor(final Port portName) { super(portName, LEGO_UART_SENSOR, LEGO_EV3_IR); setModes(new SensorMode[] { new GenericMode(this, MODE_DISTANCE, 1, "Distance", MIN_RANGE, MAX_RANGE, 1.0f), new GenericMode(this, MODE_SEEK, 8, "Seek"), new GenericMode(this, MODE_REMOTE, IR_CHANNELS, "Remote") }); } public SensorMode getDistanceMode() { return getMode(0); } public SensorMode getSeekMode() { return getMode(1); } /** * <b>EV3 Infra Red sensor, Remote mode</b><br> * In seek mode the sensor locates up to four beacons and provides bearing and distance of each beacon. * * Returns the current remote command from the specified channel. Remote commands * are a single numeric value which represents which button on the Lego IR * remote is currently pressed (0 means no buttons pressed). Four channels are * supported (0-3) which correspond to 1-4 on the remote. The button values are:<br> * 1 TOP-LEFT<br> * 2 BOTTOM-LEFT<br> * 3 TOP-RIGHT<br> * 4 BOTTOM-RIGHT<br> * 5 TOP-LEFT + TOP-RIGHT<br> * 6 TOP-LEFT + BOTTOM-RIGHT<br> * 7 BOTTOM-LEFT + TOP-RIGHT<br> * 8 BOTTOM-LEFT + BOTTOM-RIGHT<br> * 9 CENTRE/BEACON<br> * 10 BOTTOM-LEFT + TOP-LEFT<br> * 11 TOP-RIGHT + BOTTOM-RIGHT<br> * * @return A sampleProvider * See {@link lejos.robotics.SampleProvider leJOS conventions for SampleProviders} */ public SensorMode getRemoteMode() { return getMode(2); } /** * Return the current remote command from the specified channel. Remote commands * are a single numeric value which represents which button on the Lego IR * remote is currently pressed (0 means no buttons pressed). Four channels are * supported (0-3) which correspond to 1-4 on the remote. The button values are:<br> * 1 TOP-LEFT<br> * 2 BOTTOM-LEFT<br> * 3 TOP-RIGHT<br> * 4 BOTTOM-RIGHT<br> * 5 TOP-LEFT + TOP-RIGHT<br> * 6 TOP-LEFT + BOTTOM-RIGHT<br> * 7 BOTTOM-LEFT + TOP-RIGHT<br> * 8 BOTTOM-LEFT + BOTTOM-RIGHT<br> * 9 CENTRE/BEACON<br> * 10 BOTTOM-LEFT + TOP-LEFT<br> * 11 TOP-RIGHT + BOTTOM-RIGHT<br> * @param chan channel to obtain the command for * @return the current command */ public int getRemoteCommand(int chan) { if (chan < 0 || chan >= IR_CHANNELS) { throw new IllegalArgumentException("Bad channel"); } float[] samples = new float[IR_CHANNELS]; getRemoteMode().fetchSample(samples, 0); return (int)samples[chan]; } /** * Obtain the commands associated with one or more channels. Each element of * the array contains the command for the associated channel (0-3). * @param cmds the array to store the commands * @param offset the offset to start storing * @param len the number of commands to store. */ public void getRemoteCommands(byte[] cmds, int offset, int len) { // TODO this should read multiple commands, but we probably cannot easily wait for new ones float[] samples = new float[IR_CHANNELS]; getRemoteMode().fetchSample(samples, 0); for (int i = 0; i < IR_CHANNELS; i++) { int idx = offset+i; if (idx >= len) { break; } cmds[idx] = (byte) samples[i]; } } }
package fr.wseduc.cas.data; import fr.wseduc.cas.async.Handler; import fr.wseduc.cas.async.Tuple; import fr.wseduc.cas.entities.AuthCas; import fr.wseduc.cas.entities.ProxyTicket; import fr.wseduc.cas.entities.ServiceTicket; import fr.wseduc.cas.entities.User; import fr.wseduc.cas.exceptions.AuthenticationException; import fr.wseduc.cas.exceptions.ErrorCodes; import fr.wseduc.cas.exceptions.Try; import fr.wseduc.cas.exceptions.ValidationException; import fr.wseduc.cas.http.Request; public abstract class DataHandler { protected final Request request; protected DataHandler(Request request) { this.request = request; } public abstract void validateService(String service, Handler<Boolean> handler); public abstract void authenticateUser(String user, String password, AuthCas authCas, Handler<Try<AuthenticationException, AuthCas>> handler); public void validateTicket(final String ticket, final String service, final Handler<Try<ValidationException, Tuple<AuthCas, User>>> handler) { getAuth(ticket, new Handler<AuthCas>() { @Override public void handle(final AuthCas authCas) { ServiceTicket st; long now = System.currentTimeMillis(); if (authCas != null && (st = authCas.getServiceTicket(ticket)) != null && !st.isUsed() && (now - st.getIssued()) < 300000) { st.setUsed(true); validateService(authCas, st, service, handler); } else { handler.handle(new Try<ValidationException, Tuple<AuthCas, User>>( new ValidationException(ErrorCodes.INVALID_TICKET))); } } }); } protected void validateService(final AuthCas authCas, final ServiceTicket st, final String service, final Handler<Try<ValidationException, Tuple<AuthCas, User>>> handler) { if (st.getService().equalsIgnoreCase(service)) { getUser(authCas.getUser(), service, new Handler<User>() { @Override public void handle(User user) { if (user != null) { handler.handle(new Try<ValidationException, Tuple<AuthCas, User>>( new Tuple<>(authCas, user))); } else { handler.handle(new Try<ValidationException, Tuple<AuthCas, User>>( new ValidationException(ErrorCodes.INVALID_TICKET))); } } }); } else { handler.handle(new Try<ValidationException, Tuple<AuthCas, User>>( new ValidationException(ErrorCodes.INVALID_SERVICE))); } } public void validateProxyTicket(final String ticket, final String service, final Handler<Try<ValidationException, Tuple<AuthCas, User>>> handler) { getAuthByProxyTicket(ticket, new Handler<AuthCas>() { @Override public void handle(final AuthCas authCas) { ServiceTicket st; ProxyTicket pt; long now = System.currentTimeMillis(); if (authCas != null && (st = authCas.getServiceTicketByProxyTicket(ticket)) != null && st.getPgt() != null && (pt = st.getPgt().getProxyTicket(ticket)) != null && !pt.isUsed() && (now - pt.getIssued()) < 300000) { pt.setUsed(true); validateService(authCas, st, service, handler); } else { handler.handle(new Try<ValidationException, Tuple<AuthCas, User>>( new ValidationException(ErrorCodes.INVALID_TICKET))); } } }); } public void validateProxyGrantingTicket(final String pgt, final String targetService, final Handler<Try<ValidationException, AuthCas>> handler) { getAuthByProxyGrantingTicket(pgt, new Handler<AuthCas>() { @Override public void handle(AuthCas authCas) { if (authCas != null) { ServiceTicket st = authCas.getServiceTicketByProxyGrantingTicket(pgt); if (st != null && st.getService() != null && st.getService().equalsIgnoreCase(targetService)) { handler.handle(new Try<ValidationException, AuthCas>(authCas)); } else { handler.handle(new Try<ValidationException, AuthCas>( new ValidationException(ErrorCodes.INVALID_SERVICE))); } } else { handler.handle(new Try<ValidationException, AuthCas>( new ValidationException(ErrorCodes.INVALID_TICKET))); } } }); } protected abstract void getAuthByProxyGrantingTicket(String pgt, Handler<AuthCas> handler); protected abstract void getUser(String userId, String service, Handler<User> handler); protected abstract void getAuth(String ticket, Handler<AuthCas> handler); protected abstract void getAuthByProxyTicket(String ticket, Handler<AuthCas> handler); public abstract void getOrCreateAuth(Request request, Handler<AuthCas> handler); public abstract void persistAuth(AuthCas authCas, Handler<Boolean> handler); public abstract void getAndDestroyAuth(Request request, Handler<AuthCas> handler); public abstract void getAndDestroyAuth(String user, Handler<AuthCas> handler); }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tonegod.gui.controls.lists; import com.jme3.input.KeyInput; import com.jme3.input.event.KeyInputEvent; import com.jme3.input.event.MouseButtonEvent; import com.jme3.math.Vector2f; import com.jme3.math.Vector4f; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import tonegod.gui.controls.buttons.ButtonAdapter; import tonegod.gui.controls.menuing.Menu; import tonegod.gui.controls.menuing.MenuItem; import tonegod.gui.controls.text.TextField; import tonegod.gui.core.Screen; import tonegod.gui.core.utils.UIDUtil; /** * * @author t0neg0d */ public abstract class ComboBox extends TextField { private ButtonAdapter btnArrowDown; private Menu DDList = null; float btnHeight; String ddUID; private int selectedIndex = -1; private Object selectedValue; private String selectedCaption; private int hlIndex; private Object hlValue; private String hlCaption; private int ssIndex; private Object ssValue; private String ssCaption; private boolean DDListIsShowing = false; /** * Creates a new instance of the ComboBox control * * @param screen The screen control the Element is to be added to * @param position A Vector2f containing the x/y position of the Element */ public ComboBox(Screen screen, Vector2f position) { this(screen, UIDUtil.getUID(), position, screen.getStyle("TextField").getVector2f("defaultSize"), screen.getStyle("TextField").getVector4f("resizeBorders"), screen.getStyle("TextField").getString("defaultImg") ); } /** * Creates a new instance of the ComboBox control * * @param screen The screen control the Element is to be added to * @param position A Vector2f containing the x/y position of the Element * @param dimensions A Vector2f containing the width/height dimensions of the Element */ public ComboBox(Screen screen, Vector2f position, Vector2f dimensions) { this(screen, UIDUtil.getUID(), position, dimensions, screen.getStyle("TextField").getVector4f("resizeBorders"), screen.getStyle("TextField").getString("defaultImg") ); } /** * Creates a new instance of the ComboBox control * * @param screen The screen control the Element is to be added to * @param position A Vector2f containing the x/y position of the Element * @param dimensions A Vector2f containing the width/height dimensions of the Element * @param resizeBorders A Vector4f containg the border information used when resizing the default image (x = N, y = W, z = E, w = S) * @param defaultImg The default image to use for the Element */ public ComboBox(Screen screen, Vector2f position, Vector2f dimensions, Vector4f resizeBorders, String defaultImg) { this(screen, UIDUtil.getUID(), position, dimensions, resizeBorders, defaultImg); } /** * Creates a new instance of the ComboBox control * * @param screen The screen control the Element is to be added to * @param UID A unique String identifier for the Element * @param position A Vector2f containing the x/y position of the Element */ public ComboBox(Screen screen, String UID, Vector2f position) { this(screen, UID, position, screen.getStyle("TextField").getVector2f("defaultSize"), screen.getStyle("TextField").getVector4f("resizeBorders"), screen.getStyle("TextField").getString("defaultImg") ); } /** * Creates a new instance of the ComboBox control * * @param screen The screen control the Element is to be added to * @param UID A unique String identifier for the Element * @param position A Vector2f containing the x/y position of the Element * @param dimensions A Vector2f containing the width/height dimensions of the Element */ public ComboBox(Screen screen, String UID, Vector2f position, Vector2f dimensions) { this(screen, UID, position, dimensions, screen.getStyle("TextField").getVector4f("resizeBorders"), screen.getStyle("TextField").getString("defaultImg") ); } /** * Creates a new instance of the ComboBox control * * @param screen The screen control the Element is to be added to * @param UID A unique String identifier for the Element * @param position A Vector2f containing the x/y position of the Element * @param dimensions A Vector2f containing the width/height dimensions of the Element * @param resizeBorders A Vector4f containg the border information used when resizing the default image (x = N, y = W, z = E, w = S) * @param defaultImg The default image to use for the Slider's track */ public ComboBox(Screen screen, String UID, Vector2f position, Vector2f dimensions, Vector4f resizeBorders, String defaultImg) { super(screen, UID, position, dimensions, resizeBorders, defaultImg); setScaleNS(false); setScaleEW(false); ddUID = UID + ":ddMenu"; btnHeight = getHeight(); setWidth(getWidth()-btnHeight); btnArrowDown = new ButtonAdapter(screen, UID + ":ArrowDown", new Vector2f( getWidth(), 0 ), new Vector2f( btnHeight, btnHeight ) ) { @Override public void onButtonMouseLeftUp(MouseButtonEvent evt, boolean toggled) { if (validateListSize()) { if (screen.getElementById(DDList.getUID()) == null) screen.addElement(DDList); if (!DDList.getIsVisible()) { DDList.showMenu( (Menu)null, getElementParent().getAbsoluteX(), getElementParent().getAbsoluteY()-DDList.getHeight() ); } else { DDList.hide(); } } screen.setTabFocusElement((ComboBox)getElementParent()); } }; btnArrowDown.setButtonIcon(18, 18, screen.getStyle("Common").getString("arrowDown")); btnArrowDown.setDockS(true); btnArrowDown.setDockW(true); this.addChild(btnArrowDown); } /** * Adds a new list item to the drop-down list associated with this control * * @param caption The String to display as the list item * @param value A String value to associate with this list item */ public void addListItem(String caption, Object value) { if (DDList == null) { DDList = new Menu(screen, ddUID, new Vector2f(0,0), true) { @Override public void onMenuItemClicked(int index, Object value, boolean isToggled) { ((ComboBox)getCallerElement()).setSelectedWithCallback(index, DDList.getMenuItem(index).getCaption(), value); screen.setTabFocusElement(((ComboBox)getCallerElement())); hide(); } }; DDList.setCallerElement(this); DDList.setPreferredSize(new Vector2f(getWidth()+btnHeight,DDList.getMenuItemHeight()*5)); } DDList.setFontSize(fontSize); DDList.getScrollableArea().setFontSize(fontSize); DDList.addMenuItem(caption, value, null); if (screen.getElementById(DDList.getUID()) == null) { screen.addElement(DDList); } pack(); // refreshSelectedIndex(); } /** * Inserts a new List Item at the specified index * @param index - List index to insert new List Item * @param caption - Caption for new List Item * @param value - Object to store as value */ public void insertListItem(int index, String caption, Object value) { if (DDList != null) { DDList.insertMenuItem(index, caption, value, null); pack(); refreshSelectedIndex(); } } /** * Removes the List Item at the specified index * @param index */ public void removeListItem(int index) { if (DDList != null) { DDList.removeMenuItem(index); pack(); refreshSelectedIndex(); } } /** * Removes the first instance of a list item with the specified caption * @param caption */ public void removeListItem(String caption) { if (DDList != null) { DDList.removeMenuItem(caption); } } /** * Removes the first instance of a list item with the specified value * @param value */ public void removeListItem(Object value) { if (DDList != null) { DDList.removeMenuItem(value); } } /** * Removes all list items */ public void removeAllListItems() { if (DDList != null) { DDList.removeAllMenuItems(); } } private void refreshSelectedIndex() { if (DDList != null) { if (selectedIndex > DDList.getMenuItems().size()-1) this.setSelectedIndexWithCallback(DDList.getMenuItems().size()-1); // if (!DDList.getMenuItems().isEmpty()) // this.setSelectedIndex(selectedIndex); // else if (DDList.getMenuItems().isEmpty()) setText(""); } else { setText(""); } } /** * Method needs to be called once last list item has been added. This eventually * will be updated to automatically be called when a new item is added to, instert into * the list or an item is removed from the list. */ public void pack() { if (selectedIndex == -1) { setSelectedIndexWithCallback(0); } int rIndex = DDList.getMenuItems().size()-selectedIndex; float diff = rIndex * DDList.getMenuItemHeight() + (DDList.getMenuPadding()*2); DDList.scrollThumbYTo( ( DDList.getHeight()-diff ) ); refreshSelectedIndex(); } /** * Returns false if list is empty, true if list contains List Items * @return boolean */ public boolean validateListSize() { if (DDList == null) return false; else if (DDList.getMenuItems().isEmpty()) return false; else return true; } public void setSelectedByCaption(String caption, boolean useCallback) { MenuItem mItem = null; for (MenuItem mi : DDList.getMenuItems()) { if (mi.getCaption().equals(caption)) { mItem = mi; break; } } if (mItem != null) { if (useCallback) setSelectedIndexWithCallback(DDList.getMenuItems().indexOf(mItem)); else setSelectedIndex(DDList.getMenuItems().indexOf(mItem)); } } public void setSelectedByValue(Object value, boolean useCallback) { MenuItem mItem = null; for (MenuItem mi : DDList.getMenuItems()) { if (mi.getValue().equals(value)) { mItem = mi; break; } } if (mItem != null) { if (useCallback) setSelectedIndexWithCallback(DDList.getMenuItems().indexOf(mItem)); else setSelectedIndex(DDList.getMenuItems().indexOf(mItem)); } } /** * Selects the List Item at the specified index and call the onChange event * @param selectedIndex */ public void setSelectedIndexWithCallback(int selectedIndex) { if (validateListSize()) { if (selectedIndex < 0) selectedIndex = 0; else if (selectedIndex > DDList.getMenuItems().size()-1) selectedIndex = DDList.getMenuItems().size()-1; MenuItem mi = DDList.getMenuItem(selectedIndex); String caption = mi.getCaption(); Object value = mi.getValue(); setSelectedWithCallback(selectedIndex, caption, value); } } protected void setSelectedWithCallback(int index, String caption, Object value) { this.hlIndex = index; this.selectedIndex = index; this.selectedCaption = caption; this.selectedValue = value; setText(selectedCaption); int rIndex = DDList.getMenuItems().size()-index; float diff = rIndex * DDList.getMenuItemHeight() + (DDList.getMenuPadding()*2); DDList.scrollThumbYTo( ( DDList.getHeight()-diff ) ); onChange(selectedIndex, selectedValue); } /** * Selects the List Item at the specified index * @param selectedIndex */ public void setSelectedIndex(int selectedIndex) { if (validateListSize()) { if (selectedIndex < 0) selectedIndex = 0; else if (selectedIndex > DDList.getMenuItems().size()-1) selectedIndex = DDList.getMenuItems().size()-1; MenuItem mi = DDList.getMenuItem(selectedIndex); String caption = mi.getCaption(); Object value = mi.getValue(); setSelected(selectedIndex, caption, value); } } protected void setSelected(int index, String caption, Object value) { this.hlIndex = index; this.selectedIndex = index; this.selectedCaption = caption; this.selectedValue = value; setText(selectedCaption); int rIndex = DDList.getMenuItems().size()-index; float diff = rIndex * DDList.getMenuItemHeight() + (DDList.getMenuPadding()*2); DDList.scrollThumbYTo( ( DDList.getHeight()-diff ) ); // onChange(selectedIndex, selectedValue); } /** * Hides the ComboBox drop-down list */ public void hideDropDownList() { this.DDList.hideMenu(); } @Override public void controlKeyPressHook(KeyInputEvent evt, String text) { if (validateListSize()) { if (evt.getKeyCode() != KeyInput.KEY_UP && evt.getKeyCode() != KeyInput.KEY_DOWN && evt.getKeyCode() != KeyInput.KEY_RETURN) { int miIndexOf = 0; int strIndex = -1; for (MenuItem mi : DDList.getMenuItems()) { strIndex = mi.getCaption().toLowerCase().indexOf(text.toLowerCase()); if (strIndex == 0) { ssIndex = miIndexOf; hlIndex = ssIndex; hlCaption = ssCaption = DDList.getMenuItem(miIndexOf).getCaption(); hlValue = ssValue = DDList.getMenuItem(miIndexOf).getValue(); int rIndex = DDList.getMenuItems().size()-miIndexOf; float diff = rIndex * DDList.getMenuItemHeight() + (DDList.getMenuPadding()*2); DDList.scrollThumbYTo( ( DDList.getHeight()-diff ) ); break; } miIndexOf++; } if (miIndexOf > -1 && miIndexOf < DDList.getMenuItems().size()-1) handleHightlight(miIndexOf); if (screen.getElementById(DDList.getUID()) == null) screen.addElement(DDList); if (!DDList.getIsVisible() && evt.getKeyCode() != KeyInput.KEY_LSHIFT && evt.getKeyCode() != KeyInput.KEY_RSHIFT) DDList.showMenu((Menu)null, getAbsoluteX(), getAbsoluteY()-DDList.getHeight()); } else { if (evt.getKeyCode() == KeyInput.KEY_UP) { if (hlIndex > 0) { hlIndex hlCaption = DDList.getMenuItem(hlIndex).getCaption(); hlValue = DDList.getMenuItem(hlIndex).getValue(); int rIndex = DDList.getMenuItems().size()-hlIndex; float diff = rIndex * DDList.getMenuItemHeight() + (DDList.getMenuPadding()*2); DDList.scrollThumbYTo( ( DDList.getHeight()-diff ) ); handleHightlight(hlIndex); setSelectedWithCallback(hlIndex, hlCaption, hlValue); } } else if (evt.getKeyCode() == KeyInput.KEY_DOWN) { if (hlIndex < DDList.getMenuItems().size()-1) { hlIndex++; hlCaption = DDList.getMenuItem(hlIndex).getCaption(); hlValue = DDList.getMenuItem(hlIndex).getValue(); int rIndex = DDList.getMenuItems().size()-hlIndex; float diff = rIndex * DDList.getMenuItemHeight() + (DDList.getMenuPadding()*2); DDList.scrollThumbYTo( ( DDList.getHeight()-diff ) ); handleHightlight(hlIndex); setSelectedWithCallback(hlIndex, hlCaption, hlValue); } } if (evt.getKeyCode() == KeyInput.KEY_RETURN) { updateSelected(); } } } } private void updateSelected() { setSelectedWithCallback(hlIndex, hlCaption, hlValue); if (DDList.getIsVisible()) DDList.hide(); } private void handleHightlight(int index) { if (DDList.getIsVisible()) DDList.setHighlight(index); } /** * Abstract event method called when a list item is selected/navigated to. * @param selectedIndex * @param value */ public abstract void onChange(int selectedIndex, Object value); /** * Returns the current selected index * @return selectedIndex */ public int getSelectIndex() { return this.selectedIndex; } /** * Returns the object representing the current selected List Item * @return MenuITem */ public MenuItem getSelectedListItem() { return this.DDList.getMenuItem(selectedIndex); } /** * Returns the object representing the list item at the specified index * @param index * @return MenuItem */ public MenuItem getListItemByIndex(int index) { return this.DDList.getMenuItem(index); } /** * Returns a List of all ListItems * @return List<MenuItem> */ public List<MenuItem> getListItems() { return DDList.getMenuItems(); } /** * Returns a pointer to the dropdown list (Menu) * @return DDList */ public Menu getMenu() { return this.DDList; } /** * Sorts the associated drop-down list alphanumerically */ public void sortList() { Object[] orgList = DDList.getMenuItems().toArray(); List<MenuItem> currentList = new ArrayList(); List<MenuItem> finalList = new ArrayList(); List<String> map = new ArrayList(); for (int i = 0; i < orgList.length; i++) { currentList.add((MenuItem)orgList[i]); map.add(((MenuItem)orgList[i]).getCaption()); } Collections.sort(map); for (String caption : map) { int index; for (MenuItem mi : currentList) { if (mi.getCaption().equals(caption)) { index = currentList.indexOf(mi); finalList.add(mi); DDList.removeMenuItem(index); currentList.remove(mi); break; } } } for (MenuItem mi : finalList) { addListItem(mi.getCaption(), mi.getValue()); } } /** * Sorts drop-down list by true numeric values. This should only be used * with lists that start with numeric values */ public void sortListNumeric() { Object[] orgList = DDList.getMenuItems().toArray(); List<MenuItem> currentList = new ArrayList(); List<MenuItem> finalList = new ArrayList(); List<Integer> map = new ArrayList(); for (int i = 0; i < orgList.length; i++) { currentList.add((MenuItem)orgList[i]); boolean NaN = true; String tempCaption = ((MenuItem)orgList[i]).getCaption(); while(NaN && tempCaption.length() != 0) { try { Integer.parseInt(tempCaption); NaN = false; } catch (Exception ex) { tempCaption = tempCaption.substring(0,tempCaption.length()-2); } } map.add(Integer.parseInt(tempCaption)); } Collections.sort(map); for (Integer caption : map) { int index; for (MenuItem mi : currentList) { boolean NaN = true; String tempCaption = mi.getCaption(); while(NaN && tempCaption.length() != 0) { try { Integer.parseInt(tempCaption); NaN = false; } catch (Exception ex) { tempCaption = tempCaption.substring(0,tempCaption.length()-2); } } if (Integer.parseInt(tempCaption) == caption) { index = currentList.indexOf(mi); finalList.add(mi); DDList.removeMenuItem(index); currentList.remove(mi); break; } } } for (MenuItem mi : finalList) { addListItem(mi.getCaption(), mi.getValue()); } } @Override public void controlTextFieldResetTabFocusHook() { // DDList.hideMenu(); } @Override public void controlCleanupHook() { if (DDList != null) screen.removeElement(DDList); } }
package io.github.classgraph; import java.io.File; import java.lang.annotation.Inherited; import java.lang.reflect.Modifier; import java.net.MalformedURLException; import java.net.URL; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EnumMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import nonapi.io.github.classgraph.ScanSpec; import nonapi.io.github.classgraph.exceptions.ParseException; import nonapi.io.github.classgraph.json.Id; import nonapi.io.github.classgraph.types.TypeUtils; import nonapi.io.github.classgraph.types.TypeUtils.ModifierType; import nonapi.io.github.classgraph.utils.LogNode; import nonapi.io.github.classgraph.utils.URLPathEncoder; /** Holds metadata about a class encountered during a scan. */ public class ClassInfo extends ScanResultObject implements Comparable<ClassInfo>, HasName { /** The name of the class. */ private @Id String name; /** Class modifier flags, e.g. Modifier.PUBLIC */ private int modifiers; /** True if the classfile indicated this is an interface (or an annotation, which is an interface). */ private boolean isInterface; /** True if the classfile indicated this is an annotation. */ private boolean isAnnotation; /** * This annotation has the {@link Inherited} meta-annotation, which means that any class that this annotation is * applied to also implicitly causes the annotation to annotate all subclasses too. */ boolean isInherited; /** The class type signature string. */ private String typeSignatureStr; /** The class type signature, parsed. */ private transient ClassTypeSignature typeSignature; /** The fully-qualified defining method name, for anonymous inner classes. */ private String fullyQualifiedDefiningMethodName; /** * If true, this class is only being referenced by another class' classfile as a superclass / implemented * interface / annotation, but this class is not itself a whitelisted (non-blacklisted) class, or in a * whitelisted (non-blacklisted) package. * * If false, this classfile was matched during scanning (i.e. its classfile contents read), i.e. this class is a * whitelisted (and non-blacklisted) class in a whitelisted (and non-blacklisted) package. */ private boolean isExternalClass = true; /** * Set to true when the class is actually scanned (as opposed to just referenced as a superclass, interface or * annotation of a scanned class). */ private boolean isScannedClass; /** * The classpath element file (classpath root dir or jar) that this class was found within, or null if this * class was found in a module. */ transient File classpathElementFile; /** * The package root within a jarfile (e.g. "BOOT-INF/classes"), or the empty string if this is not a jarfile, or * the package root is the classpath element path (as opposed to within a subdirectory of the classpath * element). */ private transient String jarfilePackageRoot = ""; /** * The classpath element module that this class was found within, or null if this class was found within a * directory or jar. */ private transient ModuleRef moduleRef; /** The classpath element URL (classpath root dir or jar) that this class was found within. */ private transient URL classpathElementURL; /** The {@link Resource} for the classfile of this class. */ private transient Resource resource; /** The classloaders to try to load this class with before calling a MatchProcessor. */ transient ClassLoader[] classLoaders; /** Info on class annotations, including optional annotation param values. */ AnnotationInfoList annotationInfo; /** Info on fields. */ FieldInfoList fieldInfo; /** Info on fields. */ MethodInfoList methodInfo; /** For annotations, the default values of parameters. */ AnnotationParameterValueList annotationDefaultParamValues; /** * Names of classes referenced by this class in class refs and type signatures in the constant pool of the * classfile. */ private Set<String> referencedClassNames; /** A list of ClassInfo objects for classes referenced by this class. */ private ClassInfoList referencedClasses; /** * Set to true once any Object[] arrays of boxed types in annotationDefaultParamValues have been lazily * converted to primitive arrays. */ transient boolean annotationDefaultParamValuesHasBeenConvertedToPrimitive; /** The set of classes related to this one. */ private final Map<RelType, Set<ClassInfo>> relatedClasses = new EnumMap<>(RelType.class); /** * The override order for a class' fields or methods (base class, followed by interfaces, followed by * superclasses). */ private transient List<ClassInfo> overrideOrder; /** Default constructor for deserialization. */ ClassInfo() { } /** * Constructor. * * @param name * the name * @param classModifiers * the class modifiers */ private ClassInfo(final String name, final int classModifiers) { this(); this.name = name; if (name.endsWith(";")) { // Spot check to make sure class names were parsed from descriptors throw new RuntimeException("Bad class name"); } setModifiers(classModifiers); } /** How classes are related. */ private enum RelType { // Classes: /** * Superclasses of this class, if this is a regular class. * * <p> * (Should consist of only one entry, or null if superclass is java.lang.Object or unknown). */ SUPERCLASSES, /** Subclasses of this class, if this is a regular class. */ SUBCLASSES, /** Indicates that an inner class is contained within this one. */ CONTAINS_INNER_CLASS, /** Indicates that an outer class contains this one. (Should only have zero or one entries.) */ CONTAINED_WITHIN_OUTER_CLASS, // Interfaces: /** * Interfaces that this class implements, if this is a regular class, or superinterfaces, if this is an * interface. * * <p> * (May also include annotations, since annotations are interfaces, so you can implement an annotation.) */ IMPLEMENTED_INTERFACES, /** * Classes that implement this interface (including sub-interfaces), if this is an interface. */ CLASSES_IMPLEMENTING, // Class annotations: /** * Annotations on this class, if this is a regular class, or meta-annotations on this annotation, if this is * an annotation. */ CLASS_ANNOTATIONS, /** Classes annotated with this annotation, if this is an annotation. */ CLASSES_WITH_ANNOTATION, // Method annotations: /** Annotations on one or more methods of this class. */ METHOD_ANNOTATIONS, /** * Classes that have one or more methods annotated with this annotation, if this is an annotation. */ CLASSES_WITH_METHOD_ANNOTATION, // Field annotations: /** Annotations on one or more fields of this class. */ FIELD_ANNOTATIONS, /** * Classes that have one or more fields annotated with this annotation, if this is an annotation. */ CLASSES_WITH_FIELD_ANNOTATION, } /** * Add a class with a given relationship type. Return whether the collection changed as a result of the call. * * @param relType * the {@link RelType} * @param classInfo * the {@link ClassInfo} * @return true, if successful */ private boolean addRelatedClass(final RelType relType, final ClassInfo classInfo) { Set<ClassInfo> classInfoSet = relatedClasses.get(relType); if (classInfoSet == null) { relatedClasses.put(relType, classInfoSet = new LinkedHashSet<>(4)); } return classInfoSet.add(classInfo); } /** The modifier bit for annotations. */ private static final int ANNOTATION_CLASS_MODIFIER = 0x2000; /** * Get a ClassInfo object, or create it if it doesn't exist. N.B. not threadsafe, so ClassInfo objects should * only ever be constructed by a single thread. * * @param className * the class name * @param classModifiers * the class modifiers * @param classNameToClassInfo * the map from class name to class info * @return the or create class info */ static ClassInfo getOrCreateClassInfo(final String className, final int classModifiers, final Map<String, ClassInfo> classNameToClassInfo) { ClassInfo classInfo = classNameToClassInfo.get(className); if (classInfo == null) { classNameToClassInfo.put(className, classInfo = new ClassInfo(className, classModifiers)); } classInfo.setModifiers(classModifiers); return classInfo; } /** * Set class modifiers. * * @param modifiers * the class modifiers */ void setModifiers(final int modifiers) { this.modifiers |= modifiers; if ((modifiers & ANNOTATION_CLASS_MODIFIER) != 0) { this.isAnnotation = true; } if ((modifiers & Modifier.INTERFACE) != 0) { this.isInterface = true; } } /** * Set isInterface status. * * @param isInterface * true if this is an interface */ void setIsInterface(final boolean isInterface) { this.isInterface |= isInterface; } /** * Set isInterface status. * * @param isAnnotation * true if this is an annotation */ void setIsAnnotation(final boolean isAnnotation) { this.isAnnotation |= isAnnotation; } /** * Add a superclass to this class. * * @param superclassName * the superclass name * @param classNameToClassInfo * the map from class name to class info */ void addSuperclass(final String superclassName, final Map<String, ClassInfo> classNameToClassInfo) { if (superclassName != null && !superclassName.equals("java.lang.Object")) { final ClassInfo superclassClassInfo = getOrCreateClassInfo(superclassName, /* classModifiers = */ 0, classNameToClassInfo); this.addRelatedClass(RelType.SUPERCLASSES, superclassClassInfo); superclassClassInfo.addRelatedClass(RelType.SUBCLASSES, this); } } /** * Add an implemented interface to this class. * * @param interfaceName * the interface name * @param classNameToClassInfo * the map from class name to class info */ void addImplementedInterface(final String interfaceName, final Map<String, ClassInfo> classNameToClassInfo) { final ClassInfo interfaceClassInfo = getOrCreateClassInfo(interfaceName, /* classModifiers = */ Modifier.INTERFACE, classNameToClassInfo); interfaceClassInfo.isInterface = true; interfaceClassInfo.modifiers |= Modifier.INTERFACE; this.addRelatedClass(RelType.IMPLEMENTED_INTERFACES, interfaceClassInfo); interfaceClassInfo.addRelatedClass(RelType.CLASSES_IMPLEMENTING, this); } /** * Add class containment info. * * @param classContainmentEntries * the class containment entries * @param classNameToClassInfo * the map from class name to class info */ static void addClassContainment(final List<SimpleEntry<String, String>> classContainmentEntries, final Map<String, ClassInfo> classNameToClassInfo) { for (final SimpleEntry<String, String> ent : classContainmentEntries) { final String innerClassName = ent.getKey(); final ClassInfo innerClassInfo = ClassInfo.getOrCreateClassInfo(innerClassName, /* classModifiers = */ 0, classNameToClassInfo); final String outerClassName = ent.getValue(); final ClassInfo outerClassInfo = ClassInfo.getOrCreateClassInfo(outerClassName, /* classModifiers = */ 0, classNameToClassInfo); innerClassInfo.addRelatedClass(RelType.CONTAINED_WITHIN_OUTER_CLASS, outerClassInfo); outerClassInfo.addRelatedClass(RelType.CONTAINS_INNER_CLASS, innerClassInfo); } } /** * Add containing method name, for anonymous inner classes. * * @param fullyQualifiedDefiningMethodName * the fully qualified defining method name */ void addFullyQualifiedDefiningMethodName(final String fullyQualifiedDefiningMethodName) { this.fullyQualifiedDefiningMethodName = fullyQualifiedDefiningMethodName; } /** * Add an annotation to this class. * * @param classAnnotationInfo * the class annotation info * @param classNameToClassInfo * the map from class name to class info */ void addClassAnnotation(final AnnotationInfo classAnnotationInfo, final Map<String, ClassInfo> classNameToClassInfo) { final ClassInfo annotationClassInfo = getOrCreateClassInfo(classAnnotationInfo.getName(), ANNOTATION_CLASS_MODIFIER, classNameToClassInfo); if (this.annotationInfo == null) { this.annotationInfo = new AnnotationInfoList(2); } this.annotationInfo.add(classAnnotationInfo); this.addRelatedClass(RelType.CLASS_ANNOTATIONS, annotationClassInfo); annotationClassInfo.addRelatedClass(RelType.CLASSES_WITH_ANNOTATION, this); // Record use of @Inherited meta-annotation if (classAnnotationInfo.getName().equals(Inherited.class.getName())) { isInherited = true; } } /** * Add field or method annotation cross-links. * * @param annotationInfoList * the annotation info list * @param isField * the is field * @param classNameToClassInfo * the map from class name to class info */ private void addFieldOrMethodAnnotationInfo(final AnnotationInfoList annotationInfoList, final boolean isField, final Map<String, ClassInfo> classNameToClassInfo) { if (annotationInfoList != null) { for (final AnnotationInfo fieldAnnotationInfo : annotationInfoList) { final ClassInfo annotationClassInfo = getOrCreateClassInfo(fieldAnnotationInfo.getName(), ANNOTATION_CLASS_MODIFIER, classNameToClassInfo); // Mark this class as having a field or method with this annotation this.addRelatedClass(isField ? RelType.FIELD_ANNOTATIONS : RelType.METHOD_ANNOTATIONS, annotationClassInfo); annotationClassInfo.addRelatedClass( isField ? RelType.CLASSES_WITH_FIELD_ANNOTATION : RelType.CLASSES_WITH_METHOD_ANNOTATION, this); } } } /** * Add field info. * * @param fieldInfoList * the field info list * @param classNameToClassInfo * the map from class name to class info */ void addFieldInfo(final FieldInfoList fieldInfoList, final Map<String, ClassInfo> classNameToClassInfo) { for (final FieldInfo fi : fieldInfoList) { addFieldOrMethodAnnotationInfo(fi.annotationInfo, /* isField = */ true, classNameToClassInfo); } if (this.fieldInfo == null) { this.fieldInfo = fieldInfoList; } else { this.fieldInfo.addAll(fieldInfoList); } } /** * Add method info. * * @param methodInfoList * the method info list * @param classNameToClassInfo * the map from class name to class info */ void addMethodInfo(final MethodInfoList methodInfoList, final Map<String, ClassInfo> classNameToClassInfo) { for (final MethodInfo mi : methodInfoList) { addFieldOrMethodAnnotationInfo(mi.annotationInfo, /* isField = */ false, classNameToClassInfo); // // Currently it is not possible to find methods by method parameter annotation // final AnnotationInfo[][] methodParamAnnotationInfoList = methodInfo.parameterAnnotationInfo; // if (methodParamAnnotationInfoList != null) { // for (int i = 0; i < methodParamAnnotationInfoList.length; i++) { // final AnnotationInfo[] paramAnnotationInfoArr = methodParamAnnotationInfoList[i]; // if (paramAnnotationInfoArr != null) { // for (int j = 0; j < paramAnnotationInfoArr.length; j++) { // final AnnotationInfo methodParamAnnotationInfo = paramAnnotationInfoArr[j]; // final ClassInfo annotationClassInfo = getOrCreateClassInfo( // methodParamAnnotationInfo.getName(), ANNOTATION_CLASS_MODIFIER, // classNameToClassInfo); // // Index parameter annotations here } if (this.methodInfo == null) { this.methodInfo = methodInfoList; } else { this.methodInfo.addAll(methodInfoList); } } /** * Add the class type signature, including type params. * * @param typeSignatureStr * the type signature str */ void addTypeSignature(final String typeSignatureStr) { if (this.typeSignatureStr == null) { this.typeSignatureStr = typeSignatureStr; } else { if (typeSignatureStr != null && !this.typeSignatureStr.equals(typeSignatureStr)) { throw new RuntimeException("Trying to merge two classes with different type signatures for class " + name + ": " + this.typeSignatureStr + " ; " + typeSignatureStr); } } } /** * Add annotation default values. (Only called in the case of annotation class definitions, when the annotation * has default parameter values.) * * @param paramNamesAndValues * the default param names and values, if this is an annotation */ void addAnnotationParamDefaultValues(final AnnotationParameterValueList paramNamesAndValues) { if (this.annotationDefaultParamValues == null) { this.annotationDefaultParamValues = paramNamesAndValues; } else { this.annotationDefaultParamValues.addAll(paramNamesAndValues); } } /** * Add a class that has just been scanned (as opposed to just referenced by a scanned class). Not threadsafe, * should be run in single threaded context. * * @param className * the class name * @param classModifiers * the class modifiers * @param isExternalClass * true if this is an external class * @param classNameToClassInfo * the map from class name to class info * @param classpathElement * the classpath element * @param classfileResource * the classfile resource * @param log * the log * @return the class info */ static ClassInfo addScannedClass(final String className, final int classModifiers, final boolean isExternalClass, final Map<String, ClassInfo> classNameToClassInfo, final ClasspathElement classpathElement, final Resource classfileResource, final LogNode log) { ClassInfo classInfo = classNameToClassInfo.get(className); if (classInfo == null) { // This is the first time this class has been seen, add it classNameToClassInfo.put(className, classInfo = new ClassInfo(className, classModifiers)); } else { // There was a previous placeholder ClassInfo class added, due to the class being referred // to as a superclass, interface or annotation. The isScannedClass field should be false // in this case, since the actual class definition wasn't reached before now. if (classInfo.isScannedClass) { // The class should not have been scanned more than once, because of classpath masking throw new IllegalArgumentException("Class " + className + " should not have been encountered more than once due to classpath masking + " please report this bug at: https://github.com/classgraph/classgraph/issues"); } } // Mark the class as scanned classInfo.isScannedClass = true; // Mark the class as non-external if it is a whitelisted class classInfo.isExternalClass = isExternalClass; // Remember which classpath element (zipfile / classpath root directory / module) the class was found in classInfo.resource = classfileResource; classInfo.moduleRef = classpathElement instanceof ClasspathElementModule ? ((ClasspathElementModule) classpathElement).getModuleRef() : null; classInfo.classpathElementFile = classInfo.moduleRef != null ? null : classpathElement instanceof ClasspathElementDir ? ((ClasspathElementDir) classpathElement).getDirFile() : classpathElement instanceof ClasspathElementZip ? ((ClasspathElementZip) classpathElement).getZipFile() : null; classInfo.jarfilePackageRoot = classpathElement.getPackageRoot(); // Remember which classloader is used to load the class classInfo.classLoaders = classpathElement.getClassLoaders(); return classInfo; } /** The class type to return. */ private enum ClassType { /** Get all class types. */ ALL, /** A standard class (not an interface or annotation). */ STANDARD_CLASS, /** * An interface (this is named "implemented interface" rather than just "interface" to distinguish it from * an annotation.) */ IMPLEMENTED_INTERFACE, /** An annotation. */ ANNOTATION, /** An interface or annotation (used since you can actually implement an annotation). */ INTERFACE_OR_ANNOTATION, } /** * Filter classes according to scan spec and class type. * * @param classes * the classes * @param scanSpec * the scan spec * @param strictWhitelist * If true, exclude class if it is is external, blacklisted, or a system class. * @param classTypes * the class types * @return the filtered classes. */ private static Set<ClassInfo> filterClassInfo(final Collection<ClassInfo> classes, final ScanSpec scanSpec, final boolean strictWhitelist, final ClassType... classTypes) { if (classes == null) { return Collections.<ClassInfo> emptySet(); } boolean includeAllTypes = classTypes.length == 0; boolean includeStandardClasses = false; boolean includeImplementedInterfaces = false; boolean includeAnnotations = false; for (final ClassType classType : classTypes) { switch (classType) { case ALL: includeAllTypes = true; break; case STANDARD_CLASS: includeStandardClasses = true; break; case IMPLEMENTED_INTERFACE: includeImplementedInterfaces = true; break; case ANNOTATION: includeAnnotations = true; break; case INTERFACE_OR_ANNOTATION: includeImplementedInterfaces = includeAnnotations = true; break; default: throw new RuntimeException("Unknown ClassType: " + classType); } } if (includeStandardClasses && includeImplementedInterfaces && includeAnnotations) { includeAllTypes = true; } final Set<ClassInfo> classInfoSetFiltered = new LinkedHashSet<>(classes.size()); for (final ClassInfo classInfo : classes) { // Check class type against requested type(s) if (includeAllTypes || includeStandardClasses && classInfo.isStandardClass() || includeImplementedInterfaces && classInfo.isImplementedInterface() || includeAnnotations && classInfo.isAnnotation()) { if ( // Always check blacklist !scanSpec.classOrPackageIsBlacklisted(classInfo.name) && ( // Always return whitelisted classes, or external classes if enableExternalClasses is true !classInfo.isExternalClass || scanSpec.enableExternalClasses // Return external (non-whitelisted) classes if viewing class hierarchy "upwards" || !strictWhitelist)) { // Class passed strict whitelist criteria classInfoSetFiltered.add(classInfo); } } } return classInfoSetFiltered; } /** * A set of classes that indirectly reachable through a directed path, for a given relationship type, and a set * of classes that is directly related (only one relationship step away). */ static class ReachableAndDirectlyRelatedClasses { /** The reachable classes. */ final Set<ClassInfo> reachableClasses; /** The directly related classes. */ final Set<ClassInfo> directlyRelatedClasses; /** * Constructor. * * @param reachableClasses * the reachable classes * @param directlyRelatedClasses * the directly related classes */ private ReachableAndDirectlyRelatedClasses(final Set<ClassInfo> reachableClasses, final Set<ClassInfo> directlyRelatedClasses) { this.reachableClasses = reachableClasses; this.directlyRelatedClasses = directlyRelatedClasses; } } /** The constant empty return value used when no classes are reachable. */ private static final ReachableAndDirectlyRelatedClasses NO_REACHABLE_CLASSES = new ReachableAndDirectlyRelatedClasses(Collections.<ClassInfo> emptySet(), Collections.<ClassInfo> emptySet()); /** * Get the classes related to this one (the transitive closure) for the given relationship type, and those * directly related. * * @param relType * the rel type * @param strictWhitelist * the strict whitelist * @param classTypes * the class types * @return the reachable and directly related classes */ private ReachableAndDirectlyRelatedClasses filterClassInfo(final RelType relType, final boolean strictWhitelist, final ClassType... classTypes) { final Set<ClassInfo> directlyRelatedClasses = this.relatedClasses.get(relType); if (directlyRelatedClasses == null) { return NO_REACHABLE_CLASSES; } final Set<ClassInfo> reachableClasses = new LinkedHashSet<>(directlyRelatedClasses); if (relType == RelType.METHOD_ANNOTATIONS || relType == RelType.FIELD_ANNOTATIONS) { // For method and field annotations, need to change the RelType when finding meta-annotations for (final ClassInfo annotation : directlyRelatedClasses) { reachableClasses.addAll( annotation.filterClassInfo(RelType.CLASS_ANNOTATIONS, strictWhitelist).reachableClasses); } } else if (relType == RelType.CLASSES_WITH_METHOD_ANNOTATION || relType == RelType.CLASSES_WITH_FIELD_ANNOTATION) { // If looking for meta-annotated methods or fields, need to find all meta-annotated annotations, then // look for the methods or fields that they annotate for (final ClassInfo subAnnotation : this.filterClassInfo(RelType.CLASSES_WITH_ANNOTATION, strictWhitelist, ClassType.ANNOTATION).reachableClasses) { final Set<ClassInfo> annotatedClasses = subAnnotation.relatedClasses.get(relType); if (annotatedClasses != null) { reachableClasses.addAll(annotatedClasses); } } } else { // For other relationship types, the reachable type stays the same over the transitive closure. Find the // transitive closure, breaking cycles where necessary. final LinkedList<ClassInfo> queue = new LinkedList<>(directlyRelatedClasses); while (!queue.isEmpty()) { final ClassInfo head = queue.removeFirst(); final Set<ClassInfo> headRelatedClasses = head.relatedClasses.get(relType); if (headRelatedClasses != null) { for (final ClassInfo directlyReachableFromHead : headRelatedClasses) { // Don't get in cycle if (reachableClasses.add(directlyReachableFromHead)) { queue.add(directlyReachableFromHead); } } } } } if (reachableClasses.isEmpty()) { return NO_REACHABLE_CLASSES; } // Special case -- don't inherit java.lang.annotation.* meta-annotations as related meta-annotations // (but still return them as direct meta-annotations on annotation classes). Set<ClassInfo> javaLangAnnotationRelatedClasses = null; for (final ClassInfo classInfo : reachableClasses) { if (classInfo.getName().startsWith("java.lang.annotation.")) { if (javaLangAnnotationRelatedClasses == null) { javaLangAnnotationRelatedClasses = new LinkedHashSet<>(); } javaLangAnnotationRelatedClasses.add(classInfo); } } if (javaLangAnnotationRelatedClasses != null) { // Remove all java.lang.annotation annotations that are not directly related to this class Set<ClassInfo> javaLangAnnotationDirectlyRelatedClasses = null; for (final ClassInfo classInfo : directlyRelatedClasses) { if (classInfo.getName().startsWith("java.lang.annotation.")) { if (javaLangAnnotationDirectlyRelatedClasses == null) { javaLangAnnotationDirectlyRelatedClasses = new LinkedHashSet<>(); } javaLangAnnotationDirectlyRelatedClasses.add(classInfo); } } if (javaLangAnnotationDirectlyRelatedClasses != null) { javaLangAnnotationRelatedClasses.removeAll(javaLangAnnotationDirectlyRelatedClasses); } reachableClasses.removeAll(javaLangAnnotationRelatedClasses); } return new ReachableAndDirectlyRelatedClasses( filterClassInfo(reachableClasses, scanResult.scanSpec, strictWhitelist, classTypes), filterClassInfo(directlyRelatedClasses, scanResult.scanSpec, strictWhitelist, classTypes)); } /** * Get all classes found during the scan. * * @param classes * the classes * @param scanSpec * the scan spec * @return A list of all classes found during the scan, or the empty list if none. */ static ClassInfoList getAllClasses(final Collection<ClassInfo> classes, final ScanSpec scanSpec) { return new ClassInfoList( ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true, ClassType.ALL), /* sortByName = */ true); } /** * Get all standard classes found during the scan. * * @param classes * the classes * @param scanSpec * the scan spec * @return A list of all standard classes found during the scan, or the empty list if none. */ static ClassInfoList getAllStandardClasses(final Collection<ClassInfo> classes, final ScanSpec scanSpec) { return new ClassInfoList(ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true, ClassType.STANDARD_CLASS), /* sortByName = */ true); } /** * Get all implemented interface (non-annotation interface) classes found during the scan. * * @param classes * the classes * @param scanSpec * the scan spec * @return A list of all annotation classes found during the scan, or the empty list if none. */ static ClassInfoList getAllImplementedInterfaceClasses(final Collection<ClassInfo> classes, final ScanSpec scanSpec) { return new ClassInfoList(ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true, ClassType.IMPLEMENTED_INTERFACE), /* sortByName = */ true); } /** * Get all annotation classes found during the scan. See also * {@link #getAllInterfacesOrAnnotationClasses(Collection, ScanSpec, ScanResult)} ()}. * * @param classes * the classes * @param scanSpec * the scan spec * @return A list of all annotation classes found during the scan, or the empty list if none. */ static ClassInfoList getAllAnnotationClasses(final Collection<ClassInfo> classes, final ScanSpec scanSpec) { return new ClassInfoList( ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true, ClassType.ANNOTATION), /* sortByName = */ true); } /** * Get all interface or annotation classes found during the scan. (Annotations are technically interfaces, and * they can be implemented.) * * @param classes * the classes * @param scanSpec * the scan spec * @return A list of all whitelisted interfaces found during the scan, or the empty list if none. */ static ClassInfoList getAllInterfacesOrAnnotationClasses(final Collection<ClassInfo> classes, final ScanSpec scanSpec) { return new ClassInfoList(ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true, ClassType.INTERFACE_OR_ANNOTATION), /* sortByName = */ true); } // Predicates /** * Get the name of the class. * * @return The name of the class. */ @Override public String getName() { return name; } /** * Get the simple name of the class. * * @return The simple name of the class. */ public String getSimpleName() { return name.substring(name.lastIndexOf('.') + 1); } /** * Get the name of the class' package. * * @return The name of the class' package. */ public String getPackageName() { return PackageInfo.getParentPackageName(name); } /** * Checks if this is an external class. * * @return true if this class is an external class, i.e. was referenced by a whitelisted class as a superclass, * interface, or annotation, but is not itself a whitelisted class. */ public boolean isExternalClass() { return isExternalClass; } /** * Get the class modifier bits. * * @return The class modifier bits, e.g. {@link Modifier#PUBLIC}. */ public int getModifiers() { return modifiers; } /** * Get the class modifiers as a String. * * @return The field modifiers as a string, e.g. "public static final". For the modifier bits, call * {@link #getModifiers()}. */ public String getModifiersStr() { final StringBuilder buf = new StringBuilder(); TypeUtils.modifiersToString(modifiers, ModifierType.CLASS, /* ignored */ false, buf); return buf.toString(); } /** * Checks if the class is public. * * @return true if this class is a public class. */ public boolean isPublic() { return (modifiers & Modifier.PUBLIC) != 0; } /** * Checks if the class is abstract. * * @return true if this class is an abstract class. */ public boolean isAbstract() { return (modifiers & 0x400) != 0; } /** * Checks if the class is synthetic. * * @return true if this class is a synthetic class. */ public boolean isSynthetic() { return (modifiers & 0x1000) != 0; } /** * Checks if the class is final. * * @return true if this class is a final class. */ public boolean isFinal() { return (modifiers & Modifier.FINAL) != 0; } /** * Checks if the class is static. * * @return true if this class is static. */ public boolean isStatic() { return Modifier.isStatic(modifiers); } /** * Checks if the class is an annotation. * * @return true if this class is an annotation class. */ public boolean isAnnotation() { return isAnnotation; } /** * Checks if is the class an interface and is not an annotation. * * @return true if this class is an interface and is not an annotation (annotations are interfaces, and can be * implemented). */ public boolean isInterface() { return isInterface && !isAnnotation; } /** * Checks if is an interface or an annotation. * * @return true if this class is an interface or an annotation (annotations are interfaces, and can be * implemented). */ public boolean isInterfaceOrAnnotation() { return isInterface; } /** * Checks if is the class is an {@link Enum}. * * @return true if this class is an {@link Enum}. */ public boolean isEnum() { return (modifiers & 0x4000) != 0; } /** * Checks if this class is a standard class. * * @return true if this class is a standard class (i.e. is not an annotation or interface). */ public boolean isStandardClass() { return !(isAnnotation || isInterface); } /** * Checks if this class extends the named superclass. * * @param superclassName * The name of a superclass. * @return true if this class extends the named superclass. */ public boolean extendsSuperclass(final String superclassName) { return getSuperclasses().containsName(superclassName); } /** * Checks if this class is an inner class. * * @return true if this is an inner class (call {@link #isAnonymousInnerClass()} to test if this is an anonymous * inner class). If true, the containing class can be determined by calling {@link #getOuterClasses()}. */ public boolean isInnerClass() { return !getOuterClasses().isEmpty(); } /** * Checks if this class is an outer class. * * @return true if this class contains inner classes. If true, the inner classes can be determined by calling * {@link #getInnerClasses()}. */ public boolean isOuterClass() { return !getInnerClasses().isEmpty(); } /** * Checks if this class is an anonymous inner class. * * @return true if this is an anonymous inner class. If true, the name of the containing method can be obtained * by calling {@link #getFullyQualifiedDefiningMethodName()}. */ public boolean isAnonymousInnerClass() { return fullyQualifiedDefiningMethodName != null; } /** * Checks whether this class is an implemented interface (meaning a standard, non-annotation interface, or an * annotation that has also been implemented as an interface by some class). * * <p> * Annotations are interfaces, but you can also implement an annotation, so to we return whether an interface * (even an annotation) is implemented by a class or extended by a subinterface, or (failing that) if it is not * an interface but not an annotation. * * @return true if this class is an implemented interface. */ public boolean isImplementedInterface() { return relatedClasses.get(RelType.CLASSES_IMPLEMENTING) != null || (isInterface && !isAnnotation); } /** * Checks whether this class implements the named interface. * * @param interfaceName * The name of an interface. * @return true if this class implements the named interface. */ public boolean implementsInterface(final String interfaceName) { return getInterfaces().containsName(interfaceName); } /** * Checks whether this class has the named annotation. * * @param annotationName * The name of an annotation. * @return true if this class has the named annotation. */ public boolean hasAnnotation(final String annotationName) { return getAnnotations().containsName(annotationName); } /** * Checks whether this class has the named declared field. * * @param fieldName * The name of a field. * @return true if this class declares a field of the given name. */ public boolean hasDeclaredField(final String fieldName) { return getDeclaredFieldInfo().containsName(fieldName); } /** * Checks whether this class or one of its superclasses has the named field. * * @param fieldName * The name of a field. * @return true if this class or one of its superclasses declares a field of the given name. */ public boolean hasField(final String fieldName) { for (final ClassInfo ci : getOverrideOrder()) { if (ci.hasDeclaredField(fieldName)) { return true; } } return false; } /** * Checks whether this class declares a field with the named annotation. * * @param fieldAnnotationName * The name of a field annotation. * @return true if this class declares a field with the named annotation. */ public boolean hasDeclaredFieldAnnotation(final String fieldAnnotationName) { for (final FieldInfo fi : getDeclaredFieldInfo()) { if (fi.hasAnnotation(fieldAnnotationName)) { return true; } } return false; } /** * Checks whether this class or one of its superclasses declares a field with the named annotation. * * @param fieldAnnotationName * The name of a field annotation. * @return true if this class or one of its superclasses declares a field with the named annotation. */ public boolean hasFieldAnnotation(final String fieldAnnotationName) { for (final ClassInfo ci : getOverrideOrder()) { if (ci.hasDeclaredFieldAnnotation(fieldAnnotationName)) { return true; } } return false; } /** * Checks whether this class declares a field of the given name. * * @param methodName * The name of a method. * @return true if this class declares a field of the given name. */ public boolean hasDeclaredMethod(final String methodName) { return getDeclaredMethodInfo().containsName(methodName); } /** * Checks whether this class or one of its superclasses or interfaces declares a method of the given name. * * @param methodName * The name of a method. * @return true if this class or one of its superclasses or interfaces declares a method of the given name. */ public boolean hasMethod(final String methodName) { for (final ClassInfo ci : getOverrideOrder()) { if (ci.hasDeclaredMethod(methodName)) { return true; } } return false; } /** * Checks whether this class declares a method with the named annotation. * * @param methodAnnotationName * The name of a method annotation. * @return true if this class declares a method with the named annotation. */ public boolean hasDeclaredMethodAnnotation(final String methodAnnotationName) { for (final MethodInfo mi : getDeclaredMethodInfo()) { if (mi.hasAnnotation(methodAnnotationName)) { return true; } } return false; } /** * Checks whether this class or one of its superclasses or interfaces declares a method with the named * annotation. * * @param methodAnnotationName * The name of a method annotation. * @return true if this class or one of its superclasses or interfaces declares a method with the named * annotation. */ public boolean hasMethodAnnotation(final String methodAnnotationName) { for (final ClassInfo ci : getOverrideOrder()) { if (ci.hasDeclaredMethodAnnotation(methodAnnotationName)) { return true; } } return false; } /** * Checks whether this class declares a method with the named annotation. * * @param methodParameterAnnotationName * The name of a method annotation. * @return true if this class declares a method with the named annotation. */ public boolean hasDeclaredMethodParameterAnnotation(final String methodParameterAnnotationName) { for (final MethodInfo mi : getDeclaredMethodInfo()) { if (mi.hasParameterAnnotation(methodParameterAnnotationName)) { return true; } } return false; } /** * Checks whether this class or one of its superclasses or interfaces has a method with the named annotation. * * @param methodParameterAnnotationName * The name of a method annotation. * @return true if this class or one of its superclasses or interfaces has a method with the named annotation. */ public boolean hasMethodParameterAnnotation(final String methodParameterAnnotationName) { for (final ClassInfo ci : getOverrideOrder()) { if (ci.hasDeclaredMethodParameterAnnotation(methodParameterAnnotationName)) { return true; } } return false; } /** * Recurse to interfaces and superclasses to get the order that fields and methods are overridden in. * * @param visited * visited * @param overrideOrderOut * the override order * @return the override order */ private List<ClassInfo> getOverrideOrder(final Set<ClassInfo> visited, final List<ClassInfo> overrideOrderOut) { if (visited.add(this)) { overrideOrderOut.add(this); for (final ClassInfo iface : getInterfaces()) { iface.getOverrideOrder(visited, overrideOrderOut); } final ClassInfo superclass = getSuperclass(); if (superclass != null) { superclass.getOverrideOrder(visited, overrideOrderOut); } } return overrideOrderOut; } /** * Get the order that fields and methods are overridden in (base class first). * * @return the override order */ private List<ClassInfo> getOverrideOrder() { if (overrideOrder == null) { overrideOrder = getOverrideOrder(new HashSet<ClassInfo>(), new ArrayList<ClassInfo>()); } return overrideOrder; } // Standard classes /** * Get the subclasses of this class, sorted in order of name. Call {@link ClassInfoList#directOnly()} to get * direct subclasses. * * @return the list of subclasses of this class, or the empty list if none. */ public ClassInfoList getSubclasses() { if (getName().equals("java.lang.Object")) { // Make an exception for querying all subclasses of java.lang.Object return scanResult.getAllClasses(); } else { return new ClassInfoList( this.filterClassInfo(RelType.SUBCLASSES, /* strictWhitelist = */ !isExternalClass), /* sortByName = */ true); } } /** * Get all superclasses of this class, in ascending order in the class hierarchy. Does not include * superinterfaces, if this is an interface (use {@link #getInterfaces()} to get superinterfaces of an * interface.} * * @return the list of all superclasses of this class, or the empty list if none. */ public ClassInfoList getSuperclasses() { return new ClassInfoList(this.filterClassInfo(RelType.SUPERCLASSES, /* strictWhitelist = */ false), /* sortByName = */ false); } /** * Get the single direct superclass of this class, or null if none. Does not return the superinterfaces, if this * is an interface (use {@link #getInterfaces()} to get superinterfaces of an interface.} * * @return the superclass of this class, or null if none. */ public ClassInfo getSuperclass() { final Set<ClassInfo> superClasses = relatedClasses.get(RelType.SUPERCLASSES); if (superClasses == null || superClasses.isEmpty()) { return null; } else if (superClasses.size() > 2) { throw new IllegalArgumentException("More than one superclass: " + superClasses); } else { final ClassInfo superclass = superClasses.iterator().next(); if (superclass.getName().equals("java.lang.Object")) { return null; } else { return superclass; } } } /** * Get the containing outer classes, if this is an inner class. * * @return A list of the containing outer classes, if this is an inner class, otherwise the empty list. Note * that all containing outer classes are returned, not just the innermost of the containing outer * classes. */ public ClassInfoList getOuterClasses() { return new ClassInfoList( this.filterClassInfo(RelType.CONTAINED_WITHIN_OUTER_CLASS, /* strictWhitelist = */ false), /* sortByName = */ false); } /** * Get the inner classes contained within this class, if this is an outer class. * * @return A list of the inner classes contained within this class, or the empty list if none. */ public ClassInfoList getInnerClasses() { return new ClassInfoList(this.filterClassInfo(RelType.CONTAINS_INNER_CLASS, /* strictWhitelist = */ false), /* sortByName = */ true); } /** * Gets fully-qualified method name (i.e. fully qualified classname, followed by dot, followed by method name) * for the defining method, if this is an anonymous inner class. * * @return The fully-qualified method name (i.e. fully qualified classname, followed by dot, followed by method * name) for the defining method, if this is an anonymous inner class, or null if not. */ public String getFullyQualifiedDefiningMethodName() { return fullyQualifiedDefiningMethodName; } // Interfaces /** * Get the interfaces implemented by this class or by one of its superclasses, if this is a standard class, or * the superinterfaces extended by this interface, if this is an interface. * * @return The list of interfaces implemented by this class or by one of its superclasses, if this is a standard * class, or the superinterfaces extended by this interface, if this is an interface. Returns the empty * list if none. */ public ClassInfoList getInterfaces() { // Classes also implement the interfaces of their superclasses final ReachableAndDirectlyRelatedClasses implementedInterfaces = this .filterClassInfo(RelType.IMPLEMENTED_INTERFACES, /* strictWhitelist = */ false); final Set<ClassInfo> allInterfaces = new LinkedHashSet<>(implementedInterfaces.reachableClasses); for (final ClassInfo superclass : this.filterClassInfo(RelType.SUPERCLASSES, /* strictWhitelist = */ false).reachableClasses) { final Set<ClassInfo> superclassImplementedInterfaces = superclass.filterClassInfo( RelType.IMPLEMENTED_INTERFACES, /* strictWhitelist = */ false).reachableClasses; allInterfaces.addAll(superclassImplementedInterfaces); } return new ClassInfoList(allInterfaces, implementedInterfaces.directlyRelatedClasses, /* sortByName = */ true); } /** * Get the classes (and their subclasses) that implement this interface, if this is an interface. * * @return the list of the classes (and their subclasses) that implement this interface, if this is an * interface, otherwise returns the empty list. */ public ClassInfoList getClassesImplementing() { if (!isInterface) { throw new IllegalArgumentException("Class is not an interface: " + getName()); } // Subclasses of implementing classes also implement the interface final ReachableAndDirectlyRelatedClasses implementingClasses = this .filterClassInfo(RelType.CLASSES_IMPLEMENTING, /* strictWhitelist = */ !isExternalClass); final Set<ClassInfo> allImplementingClasses = new LinkedHashSet<>(implementingClasses.reachableClasses); for (final ClassInfo implementingClass : implementingClasses.reachableClasses) { final Set<ClassInfo> implementingSubclasses = implementingClass.filterClassInfo(RelType.SUBCLASSES, /* strictWhitelist = */ !implementingClass.isExternalClass).reachableClasses; allImplementingClasses.addAll(implementingSubclasses); } return new ClassInfoList(allImplementingClasses, implementingClasses.directlyRelatedClasses, /* sortByName = */ true); } // Annotations /** * Get the annotations and meta-annotations on this class. (Call {@link #getAnnotationInfo()} instead, if you * need the parameter values of annotations, rather than just the annotation classes.) * * <p> * Also handles the {@link Inherited} meta-annotation, which causes an annotation to annotate a class and all of * its subclasses. * * @return the list of annotations and meta-annotations on this class. */ public ClassInfoList getAnnotations() { if (!scanResult.scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()"); } // Get all annotations on this class final ReachableAndDirectlyRelatedClasses annotationClasses = this.filterClassInfo(RelType.CLASS_ANNOTATIONS, /* strictWhitelist = */ false); // Check for any @Inherited annotations on superclasses Set<ClassInfo> inheritedSuperclassAnnotations = null; for (final ClassInfo superclass : getSuperclasses()) { for (final ClassInfo superclassAnnotationClass : superclass.filterClassInfo(RelType.CLASS_ANNOTATIONS, /* strictWhitelist = */ false).reachableClasses) { if (superclassAnnotationClass != null) { // Check if any of the meta-annotations on this annotation are @Inherited, // which causes an annotation to annotate a class and all of its subclasses. if (superclassAnnotationClass.isInherited) { // inheritedSuperclassAnnotations is an inherited annotation if (inheritedSuperclassAnnotations == null) { inheritedSuperclassAnnotations = new LinkedHashSet<>(); } inheritedSuperclassAnnotations.add(superclassAnnotationClass); } } } } if (inheritedSuperclassAnnotations == null) { // No inherited superclass annotations return new ClassInfoList(annotationClasses, /* sortByName = */ true); } else { // Merge inherited superclass annotations and annotations on this class inheritedSuperclassAnnotations.addAll(annotationClasses.reachableClasses); return new ClassInfoList(inheritedSuperclassAnnotations, annotationClasses.directlyRelatedClasses, /* sortByName = */ true); } } /** * Get the annotations or meta-annotations on fields or methods declared by the class, (not including fields or * methods declared by the interfaces or superclasses of this class). * * @param isField * If true, return field annotations, otherwise return method annotations. * @return A list of annotations or meta-annotations on fields or methods declared by the class, (not including * fields or methods declared by the interfaces or superclasses of this class), as a list of * {@link ClassInfo} objects, or the empty list if none. */ private ClassInfoList getFieldOrMethodAnnotations(final boolean isField) { if (!(isField ? scanResult.scanSpec.enableFieldInfo : scanResult.scanSpec.enableMethodInfo) || !scanResult.scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException("Please call ClassGraph#enable" + (isField ? "Field" : "Method") + "Info() and " + "#enableAnnotationInfo() before #scan()"); } final ReachableAndDirectlyRelatedClasses fieldOrMethodAnnotations = this.filterClassInfo( isField ? RelType.FIELD_ANNOTATIONS : RelType.METHOD_ANNOTATIONS, /* strictWhitelist = */ false, ClassType.ANNOTATION); final Set<ClassInfo> fieldOrMethodAnnotationsAndMetaAnnotations = new LinkedHashSet<>( fieldOrMethodAnnotations.reachableClasses); for (final ClassInfo fieldOrMethodAnnotation : fieldOrMethodAnnotations.reachableClasses) { // Meta-annotations are all class annotations on an annotation class fieldOrMethodAnnotationsAndMetaAnnotations.addAll(fieldOrMethodAnnotation .filterClassInfo(RelType.CLASS_ANNOTATIONS, /* strictWhitelist = */ false).reachableClasses); } return new ClassInfoList(fieldOrMethodAnnotationsAndMetaAnnotations, fieldOrMethodAnnotations.directlyRelatedClasses, /* sortByName = */ true); } /** * Get the classes that have this class as a field or method annotation. * * @param isField * If true, return field annotations, otherwise return method annotations. * @return A list of classes that have a declared method with this annotation or meta-annotation, or the empty * list if none. */ private ClassInfoList getClassesWithFieldOrMethodAnnotation(final boolean isField) { if (!(isField ? scanResult.scanSpec.enableFieldInfo : scanResult.scanSpec.enableMethodInfo) || !scanResult.scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException("Please call ClassGraph#enable" + (isField ? "Field" : "Method") + "Info() and " + "#enableAnnotationInfo() before #scan()"); } final ReachableAndDirectlyRelatedClasses classesWithDirectlyAnnotatedFieldsOrMethods = this.filterClassInfo( isField ? RelType.CLASSES_WITH_FIELD_ANNOTATION : RelType.CLASSES_WITH_METHOD_ANNOTATION, /* strictWhitelist = */ !isExternalClass); final ReachableAndDirectlyRelatedClasses annotationsWithThisMetaAnnotation = this.filterClassInfo( RelType.CLASSES_WITH_ANNOTATION, /* strictWhitelist = */ !isExternalClass, ClassType.ANNOTATION); if (annotationsWithThisMetaAnnotation.reachableClasses.isEmpty()) { // This annotation does not meta-annotate another annotation that annotates a method return new ClassInfoList(classesWithDirectlyAnnotatedFieldsOrMethods, /* sortByName = */ true); } else { // Take the union of all classes with fields or methods directly annotated by this annotation, // and classes with fields or methods meta-annotated by this annotation final Set<ClassInfo> allClassesWithAnnotatedOrMetaAnnotatedFieldsOrMethods = new LinkedHashSet<>( classesWithDirectlyAnnotatedFieldsOrMethods.reachableClasses); for (final ClassInfo metaAnnotatedAnnotation : annotationsWithThisMetaAnnotation.reachableClasses) { allClassesWithAnnotatedOrMetaAnnotatedFieldsOrMethods .addAll(metaAnnotatedAnnotation.filterClassInfo( isField ? RelType.CLASSES_WITH_FIELD_ANNOTATION : RelType.CLASSES_WITH_METHOD_ANNOTATION, /* strictWhitelist = */ !metaAnnotatedAnnotation.isExternalClass).reachableClasses); } return new ClassInfoList(allClassesWithAnnotatedOrMetaAnnotatedFieldsOrMethods, classesWithDirectlyAnnotatedFieldsOrMethods.directlyRelatedClasses, /* sortByName = */ true); } } /** * Get a list of the annotations on this class, or the empty list if none. * * <p> * Also handles the {@link Inherited} meta-annotation, which causes an annotation to annotate a class and all of * its subclasses. * * @return A list of {@link AnnotationInfo} objects for the annotations on this class, or the empty list if * none. */ public AnnotationInfoList getAnnotationInfo() { if (!scanResult.scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()"); } return AnnotationInfoList.getIndirectAnnotations(annotationInfo, this); } /** * Get a the named annotation on this class, or null if the class does not have the named annotation. * * <p> * Also handles the {@link Inherited} meta-annotation, which causes an annotation to annotate a class and all of * its subclasses. * * <p> * Note that if you need to get multiple named annotations, it is faster to call {@link #getAnnotationInfo()}, * and then get the named annotations from the returned {@link AnnotationInfoList}, so that the returned list * doesn't have to be built multiple times. * * @param annotationName * The annotation name. * @return An {@link AnnotationInfo} object representing the named annotation on this class, or null if the * class does not have the named annotation. */ public AnnotationInfo getAnnotationInfo(final String annotationName) { return getAnnotationInfo().get(annotationName); } /** * Get the default parameter values for this annotation, if this is an annotation class. * * @return A list of {@link AnnotationParameterValue} objects for each of the default parameter values for this * annotation, if this is an annotation class with default parameter values, otherwise the empty list. */ public AnnotationParameterValueList getAnnotationDefaultParameterValues() { if (!scanResult.scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()"); } if (!isAnnotation) { throw new IllegalArgumentException("Class is not an annotation: " + getName()); } if (annotationDefaultParamValues == null) { return AnnotationParameterValueList.EMPTY_LIST; } if (!annotationDefaultParamValuesHasBeenConvertedToPrimitive) { annotationDefaultParamValues.convertWrapperArraysToPrimitiveArrays(this); annotationDefaultParamValuesHasBeenConvertedToPrimitive = true; } return annotationDefaultParamValues; } /** * Get the classes that have this class as an annotation. * * @return A list of standard classes and non-annotation interfaces that are annotated by this class, if this is * an annotation class, or the empty list if none. Also handles the {@link Inherited} meta-annotation, * which causes an annotation on a class to be inherited by all of its subclasses. */ public ClassInfoList getClassesWithAnnotation() { if (!scanResult.scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()"); } if (!isAnnotation) { throw new IllegalArgumentException("Class is not an annotation: " + getName()); } // Get classes that have this annotation final ReachableAndDirectlyRelatedClasses classesWithAnnotation = this .filterClassInfo(RelType.CLASSES_WITH_ANNOTATION, /* strictWhitelist = */ !isExternalClass); if (isInherited) { // If this is an inherited annotation, add into the result all subclasses of the annotated classes. final Set<ClassInfo> classesWithAnnotationAndTheirSubclasses = new LinkedHashSet<>( classesWithAnnotation.reachableClasses); for (final ClassInfo classWithAnnotation : classesWithAnnotation.reachableClasses) { classesWithAnnotationAndTheirSubclasses.addAll(classWithAnnotation.getSubclasses()); } return new ClassInfoList(classesWithAnnotationAndTheirSubclasses, classesWithAnnotation.directlyRelatedClasses, /* sortByName = */ true); } else { // If not inherited, only return the annotated classes return new ClassInfoList(classesWithAnnotation, /* sortByName = */ true); } } /** * Get the classes that have this class as a direct annotation. * * @return The list of classes that are directly (i.e. are not meta-annotated) annotated with the requested * annotation, or the empty list if none. */ ClassInfoList getClassesWithAnnotationDirectOnly() { return new ClassInfoList( this.filterClassInfo(RelType.CLASSES_WITH_ANNOTATION, /* strictWhitelist = */ !isExternalClass), /* sortByName = */ true); } // Methods /** * Get the declared methods, constructors, and/or static initializer methods of the class. * * @param methodName * the method name * @param getNormalMethods * whether to get normal methods * @param getConstructorMethods * whether to get constructor methods * @param getStaticInitializerMethods * whether to get static initializer methods * @return the declared method info */ private MethodInfoList getDeclaredMethodInfo(final String methodName, final boolean getNormalMethods, final boolean getConstructorMethods, final boolean getStaticInitializerMethods) { if (!scanResult.scanSpec.enableMethodInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableMethodInfo() before #scan()"); } if (methodInfo == null) { return MethodInfoList.EMPTY_LIST; } if (methodName == null) { // If no method name is provided, filter for methods with the right type (normal method / constructor / // static initializer) final MethodInfoList methodInfoList = new MethodInfoList(); for (final MethodInfo mi : methodInfo) { final String miName = mi.getName(); final boolean isConstructor = miName.equals("<init>"); // (Currently static initializer methods are never returned by public methods) final boolean isStaticInitializer = miName.equals("<clinit>"); if ((isConstructor && getConstructorMethods) || (isStaticInitializer && getStaticInitializerMethods) || (!isConstructor && !isStaticInitializer && getNormalMethods)) { methodInfoList.add(mi); } } return methodInfoList; } else { // If method name is provided, filter for methods whose name matches, and ignore method type boolean hasMethodWithName = false; for (final MethodInfo f : methodInfo) { if (f.getName().equals(methodName)) { hasMethodWithName = true; break; } } if (!hasMethodWithName) { return MethodInfoList.EMPTY_LIST; } final MethodInfoList methodInfoList = new MethodInfoList(); for (final MethodInfo mi : methodInfo) { if (mi.getName().equals(methodName)) { methodInfoList.add(mi); } } return methodInfoList; } } /** * Get the methods, constructors, and/or static initializer methods of the class. * * @param methodName * the method name * @param getNormalMethods * whether to get normal methods * @param getConstructorMethods * whether to get constructor methods * @param getStaticInitializerMethods * whether to get static initializer methods * @return the method info */ private MethodInfoList getMethodInfo(final String methodName, final boolean getNormalMethods, final boolean getConstructorMethods, final boolean getStaticInitializerMethods) { if (!scanResult.scanSpec.enableMethodInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableMethodInfo() before #scan()"); } // Implement method/constructor overriding final MethodInfoList methodInfoList = new MethodInfoList(); final Set<Entry<String, String>> nameAndTypeDescriptorSet = new HashSet<>(); for (final ClassInfo ci : getOverrideOrder()) { for (final MethodInfo mi : ci.getDeclaredMethodInfo(methodName, getNormalMethods, getConstructorMethods, getStaticInitializerMethods)) { // If method/constructor has not been overridden by method of same name and type descriptor if (nameAndTypeDescriptorSet .add(new SimpleEntry<>(mi.getName(), mi.getTypeDescriptor().toString()))) { // Add method/constructor to output order methodInfoList.add(mi); } } } return methodInfoList; } public MethodInfoList getDeclaredMethodInfo() { return getDeclaredMethodInfo(/* methodName = */ null, /* getNormalMethods = */ true, /* getConstructorMethods = */ false, /* getStaticInitializerMethods = */ false); } public MethodInfoList getMethodInfo() { return getMethodInfo(/* methodName = */ null, /* getNormalMethods = */ true, /* getConstructorMethods = */ false, /* getStaticInitializerMethods = */ false); } public MethodInfoList getDeclaredConstructorInfo() { return getDeclaredMethodInfo(/* methodName = */ null, /* getNormalMethods = */ false, /* getConstructorMethods = */ true, /* getStaticInitializerMethods = */ false); } public MethodInfoList getConstructorInfo() { return getMethodInfo(/* methodName = */ null, /* getNormalMethods = */ false, /* getConstructorMethods = */ true, /* getStaticInitializerMethods = */ false); } public MethodInfoList getDeclaredMethodAndConstructorInfo() { return getDeclaredMethodInfo(/* methodName = */ null, /* getNormalMethods = */ true, /* getConstructorMethods = */ true, /* getStaticInitializerMethods = */ false); } public MethodInfoList getMethodAndConstructorInfo() { return getMethodInfo(/* methodName = */ null, /* getNormalMethods = */ true, /* getConstructorMethods = */ true, /* getStaticInitializerMethods = */ false); } public MethodInfoList getDeclaredMethodInfo(final String methodName) { return getDeclaredMethodInfo(methodName, /* ignored */ false, /* ignored */ false, /* ignored */ false); } public MethodInfoList getMethodInfo(final String methodName) { return getMethodInfo(methodName, /* ignored */ false, /* ignored */ false, /* ignored */ false); } /** * Get the method annotations. * * @return A list of annotations or meta-annotations on methods declared by the class, (not including methods * declared by the interfaces or superclasses of this class), as a list of {@link ClassInfo} objects, or * the empty list if none. N.B. these annotations do not contain specific annotation parameters -- call * {@link MethodInfo#getAnnotationInfo()} to get details on specific method annotation instances. */ public ClassInfoList getMethodAnnotations() { return getFieldOrMethodAnnotations(/* isField = */ false); } /** * Get the classes that have this class as a method annotation. * * @return A list of classes that have a declared method with this annotation or meta-annotation, or the empty * list if none. */ public ClassInfoList getClassesWithMethodAnnotation() { return getClassesWithFieldOrMethodAnnotation(/* isField = */ false); } /** * Get the classes that have this class as a direct method annotation. * * @return A list of classes that declare methods that are directly annotated (i.e. are not meta-annotated) with * the requested method annotation, or the empty list if none. */ ClassInfoList getClassesWithMethodAnnotationDirectOnly() { return new ClassInfoList(this.filterClassInfo(RelType.CLASSES_WITH_METHOD_ANNOTATION, /* strictWhitelist = */ !isExternalClass), /* sortByName = */ true); } // Fields public FieldInfoList getDeclaredFieldInfo() { if (!scanResult.scanSpec.enableFieldInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableFieldInfo() before #scan()"); } return fieldInfo == null ? FieldInfoList.EMPTY_LIST : fieldInfo; } public FieldInfoList getFieldInfo() { if (!scanResult.scanSpec.enableFieldInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableFieldInfo() before #scan()"); } // Implement field overriding final FieldInfoList fieldInfoList = new FieldInfoList(); final Set<String> fieldNameSet = new HashSet<>(); for (final ClassInfo ci : getOverrideOrder()) { for (final FieldInfo fi : ci.getDeclaredFieldInfo()) { // If field has not been overridden by field of same name if (fieldNameSet.add(fi.getName())) { // Add field to output order fieldInfoList.add(fi); } } } return fieldInfoList; } public FieldInfo getDeclaredFieldInfo(final String fieldName) { if (!scanResult.scanSpec.enableFieldInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableFieldInfo() before #scan()"); } if (fieldInfo == null) { return null; } for (final FieldInfo fi : fieldInfo) { if (fi.getName().equals(fieldName)) { return fi; } } return null; } public FieldInfo getFieldInfo(final String fieldName) { if (!scanResult.scanSpec.enableFieldInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableFieldInfo() before #scan()"); } // Implement field overriding for (final ClassInfo ci : getOverrideOrder()) { final FieldInfo fi = ci.getDeclaredFieldInfo(fieldName); if (fi != null) { return fi; } } return null; } /** * Get the classes that annotate fields of this class. * * @return A list of annotations on fields of this class, or the empty list if none. N.B. these annotations do * not contain specific annotation parameters -- call {@link FieldInfo#getAnnotationInfo()} to get * details on specific field annotation instances. */ public ClassInfoList getFieldAnnotations() { return getFieldOrMethodAnnotations(/* isField = */ true); } /** * Get the classes that have this class as a field annotation or meta-annotation. * * @return A list of classes that have a field with this annotation or meta-annotation, or the empty list if * none. */ public ClassInfoList getClassesWithFieldAnnotation() { return getClassesWithFieldOrMethodAnnotation(/* isField = */ true); } /** * Get the classes that have this class as a direct field annotation. * * @return A list of classes that declare fields that are directly annotated (i.e. are not meta-annotated) with * the requested method annotation, or the empty list if none. */ ClassInfoList getClassesWithFieldAnnotationDirectOnly() { return new ClassInfoList(this.filterClassInfo(RelType.CLASSES_WITH_FIELD_ANNOTATION, /* strictWhitelist = */ !isExternalClass), /* sortByName = */ true); } /** * Get the type signature of the class. * * @return The class type signature, if available, otherwise returns null. */ public ClassTypeSignature getTypeSignature() { if (typeSignatureStr == null) { return null; } if (typeSignature == null) { try { typeSignature = ClassTypeSignature.parse(typeSignatureStr, this); typeSignature.setScanResult(scanResult); } catch (final ParseException e) { throw new IllegalArgumentException(e); } } return typeSignature; } /** * Get the {@link URL} of the classpath element that this class was found within. * * @return The {@link URL} of the classpath element that this class was found within. */ public URL getClasspathElementURL() { if (classpathElementURL == null) { try { if (moduleRef != null) { // Classpath elt is a module classpathElementURL = moduleRef.getLocation().toURL(); } else if (classpathElementFile.isFile() && !jarfilePackageRoot.isEmpty()) { // Classpath elt is a jarfile with a non-empty package root classpathElementURL = URLPathEncoder.urlPathToURL( classpathElementFile.toURI().toURL().toString() + "!/" + jarfilePackageRoot); } else { // Classpath elt is a directory, or a jarfile with an empty package root classpathElementURL = classpathElementFile.toURI().toURL(); } } catch (final MalformedURLException e) { // Shouldn't happen throw new IllegalArgumentException(e); } } return classpathElementURL; } /** * Get the {@link File} for the classpath element package root dir or jar that this class was found within, or * null if this class was found in a module. (See also {@link #getModuleRef}.) * * @return The {@link File} for the classpath element package root dir or jar that this class was found within, * or null if this class was found in a module. (See also {@link #getModuleRef}.) */ public File getClasspathElementFile() { return classpathElementFile; } /** * Get the module that this class was found within, as a {@link ModuleRef}, or null if this class was found in a * directory or jar in the classpath. (See also {@link #getClasspathElementFile()}.) * * @return The module that this class was found within, as a {@link ModuleRef}, or null if this class was found * in a directory or jar in the classpath. (See also {@link #getClasspathElementFile()}.) */ public ModuleRef getModuleRef() { return moduleRef; } /** * The {@link Resource} for the classfile of this class. * * @return The {@link Resource} for the classfile of this class, or null if this is an "external" class (a * blacklisted class, or a class in a blacklisted package, or a class that was referenced as a * superclass, interface or annotation, but that wasn't in the scanned path). */ public Resource getResource() { return resource; } @Override public <T> Class<T> loadClass(final Class<T> superclassOrInterfaceType, final boolean ignoreExceptions) { return super.loadClass(superclassOrInterfaceType, ignoreExceptions); } @Override public <T> Class<T> loadClass(final Class<T> superclassOrInterfaceType) { return super.loadClass(superclassOrInterfaceType, /* ignoreExceptions = */ false); } @Override public Class<?> loadClass(final boolean ignoreExceptions) { return super.loadClass(ignoreExceptions); } @Override public Class<?> loadClass() { return super.loadClass(/* ignoreExceptions = */ false); } /* (non-Javadoc) * @see io.github.classgraph.ScanResultObject#getClassName() */ @Override protected String getClassName() { return name; } /* (non-Javadoc) * @see io.github.classgraph.ScanResultObject#getClassInfo() */ @Override protected ClassInfo getClassInfo() { return this; } /* (non-Javadoc) * @see io.github.classgraph.ScanResultObject#setScanResult(io.github.classgraph.ScanResult) */ @Override void setScanResult(final ScanResult scanResult) { super.setScanResult(scanResult); if (this.typeSignature != null) { this.typeSignature.setScanResult(scanResult); } if (annotationInfo != null) { for (final AnnotationInfo ai : annotationInfo) { ai.setScanResult(scanResult); } } if (fieldInfo != null) { for (final FieldInfo fi : fieldInfo) { fi.setScanResult(scanResult); } } if (methodInfo != null) { for (final MethodInfo mi : methodInfo) { mi.setScanResult(scanResult); } } if (annotationDefaultParamValues != null) { for (final AnnotationParameterValue apv : annotationDefaultParamValues) { apv.setScanResult(scanResult); } } } /** * Add names of classes referenced by this class. * * @param refdClassNames * the referenced class names */ void addReferencedClassNames(final Set<String> refdClassNames) { if (this.referencedClassNames == null) { this.referencedClassNames = refdClassNames; } else { this.referencedClassNames.addAll(refdClassNames); } } /** * Get the names of any classes referenced in this class' type descriptor, or the type descriptors of fields, * methods or annotations. * * @param referencedClassNames * the referenced class names */ @Override protected void findReferencedClassNames(final Set<String> referencedClassNames) { getMethodInfo().findReferencedClassNames(referencedClassNames); getFieldInfo().findReferencedClassNames(referencedClassNames); getAnnotationInfo().findReferencedClassNames(referencedClassNames); if (annotationDefaultParamValues != null) { annotationDefaultParamValues.findReferencedClassNames(referencedClassNames); } final ClassTypeSignature classSig = getTypeSignature(); if (classSig != null) { classSig.findReferencedClassNames(referencedClassNames); } // Remove any self-references referencedClassNames.remove(name); } /** * Set the list of ClassInfo objects for classes referenced by this class. * * @param refdClasses * the referenced classes */ void setReferencedClasses(final ClassInfoList refdClasses) { this.referencedClasses = refdClasses; } /** * Get the class dependencies. * * @return A {@link ClassInfoList} of {@link ClassInfo} objects for all classes referenced by this class. Note * that you need to call {@link ClassGraph#enableInterClassDependencies()} before * {@link ClassGraph#scan()} for this method to work. You should also call * {@link ClassGraph#enableExternalClasses()} before {@link ClassGraph#scan()} if you want * non-whitelisted classes to appear in the result. */ public ClassInfoList getClassDependencies() { if (!scanResult.scanSpec.enableInterClassDependencies) { throw new IllegalArgumentException( "Please call ClassGraph#enableInterClassDependencies() before #scan()"); } return referencedClasses == null ? ClassInfoList.EMPTY_LIST : referencedClasses; } /** * Compare based on class name. * * @param o * the other object * @return the comparison result */ @Override public int compareTo(final ClassInfo o) { return this.name.compareTo(o.name); } /** * Use class name for equals(). * * @param obj * the other object * @return Whether the objects were equal. */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } final ClassInfo other = (ClassInfo) obj; return name.equals(other.name); } /** * Use hash code of class name. * * @return the hashcode */ @Override public int hashCode() { return name != null ? name.hashCode() : 33; } /** * To string. * * @param typeNameOnly * if true, convert type name to string only. * @return the string */ private String toString(final boolean typeNameOnly) { final ClassTypeSignature typeSig = getTypeSignature(); if (typeSig != null) { // Generic classes return typeSig.toString(name, typeNameOnly, modifiers, isAnnotation, isInterface); } else { // Non-generic classes final StringBuilder buf = new StringBuilder(); if (typeNameOnly) { buf.append(name); } else { TypeUtils.modifiersToString(modifiers, ModifierType.CLASS, /* ignored */ false, buf); if (buf.length() > 0) { buf.append(' '); } buf.append(isAnnotation ? "@interface " : isInterface ? "interface " : (modifiers & 0x4000) != 0 ? "enum " : "class "); buf.append(name); final ClassInfo superclass = getSuperclass(); if (superclass != null && !superclass.getName().equals("java.lang.Object")) { buf.append(" extends ").append(superclass.toString(/* typeNameOnly = */ true)); } final Set<ClassInfo> interfaces = this.filterClassInfo(RelType.IMPLEMENTED_INTERFACES, /* strictWhitelist = */ false).directlyRelatedClasses; if (!interfaces.isEmpty()) { buf.append(isInterface ? " extends " : " implements "); boolean first = true; for (final ClassInfo iface : interfaces) { if (first) { first = false; } else { buf.append(", "); } buf.append(iface.toString(/* typeNameOnly = */ true)); } } } return buf.toString(); } } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return toString(false); } }
package io.github.classgraph; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import io.github.classgraph.Scanner.ClassfileScanWorkUnit; import nonapi.io.github.classgraph.ScanSpec; import nonapi.io.github.classgraph.concurrency.WorkQueue; import nonapi.io.github.classgraph.types.ParseException; import nonapi.io.github.classgraph.utils.InputStreamOrByteBufferAdapter; import nonapi.io.github.classgraph.utils.JarUtils; import nonapi.io.github.classgraph.utils.Join; import nonapi.io.github.classgraph.utils.LogNode; /** * A classfile binary format parser. Implements its own buffering to avoid the overhead of using DataInputStream. * This class should only be used by a single thread at a time, but can be re-used to scan multiple classfiles in * sequence, to avoid re-allocating buffer memory. */ class Classfile { /** The InputStream or ByteBuffer for the current classfile. */ private InputStreamOrByteBufferAdapter inputStreamOrByteBuffer; /** The classpath element that contains this classfile. */ private final ClasspathElement classpathElement; /** The classpath order. */ private final List<ClasspathElement> classpathOrder; /** The relative path to the classfile (should correspond to className). */ private final String relativePath; /** The classfile resource. */ private final Resource classfileResource; /** The name of the class. */ private String className; /** Whether this is an external class. */ private final boolean isExternalClass; /** The class modifiers. */ private int classModifiers; /** Whether this class is an interface. */ private boolean isInterface; /** Whether this class is an annotation. */ private boolean isAnnotation; /** The superclass name. (can be null if no superclass, or if superclass is blacklisted.) */ private String superclassName; /** The implemented interfaces. */ private List<String> implementedInterfaces; /** The class annotations. */ private AnnotationInfoList classAnnotations; /** The fully qualified name of the defining method. */ private String fullyQualifiedDefiningMethodName; /** Class containment entries. */ private List<SimpleEntry<String, String>> classContainmentEntries; /** Annotation default parameter values. */ private AnnotationParameterValueList annotationParamDefaultValues; /** Referenced class names. */ private Set<String> refdClassNames; /** The field info list. */ private FieldInfoList fieldInfoList; /** The method info list. */ private MethodInfoList methodInfoList; /** The type signature. */ private String typeSignature; /** * Class names already scheduled for scanning. If a class name is not in this list, the class is external, and * has not yet been scheduled for scanning. */ private final Set<String> classNamesScheduledForScanning; /** Any additional work units scheduled for scanning. */ private List<ClassfileScanWorkUnit> additionalWorkUnits; /** The scan spec. */ private final ScanSpec scanSpec; /** The log. */ private final LogNode log; /** The number of constant pool entries plus one. */ private int cpCount; /** The byte offset for the beginning of each entry in the constant pool. */ private int[] entryOffset; /** The tag (type) for each entry in the constant pool. */ private int[] entryTag; /** The indirection index for String/Class entries in the constant pool. */ private int[] indirectStringRefs; /** An empty array for the case where there are no annotations. */ private static final AnnotationInfo[] NO_ANNOTATIONS = new AnnotationInfo[0]; /** Thrown when a classfile's contents are not in the correct format. */ class ClassfileFormatException extends IOException { /** serialVersionUID. */ static final long serialVersionUID = 1L; /** * Constructor. * * @param message * the message */ public ClassfileFormatException(final String message) { super(message); } /** * Constructor. * * @param message * the message * @param cause * the cause */ public ClassfileFormatException(final String message, final Throwable cause) { super(message, cause); } /** * Speed up exception (stack trace is not needed for this exception). * * @return this */ @Override public synchronized Throwable fillInStackTrace() { return this; } } /** Thrown when a classfile needs to be skipped. */ class SkipClassException extends IOException { /** serialVersionUID. */ static final long serialVersionUID = 1L; /** * Constructor. * * @param message * the message */ public SkipClassException(final String message) { super(message); } /** * Speed up exception (stack trace is not needed for this exception). * * @return this */ @Override public synchronized Throwable fillInStackTrace() { return this; } } /** * Extend scanning to a superclass, interface or annotation. * * @param className * the class name * @param relationship * the relationship type */ private void scheduleScanningIfExternalClass(final String className, final String relationship) { // The call to classNamesScheduledForScanning.add(className) will return true only for external classes // that have not yet been scheduled for scanning if (className != null && !className.equals("java.lang.Object") && classNamesScheduledForScanning.add(className)) { // Search for the named class' classfile among classpath elements, in classpath order (this is O(N) // for each class, but there shouldn't be too many cases of extending scanning upwards) final String classfilePath = JarUtils.classNameToClassfilePath(className); // First check current classpath element, to avoid iterating through other classpath elements Resource classResource = classpathElement.getResource(classfilePath); ClasspathElement foundInClasspathElt = null; if (classResource != null) { // Found the classfile in the current classpath element foundInClasspathElt = classpathElement; } else { // Didn't find the classfile in the current classpath element -- iterate through other elements for (final ClasspathElement classpathOrderElt : classpathOrder) { if (classpathOrderElt != classpathElement) { classResource = classpathOrderElt.getResource(classfilePath); if (classResource != null) { foundInClasspathElt = classpathOrderElt; break; } } } } if (classResource != null) { // Found class resource if (log != null) { log.log("Scheduling external class for scanning: " + relationship + " " + className + (foundInClasspathElt == classpathElement ? "" : " -- found in classpath element " + foundInClasspathElt)); } if (additionalWorkUnits == null) { additionalWorkUnits = new ArrayList<>(); } // Schedule class resource for scanning additionalWorkUnits.add(new ClassfileScanWorkUnit(foundInClasspathElt, classResource, /* isExternalClass = */ true)); } else { if (log != null) { log.log("External " + relationship + " " + className + " was not found in " + "non-blacklisted packages -- cannot extend scanning to this class"); } } } } /** * Check if scanning needs to be extended upwards to an external superclass, interface or annotation. */ private void extendScanningUpwards() { // Check superclass if (superclassName != null) { scheduleScanningIfExternalClass(superclassName, "superclass"); } // Check implemented interfaces if (implementedInterfaces != null) { for (final String interfaceName : implementedInterfaces) { scheduleScanningIfExternalClass(interfaceName, "interface"); } } // Check class annotations if (classAnnotations != null) { for (final AnnotationInfo annotationInfo : classAnnotations) { scheduleScanningIfExternalClass(annotationInfo.getName(), "class annotation"); } } // Check method annotations and method parameter annotations if (methodInfoList != null) { for (final MethodInfo methodInfo : methodInfoList) { if (methodInfo.annotationInfo != null) { for (final AnnotationInfo methodAnnotationInfo : methodInfo.annotationInfo) { scheduleScanningIfExternalClass(methodAnnotationInfo.getName(), "method annotation"); } if (methodInfo.parameterAnnotationInfo != null && methodInfo.parameterAnnotationInfo.length > 0) { for (final AnnotationInfo[] paramAnns : methodInfo.parameterAnnotationInfo) { if (paramAnns != null && paramAnns.length > 0) { for (final AnnotationInfo paramAnn : paramAnns) { scheduleScanningIfExternalClass(paramAnn.getName(), "method parameter annotation"); } } } } } } } // Check field annotations if (fieldInfoList != null) { for (final FieldInfo fieldInfo : fieldInfoList) { if (fieldInfo.annotationInfo != null) { for (final AnnotationInfo fieldAnnotationInfo : fieldInfo.annotationInfo) { scheduleScanningIfExternalClass(fieldAnnotationInfo.getName(), "field annotation"); } } } } } /** * Link classes. Not threadsafe, should be run in a single-threaded context. * * @param classNameToClassInfo * map from class name to class info * @param packageNameToPackageInfo * map from package name to package info * @param moduleNameToModuleInfo * map from module name to module info */ void link(final Map<String, ClassInfo> classNameToClassInfo, final Map<String, PackageInfo> packageNameToPackageInfo, final Map<String, ModuleInfo> moduleNameToModuleInfo) { boolean isModuleDescriptor = false; boolean isPackageDescriptor = false; ClassInfo classInfo = null; if (className.equals("module-info")) { isModuleDescriptor = true; } else if (className.equals("package-info") || className.endsWith(".package-info")) { isPackageDescriptor = true; } else { // Handle regular classfile classInfo = ClassInfo.addScannedClass(className, classModifiers, isExternalClass, classNameToClassInfo, classpathElement, classfileResource); classInfo.setModifiers(classModifiers); classInfo.setIsInterface(isInterface); classInfo.setIsAnnotation(isAnnotation); if (superclassName != null) { classInfo.addSuperclass(superclassName, classNameToClassInfo); } if (implementedInterfaces != null) { for (final String interfaceName : implementedInterfaces) { classInfo.addImplementedInterface(interfaceName, classNameToClassInfo); } } if (classAnnotations != null) { for (final AnnotationInfo classAnnotation : classAnnotations) { classInfo.addClassAnnotation(classAnnotation, classNameToClassInfo); } } if (classContainmentEntries != null) { ClassInfo.addClassContainment(classContainmentEntries, classNameToClassInfo); } if (annotationParamDefaultValues != null) { classInfo.addAnnotationParamDefaultValues(annotationParamDefaultValues); } if (fullyQualifiedDefiningMethodName != null) { classInfo.addFullyQualifiedDefiningMethodName(fullyQualifiedDefiningMethodName); } if (fieldInfoList != null) { classInfo.addFieldInfo(fieldInfoList, classNameToClassInfo); } if (methodInfoList != null) { classInfo.addMethodInfo(methodInfoList, classNameToClassInfo); } if (typeSignature != null) { classInfo.setTypeSignature(typeSignature); } if (refdClassNames != null) { classInfo.addReferencedClassNames(refdClassNames); } } // Get or create PackageInfo, if this is not a module descriptor (the module descriptor's package is "") PackageInfo packageInfo = null; if (!isModuleDescriptor) { // Get package for this class or package descriptor packageInfo = PackageInfo.getOrCreatePackage(PackageInfo.getParentPackageName(className), packageNameToPackageInfo); if (isPackageDescriptor) { // Add any class annotations on the package-info.class file to the ModuleInfo packageInfo.addAnnotations(classAnnotations); } else if (classInfo != null) { // Add ClassInfo to PackageInfo, and vice versa packageInfo.addClassInfo(classInfo); classInfo.packageInfo = packageInfo; } } // Get or create ModuleInfo, if there is a module name final String moduleName = classpathElement.getModuleName(); if (moduleName != null) { // Get or create a ModuleInfo object for this module ModuleInfo moduleInfo = moduleNameToModuleInfo.get(moduleName); if (moduleInfo == null) { moduleNameToModuleInfo.put(moduleName, moduleInfo = new ModuleInfo(classfileResource.getModuleRef(), classpathElement)); } if (isModuleDescriptor) { // Add any class annotations on the module-info.class file to the ModuleInfo moduleInfo.addAnnotations(classAnnotations); } if (classInfo != null) { // Add ClassInfo to ModuleInfo, and vice versa moduleInfo.addClassInfo(classInfo); classInfo.moduleInfo = moduleInfo; } if (packageInfo != null) { // Add PackageInfo to ModuleInfo moduleInfo.addPackageInfo(packageInfo); } } } /** * Get the byte offset within the buffer of a string from the constant pool, or 0 for a null string. * * @param cpIdx * the constant pool index * @param subFieldIdx * should be 0 for CONSTANT_Utf8, CONSTANT_Class and CONSTANT_String, and for * CONSTANT_NameAndType_info, fetches the name for value 0, or the type descriptor for value 1. * @return the constant pool string offset * @throws ClassfileFormatException * If a problem is detected */ private int getConstantPoolStringOffset(final int cpIdx, final int subFieldIdx) throws ClassfileFormatException { if (cpIdx < 1 || cpIdx >= cpCount) { throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, " + (cpCount - 1) + "] -- cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } final int t = entryTag[cpIdx]; if ((t != 12 && subFieldIdx != 0) || (t == 12 && subFieldIdx != 0 && subFieldIdx != 1)) { throw new ClassfileFormatException( "Bad subfield index " + subFieldIdx + " for tag " + t + ", cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } int cpIdxToUse; if (t == 0) { // Assume this means null return 0; } else if (t == 1) { // CONSTANT_Utf8 cpIdxToUse = cpIdx; } else if (t == 7 || t == 8 || t == 19) { // t == 7 => CONSTANT_Class, e.g. "[[I", "[Ljava/lang/Thread;"; t == 8 => CONSTANT_String; // t == 19 => CONSTANT_Method_Info final int indirIdx = indirectStringRefs[cpIdx]; if (indirIdx == -1) { // Should not happen throw new ClassfileFormatException("Bad string indirection index, cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } if (indirIdx == 0) { // I assume this represents a null string, since the zeroeth entry is unused return 0; } cpIdxToUse = indirIdx; } else if (t == 12) { // CONSTANT_NameAndType_info final int compoundIndirIdx = indirectStringRefs[cpIdx]; if (compoundIndirIdx == -1) { // Should not happen throw new ClassfileFormatException("Bad string indirection index, cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } final int indirIdx = (subFieldIdx == 0 ? (compoundIndirIdx >> 16) : compoundIndirIdx) & 0xffff; if (indirIdx == 0) { // Should not happen throw new ClassfileFormatException("Bad string indirection index, cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } cpIdxToUse = indirIdx; } else { throw new ClassfileFormatException("Wrong tag number " + t + " at constant pool index " + cpIdx + ", " + "cannot continue reading class. Please report this at " + "https://github.com/classgraph/classgraph/issues"); } if (cpIdxToUse < 1 || cpIdxToUse >= cpCount) { throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, " + (cpCount - 1) + "] -- cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } return entryOffset[cpIdxToUse]; } /** * Get a string from the constant pool, optionally replacing '/' with '.'. * * @param cpIdx * the constant pool index * @param replaceSlashWithDot * if true, replace slash with dot in the result. * @param stripLSemicolon * if true, strip 'L' from the beginning and ';' from the end before returning (for class reference * constants) * @return the constant pool string * @throws ClassfileFormatException * If a problem occurs. * @throws IOException * If an IO exception occurs. */ private String getConstantPoolString(final int cpIdx, final boolean replaceSlashWithDot, final boolean stripLSemicolon) throws ClassfileFormatException, IOException { final int constantPoolStringOffset = getConstantPoolStringOffset(cpIdx, /* subFieldIdx = */ 0); return constantPoolStringOffset == 0 ? null : inputStreamOrByteBuffer.readString(constantPoolStringOffset, replaceSlashWithDot, stripLSemicolon); } /** * Get a string from the constant pool. * * @param cpIdx * the constant pool index * @param subFieldIdx * should be 0 for CONSTANT_Utf8, CONSTANT_Class and CONSTANT_String, and for * CONSTANT_NameAndType_info, fetches the name for value 0, or the type descriptor for value 1. * @return the constant pool string * @throws ClassfileFormatException * If a problem occurs. * @throws IOException * If an IO exception occurs. */ private String getConstantPoolString(final int cpIdx, final int subFieldIdx) throws ClassfileFormatException, IOException { final int constantPoolStringOffset = getConstantPoolStringOffset(cpIdx, subFieldIdx); return constantPoolStringOffset == 0 ? null : inputStreamOrByteBuffer.readString(constantPoolStringOffset, /* replaceSlashWithDot = */ false, /* stripLSemicolon = */ false); } /** * Get a string from the constant pool. * * @param cpIdx * the constant pool index * @return the constant pool string * @throws ClassfileFormatException * If a problem occurs. * @throws IOException * If an IO exception occurs. */ private String getConstantPoolString(final int cpIdx) throws ClassfileFormatException, IOException { return getConstantPoolString(cpIdx, /* subFieldIdx = */ 0); } /** * Get the first UTF8 byte of a string in the constant pool, or '\0' if the string is null or empty. * * @param cpIdx * the constant pool index * @return the first byte of the constant pool string * @throws ClassfileFormatException * If a problem occurs. * @throws IOException * If an IO exception occurs. */ private byte getConstantPoolStringFirstByte(final int cpIdx) throws ClassfileFormatException, IOException { final int constantPoolStringOffset = getConstantPoolStringOffset(cpIdx, /* subFieldIdx = */ 0); if (constantPoolStringOffset == 0) { return '\0'; } final int utfLen = inputStreamOrByteBuffer.readUnsignedShort(constantPoolStringOffset); if (utfLen == 0) { return '\0'; } return inputStreamOrByteBuffer.buf[constantPoolStringOffset + 2]; } /** * Get a string from the constant pool, and interpret it as a class name by replacing '/' with '.'. * * @param cpIdx * the constant pool index * @return the constant pool class name * @throws ClassfileFormatException * If a problem occurs. * @throws IOException * If an IO exception occurs. */ private String getConstantPoolClassName(final int cpIdx) throws ClassfileFormatException, IOException { return getConstantPoolString(cpIdx, /* replaceSlashWithDot = */ true, /* stripLSemicolon = */ false); } /** * Get a string from the constant pool representing an internal string descriptor for a class name * ("Lcom/xyz/MyClass;"), and interpret it as a class name by replacing '/' with '.', and removing the leading * "L" and the trailing ";". * * @param cpIdx * the constant pool index * @return the constant pool class descriptor * @throws ClassfileFormatException * If a problem occurs. * @throws IOException * If an IO exception occurs. */ private String getConstantPoolClassDescriptor(final int cpIdx) throws ClassfileFormatException, IOException { return getConstantPoolString(cpIdx, /* replaceSlashWithDot = */ true, /* stripLSemicolon = */ true); } /** * Compare a string in the constant pool with a given constant, without constructing the String object. * * @param cpIdx * the constant pool index * @param otherString * the other string * @return true, if successful * @throws ClassfileFormatException * If a problem occurs. * @throws IOException * If an IO exception occurs. */ private boolean constantPoolStringEquals(final int cpIdx, final String otherString) throws ClassfileFormatException, IOException { final int strOffset = getConstantPoolStringOffset(cpIdx, /* subFieldIdx = */ 0); if (strOffset == 0) { return otherString == null; } else if (otherString == null) { return false; } final int strLen = inputStreamOrByteBuffer.readUnsignedShort(strOffset); final int otherLen = otherString.length(); if (strLen != otherLen) { return false; } final int strStart = strOffset + 2; for (int i = 0; i < strLen; i++) { if ((char) (inputStreamOrByteBuffer.buf[strStart + i] & 0xff) != otherString.charAt(i)) { return false; } } return true; } /** * Read an unsigned short from the constant pool. * * @param cpIdx * the constant pool index. * @return the unsigned short * @throws IOException * If an I/O exception occurred. */ private int cpReadUnsignedShort(final int cpIdx) throws IOException { if (cpIdx < 1 || cpIdx >= cpCount) { throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, " + (cpCount - 1) + "] -- cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } return inputStreamOrByteBuffer.readUnsignedShort(entryOffset[cpIdx]); } /** * Read an int from the constant pool. * * @param cpIdx * the constant pool index. * @return the int * @throws IOException * If an I/O exception occurred. */ private int cpReadInt(final int cpIdx) throws IOException { if (cpIdx < 1 || cpIdx >= cpCount) { throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, " + (cpCount - 1) + "] -- cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } return inputStreamOrByteBuffer.readInt(entryOffset[cpIdx]); } /** * Read a long from the constant pool. * * @param cpIdx * the constant pool index. * @return the long * @throws IOException * If an I/O exception occurred. */ private long cpReadLong(final int cpIdx) throws IOException { if (cpIdx < 1 || cpIdx >= cpCount) { throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, " + (cpCount - 1) + "] -- cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } return inputStreamOrByteBuffer.readLong(entryOffset[cpIdx]); } /** * Get a field constant from the constant pool. * * @param tag * the tag * @param fieldTypeDescriptorFirstChar * the first char of the field type descriptor * @param cpIdx * the constant pool index * @return the field constant pool value * @throws ClassfileFormatException * If a problem occurs. * @throws IOException * If an IO exception occurs. */ private Object getFieldConstantPoolValue(final int tag, final char fieldTypeDescriptorFirstChar, final int cpIdx) throws ClassfileFormatException, IOException { switch (tag) { case 1: // Modified UTF8 case 7: // Class -- N.B. Unused? Class references do not seem to actually be stored as constant initalizers case 8: // String // Forward or backward indirect reference to a modified UTF8 entry return getConstantPoolString(cpIdx); case 3: // int, short, char, byte, boolean are all represented by Constant_INTEGER final int intVal = cpReadInt(cpIdx); switch (fieldTypeDescriptorFirstChar) { case 'I': return intVal; case 'S': return (short) intVal; case 'C': return (char) intVal; case 'B': return (byte) intVal; case 'Z': return intVal != 0; default: // Fall through } throw new ClassfileFormatException("Unknown Constant_INTEGER type " + fieldTypeDescriptorFirstChar + ", " + "cannot continue reading class. Please report this at " + "https://github.com/classgraph/classgraph/issues"); case 4: // float return Float.intBitsToFloat(cpReadInt(cpIdx)); case 5: // long return cpReadLong(cpIdx); case 6: // double return Double.longBitsToDouble(cpReadLong(cpIdx)); default: // ClassGraph doesn't expect other types // (N.B. in particular, enum values are not stored in the constant pool, so don't need to be handled) throw new ClassfileFormatException("Unknown constant pool tag " + tag + ", " + "cannot continue reading class. Please report this at " + "https://github.com/classgraph/classgraph/issues"); } } /** * Read annotation entry from classfile. * * @return the annotation, as an {@link AnnotationInfo} object. * @throws IOException * If an IO exception occurs. */ private AnnotationInfo readAnnotation() throws IOException { // Lcom/xyz/Annotation; -> Lcom.xyz.Annotation; final String annotationClassName = getConstantPoolClassDescriptor( inputStreamOrByteBuffer.readUnsignedShort()); final int numElementValuePairs = inputStreamOrByteBuffer.readUnsignedShort(); AnnotationParameterValueList paramVals = null; if (numElementValuePairs > 0) { paramVals = new AnnotationParameterValueList(numElementValuePairs); for (int i = 0; i < numElementValuePairs; i++) { final String paramName = getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort()); final Object paramValue = readAnnotationElementValue(); paramVals.add(new AnnotationParameterValue(paramName, paramValue)); } } return new AnnotationInfo(annotationClassName, paramVals); } /** * Read annotation element value from classfile. * * @return the annotation element value * @throws IOException * If an IO exception occurs. */ private Object readAnnotationElementValue() throws IOException { final int tag = (char) inputStreamOrByteBuffer.readUnsignedByte(); switch (tag) { case 'B': return (byte) cpReadInt(inputStreamOrByteBuffer.readUnsignedShort()); case 'C': return (char) cpReadInt(inputStreamOrByteBuffer.readUnsignedShort()); case 'D': return Double.longBitsToDouble(cpReadLong(inputStreamOrByteBuffer.readUnsignedShort())); case 'F': return Float.intBitsToFloat(cpReadInt(inputStreamOrByteBuffer.readUnsignedShort())); case 'I': return cpReadInt(inputStreamOrByteBuffer.readUnsignedShort()); case 'J': return cpReadLong(inputStreamOrByteBuffer.readUnsignedShort()); case 'S': return (short) cpReadUnsignedShort(inputStreamOrByteBuffer.readUnsignedShort()); case 'Z': return cpReadInt(inputStreamOrByteBuffer.readUnsignedShort()) != 0; case 's': return getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort()); case 'e': { // Return type is AnnotationEnumVal. final String annotationClassName = getConstantPoolClassDescriptor( inputStreamOrByteBuffer.readUnsignedShort()); final String annotationConstName = getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort()); return new AnnotationEnumValue(annotationClassName, annotationConstName); } case 'c': // Return type is AnnotationClassRef (for class references in annotations) final String classRefTypeDescriptor = getConstantPoolString( inputStreamOrByteBuffer.readUnsignedShort()); return new AnnotationClassRef(classRefTypeDescriptor); case '@': // Complex (nested) annotation. Return type is AnnotationInfo. return readAnnotation(); case '[': // Return type is Object[] (of nested annotation element values) final int count = inputStreamOrByteBuffer.readUnsignedShort(); final Object[] arr = new Object[count]; for (int i = 0; i < count; ++i) { // Nested annotation element value arr[i] = readAnnotationElementValue(); } return arr; default: throw new ClassfileFormatException("Class " + className + " has unknown annotation element type tag '" + ((char) tag) + "': element size unknown, cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } } /** * Read constant pool entries. * * @throws IOException * Signals that an I/O exception has occurred. */ private void readConstantPoolEntries() throws IOException { // Only record class dependency info if inter-class dependencies are enabled List<Integer> classNameCpIdxs = null; List<Integer> typeSignatureIdxs = null; if (scanSpec.enableInterClassDependencies) { classNameCpIdxs = new ArrayList<Integer>(); typeSignatureIdxs = new ArrayList<Integer>(); } // Read size of constant pool cpCount = inputStreamOrByteBuffer.readUnsignedShort(); // Allocate storage for constant pool entryOffset = new int[cpCount]; entryTag = new int[cpCount]; indirectStringRefs = new int[cpCount]; Arrays.fill(indirectStringRefs, 0, cpCount, -1); // Read constant pool entries for (int i = 1, skipSlot = 0; i < cpCount; i++) { if (skipSlot == 1) { // Skip a slot (keeps Scrutinizer happy -- it doesn't like i++ in case 6) skipSlot = 0; continue; } entryTag[i] = inputStreamOrByteBuffer.readUnsignedByte(); entryOffset[i] = inputStreamOrByteBuffer.curr; switch (entryTag[i]) { case 0: // Impossible, probably buffer underflow throw new ClassfileFormatException("Unknown constant pool tag 0 in classfile " + relativePath + " (possible buffer underflow issue). Please report this at " + "https://github.com/classgraph/classgraph/issues"); case 1: // Modified UTF8 final int strLen = inputStreamOrByteBuffer.readUnsignedShort(); inputStreamOrByteBuffer.skip(strLen); break; case 3: // int, short, char, byte, boolean are all represented by Constant_INTEGER case 4: // float inputStreamOrByteBuffer.skip(4); break; case 5: // long case 6: // double inputStreamOrByteBuffer.skip(8); skipSlot = 1; // double slot break; case 7: // Class reference (format is e.g. "java/lang/String") // Forward or backward indirect reference to a modified UTF8 entry indirectStringRefs[i] = inputStreamOrByteBuffer.readUnsignedShort(); if (scanSpec.enableInterClassDependencies && entryTag[i] == 7) { // If this is a class ref, and inter-class dependencies are enabled, record the dependency classNameCpIdxs.add(indirectStringRefs[i]); } break; case 8: // String // Forward or backward indirect reference to a modified UTF8 entry indirectStringRefs[i] = inputStreamOrByteBuffer.readUnsignedShort(); break; case 9: // field ref // Refers to a class ref (case 7) and then a name and type (case 12) inputStreamOrByteBuffer.skip(4); break; case 10: // method ref // Refers to a class ref (case 7) and then a name and type (case 12) inputStreamOrByteBuffer.skip(4); break; case 11: // interface method ref // Refers to a class ref (case 7) and then a name and type (case 12) inputStreamOrByteBuffer.skip(4); break; case 12: // name and type final int nameRef = inputStreamOrByteBuffer.readUnsignedShort(); final int typeRef = inputStreamOrByteBuffer.readUnsignedShort(); if (scanSpec.enableInterClassDependencies) { typeSignatureIdxs.add(typeRef); } indirectStringRefs[i] = (nameRef << 16) | typeRef; break; case 15: // method handle inputStreamOrByteBuffer.skip(3); break; case 16: // method type inputStreamOrByteBuffer.skip(2); break; case 18: // invoke dynamic inputStreamOrByteBuffer.skip(4); break; case 19: // module (for module-info.class in JDK9+) // see https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.4 indirectStringRefs[i] = inputStreamOrByteBuffer.readUnsignedShort(); break; case 20: // package (for module-info.class in JDK9+) // see https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.4 inputStreamOrByteBuffer.skip(2); break; default: throw new ClassfileFormatException("Unknown constant pool tag " + entryTag[i] + " (element size unknown, cannot continue reading class). Please report this at " + "https://github.com/classgraph/classgraph/issues"); } } // Find classes referenced in the constant pool (note that there are some class refs that will not be // found this way, e.g. enum classes and class refs in annotation parameter values, since they are // referenced as strings (tag 1) rather than classes (tag 7) or type signatures (part of tag 12)). if (scanSpec.enableInterClassDependencies) { refdClassNames = new HashSet<>(); // Get class names from direct class references in constant pool for (final int cpIdx : classNameCpIdxs) { final String refdClassName = getConstantPoolString(cpIdx, /* replaceSlashWithDot = */ true, /* stripLSemicolon = */ false); if (refdClassName != null) { if (refdClassName.startsWith("[")) { // Parse array type signature, e.g. "[Ljava.lang.String;" -- uses '.' rather than '/' try { final TypeSignature typeSig = TypeSignature.parse(refdClassName.replace('.', '/'), /* definingClass = */ null); typeSig.findReferencedClassNames(refdClassNames); } catch (final ParseException e) { // Should not happen throw new ClassfileFormatException("Could not parse class name: " + refdClassName, e); } } else { refdClassNames.add(refdClassName); } } } // Get class names from type signatures in "name and type" entries in constant pool for (final int cpIdx : typeSignatureIdxs) { final String typeSigStr = getConstantPoolString(cpIdx); if (typeSigStr != null) { try { if (typeSigStr.indexOf('(') >= 0 || "<init>".equals(typeSigStr)) { // Parse the type signature final MethodTypeSignature typeSig = MethodTypeSignature.parse(typeSigStr, /* definingClassName = */ null); // Extract class names from type signature typeSig.findReferencedClassNames(refdClassNames); } else { // Parse the type signature final TypeSignature typeSig = TypeSignature.parse(typeSigStr, /* definingClassName = */ null); // Extract class names from type signature typeSig.findReferencedClassNames(refdClassNames); } } catch (final ParseException e) { throw new ClassfileFormatException("Could not parse type signature: " + typeSigStr, e); } } } } } /** * Read basic class information. * * @throws IOException * if an I/O exception occurs. * @throws ClassfileFormatException * if the classfile is incorrectly formatted. * @throws SkipClassException * if the classfile needs to be skipped (e.g. the class is non-public, and ignoreClassVisibility is * false) */ private void readBasicClassInfo() throws IOException, ClassfileFormatException, SkipClassException { // Modifier flags classModifiers = inputStreamOrByteBuffer.readUnsignedShort(); isInterface = (classModifiers & 0x0200) != 0; isAnnotation = (classModifiers & 0x2000) != 0; // The fully-qualified class name of this class, with slashes replaced with dots final String classNamePath = getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort()); if (classNamePath == null) { throw new ClassfileFormatException("Class name is null"); } className = classNamePath.replace('/', '.'); if ("java.lang.Object".equals(className)) { // Don't process java.lang.Object (it has a null superclass), though you can still search for classes // that are subclasses of java.lang.Object (as an external class). throw new SkipClassException("No need to scan java.lang.Object"); } // Check class visibility modifiers final boolean isModule = (classModifiers & 0x8000) != 0; // Equivalently filename is "module-info.class" final boolean isPackage = relativePath.regionMatches(relativePath.lastIndexOf('/') + 1, "package-info.class", 0, 18); if (!scanSpec.ignoreClassVisibility && !Modifier.isPublic(classModifiers) && !isModule && !isPackage) { throw new SkipClassException("Class is not public, and ignoreClassVisibility() was not called"); } // Make sure classname matches relative path if (!relativePath.endsWith(".class")) { // Should not happen throw new SkipClassException("Classfile filename " + relativePath + " does not end in \".class\""); } final int len = classNamePath.length(); if (relativePath.length() != len + 6 || !classNamePath.regionMatches(0, relativePath, 0, len)) { throw new SkipClassException( "Relative path " + relativePath + " does not match class name " + className); } // Superclass name, with slashes replaced with dots final int superclassNameCpIdx = inputStreamOrByteBuffer.readUnsignedShort(); if (superclassNameCpIdx > 0) { superclassName = getConstantPoolClassName(superclassNameCpIdx); } } /** * Read the class' interfaces. * * @throws IOException * if an I/O exception occurs. */ private void readInterfaces() throws IOException { // Interfaces final int interfaceCount = inputStreamOrByteBuffer.readUnsignedShort(); for (int i = 0; i < interfaceCount; i++) { final String interfaceName = getConstantPoolClassName(inputStreamOrByteBuffer.readUnsignedShort()); if (implementedInterfaces == null) { implementedInterfaces = new ArrayList<>(); } implementedInterfaces.add(interfaceName); } } /** * Read the class' fields. * * @throws IOException * if an I/O exception occurs. * @throws ClassfileFormatException * if the classfile is incorrectly formatted. */ private void readFields() throws IOException, ClassfileFormatException { // Fields final int fieldCount = inputStreamOrByteBuffer.readUnsignedShort(); for (int i = 0; i < fieldCount; i++) { // Info on modifier flags: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.5 final int fieldModifierFlags = inputStreamOrByteBuffer.readUnsignedShort(); final boolean isPublicField = ((fieldModifierFlags & 0x0001) == 0x0001); final boolean isStaticFinalField = ((fieldModifierFlags & 0x0018) == 0x0018); final boolean fieldIsVisible = isPublicField || scanSpec.ignoreFieldVisibility; final boolean getStaticFinalFieldConstValue = scanSpec.enableStaticFinalFieldConstantInitializerValues && isStaticFinalField && fieldIsVisible; if (!fieldIsVisible || (!scanSpec.enableFieldInfo && !getStaticFinalFieldConstValue)) { // Skip field inputStreamOrByteBuffer.readUnsignedShort(); // fieldNameCpIdx inputStreamOrByteBuffer.readUnsignedShort(); // fieldTypeDescriptorCpIdx final int attributesCount = inputStreamOrByteBuffer.readUnsignedShort(); for (int j = 0; j < attributesCount; j++) { inputStreamOrByteBuffer.readUnsignedShort(); // attributeNameCpIdx final int attributeLength = inputStreamOrByteBuffer.readInt(); inputStreamOrByteBuffer.skip(attributeLength); } } else { final int fieldNameCpIdx = inputStreamOrByteBuffer.readUnsignedShort(); final String fieldName = getConstantPoolString(fieldNameCpIdx); final int fieldTypeDescriptorCpIdx = inputStreamOrByteBuffer.readUnsignedShort(); final char fieldTypeDescriptorFirstChar = (char) getConstantPoolStringFirstByte( fieldTypeDescriptorCpIdx); String fieldTypeDescriptor; String fieldTypeSignature = null; fieldTypeDescriptor = getConstantPoolString(fieldTypeDescriptorCpIdx); Object fieldConstValue = null; AnnotationInfoList fieldAnnotationInfo = null; final int attributesCount = inputStreamOrByteBuffer.readUnsignedShort(); for (int j = 0; j < attributesCount; j++) { final int attributeNameCpIdx = inputStreamOrByteBuffer.readUnsignedShort(); final int attributeLength = inputStreamOrByteBuffer.readInt(); // See if field name matches one of the requested names for this class, and if it does, // check if it is initialized with a constant value if ((getStaticFinalFieldConstValue) && constantPoolStringEquals(attributeNameCpIdx, "ConstantValue")) { // http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.2 final int cpIdx = inputStreamOrByteBuffer.readUnsignedShort(); if (cpIdx < 1 || cpIdx >= cpCount) { throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, " + (cpCount - 1) + "] -- cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } fieldConstValue = getFieldConstantPoolValue(entryTag[cpIdx], fieldTypeDescriptorFirstChar, cpIdx); } else if (fieldIsVisible && constantPoolStringEquals(attributeNameCpIdx, "Signature")) { fieldTypeSignature = getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort()); } else if (scanSpec.enableAnnotationInfo && (constantPoolStringEquals(attributeNameCpIdx, "RuntimeVisibleAnnotations") || (!scanSpec.disableRuntimeInvisibleAnnotations && constantPoolStringEquals( attributeNameCpIdx, "RuntimeInvisibleAnnotations")))) { // Read annotation names final int fieldAnnotationCount = inputStreamOrByteBuffer.readUnsignedShort(); if (fieldAnnotationInfo == null && fieldAnnotationCount > 0) { fieldAnnotationInfo = new AnnotationInfoList(1); } if (fieldAnnotationInfo != null) { for (int k = 0; k < fieldAnnotationCount; k++) { final AnnotationInfo fieldAnnotation = readAnnotation(); fieldAnnotationInfo.add(fieldAnnotation); } } } else { // No match, just skip attribute inputStreamOrByteBuffer.skip(attributeLength); } } if (scanSpec.enableFieldInfo && fieldIsVisible) { if (fieldInfoList == null) { fieldInfoList = new FieldInfoList(); } fieldInfoList.add(new FieldInfo(className, fieldName, fieldModifierFlags, fieldTypeDescriptor, fieldTypeSignature, fieldConstValue, fieldAnnotationInfo)); } } } } /** * Read the class' methods. * * @throws IOException * if an I/O exception occurs. * @throws ClassfileFormatException * if the classfile is incorrectly formatted. */ private void readMethods() throws IOException, ClassfileFormatException { // Methods final int methodCount = inputStreamOrByteBuffer.readUnsignedShort(); for (int i = 0; i < methodCount; i++) { // Info on modifier flags: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.6 final int methodModifierFlags = inputStreamOrByteBuffer.readUnsignedShort(); final boolean isPublicMethod = ((methodModifierFlags & 0x0001) == 0x0001); final boolean methodIsVisible = isPublicMethod || scanSpec.ignoreMethodVisibility; String methodName = null; String methodTypeDescriptor = null; String methodTypeSignature = null; // Always enable MethodInfo for annotations (this is how annotation constants are defined) final boolean enableMethodInfo = scanSpec.enableMethodInfo || isAnnotation; if (enableMethodInfo || isAnnotation) { // Annotations store defaults in method_info final int methodNameCpIdx = inputStreamOrByteBuffer.readUnsignedShort(); methodName = getConstantPoolString(methodNameCpIdx); final int methodTypeDescriptorCpIdx = inputStreamOrByteBuffer.readUnsignedShort(); methodTypeDescriptor = getConstantPoolString(methodTypeDescriptorCpIdx); } else { inputStreamOrByteBuffer.skip(4); // name_index, descriptor_index } final int attributesCount = inputStreamOrByteBuffer.readUnsignedShort(); String[] methodParameterNames = null; int[] methodParameterModifiers = null; AnnotationInfo[][] methodParameterAnnotations = null; AnnotationInfoList methodAnnotationInfo = null; boolean methodHasBody = false; if (!methodIsVisible || (!enableMethodInfo && !isAnnotation)) { // Skip method attributes for (int j = 0; j < attributesCount; j++) { inputStreamOrByteBuffer.skip(2); // attribute_name_index final int attributeLength = inputStreamOrByteBuffer.readInt(); inputStreamOrByteBuffer.skip(attributeLength); } } else { // Look for method annotations for (int j = 0; j < attributesCount; j++) { final int attributeNameCpIdx = inputStreamOrByteBuffer.readUnsignedShort(); final int attributeLength = inputStreamOrByteBuffer.readInt(); if (scanSpec.enableAnnotationInfo && (constantPoolStringEquals(attributeNameCpIdx, "RuntimeVisibleAnnotations") || (!scanSpec.disableRuntimeInvisibleAnnotations && constantPoolStringEquals( attributeNameCpIdx, "RuntimeInvisibleAnnotations")))) { final int methodAnnotationCount = inputStreamOrByteBuffer.readUnsignedShort(); if (methodAnnotationInfo == null && methodAnnotationCount > 0) { methodAnnotationInfo = new AnnotationInfoList(1); } if (methodAnnotationInfo != null) { for (int k = 0; k < methodAnnotationCount; k++) { final AnnotationInfo annotationInfo = readAnnotation(); methodAnnotationInfo.add(annotationInfo); } } } else if (scanSpec.enableAnnotationInfo && (constantPoolStringEquals(attributeNameCpIdx, "RuntimeVisibleParameterAnnotations") || (!scanSpec.disableRuntimeInvisibleAnnotations && constantPoolStringEquals( attributeNameCpIdx, "RuntimeInvisibleParameterAnnotations")))) { final int paramCount = inputStreamOrByteBuffer.readUnsignedByte(); methodParameterAnnotations = new AnnotationInfo[paramCount][]; for (int k = 0; k < paramCount; k++) { final int numAnnotations = inputStreamOrByteBuffer.readUnsignedShort(); methodParameterAnnotations[k] = numAnnotations == 0 ? NO_ANNOTATIONS : new AnnotationInfo[numAnnotations]; for (int l = 0; l < numAnnotations; l++) { methodParameterAnnotations[k][l] = readAnnotation(); } } } else if (constantPoolStringEquals(attributeNameCpIdx, "MethodParameters")) { // Read method parameters. For Java, these are only produced in JDK8+, and only if the // commandline switch `-parameters` is provided at compiletime. final int paramCount = inputStreamOrByteBuffer.readUnsignedByte(); methodParameterNames = new String[paramCount]; methodParameterModifiers = new int[paramCount]; for (int k = 0; k < paramCount; k++) { final int cpIdx = inputStreamOrByteBuffer.readUnsignedShort(); // If the constant pool index is zero, then the parameter is unnamed => use null methodParameterNames[k] = cpIdx == 0 ? null : getConstantPoolString(cpIdx); methodParameterModifiers[k] = inputStreamOrByteBuffer.readUnsignedShort(); } } else if (constantPoolStringEquals(attributeNameCpIdx, "Signature")) { // Add type params to method type signature methodTypeSignature = getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort()); } else if (constantPoolStringEquals(attributeNameCpIdx, "AnnotationDefault")) { if (annotationParamDefaultValues == null) { annotationParamDefaultValues = new AnnotationParameterValueList(); } this.annotationParamDefaultValues.add(new AnnotationParameterValue(methodName, // Get annotation parameter default value readAnnotationElementValue())); } else if (constantPoolStringEquals(attributeNameCpIdx, "Code")) { methodHasBody = true; inputStreamOrByteBuffer.skip(attributeLength); } else { inputStreamOrByteBuffer.skip(attributeLength); } } // Create MethodInfo if (enableMethodInfo) { if (methodInfoList == null) { methodInfoList = new MethodInfoList(); } methodInfoList.add(new MethodInfo(className, methodName, methodAnnotationInfo, methodModifierFlags, methodTypeDescriptor, methodTypeSignature, methodParameterNames, methodParameterModifiers, methodParameterAnnotations, methodHasBody)); } } } } /** * Read class attributes. * * @throws IOException * if an I/O exception occurs. * @throws ClassfileFormatException * if the classfile is incorrectly formatted. */ private void readClassAttributes() throws IOException, ClassfileFormatException { // Class attributes (including class annotations, class type variables, module info, etc.) final int attributesCount = inputStreamOrByteBuffer.readUnsignedShort(); for (int i = 0; i < attributesCount; i++) { final int attributeNameCpIdx = inputStreamOrByteBuffer.readUnsignedShort(); final int attributeLength = inputStreamOrByteBuffer.readInt(); if (scanSpec.enableAnnotationInfo && (constantPoolStringEquals(attributeNameCpIdx, "RuntimeVisibleAnnotations") || (!scanSpec.disableRuntimeInvisibleAnnotations && constantPoolStringEquals( attributeNameCpIdx, "RuntimeInvisibleAnnotations")))) { final int annotationCount = inputStreamOrByteBuffer.readUnsignedShort(); for (int m = 0; m < annotationCount; m++) { if (classAnnotations == null) { classAnnotations = new AnnotationInfoList(); } classAnnotations.add(readAnnotation()); } } else if (constantPoolStringEquals(attributeNameCpIdx, "InnerClasses")) { final int numInnerClasses = inputStreamOrByteBuffer.readUnsignedShort(); for (int j = 0; j < numInnerClasses; j++) { final int innerClassInfoCpIdx = inputStreamOrByteBuffer.readUnsignedShort(); final int outerClassInfoCpIdx = inputStreamOrByteBuffer.readUnsignedShort(); if (innerClassInfoCpIdx != 0 && outerClassInfoCpIdx != 0) { if (classContainmentEntries == null) { classContainmentEntries = new ArrayList<>(); } classContainmentEntries.add(new SimpleEntry<>(getConstantPoolClassName(innerClassInfoCpIdx), getConstantPoolClassName(outerClassInfoCpIdx))); } inputStreamOrByteBuffer.skip(2); // inner_name_idx inputStreamOrByteBuffer.skip(2); // inner_class_access_flags } } else if (constantPoolStringEquals(attributeNameCpIdx, "Signature")) { // Get class type signature, including type variables typeSignature = getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort()); } else if (constantPoolStringEquals(attributeNameCpIdx, "EnclosingMethod")) { final String innermostEnclosingClassName = getConstantPoolClassName( inputStreamOrByteBuffer.readUnsignedShort()); final int enclosingMethodCpIdx = inputStreamOrByteBuffer.readUnsignedShort(); String definingMethodName; if (enclosingMethodCpIdx == 0) { // A cpIdx of 0 (which is an invalid value) is used for anonymous inner classes declared in // class initializer code, e.g. assigned to a class field. definingMethodName = "<clinit>"; } else { definingMethodName = getConstantPoolString(enclosingMethodCpIdx, /* subFieldIdx = */ 0); // Could also fetch method type signature using subFieldIdx = 1, if needed } // Link anonymous inner classes into the class with their containing method if (classContainmentEntries == null) { classContainmentEntries = new ArrayList<>(); } classContainmentEntries.add(new SimpleEntry<>(className, innermostEnclosingClassName)); // Also store the fully-qualified name of the enclosing method, to mark this as an anonymous inner // class this.fullyQualifiedDefiningMethodName = innermostEnclosingClassName + "." + definingMethodName; } else if (constantPoolStringEquals(attributeNameCpIdx, "Module")) { final int moduleNameCpIdx = inputStreamOrByteBuffer.readUnsignedShort(); classpathElement.moduleNameFromModuleDescriptor = getConstantPoolString(moduleNameCpIdx); // (Future work): parse the rest of the module descriptor fields, and add to ModuleInfo: // https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.25 inputStreamOrByteBuffer.skip(attributeLength - 2); } else { inputStreamOrByteBuffer.skip(attributeLength); } } } /** * Directly examine contents of classfile binary header to determine annotations, implemented interfaces, the * super-class etc. Creates a new ClassInfo object, and adds it to classNameToClassInfoOut. Assumes classpath * masking has already been performed, so that only one class of a given name will be added. * * @param classpathElement * the classpath element * @param classpathOrder * the classpath order * @param classNamesScheduledForScanning * the class names scheduled for scanning * @param relativePath * the relative path * @param classfileResource * the classfile resource * @param isExternalClass * if this is an external class * @param workQueue * the work queue * @param scanSpec * the scan spec * @param log * the log * @throws IOException * If an IO exception occurs. * @throws ClassfileFormatException * If a problem occurs while parsing the classfile. * @throws SkipClassException * if the classfile needs to be skipped (e.g. the class is non-public, and ignoreClassVisibility is * false) */ Classfile(final ClasspathElement classpathElement, final List<ClasspathElement> classpathOrder, final Set<String> classNamesScheduledForScanning, final String relativePath, final Resource classfileResource, final boolean isExternalClass, final WorkQueue<ClassfileScanWorkUnit> workQueue, final ScanSpec scanSpec, final LogNode log) throws IOException, ClassfileFormatException, SkipClassException { this.classpathElement = classpathElement; this.classpathOrder = classpathOrder; this.relativePath = relativePath; this.classNamesScheduledForScanning = classNamesScheduledForScanning; this.classfileResource = classfileResource; this.isExternalClass = isExternalClass; this.scanSpec = scanSpec; this.log = log; try { // Open classfile as a ByteBuffer or InputStream inputStreamOrByteBuffer = classfileResource.openOrRead(); // Check magic number if (inputStreamOrByteBuffer.readInt() != 0xCAFEBABE) { throw new ClassfileFormatException("Classfile does not have correct magic number"); } // Read classfile minor version inputStreamOrByteBuffer.readUnsignedShort(); // Read classfile major version inputStreamOrByteBuffer.readUnsignedShort(); // Read the constant pool readConstantPoolEntries(); // Read basic class info ( readBasicClassInfo(); // Read interfaces readInterfaces(); // Read fields readFields(); // Read methods readMethods(); // Read class attributes readClassAttributes(); } finally { // Close ByteBuffer or InputStream classfileResource.close(); inputStreamOrByteBuffer = null; } // Check if any superclasses, interfaces or annotations are external (non-whitelisted) classes // that need to be scheduled for scanning, so that all of the "upwards" direction of the class // graph is scanned for any whitelisted class, even if the superclasses / interfaces / annotations // are not themselves whitelisted. if (scanSpec.extendScanningUpwardsToExternalClasses) { extendScanningUpwards(); // If any external classes were found, schedule them for scanning if (additionalWorkUnits != null) { workQueue.addWorkUnits(additionalWorkUnits); } } // Write class info to log if (log != null) { final LogNode subLog = log.log("Found " + (isAnnotation ? "annotation class" : isInterface ? "interface class" : "class") + " " + className); if (superclassName != null) { subLog.log( "Super" + (isInterface && !isAnnotation ? "interface" : "class") + ": " + superclassName); } if (implementedInterfaces != null) { subLog.log("Interfaces: " + Join.join(", ", implementedInterfaces)); } if (classAnnotations != null) { subLog.log("Class annotations: " + Join.join(", ", classAnnotations)); } if (annotationParamDefaultValues != null) { for (final AnnotationParameterValue apv : annotationParamDefaultValues) { subLog.log("Annotation default param value: " + apv); } } if (fieldInfoList != null) { for (final FieldInfo fieldInfo : fieldInfoList) { subLog.log("Field: " + fieldInfo); } } if (methodInfoList != null) { for (final MethodInfo methodInfo : methodInfoList) { subLog.log("Method: " + methodInfo); } } if (typeSignature != null) { ClassTypeSignature typeSig = null; try { typeSig = ClassTypeSignature.parse(typeSignature, /* classInfo = */ null); } catch (final ParseException e) { // Ignore } subLog.log("Class type signature: " + (typeSig == null ? typeSignature : typeSig.toString(className, /* typeNameOnly = */ false, classModifiers, isAnnotation, isInterface))); } if (refdClassNames != null) { final List<String> refdClassNamesSorted = new ArrayList<>(refdClassNames); Collections.sort(refdClassNamesSorted); subLog.log("Referenced class names: " + Join.join(", ", refdClassNamesSorted)); } } } }
package csapps.layout.algorithms.graphPartition; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; import org.cytoscape.model.CyEdge; import org.cytoscape.model.CyNetwork; import org.cytoscape.model.CyNode; import org.cytoscape.model.CyTable; import org.cytoscape.view.layout.AbstractPartitionLayoutTask; import org.cytoscape.view.layout.LayoutNode; import org.cytoscape.view.layout.LayoutPartition; import org.cytoscape.view.model.CyNetworkView; import org.cytoscape.view.model.View; import org.cytoscape.work.undo.UndoSupport; public class DegreeSortedCircleLayoutTask extends AbstractPartitionLayoutTask { private static final String DEGREE_ATTR_NAME = "degree.layout"; private final CyNetwork network; /** * Creates a new GridNodeLayout object. */ public DegreeSortedCircleLayoutTask(final String name, CyNetworkView networkView, Set<View<CyNode>> nodesToLayOut, DegreeSortedCircleContext context, String attrName, UndoSupport undo) { super(name, context.singlePartition, networkView, nodesToLayOut, attrName, undo); this.network = networkView.getModel(); } @Override public void layoutPartion(LayoutPartition partition) { // Create attribute final CyTable table = network.getDefaultNodeTable(); if (table.getColumn(DEGREE_ATTR_NAME) == null) table.createColumn(DEGREE_ATTR_NAME, Integer.class, false); // just add the unlocked nodes final List<LayoutNode> nodes = new ArrayList<LayoutNode>(); for (final LayoutNode ln : partition.getNodeList()) { if (!ln.isLocked()) nodes.add(ln); } if (cancelled) return; // sort the Nodes based on the degree Collections.sort(nodes, new Comparator<LayoutNode>() { public int compare(LayoutNode o1, LayoutNode o2) { final CyNode node1 = o1.getNode(); final CyNode node2 = o2.getNode(); // FIXME: should allow parametrization of edge type? (expose as // tunable) final int d1 = network.getAdjacentEdgeList(node1, CyEdge.Type.ANY).size(); final int d2 = network.getAdjacentEdgeList(node2, CyEdge.Type.ANY).size(); // Create Degree Attribute o1.getRow().set(DEGREE_ATTR_NAME, d1); o2.getRow().set(DEGREE_ATTR_NAME, d2); return (d2 - d1); } public boolean equals(Object o) { return false; } }); if (cancelled) return; // place each Node in a circle int r = 100 * (int) Math.sqrt(nodes.size()); double phi = (2 * Math.PI) / nodes.size(); partition.resetNodes(); // We want to figure out our mins & maxes anew for (int i = 0; i < nodes.size(); i++) { LayoutNode node = nodes.get(i); node.setX(r + (r * Math.sin(i * phi))); node.setY(r + (r * Math.cos(i * phi))); partition.moveNodeToLocation(node); } } }
package org.aksw.kbox.kibe; import org.aksw.kbox.Install; import org.aksw.kbox.ZipLocate; import org.aksw.kbox.apple.AppInstall; import org.aksw.kbox.fusca.Listener; import org.aksw.kbox.fusca.Server; import org.aksw.kbox.fusca.exception.ServerStartException; import org.aksw.kbox.kibe.console.ConsoleInstallInputStreamFactory; import org.aksw.kbox.kibe.exception.KBDereferencingException; import org.aksw.kbox.kibe.exception.KBNotLocatedException; import org.aksw.kbox.kns.CustomKNSServerList; import org.aksw.kbox.kns.InstallFactory; import org.aksw.kbox.kns.KNSServerListVisitor; import org.aksw.kbox.kns.ServerAddress; import org.aksw.kbox.kns.Source; import org.aksw.kbox.kns.exception.ResourceNotResolvedException; import org.aksw.kbox.utils.GzipUtils; import org.aksw.kbox.utils.URLUtils; import org.apache.jena.query.ResultSet; import org.apache.jena.query.ResultSetFormatter; import org.apache.jena.rdf.model.Model; import org.apache.jena.sparql.engine.http.QueryExceptionHTTP; import org.apache.log4j.Logger; import org.json.JSONArray; import org.json.JSONObject; import org.zeroturnaround.zip.ZipUtil; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.net.UnknownHostException; 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; public class Main { private final static Logger logger = Logger.getLogger(Main.class); // CONSTANTS private final static String VERSION = "v0.0.2-beta"; public final static String KNS_FILE_NAME = "kbox.kibe.kns"; public final static String CONTEXT_NAME = "kbox.kibe"; public final static String FILE_SERVER_TABLE_FILE_NAME = "table.kns"; public final static String KB_GRAPH_FILE_NAME = "kbox.kb"; public final static String KB_KNS_NAME = "kns.kb"; public final static String KB_EXTENSION = ".kb"; public final static String ZIP_EXTENSION = ".zip"; public final static String GZIP_EXTENSION = ".gzip"; public final static String COMMAND_PRAGMA = "-"; public final static String SUB_COMMAND_PRAGMA = "/"; public final static String KB_COMMAND_SEPARATOR = ","; private final static String KB_WEB_CLIENT = "http://kbox.aksw.org/webclient"; // COMMANDS private final static String INSTALL_COMMAND = "install"; private final static String KB_COMMAND = "kb"; private final static String KN_COMMAND = "kn"; private final static String KNS_COMMAND = "kns"; private final static String REMOVE_COMMAND = "remove"; private final static String SERVER_COMMAND = "server"; private final static String LIST_COMMAND = "list"; private final static String PAGINATION_COMMAND = "/p"; private final static String SPARQL_QUERY_COMMAND = "sparql"; private final static String SPARQL_QUERY_JSON_OUTPUT_FORMAT_COMMAND = "-json"; private final static String FILE_COMMAND = "file"; private final static String INFO_COMMAND = "info"; private final static String SEARCH_COMMAND = "search"; private final static String CONVERT_COMMAND = "convert"; private final static String ZIP_ENCODE_COMMAND = "zip"; private final static String GZIP_ENCODE_COMMAND = "gzip"; private final static String VERSION_COMMAND = "version"; private final static String RESOURCE_DIR_COMMAND = "r-dir"; private final static String SERVER_COMMAND_PORT = "port"; private final static String LOCATE_COMMAND = "locate"; private final static String SEVER_COMMAND_SUBDOMAIN = "subDomain"; private final static String FORMAT_COMMAND = "-format"; private final static String RDF_COMMAND = "rdf"; private final static String TARGET_COMMAND = "target"; public static void main(String[] args) { Map<String, String[]> commands = parse(args); ConsoleInstallInputStreamFactory inputStreamFactory = new ConsoleInstallInputStreamFactory(); JSONSerializer jsonSerializer = JSONSerializer.getInstance(); jsonSerializer.containsJsonOutputCommand(commands); if (commands.containsKey(CONVERT_COMMAND) && !commands.containsKey(ZIP_ENCODE_COMMAND) && !commands.containsKey(GZIP_ENCODE_COMMAND)) { String directoryParam = commands.get(CONVERT_COMMAND)[0]; String destFileParam = commands.get(CONVERT_COMMAND)[1]; File source = new File(directoryParam); File destFile = null; if (destFileParam == null) { destFile = new File(source.getName() + KB_EXTENSION); } else { destFile = new File(destFileParam); } try { if (source.isDirectory()) { System.out.println("Converting content inside the directory " + source); KBox.dirToKB(destFile, source); } else { System.out.println("Converting RDF file " + source); KBox.RDFToKB(destFile, source); } System.out.println("Converting completed."); } catch (Exception e) { String message = "An error occurred while creating the index: " + e.getMessage(); System.out.println(message); logger.error(message, e); } } else if (commands.containsKey(CONVERT_COMMAND) && commands.containsKey(ZIP_ENCODE_COMMAND)) { String directoryParam = commands.get(CONVERT_COMMAND)[0]; String destFileParam = commands.get(CONVERT_COMMAND)[1]; File source = new File(directoryParam); try { File destFile = null; if (destFileParam == null) { destFile = new File(source.getName() + ZIP_EXTENSION); } else { destFile = new File(destFileParam); } if (source.isDirectory()) { System.out.println("Converting content inside the directory: " + source); ZipUtil.pack(source, destFile); } else { System.out.println("Converting file: " + source); ZipUtil.packEntries(new File[] { source }, destFile); } System.out.println("Converting completed."); } catch (Exception e) { String message = "An error occurred while converting: " + e.getMessage(); System.out.println(message); logger.error(message, e); } } else if (commands.containsKey(CONVERT_COMMAND) && commands.containsKey(GZIP_ENCODE_COMMAND)) { String fileParam = commands.get(CONVERT_COMMAND)[0]; String destFileParam = commands.get(CONVERT_COMMAND)[1]; File targetFile = new File(fileParam); if (targetFile.isDirectory()) { System.out.println("The target file cannot be a directory."); return; } try { System.out.println("Converting file: " + targetFile); File destFile = null; if (destFileParam == null) { destFile = new File(targetFile.getName() + GZIP_EXTENSION); } else { destFile = new File(destFileParam); } GzipUtils.pack(targetFile, destFile); System.out.println("Converting completed."); } catch (Exception e) { String message = "An error occurred while converting: " + e.getMessage(); System.out.println(message); logger.error(message, e); } } else if (commands.containsKey(INSTALL_COMMAND) && commands.size() == 1) { String resource = getSingleParam(commands, INSTALL_COMMAND); try { jsonSerializer.printOutput("Installing resource " + resource); URL url = new URL(resource); org.aksw.kbox.KBox.install(url); String msg = "Resource installed."; jsonSerializer.printOutput(msg); jsonSerializer.printInstallCommandJsonResponse( msg); } catch (Exception e) { String message = "Error installing the resource " + resource + ": " + e.getMessage(); jsonSerializer.printOutput(message); jsonSerializer.printErrorInJsonFormat(message, false); logger.error(message, e); } } else if (commands.containsKey(INSTALL_COMMAND) && commands.containsKey(KB_COMMAND) && commands.containsKey(FILE_COMMAND)) { String kb2Install = getSingleParam(commands, KB_COMMAND); try { URL kbURL = new URL(kb2Install); String resource = getSingleParam(commands, FILE_COMMAND); File resourceFile = new File(resource); URL file = resourceFile.toURI().toURL(); jsonSerializer.printOutput("Installing KB " + kb2Install); KBox.install(file, kbURL, inputStreamFactory); String msg = "KB installed."; jsonSerializer.printOutput(msg); jsonSerializer.printInstallCommandJsonResponse(msg); } catch (Exception e) { String message = "Error installing the knowledge base " + kb2Install + ": " + e.getMessage(); jsonSerializer.printOutput(message); jsonSerializer.printErrorInJsonFormat(message, false); logger.error(message, e); } } else if (commands.containsKey(INSTALL_COMMAND) && commands.containsKey(KB_COMMAND) && commands.containsKey(KNS_COMMAND)) { String knsServer = getSingleParam(commands, KNS_COMMAND); String kbURL = getSingleParam(commands, KB_COMMAND); String version = getSingleParam(commands, VERSION_COMMAND); try { jsonSerializer.printOutput("Installing KB " + kbURL + " from KNS " + knsServer); KBox.installFromKNSServer(new URL(kbURL), new URL(knsServer), KBox.KIBE_FORMAT, version, inputStreamFactory); String message = "KB installed."; jsonSerializer.printOutput(message); jsonSerializer.printInstallCommandJsonResponse(message); } catch (MalformedURLException e) { jsonSerializer.printOutput(e.getMessage()); jsonSerializer.printErrorInJsonFormat(e.getMessage(), false); logger.error(e); } catch (KBNotLocatedException e) { String message = "The knowledge base " + kbURL + " is not available in " + knsServer + "."; jsonSerializer.printOutput(message); jsonSerializer.printErrorInJsonFormat(message, false); } catch (Exception e) { String message = "Error installing knowledge base " + kbURL + " from " + knsServer + "."; jsonSerializer.printOutput(message); jsonSerializer.printErrorInJsonFormat(message, false); logger.error(message, e); } } else if (commands.containsKey(INSTALL_COMMAND) && commands.containsKey(KN_COMMAND) && commands.containsKey(KNS_COMMAND)) { String knsServer = getSingleParam(commands, KNS_COMMAND); String knURL = getSingleParam(commands, KN_COMMAND); String format = getSingleParam(commands, FORMAT_COMMAND); String version = getSingleParam(commands, VERSION_COMMAND); try { jsonSerializer.printOutput("Installing KN " + knURL + " from KNS " + knsServer); KBox.installFromKNSServer(new URL(knURL), new URL(knsServer), format, version, inputStreamFactory); String message = "KN installed."; jsonSerializer.printOutput(message); jsonSerializer.printInstallCommandJsonResponse(message); } catch (MalformedURLException e) { jsonSerializer.printOutput(e.getMessage()); jsonSerializer.printErrorInJsonFormat(e.getMessage(), false); logger.error(e); } catch (KBNotLocatedException e) { String message = "The knowledge name " + knURL + " is not available in " + knsServer + "."; jsonSerializer.printOutput(message); jsonSerializer.printErrorInJsonFormat(message, false); } catch (Exception e) { String message = "Error installing knowledge name " + knURL + " from " + knsServer + "."; jsonSerializer.printOutput(message); jsonSerializer.printErrorInJsonFormat(message, false); logger.error(message, e); } } else if (commands.containsKey(INSTALL_COMMAND) && commands.containsKey(RDF_COMMAND) && commands.containsKey(KB_COMMAND)) { String install = DefaultInstallFactory.RDF2KB; String source = getSingleParam(commands, RDF_COMMAND); if(commands.containsKey(INSTALL_COMMAND)) { install = getSingleParam(commands, INSTALL_COMMAND, install); } String kbURL = getSingleParam(commands, KB_COMMAND); String version = getSingleParam(commands, VERSION_COMMAND); try { String[] filePaths = source.split(KB_COMMAND_SEPARATOR); List<URL> inputRDFFiles = new java.util.ArrayList<URL>(); for(String filePath : filePaths) { if(!filePath.startsWith("http")) { File sourceFile = new File(filePath); if(sourceFile != null && sourceFile.isDirectory()) { inputRDFFiles.addAll(Arrays.asList(URLUtils.fileToURL(sourceFile.listFiles()))); } else { inputRDFFiles.add(sourceFile.toURI().toURL()); } } else { URL fileURL = new URL(filePath); inputRDFFiles.add(fileURL); } } jsonSerializer.printOutput("Installing KB " + kbURL + " from files " + source); InstallFactory installFactory = new DefaultInstallFactory(); AppInstall installMethod = installFactory.get(install); KBox.install(inputRDFFiles.toArray(new URL[inputRDFFiles.size()]), new URL(kbURL), KBox.KIBE_FORMAT, version, installMethod, inputStreamFactory); String message = "KN installed."; jsonSerializer.printOutput(message); jsonSerializer.printInstallCommandJsonResponse(message); } catch (MalformedURLException e) { String message = e.getMessage(); jsonSerializer.printOutput(message); jsonSerializer.printErrorInJsonFormat(message, false); logger.error(e); } catch (Exception e) { String message = "Error installing knowledge name " + kbURL + " from files " + source + "."; jsonSerializer.printOutput(message); jsonSerializer.printErrorInJsonFormat(message, false); logger.error(message, e); } } else if (!commands.containsKey(SPARQL_QUERY_COMMAND) && !commands.containsKey(SERVER_COMMAND) && commands.containsKey(INSTALL_COMMAND) && commands.containsKey(KB_COMMAND)) { String graphNamesList = getSingleParam(commands, KB_COMMAND); String version = getSingleParam(commands, VERSION_COMMAND); String[] graphNames = graphNamesList.split(KB_COMMAND_SEPARATOR); URL[] urls; try { urls = URLUtils.stringToURL(graphNames); for (URL resourceName : urls) { try { File kbFile = KBox.getResource(resourceName, KBox.KIBE_FORMAT, version, true); if(kbFile != null) { String message = resourceName + " KB installed."; jsonSerializer.printOutput(message); jsonSerializer.printInstallCommandJsonResponse(message); } else { String message = resourceName + " KB could NOT be installed."; jsonSerializer.printOutput(message); jsonSerializer.printErrorInJsonFormat(message, false); } } catch (MalformedURLException e) { String message = e.getMessage(); jsonSerializer.printOutput(message); jsonSerializer.printErrorInJsonFormat(message, false); logger.error(message, e); } catch (Exception e) { String message = "The knowledge base could not be found: URL:" + resourceName; if (version != null) { message += ", " + "version: " + version; } jsonSerializer.printOutput(message); jsonSerializer.printErrorInJsonFormat(message, false); logger.error(message, e); } } } catch (Exception e) { String message = "An error occurred while parsing the KB Name list \"" + graphNames + "\": " + e.getMessage(); jsonSerializer.printOutput(message); jsonSerializer.printErrorInJsonFormat(message, false); logger.error(message, e); } } else if (commands.containsKey(INSTALL_COMMAND) && commands.containsKey(KNS_COMMAND)) { String url = getSingleParam(commands, KNS_COMMAND); try { URL knsURL = new URL(url); jsonSerializer.printOutput("Installing KNS " + url); KBox.installKNS(knsURL); String message = "KNS installed."; jsonSerializer.printOutput(message); jsonSerializer.printInstallCommandJsonResponse(message); } catch (MalformedURLException e) { String message = e.getMessage(); jsonSerializer.printOutput(message); jsonSerializer.printErrorInJsonFormat(message, false); logger.error(e); } } else if (commands.containsKey(SPARQL_QUERY_COMMAND) && (commands.containsKey(KB_COMMAND) || commands.containsKey(SERVER_COMMAND))) { String sparql = getSingleParam(commands, SPARQL_QUERY_COMMAND); String graphNamesList = getSingleParam(commands, KB_COMMAND); if (graphNamesList != null) { String[] graphNames = graphNamesList.split(KB_COMMAND_SEPARATOR); boolean install = commands.containsKey(INSTALL_COMMAND); try { URL[] urls = URLUtils.stringToURL(graphNames); ResultSet rs = KBox.query(sparql, inputStreamFactory, install, urls); out(commands, rs); } catch (Exception e) { String message = "Error executing query '" + sparql + "': " + e.getMessage(); System.out.println(message); logger.error(message, e); } } else { String url = getSingleParam(commands, SERVER_COMMAND); ServerAddress serverURL = new ServerAddress(url); try { ResultSet rs = KBox.query(sparql, serverURL); out(commands, rs); } catch (QueryExceptionHTTP e) { String message = "An error occurred while trying to connect to server: " + url + "." + " The server seems to be unavailable, check the server address and try again."; System.out.println(message); logger.error(message, e); } catch (Exception e) { String message = "An error occurred while querying the server: " + url; System.out.println(message); logger.error(message, e); } } } else if (commands.containsKey(LIST_COMMAND) && commands.containsKey(KNS_COMMAND)) { jsonSerializer.printOutput("KNS table list"); CustomKNSServerList knsServerList = new CustomKNSServerList(); List<String> knsList = new ArrayList<>(); try { knsServerList.visit((KNSServerListVisitor) knsServer -> { knsList.add(knsServer.getURL().toString()); jsonSerializer.printOutput("\t - " + knsServer.getURL()); return true; }); jsonSerializer.printKnsListJsonFormat(knsList, "KNS table list"); } catch (Exception e) { String message = "An error occurred while listing the available knowledge bases: " + e.getCause().getMessage(); jsonSerializer.printOutput(message); jsonSerializer.printErrorInJsonFormat(message, true); logger.error(message, e); } } else if (commands.containsKey(LIST_COMMAND) && !commands.containsKey(KNS_COMMAND)) { try { String format = getSingleParam(commands, FORMAT_COMMAND); boolean pagination = commands.containsKey(PAGINATION_COMMAND); ConsoleKNSServerListVisitor listAllVisitor = null; if (format != null) { listAllVisitor = new ConsoleKNSServerListVisitor(format, pagination); } else { listAllVisitor = new ConsoleKNSServerListVisitor(pagination); } KBox.visit(listAllVisitor); jsonSerializer.printVisitedKNAsJsonResponse("visited all KNs."); } catch (UnknownHostException e) { String message = "An error occurred while listing the available resources. Check your connection."; jsonSerializer.printOutput(message); logger.error(message, e); jsonSerializer.printErrorInJsonFormat(message, true); } catch (Exception e) { String message = "An error occurred while listing the available resources: " + e.getMessage(); jsonSerializer.printOutput(message); logger.error(message, e); jsonSerializer.printErrorInJsonFormat(message, true); } } else if (commands.containsKey(REMOVE_COMMAND) && commands.containsKey(KNS_COMMAND)) { String knsURL = getSingleParam(commands, KNS_COMMAND); try { jsonSerializer.printOutput("Removing KNS " + knsURL); KBox.removeKNS(new URL(knsURL)); jsonSerializer.printOutput("KNS removed."); jsonSerializer.printRemoveCommandJsonResponse("KNS removed."); } catch (Exception e) { String message = "An error occurred while removing the KNS: " + knsURL + "."; jsonSerializer.printOutput(message); jsonSerializer.printErrorInJsonFormat(message, true); logger.error(message, e); } } else if (commands.containsKey(RESOURCE_DIR_COMMAND)) { String resourceDir = getSingleParam(commands, RESOURCE_DIR_COMMAND); if (resourceDir != null) { try { KBox.setResourceFolder(resourceDir); String message = "Resource directory redirected to " + resourceDir + "."; jsonSerializer.printOutput(message); jsonSerializer.printResourceDirectoryAsJsonResponse(message, resourceDir); } catch (Exception e) { String errorMessage = "Error changing KBox resource repository to " + resourceDir + "."; jsonSerializer.printOutput(errorMessage); jsonSerializer.printErrorInJsonFormat(errorMessage, true); logger.error(errorMessage, e); } } else { resourceDir = KBox.getResourceFolder(); String message = "Your current resource directory is: " + resourceDir; jsonSerializer.printOutput(message); jsonSerializer.printResourceDirectoryAsJsonResponse(message, resourceDir); } } else if (commands.containsKey(SEARCH_COMMAND)) { String pattern = getSingleParam(commands, SEARCH_COMMAND); String format = getSingleParam(commands, FORMAT_COMMAND); String version = getSingleParam(commands, VERSION_COMMAND); SearchKBKNSVisitor searchVisitor = new SearchKBKNSVisitor(pattern, format, version, commands.containsKey(PAGINATION_COMMAND)); try { KBox.visit(searchVisitor); jsonSerializer.printVisitedKNAsJsonResponse("searching completed."); } catch (Exception e) { String message = "An error occurred while enquiring search using the pattern: " + pattern; jsonSerializer.printOutput(message); logger.error(message, e); jsonSerializer.printErrorInJsonFormat(message, true); } } else if (commands.containsKey(INFO_COMMAND)) { String kn = getSingleParam(commands, INFO_COMMAND); String format = getSingleParam(commands, FORMAT_COMMAND); String version = getSingleParam(commands, VERSION_COMMAND); InfoKBKNSVisitor visitor = new InfoKBKNSVisitor(kn, format, version); try { KBox.visit(visitor); jsonSerializer.printKNInfoAsJsonResponse("Information has been fetched."); } catch (Exception e) { String message = "An error occurred while enquiring information from the KN " + kn; jsonSerializer.printOutput(message); jsonSerializer.printErrorInJsonFormat(message, true); logger.error(message, e); } } else if (commands.containsKey(LOCATE_COMMAND) && !commands.containsKey(KB_COMMAND)) { String resourceURL = getSingleParam(commands, LOCATE_COMMAND); try { String path = org.aksw.kbox.KBox.locate(new URL(resourceURL)).getAbsolutePath(); jsonSerializer.printOutput(path); jsonSerializer.printLocateCommandJsonResponse("Action Completed.",path); } catch (Exception e) { String message = "An error occurred while resolving the resource: " + resourceURL; jsonSerializer.printOutput(message); jsonSerializer.printErrorInJsonFormat(message, true); logger.error(message, e); } } else if (commands.containsKey(LOCATE_COMMAND) && commands.containsKey(KB_COMMAND)) { String kbURL = getSingleParam(commands, KB_COMMAND); String version = getSingleParam(commands, VERSION_COMMAND); try { String path = KBox.locate(new URL(kbURL), KBox.KIBE_FORMAT, version).getAbsolutePath(); jsonSerializer.printOutput(path); jsonSerializer.printLocateCommandJsonResponse("Action Completed.", path); } catch (Exception e) { String message = "An error occurred while resolving the KB: " + kbURL; jsonSerializer.printOutput(message); jsonSerializer.printErrorInJsonFormat(message, true); logger.error(message, e); } } else if (commands.containsKey(LOCATE_COMMAND) && commands.containsKey(KN_COMMAND)) { String kbURL = getSingleParam(commands, KN_COMMAND); String format = getSingleParam(commands, FORMAT_COMMAND); String version = getSingleParam(commands, VERSION_COMMAND); try { String path = KBox.locate(new URL(kbURL), format, version).getAbsolutePath(); jsonSerializer.printOutput(path); jsonSerializer.printLocateCommandJsonResponse("Action Completed.", path); } catch (Exception e) { String message = "An error occurred while resolving the KN: " + kbURL; jsonSerializer.printOutput(message); jsonSerializer.printErrorInJsonFormat(message, true); logger.error(message, e); } } else if (commands.containsKey(SERVER_COMMAND)) { int port = 8080; String subDomain = "kbox"; if (commands.containsKey(SERVER_COMMAND_PORT)) { port = Integer.parseInt(getSingleParam(commands, SERVER_COMMAND_PORT)); } if (commands.containsKey(SEVER_COMMAND_SUBDOMAIN)) { subDomain = getSingleParam(commands, SEVER_COMMAND_SUBDOMAIN); } try { System.out.println("Loading Model..."); Model model = null; if(commands.containsKey(KB_COMMAND)) { String graphNamesList = getSingleParam(commands, KB_COMMAND); String[] graphNames = graphNamesList.split(KB_COMMAND_SEPARATOR); boolean install = commands.containsKey(INSTALL_COMMAND); URL[] urls = new URL[graphNames.length]; for (int i = 0; i < graphNames.length; i++) { urls[i] = new URL(graphNames[i]); } model = KBox.createModel(inputStreamFactory, install, urls); } if(commands.containsKey(TARGET_COMMAND)) { String targetArray = getSingleParam(commands, TARGET_COMMAND); List<Source> sources = Source.toTarget(targetArray); model = KBox.createTempModel(inputStreamFactory, sources.toArray(new Source[sources.size()])); } else if (commands.containsKey(RDF_COMMAND)){ String install = DefaultInstallFactory.RDF2KB; if(commands.containsKey(INSTALL_COMMAND)) { install = getSingleParam(commands, INSTALL_COMMAND, install); } String fileNamesList = getSingleParam(commands, RDF_COMMAND); String[] filePaths = fileNamesList.split(KB_COMMAND_SEPARATOR); List<URL> inputRDFFiles = new java.util.ArrayList<URL>(); for(String filePath : filePaths) { if(!(filePath.startsWith("http") || filePath.startsWith("ftp"))) { File sourceFile = new File(filePath); if(sourceFile != null && sourceFile.isDirectory()) { inputRDFFiles.addAll(Arrays.asList(URLUtils.fileToURL(sourceFile.listFiles()))); } else { inputRDFFiles.add(sourceFile.toURI().toURL()); } } else { URL fileURL = new URL(filePath); inputRDFFiles.add(fileURL); } } model = KBox.createTempModel( inputRDFFiles.toArray(new URL[inputRDFFiles.size()]), install, inputStreamFactory); } final int servicePort = port; final String serverAddress = "http://localhost:" + servicePort + "/" + subDomain + "/sparql"; Listener serverListener = new Listener() { @Override public void starting() { System.out.println("Publishing service on " + serverAddress); } @Override public void started() { System.out.println("SPARQL client accessible at http://localhost:" + servicePort); System.out.println("Service up and running ;-) ..."); } }; URL webclient = Main.class.getResource("/web-client.zip"); URL webClientURL = new URL(KB_WEB_CLIENT); Install webClientInstall = new WebAppInstall(serverAddress); File webInterfaceDir = KBox.getResource(webclient, webClientURL, new ZipLocate(), webClientInstall, true); Server server = new Server(port, webInterfaceDir.getAbsolutePath(), subDomain, model, serverListener); server.start(); } catch (KBDereferencingException e) { System.out.println( "Error installing KB: " + "The knowledge base could not be found in any of the KNS servers."); System.out.println("Check if the servers are online or if the requested resource exist."); logger.error(e); } catch (KBNotLocatedException e) { System.out.println( "Error installing KB: " + "The knowledge base could not be located."); System.out.println("Try to install it adding the pragma -install to your command."); logger.error(e); } catch (ResourceNotResolvedException e) { System.out.println( "Error installing KB: " + "The knowledge base could not be resolved."); System.out.println("Check if the servers are online or if the requested resource exist."); logger.error(e); } catch (ServerStartException e) { String message = "An error occurred while starting the server, " + "check if the port is not being used by another " + "application or if the parameters are valid."; System.out.println(message); logger.error(message, e); } catch (MalformedURLException e) { System.out.println(e.getMessage()); logger.error(e); } catch (Exception e) { System.out.println(e); String message = "Error installing the Knowledge Bases."; System.out.println(message); logger.error(message, e); } } else if (commands.containsKey(VERSION_COMMAND)) { printVersion(); } else { printHelp(); } } public static void printVersion() { if (!JSONSerializer.getInstance().getIsJsonOutput()) { System.out.println("KBox version " + VERSION); } else { JSONSerializer.getInstance().printKBoxVersionAsJsonResponse("KBox Version.", VERSION); } } public static void printHelp() { System.out.println("KBox.jar <command> [option]"); System.out.println("Where [command] is:"); System.out.println( " * convert <directory|file> [<destFile>] [kb|zip]\t - convert the content of a directory (default kb)."); System.out.println( " kb\t - into a kb file. ps: the directory might contain only RDF compatible file formats."); System.out.println(" zip\t - into a zip file."); System.out.println(" * convert <file> [<destFile>] gzip\t - encode a given file."); System.out.println( " * sparql <query> (kb <KB> | server <URL>) [install] [-json]\t - Query a given knowledge base (e.g. sparql \"Select ...\" kb \"KB1,KB2\")"); System.out.println( " \t - ps: use -install in case you want to enable the auto-dereference."); System.out.println( " * server [port <port> (default 8080)] [subDomain <subDomain> (default kbox)] kb <kb-URL> [install] \t - Start an SPARQL endpoint in the given subDomain containing the given bases."); System.out.println( " * server [port <port> (default 8080)] [subDomain <subDomain> (default kbox)] rdf <directories|files> [install [install]]\t - Start an SPARQL endpoint in the given subDomain containing the given RDF files."); System.out.println( " * server [port <port> (default 8080)] [subDomain <subDomain> (default kbox)] target <target>\t - Start an SPARQL endpoint in the given subDomain containing the target RDF files."); System.out.println(" * list [/p]\t - List all available KNS services and knowledge bases."); System.out.println(" * list kns\t - List all available KNS services."); System.out.println(" * install <URL>\t - Install a given resource."); System.out.println(" * install kns <kns-URL>\t - Install a given KNS service."); System.out.println( " * install kb <kb-URL> [version <version>]\t - Install a given knowledge base using the available KNS services to resolve it."); System.out.println(" * install kb <kb-URL> file <kbFile>\t - Install a given kb file in a given Kb-URL."); System.out.println( " * install kb <kb-URL> kns <kns-URL> [version <version>]\t - Install a knowledge base from a a given KNS service with the specific version."); System.out.println( " * install [install] kb <kb-URL> rdf <directories|files> [version <version>]\t - Install a knowledge base from a a given RDF files with the specific version."); System.out.println( " * install kn <kn-URL> [format [version <version>]]\t - Install a given knowledge base using the available KNS services to resolve it."); System.out.println(" * remove kns <kns-URL>\t - Remove a given KNS service."); System.out.println( " * info <URL> format <format> version <version>]]\t - Gives the information about a specific KB."); System.out.println(" * locate <URL>\t - returns the local address of the given resource."); System.out.println( " * locate kb <kb-URL> version <version>]\t - returns the local address of the given KB."); System.out.println( " * locate kn <kn-URL> format version <version>]]\t - returns the local address of the given KB."); System.out.println( " * search <kn-URL-pattern> [format <format> [version <version>]] [/p]\t - Search for all kb-URL containing a given pattern."); System.out.println(" * r-dir\t - Show the path to the resource folder."); System.out.println(" * r-dir <resourceDir>\t - Change the path of the resource folder."); System.out.println(" * version \t - display KBox version."); } private static void out(Map<String, String[]> commands, ResultSet rs) { if (commands.containsKey(SPARQL_QUERY_JSON_OUTPUT_FORMAT_COMMAND)) { ResultSetFormatter.outputAsJSON(System.out, rs); } else { ResultSetFormatter.out(System.out, rs); } } /** * Retrieve the value of the first command's parameter. * * @param commands * the parsed commands. * @param command * the command to retrieve the parameter. * @param defaultValue * the defaultValue to return in case command value is null. * * @return the value of the first command's parameter or defaultValue in case it is null. */ public static String getSingleParam(Map<String, String[]> commands, String command, String defaultValue) { String value = getSingleParam(commands, command); if (value == null) { return defaultValue; } return null; } /** * Retrieve the value of the first command's parameter. * * @param commands * the parsed commands. * @param command * the command to retrieve the parameter. * * @return the value of the first command's parameter. */ public static String getSingleParam(Map<String, String[]> commands, String command) { if (commands.containsKey(command)) { return commands.get(command)[0]; } return null; } /** * Retrieve the value of the first command's parameter. * * @param commands * the parsed commands. * @param command * the command to retrieve the parameter. * * @return the value of the first command's parameter. */ public static String getParam(Map<String, String[]> commands, String command, int i) { if (commands.containsKey(command) && commands.get(command).length > i + 1) { return commands.get(command)[i]; } return null; } /** * Command line parser. * * @param args * a set o arguments received by command line. * * @return a Map containing the parsed arguments. */ public static Map<String, String[]> parse(String[] args) { Map<String, String[]> map = new HashMap<String, String[]>(); Set<String> commandList = new HashSet<>(); addCommands(commandList); for (int i = 0; i < args.length; i++) { if (commandList.contains(args[i]) || args[i].startsWith(SUB_COMMAND_PRAGMA)) { // command map.put(args[i], new String[] { null, null }); int j = i + 1; while (j < args.length && !commandList.contains(args[j])) { map.get(args[i])[(j - i) - 1] = args[j]; j++; } } } return map; } private static void addCommands(Set<String> commandList) { commandList.add(INSTALL_COMMAND); commandList.add(KB_COMMAND); commandList.add(KN_COMMAND); commandList.add(KNS_COMMAND); commandList.add(REMOVE_COMMAND); commandList.add(LIST_COMMAND); commandList.add(PAGINATION_COMMAND); commandList.add(SPARQL_QUERY_COMMAND); commandList.add(SPARQL_QUERY_JSON_OUTPUT_FORMAT_COMMAND); commandList.add(FILE_COMMAND); commandList.add(INFO_COMMAND); commandList.add(SEARCH_COMMAND); commandList.add(CONVERT_COMMAND); commandList.add(ZIP_ENCODE_COMMAND); commandList.add(GZIP_ENCODE_COMMAND); commandList.add(VERSION_COMMAND); commandList.add(RESOURCE_DIR_COMMAND); commandList.add(SERVER_COMMAND_PORT); commandList.add(LOCATE_COMMAND); commandList.add(SEVER_COMMAND_SUBDOMAIN); commandList.add(FORMAT_COMMAND); commandList.add(RDF_COMMAND); commandList.add(TARGET_COMMAND); commandList.add("-o"); } }
package io.github.lumue.nfotools; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.ResolverStyle; import java.util.*; @SuppressWarnings("unused") @XmlRootElement(name = "movie") @XmlAccessorType(XmlAccessType.FIELD) public class Movie implements Serializable{ private final static DateTimeFormatter DATE_TIME_FORMATTER=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); @XmlElement private String title; @XmlElement private String originaltitle; @XmlElement private String sorttitle; @XmlElement private String set; @XmlElement private String rating; @XmlElement private String year; @XmlElement private String top250; @XmlElement private String votes; @XmlElement private String outline; @XmlElement private String plot; @XmlElement private String tagline; @XmlElement private String runtime; @XmlElement private String thumb; @XmlElement private String mpaa; @XmlElement private String playcount; @XmlElement private String id; @XmlElement private String filenameandpath; @XmlElement private String trailer; @XmlElement private String genre; @XmlElement private String credits; @XmlElement private Fileinfo fileinfo=new Fileinfo(); @XmlElement private String director; @XmlElement(name="actor") private List<Actor> actorList=new ArrayList<>(); @XmlElement(name="tag") private List<String> tagList=new ArrayList<>(); @XmlElement String dateadded; @XmlElement String aired; Movie() { } public Movie(String title, String originaltitle, String sorttitle, String set, String rating, String year, String top250, String votes, String outline, String plot, String tagline, String runtime, String thumb, String mpaa, String playcount, String id, String filenameandpath, String trailer, String genre, String credits, Fileinfo fileinfo, String director,String dateadded,String aired,Collection<Actor> actorList,Collection<String> tagList) { this.title = title; this.originaltitle = originaltitle; this.sorttitle = sorttitle; this.set = set; this.rating = rating; this.year = year; this.top250 = top250; this.votes = votes; this.outline = outline; this.plot = plot; this.tagline = tagline; this.runtime = runtime; this.thumb = thumb; this.mpaa = mpaa; this.playcount = playcount; this.id = id; this.filenameandpath = filenameandpath; this.trailer = trailer; this.genre = genre; this.credits = credits; this.fileinfo = fileinfo; this.director = director; this.actorList.addAll(actorList); this.tagList.addAll(tagList); this.dateadded=dateadded; this.aired=aired; } public static MovieBuilder builder(){ return new MovieBuilder(); }; public MovieBuilder copyBuilder(){ return new MovieBuilder(this); }; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Movie that = (Movie) o; if (title != null ? !title.equals(that.title) : that.title != null) return false; if (originaltitle != null ? !originaltitle.equals(that.originaltitle) : that.originaltitle != null) return false; if (sorttitle != null ? !sorttitle.equals(that.sorttitle) : that.sorttitle != null) return false; if (set != null ? !set.equals(that.set) : that.set != null) return false; if (rating != null ? !rating.equals(that.rating) : that.rating != null) return false; if (year != null ? !year.equals(that.year) : that.year != null) return false; if (top250 != null ? !top250.equals(that.top250) : that.top250 != null) return false; if (votes != null ? !votes.equals(that.votes) : that.votes != null) return false; if (outline != null ? !outline.equals(that.outline) : that.outline != null) return false; if (plot != null ? !plot.equals(that.plot) : that.plot != null) return false; if (tagline != null ? !tagline.equals(that.tagline) : that.tagline != null) return false; if (runtime != null ? !runtime.equals(that.runtime) : that.runtime != null) return false; if (thumb != null ? !thumb.equals(that.thumb) : that.thumb != null) return false; if (mpaa != null ? !mpaa.equals(that.mpaa) : that.mpaa != null) return false; if (playcount != null ? !playcount.equals(that.playcount) : that.playcount != null) return false; if (id != null ? !id.equals(that.id) : that.id != null) return false; if (filenameandpath != null ? !filenameandpath.equals(that.filenameandpath) : that.filenameandpath != null) return false; if (trailer != null ? !trailer.equals(that.trailer) : that.trailer != null) return false; if (genre != null ? !genre.equals(that.genre) : that.genre != null) return false; if (credits != null ? !credits.equals(that.credits) : that.credits != null) return false; if (fileinfo != null ? !fileinfo.equals(that.fileinfo) : that.fileinfo != null) return false; if (director != null ? !director.equals(that.director) : that.director != null) return false; return actorList != null ? actorList.equals(that.actorList) : that.actorList == null; } @Override public int hashCode() { int result = title != null ? title.hashCode() : 0; result = 31 * result + (originaltitle != null ? originaltitle.hashCode() : 0); result = 31 * result + (sorttitle != null ? sorttitle.hashCode() : 0); result = 31 * result + (set != null ? set.hashCode() : 0); result = 31 * result + (rating != null ? rating.hashCode() : 0); result = 31 * result + (year != null ? year.hashCode() : 0); result = 31 * result + (top250 != null ? top250.hashCode() : 0); result = 31 * result + (votes != null ? votes.hashCode() : 0); result = 31 * result + (outline != null ? outline.hashCode() : 0); result = 31 * result + (plot != null ? plot.hashCode() : 0); result = 31 * result + (tagline != null ? tagline.hashCode() : 0); result = 31 * result + (runtime != null ? runtime.hashCode() : 0); result = 31 * result + (thumb != null ? thumb.hashCode() : 0); result = 31 * result + (mpaa != null ? mpaa.hashCode() : 0); result = 31 * result + (playcount != null ? playcount.hashCode() : 0); result = 31 * result + (id != null ? id.hashCode() : 0); result = 31 * result + (filenameandpath != null ? filenameandpath.hashCode() : 0); result = 31 * result + (trailer != null ? trailer.hashCode() : 0); result = 31 * result + (genre != null ? genre.hashCode() : 0); result = 31 * result + (credits != null ? credits.hashCode() : 0); result = 31 * result + (fileinfo != null ? fileinfo.hashCode() : 0); result = 31 * result + (director != null ? director.hashCode() : 0); result = 31 * result + (actorList != null ? actorList.hashCode() : 0); return result; } @Override public String toString() { return "Movie{" + "title='" + title + '\'' + ", originaltitle='" + originaltitle + '\'' + ", sorttitle='" + sorttitle + '\'' + ", set='" + set + '\'' + ", rating='" + rating + '\'' + ", year='" + year + '\'' + ", top250='" + top250 + '\'' + ", votes='" + votes + '\'' + ", outline='" + outline + '\'' + ", plot='" + plot + '\'' + ", tagline='" + tagline + '\'' + ", runtime='" + runtime + '\'' + ", thumb='" + thumb + '\'' + ", mpaa='" + mpaa + '\'' + ", playcount='" + playcount + '\'' + ", id='" + id + '\'' + ", filenameandpath='" + filenameandpath + '\'' + ", trailer='" + trailer + '\'' + ", genre='" + genre + '\'' + ", credits='" + credits + '\'' + ", fileinfo=" + fileinfo + ", director='" + director + '\'' + ", actorList=" + actorList + '}'; } public String getTitle() { return title; } public String getOriginaltitle() { return originaltitle; } public String getSorttitle() { return sorttitle; } public String getSet() { return set; } public String getRating() { return rating; } public String getYear() { return year; } public String getTop250() { return top250; } public String getVotes() { return votes; } public String getOutline() { return outline; } public String getPlot() { return plot; } public String getTagline() { return tagline; } public String getRuntime() { return runtime; } public String getThumb() { return thumb; } public String getMpaa() { return mpaa; } public String getPlaycount() { return playcount; } public String getId() { return id; } public String getFilenameandpath() { return filenameandpath; } public String getTrailer() { return trailer; } public String getGenre() { return genre; } public String getCredits() { return credits; } public String getDirector() { return director; } public List<Actor> actors() { return Collections.unmodifiableList(actorList); } public void addActor(Actor actor){ actorList.add(actor); } public void removeActors(){ actorList.clear(); } public String getDateadded() { return dateadded; } public String getAired() { return aired; } public Set<String> tags() { return new HashSet<>(tagList); } public static class MovieBuilder { private String title; private String originaltitle; private String sorttitle; private String set; private String rating; private String year; private String top250; private String votes; private String outline; private String plot; private String tagline; private String runtime; private String thumb; private String mpaa; private String playcount; private String id; private String filenameandpath; private String trailer; private String genre; private String credits; private Fileinfo fileinfo=new Fileinfo(); private String director; private final Set<Actor> actorSet =new HashSet<>(); private final Set<String> tagList=new HashSet<>(); private String dateAdded; private String aired; private MovieBuilder(){ super(); } private MovieBuilder(Movie movie){ this.title = movie.title; this.originaltitle = movie.originaltitle; this.sorttitle = movie.sorttitle; this.set = movie.set; this.rating = movie.rating; this.year = movie.year; this.top250 = movie.top250; this.votes = movie.votes; this.outline = movie.outline; this.plot = movie.plot; this.tagline = movie.tagline; this.runtime = movie.runtime; this.thumb = movie.thumb; this.mpaa = movie.mpaa; this.playcount = movie.playcount; this.id = movie.id; this.filenameandpath = movie.filenameandpath; this.trailer = movie.trailer; this.genre = movie.genre; this.credits = movie.credits; this.fileinfo = movie.fileinfo; this.director = movie.director; this.actorSet.addAll(movie.actorList); this.tagList.addAll(tagList); if(movie.dateadded!=null) { String date = movie.dateadded; this.dateAdded = date; } if(movie.aired!=null) { String aired = movie.aired; this.aired =aired; } } public MovieBuilder withTitle(String title) { this.title = title; return this; } public MovieBuilder withOriginaltitle(String originaltitle) { this.originaltitle = originaltitle; return this; } public MovieBuilder withSorttitle(String sorttitle) { this.sorttitle = sorttitle; return this; } public MovieBuilder withSet(String set) { this.set = set; return this; } public MovieBuilder withRating(String rating) { this.rating = rating; return this; } public MovieBuilder withYear(String year) { this.year = year; return this; } public MovieBuilder withTop250(String top250) { this.top250 = top250; return this; } public MovieBuilder withVotes(String votes) { this.votes = votes; return this; } public MovieBuilder withOutline(String outline) { this.outline = outline; return this; } public MovieBuilder withPlot(String plot) { this.plot = plot; return this; } public MovieBuilder withTagline(String tagline) { this.tagline = tagline; return this; } public MovieBuilder withRuntime(String runtime) { this.runtime = runtime; return this; } public MovieBuilder withThumb(String thumb) { this.thumb = thumb; return this; } public MovieBuilder withMpaa(String mpaa) { this.mpaa = mpaa; return this; } public MovieBuilder withPlaycount(String playcount) { this.playcount = playcount; return this; } public MovieBuilder withId(String id) { this.id = id; return this; } public MovieBuilder withFilenameandpath(String filenameandpath) { this.filenameandpath = filenameandpath; return this; } public MovieBuilder withTrailer(String trailer) { this.trailer = trailer; return this; } public MovieBuilder withGenre(String genre) { this.genre = genre; return this; } public MovieBuilder withCredits(String credits) { this.credits = credits; return this; } public MovieBuilder withDirector(String director) { this.director = director; return this; } public MovieBuilder addActor(Actor actor) { this.actorSet.add(actor); return this; } public Movie build() { this.aired=this.aired!=null?this.aired:dateAdded; this.year=this.year!=null?this.year: parseYear(aired); return new Movie(title, originaltitle, sorttitle, set, rating, year, top250, votes, outline, plot, tagline, runtime, thumb, mpaa, playcount, id, filenameandpath, trailer, genre, credits, fileinfo, director,dateAdded,aired , actorSet,tagList); } public MovieBuilder withTag(String val) { this.tagList.add(val); return this; } public MovieBuilder withDateAdded(LocalDateTime localDateTime) { this.dateAdded=DATE_TIME_FORMATTER.format(localDateTime); return this; } public MovieBuilder withAired(LocalDateTime localDateTime) { this.aired=DATE_TIME_FORMATTER.format(localDateTime); return this; } } private static String parseYear(String aired) { try { String s = Integer.toString(parseDateTime(aired).getYear()); return s; } catch(RuntimeException e){ return null; } } private static LocalDateTime parseDateTime(String date) { DateTimeFormatter dateTimeFormatter = DATE_TIME_FORMATTER .withLocale(Locale.getDefault()) .withZone(TimeZone.getDefault().toZoneId()) .withResolverStyle(ResolverStyle.LENIENT); return LocalDateTime.parse(date,dateTimeFormatter); } @XmlAccessorType(XmlAccessType.FIELD) public static class Actor implements Serializable{ @XmlElement private String name; @XmlElement private String role; public Actor(String name, String role) { this.name = name; this.role = role; } Actor() { } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Actor that = (Actor) o; if (name != null ? !name.equals(that.name) : that.name != null) return false; return role != null ? role.equals(that.role) : that.role == null; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (role != null ? role.hashCode() : 0); return result; } @Override public String toString() { return "Actor{" + "name='" + name + '\'' + ", role='" + role + '\'' + '}'; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public String getName() { return name; } } }
package it.unito.geosummly.api; import java.io.IOException; import java.util.Arrays; import it.unito.geosummly.api.cli.Clustering; import it.unito.geosummly.api.cli.Discovery; import it.unito.geosummly.api.cli.Evaluation; import it.unito.geosummly.api.cli.Sampling; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; public class MainCLI { public static void main(String[] args) { MainCLI mainCLI=new MainCLI(); mainCLI.run(args); } private void run(String[] args) { CommandLineParser parser=new PosixParser(); //create the command line parser try { CommandLine line = parser.parse(new Options(), args, true); String action= line.getArgs()[0]; args=Arrays.copyOfRange(args, 1, args.length); //delete the argument of the action switch (action) { case "sampling": Sampling sampling=new Sampling(); sampling.run(args); break; case "discovery": Discovery discovery = new Discovery(); discovery.run(args); break; case "clustering": Clustering clustering=new Clustering(); clustering.run(args); break; case "evaluation": Evaluation evaluation=new Evaluation(); evaluation.run(args); break; default: throw new IllegalArgumentException("Invalid operation: " + action + ". Allowed operation: sampling, discovery, clustering, evaluation"); } } catch (ParseException | IOException e) { System.out.println("Unexpected exception: " + e.getMessage()); } } }
package mho.wheels.math; import mho.wheels.misc.BigDecimalUtils; import mho.wheels.misc.FloatingPointUtils; import mho.wheels.misc.Readers; import mho.wheels.ordering.Ordering; import mho.wheels.structures.Pair; import org.jetbrains.annotations.NotNull; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Optional; import static mho.wheels.iterables.IterableUtils.*; import static mho.wheels.ordering.Ordering.gt; import static mho.wheels.testing.Testing.*; public strictfp class BinaryFraction implements Comparable<BinaryFraction> { public static final @NotNull BinaryFraction ZERO = new BinaryFraction(BigInteger.ZERO, 0); public static final @NotNull BinaryFraction ONE = new BinaryFraction(BigInteger.ONE, 0); public static final @NotNull BinaryFraction SMALLEST_FLOAT = of(Float.MIN_VALUE).get(); public static final @NotNull BinaryFraction LARGEST_SUBNORMAL_FLOAT = of(FloatingPointUtils.predecessor(Float.MIN_NORMAL)).get(); public static final @NotNull BinaryFraction SMALLEST_NORMAL_FLOAT = of(Float.MIN_NORMAL).get(); public static final @NotNull BinaryFraction LARGEST_FLOAT = of(Float.MAX_VALUE).get(); public static final @NotNull BinaryFraction SMALLEST_DOUBLE = of(Double.MIN_VALUE).get(); public static final @NotNull BinaryFraction LARGEST_SUBNORMAL_DOUBLE = of(FloatingPointUtils.predecessor(Double.MIN_NORMAL)).get(); public static final @NotNull BinaryFraction SMALLEST_NORMAL_DOUBLE = of(Double.MIN_NORMAL).get(); public static final @NotNull BinaryFraction LARGEST_DOUBLE = of(Double.MAX_VALUE).get(); /** * The {@code String} representation of 2<sup>31</sup> */ private static final @NotNull String NEGATIVE_MIN_INTEGER = "2147483648"; /** * If {@code this} is 0, then 0; otherwise, the unique odd integer equal to {@code this} times an integer power of * 2 */ private @NotNull BigInteger mantissa; /** * log<sub>2</sub>({@code this}/{@code mantissa}) */ private int exponent; /** * Private constructor; assumes arguments are valid. * * <ul> * <li>{@code mantissa} is odd or zero.</li> * <li>{@code exponent} may be any {@code int}.</li> * <li>If {@code mantissa} is zero, {@code exponent} must also be zero.</li> * <li>Any {@code BinaryFraction} may be constructed with this constructor.</li> * </ul> * * @param mantissa the mantissa * @param exponent the exponent */ private BinaryFraction(@NotNull BigInteger mantissa, int exponent) { this.mantissa = mantissa; this.exponent = exponent; } /** * Returns this {@code BinaryFraction}'s mantissa. * * <ul> * <li>The result is odd or zero.</li> * </ul> * * @return the mantissa */ public @NotNull BigInteger getMantissa() { return mantissa; } /** * Returns this {@code BinaryFraction}'s exponent. * * <ul> * <li>The result may be any {@code int}.</li> * </ul> * * @return the exponent */ public int getExponent() { return exponent; } public static @NotNull BinaryFraction of(@NotNull BigInteger mantissa, int exponent) { if (mantissa.equals(BigInteger.ZERO)) return ZERO; int trailingZeroes = mantissa.getLowestSetBit(); if ((long) exponent + trailingZeroes > Integer.MAX_VALUE) { throw new ArithmeticException("The sum of exponent and the number of trailing zero bits of mantissa" + " must be less than 2^31. exponent is " + exponent + " and mantissa is " + mantissa + "."); } if (trailingZeroes != 0) { mantissa = mantissa.shiftRight(trailingZeroes); exponent += trailingZeroes; } return mantissa.equals(BigInteger.ONE) && exponent == 0 ? ONE : new BinaryFraction(mantissa, exponent); } /** * Creates a {@code BinaryFraction} from a {@code BigInteger}. * * <ul> * <li>{@code n} cannot be null.</li> * <li>The result is an integral {@code BinaryFraction}.</li> * </ul> * * @param n the {@code BigInteger} * @return the {@code BinaryFraction} equal to {@code n} */ public static @NotNull BinaryFraction of(@NotNull BigInteger n) { return of(n, 0); } public static @NotNull BinaryFraction of(int n) { return of(BigInteger.valueOf(n), 0); } /** * Creates a {@code BinaryFraction} from a {@code float}. No rounding occurs; the {@code Rational} has exactly the * same value as the {@code float}. For example, {@code of(1.0f/3.0f)} yields 11184811 {@literal >>} 25. Returns * empty if the {@code float} is {@code Infinity}, {@code -Infinity}, or {@code NaN}. * * <ul> * <li>{@code f} may be any {@code float}.</li> * <li> * The result is empty or a {@code BinaryFraction} that may be exactly represented as a {@code float}. Here are * some, but not all, of the conditions on the result: * <ul> * <li>The absolute value of {@code exponent} less than or equal to 149.</li> * <li>The absolute value of {@code mantissa} is less than to 2<sup>24</sup>.</li> * </ul> * </li> * </ul> * * @param f the {@code float} * @return the {@code BinaryFraction} equal to {@code f} */ public static @NotNull Optional<BinaryFraction> of(float f) { if (f == 0.0f) return Optional.of(ZERO); if (f == 1.0f) return Optional.of(ONE); if (Float.isInfinite(f) || Float.isNaN(f)) return Optional.empty(); boolean isPositive = f > 0.0f; if (!isPositive) f = -f; int bits = Float.floatToIntBits(f); int exponent = bits >> 23 & ((1 << 8) - 1); int mantissa = bits & ((1 << 23) - 1); if (exponent == 0) { exponent = -149; } else { mantissa += 1 << 23; exponent -= 150; } return Optional.of(of(BigInteger.valueOf(isPositive ? mantissa : -mantissa), exponent)); } /** * Creates a {@code BinaryFraction} from a {@code double}. No rounding occurs; the {@code Rational} has exactly the * same value as the {@code double}. For example, {@code of(1.0/3.0)} yields 6004799503160661 {@literal >>} 54. * Returns empty if the {@code double} is {@code Infinity}, {@code -Infinity}, or {@code NaN}. * * <ul> * <li>{@code d} may be any {@code double}.</li> * <li> * The result is empty or a {@code BigInteger} that may be exactly represented as a {@code double}. Here are * some, but not all, of the conditions on the result: * <ul> * <li>The absolute value of {@code exponent} less than or equal to 1074.</li> * <li>The absolute value of {@code mantissa} is less than to 2<sup>53</sup>.</li> * </ul> * </li> * </ul> * * @param d the {@code double} * @return the {@code BinaryFraction} equal to {@code d} */ public static @NotNull Optional<BinaryFraction> of(double d) { if (d == 0.0) return Optional.of(ZERO); if (d == 1.0) return Optional.of(ONE); if (Double.isInfinite(d) || Double.isNaN(d)) return Optional.empty(); boolean isPositive = d > 0.0f; if (!isPositive) d = -d; long bits = Double.doubleToLongBits(d); int exponent = (int) (bits >> 52 & ((1 << 11) - 1)); long mantissa = bits & ((1L << 52) - 1); if (exponent == 0) { exponent = -1074; } else { mantissa += 1L << 52; exponent -= 1075; } return Optional.of(of(BigInteger.valueOf(isPositive ? mantissa : -mantissa), exponent)); } /** * Converts {@code this} to a {@code BigInteger}. Throws an {@link java.lang.ArithmeticException} if {@code this} * is not integral. * * <ul> * <li>{@code this} must be an integer.</li> * <li>The result is not null.</li> * </ul> * * @return the {@code BigInteger} value of {@code this} */ public @NotNull BigInteger bigIntegerValueExact() { if (exponent < 0) { throw new ArithmeticException("this must be an integer. This: " + this); } return mantissa.shiftLeft(exponent); } public @NotNull BigDecimal bigDecimalValue() { return BigDecimalUtils.shiftLeft(new BigDecimal(mantissa), exponent); } /** * Every {@code BinaryFraction} has a <i>left-neighboring {@code float}</i>, or the largest {@code float} that is * less than or equal to the {@code BinaryFraction}; this {@code float} may be -Infinity. Likewise, every * {@code BinaryFraction} has a <i>right-neighboring {@code float}</i>: the smallest {@code float} greater than or * equal to the {@code BinaryFraction}. This {@code float} may be Infinity. If {@code this} is exactly equal to * some {@code float}, the left- and right-neighboring {@code float}s will both be equal to that {@code float} and * to each other. This method returns the pair made up of the left- and right-neighboring {@code float}s. If the * left-neighboring {@code float} is a zero, it is a positive zero; if the right-neighboring {@code float} is a * zero, it is a negative zero. The exception is when {@code this} is equal to zero; then both neighbors are * positive zeroes. * * <ul> * <li>{@code this} may be any {@code BinaryFraction}.</li> * <li>The result is a pair of {@code float}s that are either equal, or the second is the next-largest * {@code float} after the first. Negative zero may not appear in the first slot of the pair, and positive zero * may only appear in the second slot if the first slot also contains a positive zero. Neither slot may contain a * {@code NaN}.</li> * </ul> * * @return The pair of left- and right-neighboring {@code float}s. */ public @NotNull Pair<Float, Float> floatRange() { if (this == ZERO) return new Pair<>(0.0f, 0.0f); if (mantissa.signum() == -1) { Pair<Float, Float> negativeRange = negate().floatRange(); return new Pair<>(-negativeRange.b, -negativeRange.a); } long floatExponent = mantissa.bitLength() + exponent - 1; if (floatExponent > 127 || floatExponent == 127 && gt(this, LARGEST_FLOAT)) { return new Pair<>(Float.MAX_VALUE, Float.POSITIVE_INFINITY); } BinaryFraction fraction; int adjustedExponent; if (floatExponent < -126) { fraction = shiftLeft(149); adjustedExponent = 0; } else { fraction = shiftRight((int) floatExponent).subtract(ONE).shiftLeft(23); adjustedExponent = ((int) floatExponent) + 127; } float loFloat = Float.intBitsToFloat((adjustedExponent << 23) + fraction.floor().intValueExact()); float hiFloat = fraction.getExponent() >= 0 ? loFloat : FloatingPointUtils.successor(loFloat); return new Pair<>(loFloat, hiFloat); } /** * Every {@code BinaryFraction} has a <i>left-neighboring {@code double}</i>, or the largest {@code double} that is * less than or equal to the {@code BinaryFraction}; this {@code double} may be -Infinity. Likewise, every * {@code BinaryFraction} has a <i>right-neighboring {@code double}</i>: the smallest {@code double} greater than * or equal to the {@code BinaryFraction}. This {@code double} may be Infinity. If {@code this} is exactly equal to * some {@code double}, the left- and right-neighboring {@code double}s will both be equal to that {@code double} * and to each other. This method returns the pair made up of the left- and right-neighboring {@code double}s. If * the left-neighboring {@code double} is a zero, it is a positive zero; if the right-neighboring {@code double} is * a zero, it is a negative zero. The exception is when {@code this} is equal to zero; then both neighbors are * positive zeroes. * * <ul> * <li>{@code this} may be any {@code BinaryFraction}.</li> * <li>The result is a pair of {@code double}s that are either equal, or the second is the next-largest * {@code double} after the first. Negative zero may not appear in the first slot of the pair, and positive zero * may only appear in the second slot if the first slot also contains a positive zero. Neither slot may contain a * {@code NaN}.</li> * </ul> * * @return The pair of left- and right-neighboring {@code double}s. */ public @NotNull Pair<Double, Double> doubleRange() { if (this == ZERO) return new Pair<>(0.0, 0.0); if (mantissa.signum() == -1) { Pair<Double, Double> negativeRange = negate().doubleRange(); return new Pair<>(-negativeRange.b, -negativeRange.a); } long doubleExponent = mantissa.bitLength() + exponent - 1; if (doubleExponent > 1023 || doubleExponent == 1023 && gt(this, LARGEST_DOUBLE)) { return new Pair<>(Double.MAX_VALUE, Double.POSITIVE_INFINITY); } BinaryFraction fraction; long adjustedExponent; if (doubleExponent < -1022) { fraction = shiftLeft(1074); adjustedExponent = 0; } else { fraction = shiftRight((int) doubleExponent).subtract(ONE).shiftLeft(52); adjustedExponent = doubleExponent + 1023; } double loDouble = Double.longBitsToDouble((adjustedExponent << 52) + fraction.floor().longValueExact()); double hiDouble = fraction.getExponent() >= 0 ? loDouble : FloatingPointUtils.successor(loDouble); return new Pair<>(loDouble, hiDouble); } /** * Determines whether {@code this} is integral. * * <ul> * <li>{@code this} may be any {@code BinaryFraction}.</li> * <li>The result may be either {@code boolean}.</li> * </ul> * * @return whether this is an integer */ public boolean isInteger() { return exponent >= 0; } public @NotNull BinaryFraction add(@NotNull BinaryFraction that) { if (this == ZERO) return that; if (that == ZERO) return this; switch (Ordering.compare(exponent, that.exponent)) { case EQ: return of(mantissa.add(that.mantissa), exponent); case LT: return of(that.mantissa.shiftLeft(that.exponent - exponent).add(mantissa), exponent); case GT: return of(mantissa.shiftLeft(exponent - that.exponent).add(that.mantissa), that.exponent); default: throw new IllegalStateException("unreachable"); } } public @NotNull BinaryFraction negate() { if (this == ZERO) return ZERO; if (mantissa.equals(BigInteger.valueOf(-1)) && exponent == 0) return ONE; return new BinaryFraction(mantissa.negate(), exponent); } /** * Returns the absolute value of {@code this}. * * <ul> * <li>{@code this} may be any {@code BinaryFraction}.</li> * <li>The result is a non-negative {@code BinaryFraction}.</li> * </ul> * * @return |{@code this}| */ public @NotNull BinaryFraction abs() { return signum() == -1 ? negate() : this; } @SuppressWarnings("JavaDoc") public int signum() { return mantissa.signum(); } public @NotNull BinaryFraction subtract(@NotNull BinaryFraction that) { if (this == ZERO) return that.negate(); if (that == ZERO) return this; switch (Ordering.compare(exponent, that.exponent)) { case EQ: return of(mantissa.subtract(that.mantissa), exponent); case LT: return of(mantissa.subtract(that.mantissa.shiftLeft(that.exponent - exponent)), exponent); case GT: return of(mantissa.shiftLeft(exponent - that.exponent).subtract(that.mantissa), that.exponent); default: throw new IllegalStateException("unreachable"); } } public @NotNull BinaryFraction multiply(@NotNull BinaryFraction that) { if (this == ZERO || that == ZERO) return ZERO; if (this == ONE) return that; if (that == ONE) return this; long productExponent = (long) exponent + that.exponent; if (productExponent > Integer.MAX_VALUE || productExponent < Integer.MIN_VALUE) { throw new ArithmeticException("The sum of the exponents of this and that must be less than 2^31 and" + " greater than or equal to -2^31."); } BigInteger productMantissa = mantissa.multiply(that.mantissa); if (productMantissa.equals(BigInteger.ONE) && productExponent == 0L) { return ONE; } else { return new BinaryFraction(productMantissa, (int) productExponent); } } public @NotNull BinaryFraction shiftLeft(int bits) { if (this == ZERO || bits == 0) return this; if (bits < 0) { return shiftRight(-bits); } long shiftedExponent = (long) exponent + bits; if (shiftedExponent > Integer.MAX_VALUE) { throw new ArithmeticException("The sum of bits and the exponent of this must be less than 2^31 and" + " greater than or equal to -2^31. this is " + this + " and bits is " + bits + "."); } if (mantissa.equals(BigInteger.ONE) && shiftedExponent == 0L) { return ONE; } else { return new BinaryFraction(mantissa, (int) shiftedExponent); } } public @NotNull BinaryFraction shiftRight(int bits) { if (this == ZERO || bits == 0) return this; if (bits < 0) { return shiftLeft(-bits); } long shiftedExponent = (long) exponent - bits; if (shiftedExponent < Integer.MIN_VALUE) { throw new ArithmeticException("bits subtracted from the exponent of this must be less than 2^31 and" + " greater than or equal to -2^31. this is " + this + " and bits is " + bits + "."); } if (mantissa.equals(BigInteger.ONE) && shiftedExponent == 0L) { return ONE; } else { return new BinaryFraction(mantissa, (int) shiftedExponent); } } public static @NotNull BinaryFraction sum(@NotNull Iterable<BinaryFraction> xs) { if (any(x -> x == null, xs)) { throw new NullPointerException("xs may not contain any nulls. xs: " + xs); } if (isEmpty(xs)) return ZERO; int smallestExponent = minimum(map(BinaryFraction::getExponent, xs)); return of( sumBigInteger(map(x -> x.shiftRight(smallestExponent).bigIntegerValueExact(), xs)), smallestExponent ); } public static @NotNull BinaryFraction product(@NotNull Iterable<BinaryFraction> xs) { if (any(x -> x == null, xs)) { throw new NullPointerException("xs may not contain any nulls. xs: " + xs); } if (any(x -> x == ZERO, xs)) return ZERO; return of( productBigInteger(map(BinaryFraction::getMantissa, xs)), //BigInteger conversion protects against over- and underflow sumBigInteger(map(x -> BigInteger.valueOf(x.getExponent()), xs)).intValueExact() ); } public static @NotNull Iterable<BinaryFraction> delta(@NotNull Iterable<BinaryFraction> xs) { if (isEmpty(xs)) { throw new IllegalArgumentException("xs must not be empty."); } if (head(xs) == null) { throw new NullPointerException("xs may not contain any nulls. xs: " + xs); } return adjacentPairsWith((x, y) -> y.subtract(x), xs); } public @NotNull BigInteger floor() { return mantissa.shiftLeft(exponent); } public @NotNull BigInteger ceiling() { BigInteger shifted = mantissa.shiftLeft(exponent); return exponent >= 0 ? shifted : shifted.add(BigInteger.ONE); } /** * Determines whether {@code this} is equal to {@code that}. * * <ul> * <li>{@code this} may be any {@code BinaryFraction}.</li> * <li>{@code that} may be any {@code Object}.</li> * <li>The result may be either {@code boolean}.</li> * </ul> * * @param that The {@code Object} to be compared with {@code this} * @return {@code this}={@code that} */ @Override public boolean equals(Object that) { if (this == that) return true; if (that == null || getClass() != that.getClass()) return false; BinaryFraction bf = (BinaryFraction) that; return exponent == bf.exponent && mantissa.equals(bf.mantissa); } /** * Calculates the hash code of {@code this}. * * <ul> * <li>{@code this} may be any {@code BinaryFraction}.</li> * <li>(conjecture) The result may be any {@code int}.</li> * </ul> * * @return {@code this}'s hash code. */ @Override public int hashCode() { return 31 * mantissa.hashCode() + exponent; } @Override public int compareTo(@NotNull BinaryFraction that) { if (this == that) return 0; Ordering signumOrdering = Ordering.compare(mantissa.signum(), that.mantissa.signum()); if (signumOrdering != Ordering.EQ) return signumOrdering.toInt(); switch (Ordering.compare(exponent, that.exponent)) { case LT: return mantissa.compareTo(that.mantissa.shiftLeft(that.exponent - exponent)); case GT: return mantissa.shiftLeft(exponent - that.exponent).compareTo(that.mantissa); case EQ: return mantissa.compareTo(that.mantissa); } throw new IllegalStateException("unreachable"); } /** * Creates an {@code BinaryFraction} from a {@code String}. Valid input takes the form of a {@code String} that * could have been returned by {@link BinaryFraction#toString()}. See that method's tests and demos for examples of * valid input. * * <ul> * <li>{@code s} cannot be null.</li> * <li>The result may be any {@code Optional<BinaryFraction>}.</li> * </ul> * * @param s a string representation of a {@code BinaryFraction}. * @return the wrapped {@code BinaryFraction} represented by {@code s}, or {@code empty} if {@code s} is invalid. */ public static @NotNull Optional<BinaryFraction> read(@NotNull String s) { if (s.equals("0")) return Optional.of(ZERO); if (s.equals("1")) return Optional.of(ONE); return Readers.genericRead( t -> { int leftShiftIndex = s.indexOf(" << "); if (leftShiftIndex != -1) { Optional<BigInteger> oMantissa = Readers.readBigInteger(s.substring(0, leftShiftIndex)); if (!oMantissa.isPresent()) return null; Optional<Integer> oExponent = Readers.readInteger(s.substring(leftShiftIndex + 4)); if (!oExponent.isPresent()) return null; return of(oMantissa.get(), oExponent.get()); } int rightShiftIndex = s.indexOf(" >> "); if (rightShiftIndex != -1) { Optional<BigInteger> oMantissa = Readers.readBigInteger(s.substring(0, rightShiftIndex)); if (!oMantissa.isPresent()) return null; String exponentSubstring = s.substring(rightShiftIndex + 4); int exponent; if (exponentSubstring.equals(NEGATIVE_MIN_INTEGER)) { exponent = Integer.MIN_VALUE; } else { Optional<Integer> oExponent = Readers.readInteger(exponentSubstring); if (!oExponent.isPresent()) return null; exponent = -oExponent.get(); } return of(oMantissa.get(), exponent); } Optional<BigInteger> oMantissa = Readers.readBigInteger(s); return oMantissa.isPresent() ? of(oMantissa.get()) : null; } ).apply(s); } /** * Finds the first occurrence of a {@code BinaryFraction} in a {@code String}. Returns the {@code BinaryFraction} * and the index at which it was found. Returns an empty {@code Optional} if no {@code BinaryFraction} is found. * Only {@code String}s which could have been emitted by {@link BinaryFraction#toString} are recognized. The * longest possible {@code BinaryFraction} is parsed. * * <ul> * <li>{@code s} must be non-null.</li> * <li>The result is non-null. If it is non-empty, then neither of the {@code Pair}'s components is null, and the * second component is non-negative.</li> * </ul> * * @param s the input {@code String} * @return the first {@code BinaryFraction} found in {@code s}, and the index at which it was found */ public static @NotNull Optional<Pair<BinaryFraction, Integer>> findIn(@NotNull String s) { return Readers.genericFindIn(BinaryFraction::read, " -0123456789<>").apply(s); } /** * Creates a {@code String} representation of {@code this}. * * <ul> * <li>{@code this} may be any {@code BinaryFraction}.</li> * <li>See tests and demos for example results.</li> * </ul> * * @return a {@code String} representation of {@code this} */ public @NotNull String toString() { switch (Integer.signum(exponent)) { case 0: return mantissa.toString(); case 1: return mantissa + " << " + exponent; case -1: return mantissa + " >> " + (exponent == Integer.MIN_VALUE ? NEGATIVE_MIN_INTEGER : -exponent); default: throw new IllegalStateException("unreachable"); } } /** * Ensures that {@code this} is valid. Must return true for any {@code BinaryFraction} used outside this class. */ public void validate() { if (mantissa.equals(BigInteger.ZERO)) { assertEquals(this, exponent, 0); } else { assertTrue(this, mantissa.testBit(0)); } if (equals(ZERO)) assertTrue(this, this == ZERO); if (equals(ONE)) assertTrue(this, this == ONE); } }
package mho.wheels.math; import mho.wheels.misc.FloatingPointUtils; import mho.wheels.misc.Readers; import mho.wheels.ordering.Ordering; import mho.wheels.structures.Pair; import org.jetbrains.annotations.NotNull; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Optional; import static org.junit.Assert.*; /** * <p>The {@code BinaryFraction} class uniquely represents rational numbers whose denominator is a power of 2. Every * such number is either zero or an equal to an odd integer (the mantissa) times 2 raised to an integer (the exponent). * Zero is considered to have a mantissa of zero (this is the only case when the mantissa is even) and an exponent of * zero. * * <p>There is only one instance of {@code ZERO} and one instance of {@code ONE}, so these may be compared with other * {@code BigInteger}s using {@code ==}. * * <p>This class is immutable. */ public class BinaryFraction implements Comparable<BinaryFraction> { public static final @NotNull BinaryFraction ZERO = new BinaryFraction(BigInteger.ZERO, 0); public static final @NotNull BinaryFraction ONE = new BinaryFraction(BigInteger.ONE, 0); public static final @NotNull BinaryFraction SMALLEST_FLOAT = of(Float.MIN_VALUE).get(); public static final @NotNull BinaryFraction LARGEST_SUBNORMAL_FLOAT = of(FloatingPointUtils.predecessor(Float.MIN_NORMAL)).get(); public static final @NotNull BinaryFraction SMALLEST_NORMAL_FLOAT = of(Float.MIN_NORMAL).get(); public static final @NotNull BinaryFraction LARGEST_FLOAT = of(Float.MAX_VALUE).get(); public static final @NotNull BinaryFraction SMALLEST_DOUBLE = of(Double.MIN_VALUE).get(); public static final @NotNull BinaryFraction LARGEST_SUBNORMAL_DOUBLE = of(FloatingPointUtils.predecessor(Double.MIN_NORMAL)).get(); public static final @NotNull BinaryFraction SMALLEST_NORMAL_DOUBLE = of(Double.MIN_NORMAL).get(); public static final @NotNull BinaryFraction LARGEST_DOUBLE = of(Double.MAX_VALUE).get(); /** * If {@code this} is 0, then 0; otherwise, the unique odd integer equal to {@code this} times an integer power of * 2 */ private @NotNull BigInteger mantissa; /** * log<sub>2</sub>({@code this}/{@code mantissa}) */ private int exponent; /** * Private constructor; assumes arguments are valid. * * <ul> * <li>{@code mantissa} is odd or zero.</li> * <li>{@code exponent} may be any {@code int}.</li> * <li>If {@code mantissa} is zero, {@code exponent} must also be zero.</li> * <li>Any {@code BinaryFraction} may be constructed with this constructor.</li> * </ul> * * @param mantissa the mantissa * @param exponent the exponent */ private BinaryFraction(@NotNull BigInteger mantissa, int exponent) { this.mantissa = mantissa; this.exponent = exponent; } /** * Returns this {@code BinaryFraction}'s mantissa. * * <ul> * <li>The result is odd or zero.</li> * </ul> * * @return the mantissa */ public @NotNull BigInteger getMantissa() { return mantissa; } /** * Returns this {@code BinaryFraction}'s exponent. * * <ul> * <li>The result may be any {@code int}.</li> * </ul> * * @return the exponent */ public int getExponent() { return exponent; } public static @NotNull BinaryFraction of(@NotNull BigInteger mantissa, int exponent) { if (mantissa.equals(BigInteger.ZERO)) { return new BinaryFraction(BigInteger.ZERO, 0); } int trailingZeroes = mantissa.getLowestSetBit(); if (trailingZeroes != 0) { mantissa = mantissa.shiftRight(trailingZeroes); exponent += trailingZeroes; } return mantissa.equals(BigInteger.ONE) && exponent == 0 ? ONE : new BinaryFraction(mantissa, exponent); } /** * Creates a {@code BinaryFraction} from a {@code BigInteger}. * * <ul> * <li>{@code n} cannot be null.</li> * <li>The result is an integral {@code BinaryFraction}.</li> * </ul> * * @param n the {@code BigInteger} * @return the {@code BigInteger} equal to {@code n} */ public static @NotNull BinaryFraction of(@NotNull BigInteger n) { return of(n, 0); } public static @NotNull BinaryFraction of(int n) { return of(BigInteger.valueOf(n), 0); } public static @NotNull Optional<BinaryFraction> of(float f) { if (f == 0.0f) return Optional.of(ZERO); if (f == 1.0f) return Optional.of(ONE); if (Float.isInfinite(f) || Float.isNaN(f)) return Optional.empty(); boolean isPositive = f > 0.0f; if (!isPositive) f = -f; int bits = Float.floatToIntBits(f); int exponent = bits >> 23 & ((1 << 8) - 1); int mantissa = bits & ((1 << 23) - 1); if (exponent == 0) { exponent = -149; } else { mantissa += 1 << 23; exponent -= 150; } return Optional.of(of(BigInteger.valueOf(isPositive ? mantissa : -mantissa), exponent)); } public static @NotNull Optional<BinaryFraction> of(double d) { if (d == 0.0) return Optional.of(ZERO); if (d == 1.0) return Optional.of(ONE); if (Double.isInfinite(d) || Double.isNaN(d)) return Optional.empty(); boolean isPositive = d > 0.0f; if (!isPositive) d = -d; long bits = Double.doubleToLongBits(d); int exponent = (int) (bits >> 52 & ((1 << 11) - 1)); long mantissa = bits & ((1L << 52) - 1); if (exponent == 0) { exponent = -1074; } else { mantissa += 1L << 52; exponent -= 1075; } return Optional.of(of(BigInteger.valueOf(isPositive ? mantissa : -mantissa), exponent)); } public @NotNull BigDecimal bigDecimalValue() { switch (Integer.signum(exponent)) { case 0: return new BigDecimal(mantissa); case 1: return new BigDecimal(mantissa).multiply(new BigDecimal(BigInteger.ONE.shiftLeft(exponent))); case -1: //noinspection BigDecimalMethodWithoutRoundingCalled return new BigDecimal(mantissa).divide(new BigDecimal(BigInteger.ONE.shiftLeft(-exponent))); default: throw new IllegalStateException("unreachable"); } } @Override public boolean equals(Object that) { if (this == that) return true; if (that == null || getClass() != that.getClass()) return false; BinaryFraction bf = (BinaryFraction) that; return exponent == bf.exponent && mantissa.equals(bf.mantissa); } @Override public int hashCode() { return 31 * mantissa.hashCode() + exponent; } @Override public int compareTo(@NotNull BinaryFraction that) { if (this == that) return 0; Ordering signumOrdering = Ordering.compare(mantissa.signum(), that.mantissa.signum()); if (signumOrdering != Ordering.EQ) return signumOrdering.toInt(); switch (Ordering.compare(exponent, that.exponent)) { case LT: return mantissa.shiftLeft(that.exponent - exponent).compareTo(that.mantissa); case GT: return mantissa.compareTo(that.mantissa.shiftLeft(exponent - that.exponent)); case EQ: return mantissa.compareTo(that.mantissa); } throw new IllegalStateException("unreachable"); } public static @NotNull Optional<BinaryFraction> read(@NotNull String s) { return Readers.genericRead( t -> { int leftShiftIndex = s.indexOf(" << "); if (leftShiftIndex != -1) { Optional<BigInteger> oMantissa = Readers.readBigInteger(s.substring(0, leftShiftIndex)); if (!oMantissa.isPresent()) return null; Optional<Integer> oExponent = Readers.readInteger(s.substring(leftShiftIndex + 4)); if (!oExponent.isPresent()) return null; return of(oMantissa.get(), oExponent.get()); } int rightShiftIndex = s.indexOf(" >> "); if (rightShiftIndex != -1) { Optional<BigInteger> oMantissa = Readers.readBigInteger(s.substring(0, rightShiftIndex)); if (!oMantissa.isPresent()) return null; Optional<Integer> oExponent = Readers.readInteger(s.substring(rightShiftIndex + 4)); if (!oExponent.isPresent()) return null; return of(oMantissa.get(), -oExponent.get()); } Optional<BigInteger> oMantissa = Readers.readBigInteger(s); return oMantissa.isPresent() ? new BinaryFraction(oMantissa.get(), 0) : null; } ).apply(s); } /** * Finds the first occurrence of a {@code BinaryFraction} in a {@code String}. Returns the {@code BinaryFraction} * and the index at which it was found. Returns an empty {@code Optional} if no {@code BinaryFraction} is found. * Only {@code String}s which could have been emitted by {@link BinaryFraction#toString} are recognized. The * longest possible {@code BinaryFraction} is parsed. * * <ul> * <li>{@code s} must be non-null.</li> * <li>The result is non-null. If it is non-empty, then neither of the {@code Pair}'s components is null, and the * second component is non-negative.</li> * </ul> * * @param s the input {@code String} * @return the first {@code BinaryFraction} found in {@code s}, and the index at which it was found */ public static @NotNull Optional<Pair<BinaryFraction, Integer>> findIn(@NotNull String s) { return Readers.genericFindIn(BinaryFraction::read, " -0123456789<>").apply(s); } /** * Creates a {@code String} representation of {@code this}. * * <ul> * <li>{@code this} may be any {@code BinaryFraction}.</li> * <li>See tests and demos for example results.</li> * </ul> * * @return a {@code String} representation of {@code this} */ public @NotNull String toString() { switch (Integer.signum(exponent)) { case 0: return mantissa.toString(); case 1: return mantissa + " << " + exponent; case -1: return mantissa + " >> " + -exponent; default: throw new IllegalStateException("unreachable"); } } /** * Ensures that {@code this} is valid. Must return true for any {@code Rational} used outside this class. */ public void validate() { if (mantissa.equals(BigInteger.ZERO)) { assertEquals(toString(), exponent, 0); } else { assertTrue(toString(), mantissa.testBit(0)); } if (equals(ZERO)) assertTrue(toString(), this == ZERO); if (equals(ONE)) assertTrue(toString(), this == ONE); } }
package org.motechproject.appointmentreminder.model; import org.ektorp.support.TypeDiscriminator; import org.motechproject.model.MotechBaseDataObject; public class Preferences extends MotechBaseDataObject { private static final long serialVersionUID = 7959940892352071956L; @TypeDiscriminator private String patientId; // FIXME: best time to call is not only the hour but also the minute in 24 hour format private Integer bestTimeToCall; private Boolean enabled = Boolean.FALSE; /** * @return the patientId */ public String getPatientId() { return patientId; } /** * @param patientId the patientId to set */ public void setPatientId(String patientId) { this.patientId = patientId; } /** * @return the bestTimeToCall */ public Integer getBestTimeToCall() { return bestTimeToCall; } /** * @param bestTimeToCall the bestTimeToCall to set */ public void setBestTimeToCall(Integer bestTimeToCall) { this.bestTimeToCall = bestTimeToCall; } /** * @return the enabled */ public Boolean isEnabled() { return enabled; } /** * @param enabled the enabled to set */ public void setEnabled(Boolean enabled) { this.enabled = enabled; } @Override public String toString() { return "id = " + this.getId() + ", enabled = " + enabled + ", best time to call = " + this.bestTimeToCall + ", patient id = " + patientId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Preferences p = (Preferences) o; if (this.getId() != null ? !this.getId().equals(p.getId()) : p.getId() != null) return false; if (this.enabled != p.isEnabled()) return false; if (this.bestTimeToCall != p.getBestTimeToCall()) return false; if (this.patientId != null ? !this.patientId.equals(p.getPatientId()) : p.getPatientId() != null) return false; return true; } @Override public int hashCode() { int result = bestTimeToCall; result = 31 * result + (this.getId() != null ? this.getId().hashCode() : 0); result = 31 * result + (this.patientId != null ? this.patientId.hashCode() : 0); return result; } }
package net.reini.groupshuffle; import java.util.function.IntConsumer; import javafx.application.Application; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.ScrollPane.ScrollBarPolicy; import javafx.scene.control.TextArea; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class Shuffle extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { Button editBtn = new Button("Edit"); editBtn.setMinWidth(50); TextArea text = new TextArea(); HBox hbox = new HBox(5); hbox.setPadding(new Insets(5)); hbox.setAlignment(Pos.CENTER_LEFT); ScrollPane buttons = new ScrollPane(hbox); buttons.setVbarPolicy(ScrollBarPolicy.NEVER); buttons.setHbarPolicy(ScrollBarPolicy.NEVER); ObservableList<Node> children = hbox.getChildren(); children.add(editBtn); children.add(new Label("Gruppen:")); for (int i = 2; i < 6; i++) { Button shuffleBtn = new ShuffleButton(i, value -> text.textProperty().set("groups" + value)); shuffleBtn.setMinWidth(50); children.add(shuffleBtn); } BorderPane root = new BorderPane(); root.setTop(buttons); root.setCenter(text); editBtn.setOnAction(event -> text.textProperty().set(text.getText().concat("Hello World!\n"))); primaryStage.setTitle("Shuffle"); primaryStage.setScene(new Scene(root, 300, 250)); primaryStage.show(); } class ShuffleButton extends Button { ShuffleButton(int groups, IntConsumer shuffleAction) { super(String.valueOf(groups)); setOnAction(event -> shuffleAction.accept(groups)); } } }
package info.tregmine.database.db; import java.math.BigInteger; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.bukkit.entity.Player; import info.tregmine.Tregmine; import info.tregmine.api.Badge; import info.tregmine.api.Rank; import info.tregmine.api.TregminePlayer; import info.tregmine.api.TregminePlayer.Property; import info.tregmine.database.DAOException; import info.tregmine.database.IPlayerDAO; public class DBPlayerDAO implements IPlayerDAO { private Connection conn; private Tregmine plugin; public DBPlayerDAO(Connection conn) { this.conn = conn; } public DBPlayerDAO(Connection conn, Tregmine instance) { this.conn = conn; this.plugin = instance; } @Override public TregminePlayer createPlayer(Player wrap) throws DAOException { String sql = "INSERT INTO player (player_uuid, player_name, player_rank, player_keywords) VALUE (?, ?, ?, ?)"; TregminePlayer player = new TregminePlayer(wrap, plugin); player.setStoredUuid(player.getUniqueId()); try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, player.getUniqueId().toString()); stmt.setString(2, player.getName()); stmt.setString(3, player.getTrueRank().toString()); stmt.setString(4, player.getRealName()); stmt.execute(); stmt.executeQuery("SELECT LAST_INSERT_ID()"); try (ResultSet rs = stmt.getResultSet()) { if (!rs.next()) { throw new DAOException("Failed to get player id", sql); } player.setId(rs.getInt(1)); } } catch (SQLException e) { throw new DAOException(sql, e); } return player; } @Override public boolean doesIgnore(TregminePlayer player, TregminePlayer victim) throws DAOException { return false; // String sql = "SELECT * FROM player " + // "WHERE player_id = ? "; // try (PreparedStatement stmt = conn.prepareStatement(sql)) { // stmt.setInt(1, player.getId()); // stmt.execute(); // try (ResultSet rs = stmt.getResultSet()) { // if(!rs.next()) return false; // String stringofignored = rs.getString("player_ignore"); // String[] strings = stringofignored.split(","); // List<String> playerignore = new ArrayList<String>(); // for (String i : strings){ // if("".equalsIgnoreCase(i)) continue; // playerignore.add(i); // if (playerignore.contains(victim.getRealName())) { // return true; // } else { // return false; // } catch (SQLException e) { // throw new DAOException(sql, e); } @Override public Map<Badge, Integer> getBadges(TregminePlayer player) throws DAOException { String sql = "SELECT * FROM player_badge " + "WHERE player_id = ?"; Map<Badge, Integer> badges = new EnumMap<Badge, Integer>(Badge.class); try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, player.getId()); stmt.execute(); try (ResultSet rs = stmt.getResultSet()) { while (rs.next()) { Badge badge = Badge.fromString(rs.getString("badge_name")); int lvl = rs.getInt("badge_level"); badges.put(badge, lvl); } } } catch (SQLException e) { throw new DAOException(sql, e); } return badges; } @Override public List<String> getIgnored(TregminePlayer to) throws DAOException { String sql = "SELECT * FROM player " + "WHERE player_id = ? "; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, to.getId()); stmt.execute(); try (ResultSet rs = stmt.getResultSet()) { if (!rs.next()) return null; String[] strings; String stringofignored = rs.getString("player_ignore"); if (stringofignored == null) { strings = new String[0]; } else { strings = stringofignored.split(","); } List<String> playerignore = new ArrayList<String>(); for (String i : strings) { if ("".equalsIgnoreCase(i)) continue; playerignore.add(i); } return playerignore; } } catch (SQLException e) { throw new DAOException(sql, e); } } @Override public List<String> getKeywords(TregminePlayer to) throws DAOException { String sql = "SELECT * FROM player " + "WHERE player_id = ? "; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, to.getId()); stmt.execute(); try (ResultSet rs = stmt.getResultSet()) { if (!rs.next()) return null; String stringofkeywords = rs.getString("player_keywords"); String[] strings = stringofkeywords.split(","); List<String> playerkeywords = new ArrayList<String>(); for (String i : strings) { if ("".equalsIgnoreCase(i)) continue; playerkeywords.add(i); } return playerkeywords; } } catch (SQLException e) { throw new DAOException(sql, e); } } @Override public TregminePlayer getPlayer(int id) throws DAOException { String sql = "SELECT * FROM player WHERE player_id = ?"; TregminePlayer player = null; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, id); stmt.execute(); try (ResultSet rs = stmt.getResultSet()) { if (!rs.next()) { return null; } player = new TregminePlayer(UUID.fromString(rs.getString("player_uuid")), plugin, rs.getString("player_name")); player.setId(rs.getInt("player_id")); String uniqueIdStr = rs.getString("player_uuid"); if (uniqueIdStr != null) { player.setStoredUuid(UUID.fromString(uniqueIdStr)); } player.setPasswordHash(rs.getString("player_password")); player.setRank(Rank.fromString(rs.getString("player_rank"))); // if(rs.getString("player_referralcode") == null){ // player.setReferralCode(generateReferralCode(player)); // }else{ // player.setReferralCode(rs.getString("player_referralcode")); if (rs.getString("player_inventory") == null) { player.setCurrentInventory("survival"); } else { player.setCurrentInventory(rs.getString("player_inventory")); } int flags = rs.getInt("player_flags"); for (TregminePlayer.Flags flag : TregminePlayer.Flags.values()) { if ((flags & (1 << flag.ordinal())) != 0) { player.setFlag(flag); } } } } catch (SQLException e) { throw new DAOException(sql, e); } loadSettings(player); return player; } @Override public TregminePlayer getPlayer(String username) throws DAOException { String sql = "SELECT * FROM player WHERE player_name = ?"; TregminePlayer player = null; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, username); stmt.execute(); try (ResultSet rs = stmt.getResultSet()) { if (!rs.next()) { return null; } player = new TregminePlayer(UUID.fromString(rs.getString("player_uuid")), plugin, rs.getString("player_name")); player.setId(rs.getInt("player_id")); String uniqueIdStr = rs.getString("player_uuid"); if (uniqueIdStr != null) { player.setStoredUuid(UUID.fromString(uniqueIdStr)); } player.setPasswordHash(rs.getString("player_password")); player.setRank(Rank.fromString(rs.getString("player_rank"))); // if(rs.getString("player_referralcode") == null){ // player.setReferralCode(generateReferralCode(player)); // }else{ // player.setReferralCode(rs.getString("player_referralcode")); if (rs.getString("player_inventory") == null) { player.setCurrentInventory("survival"); } else { player.setCurrentInventory(rs.getString("player_inventory")); } int flags = rs.getInt("player_flags"); for (TregminePlayer.Flags flag : TregminePlayer.Flags.values()) { if ((flags & (1 << flag.ordinal())) != 0) { player.setFlag(flag); } } } } catch (SQLException e) { throw new DAOException(sql, e); } loadSettings(player); return player; } @Override public TregminePlayer getPlayer(UUID id) throws DAOException { String sql = "SELECT * FROM player WHERE player_uuid = ?"; TregminePlayer player = null; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, id.toString()); stmt.execute(); try (ResultSet rs = stmt.getResultSet()) { if (!rs.next()) { return null; } player = new TregminePlayer(UUID.fromString(rs.getString("player_uuid")), plugin, rs.getString("player_name")); player.setId(rs.getInt("player_id")); String uniqueIdStr = rs.getString("player_uuid"); if (uniqueIdStr != null) { player.setStoredUuid(UUID.fromString(uniqueIdStr)); } player.setPasswordHash(rs.getString("player_password")); player.setRank(Rank.fromString(rs.getString("player_rank"))); // if(rs.getString("player_referralcode") == null){ // player.setReferralCode(generateReferralCode(player)); // }else{ // player.setReferralCode(rs.getString("player_referralcode")); if (rs.getString("player_inventory") == null) { player.setCurrentInventory("survival"); } else { player.setCurrentInventory(rs.getString("player_inventory")); } int flags = rs.getInt("player_flags"); for (TregminePlayer.Flags flag : TregminePlayer.Flags.values()) { if ((flags & (1 << flag.ordinal())) != 0) { player.setFlag(flag); } } } } catch (SQLException e) { throw new DAOException(sql, e); } loadSettings(player); return player; } @Override public TregminePlayer getPlayer(Player wrap) throws DAOException { String sql = "SELECT * FROM player WHERE player_uuid = ?"; String sql1 = "UPDATE `player` SET player_name = ? WHERE player_uuid = ?"; try (PreparedStatement stmt1 = conn.prepareStatement(sql1)) { stmt1.setString(1, wrap.getName()); stmt1.setString(2, wrap.getUniqueId().toString()); stmt1.execute(); } catch (SQLException e1) { e1.printStackTrace(); } TregminePlayer player; if (wrap != null) { player = new TregminePlayer(wrap, plugin); } else { return null; } try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, wrap.getUniqueId().toString()); stmt.execute(); try (ResultSet rs = stmt.getResultSet()) { if (!rs.next()) { return null; } if (rs.getString("player_name") != wrap.getName()) { // Name change! Call 911! } UUID uniqueId = wrap.getUniqueId(); player.setId(rs.getInt("player_id")); player.setStoredUuid(uniqueId); player.setPasswordHash(rs.getString("player_password")); player.setRank(Rank.fromString(rs.getString("player_rank"))); // if(rs.getString("player_referralcode") == null){ // player.setReferralCode(generateReferralCode(player)); // }else{ // player.setReferralCode(rs.getString("player_referralcode")); if (rs.getString("player_inventory") == null) { player.setCurrentInventory("survival"); } else { player.setCurrentInventory(rs.getString("player_inventory")); } int flags = rs.getInt("player_flags"); for (TregminePlayer.Flags flag : TregminePlayer.Flags.values()) { if ((flags & (1 << flag.ordinal())) != 0) { player.setFlag(flag); } } } } catch (SQLException e) { throw new DAOException(sql, e); } loadSettings(player); loadReports(player); return player; } private void loadReports(TregminePlayer player) throws DAOException { String sql = "SELECT * FROM player_report WHERE subject_id = ?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, player.getId()); stmt.execute(); try (ResultSet rs = stmt.getResultSet()) { while (rs.next()) { if ("softwarn".equals(rs.getString("report_action"))) { player.setTotalSofts(player.getTotalSofts() + 1); } if ("hardwarn".equals(rs.getString("report_action"))) { player.setTotalHards(player.getTotalHards() + 1); } if ("kick".equals(rs.getString("report_action"))) { player.setTotalKicks(player.getTotalKicks() + 1); } if ("ban".equals(rs.getString("report_action"))) { player.setTotalBans(player.getTotalBans() + 1); } } } } catch (SQLException e) { e.printStackTrace(); } } private void loadSettings(TregminePlayer player) throws DAOException { String sql = "SELECT * FROM player_property WHERE player_id = ?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, player.getId()); stmt.execute(); try (ResultSet rs = stmt.getResultSet()) { while (rs.next()) { String key = rs.getString("property_key"); String value = rs.getString("property_value"); if ("keyword".equals(key)) { player.setKeyword(value); } else if ("guardian".equals(key)) { player.setGuardianRank(Integer.parseInt(value)); } else if ("quitmessage".equals(key)) { player.setQuitMessage(value); } else if ("playtime".equals(key)) { player.setPlayTime(Integer.parseInt(value)); } else if ("afkkick".equals(key)) { player.setAfkKick(Boolean.valueOf(value)); } else if ("cursewarned".equals(key)) { player.setCurseWarned(Boolean.valueOf(value)); } else if ("nick".equals(key)) { player.setProperty(Property.NICKNAME); player.setTemporaryChatName(player.getRank().getName(plugin) + value); } } } } catch (SQLException e) { throw new DAOException(sql, e); } } // public String generateReferralCode(TregminePlayer source) throws DAOException { // //Generate a six-character securely randomized string, to be used as a referral code. // String referralCode = new BigInteger(130, this.plugin.getSecureRandom()).toString(32).substring(0, 6); // String sql = "UPDATE player SET player_referralcode = ? WHERE player_id = ?"; // try(PreparedStatement stmt = conn.prepareStatement(sql)){ // stmt.setString(1, referralCode); // stmt.setInt(2, source.getId()); // stmt.execute(); // }catch(SQLException e){ // throw new DAOException(sql, e); // return referralCode; @Override public void updateBadges(TregminePlayer player) throws DAOException { Map<Badge, Integer> dbBadges = player.getBadges(); Map<Badge, Integer> memBadges = getBadges(player); Map<Badge, Integer> added = new EnumMap<Badge, Integer>(Badge.class); Map<Badge, Integer> changed = new EnumMap<Badge, Integer>(Badge.class); for (Map.Entry<Badge, Integer> entry : memBadges.entrySet()) { if (dbBadges.containsKey(entry.getKey()) && dbBadges.get(entry.getKey()) != entry.getValue()) { changed.put(entry.getKey(), entry.getValue()); } else if (!dbBadges.containsKey(entry.getKey())) { added.put(entry.getKey(), entry.getValue()); } } Map<Badge, Integer> deleted = new EnumMap<Badge, Integer>(Badge.class); for (Map.Entry<Badge, Integer> entry : dbBadges.entrySet()) { if (!memBadges.containsKey(entry.getKey())) { deleted.put(entry.getKey(), entry.getValue()); } } String sqlInsert = "INSERT INTO player_badge (player_id, badge_name, " + "badge_level, badge_timestamp) "; sqlInsert += "VALUES (?, ?, ?, unix_timestamp())"; try (PreparedStatement stmt = conn.prepareStatement(sqlInsert)) { for (Map.Entry<Badge, Integer> entry : added.entrySet()) { stmt.setInt(1, player.getId()); stmt.setString(2, entry.getKey().toString()); stmt.setInt(3, entry.getValue()); stmt.execute(); } } catch (SQLException e) { throw new DAOException(sqlInsert, e); } String sqlUpdate = "UPDATE player_badge SET badge_level = ? " + "WHERE player_id = ? AND badge_name = ?"; try (PreparedStatement stmt = conn.prepareStatement(sqlUpdate)) { for (Map.Entry<Badge, Integer> entry : changed.entrySet()) { stmt.setInt(1, entry.getValue()); stmt.setInt(2, player.getId()); stmt.setString(3, entry.getKey().toString()); stmt.execute(); } } catch (SQLException e) { throw new DAOException(sqlUpdate, e); } String sqlDelete = "DELETE FROM player_badge " + "WHERE player_id = ? AND badge_name = ?"; try (PreparedStatement stmt = conn.prepareStatement(sqlDelete)) { for (Map.Entry<Badge, Integer> entry : deleted.entrySet()) { stmt.setInt(1, player.getId()); stmt.setString(2, entry.getKey().toString()); stmt.execute(); } } catch (SQLException e) { throw new DAOException(sqlDelete, e); } } @Override public void updateIgnore(TregminePlayer player, List<String> update) throws DAOException { String sql = "UPDATE player SET player_ignore = ? " + "WHERE player_id = ?"; StringBuilder buffer = new StringBuilder(); String delim = ""; for (String ignored : update) { buffer.append(delim); buffer.append(ignored); delim = ","; } String updateIgnoreString = buffer.toString(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, updateIgnoreString); stmt.setInt(2, player.getId()); stmt.execute(); } catch (SQLException e) { throw new DAOException(sql, e); } } @Override public void updateKeywords(TregminePlayer player, List<String> update) throws DAOException { String sql = "UPDATE player SET player_keywords = ? " + "WHERE player_id = ?"; StringBuilder buffer = new StringBuilder(); String delim = ""; for (String keyword : update) { buffer.append(delim); buffer.append(keyword); delim = ","; } String keywordsString = buffer.toString(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, keywordsString); stmt.setInt(2, player.getId()); stmt.execute(); } catch (SQLException e) { throw new DAOException(sql, e); } } @Override public void updatePlayer(TregminePlayer player) throws DAOException { String sql = "UPDATE player SET player_uuid = ?, player_password = ?, " + "player_rank = ?, player_flags = ?, player_inventory = ? "; sql += "WHERE player_id = ?"; int flags = 0; for (TregminePlayer.Flags flag : TregminePlayer.Flags.values()) { flags |= player.hasFlag(flag) ? 1 << flag.ordinal() : 0; } try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, player.getStoredUuid().toString()); stmt.setString(2, player.getPasswordHash()); stmt.setString(3, player.getRank().toString()); stmt.setInt(4, flags); stmt.setString(5, player.getCurrentInventory()); stmt.setInt(6, player.getId()); stmt.execute(); } catch (SQLException e) { throw new DAOException(sql, e); } } @Override public void updatePlayerInfo(TregminePlayer player) throws DAOException { updateProperty(player, "quitmessage", player.getQuitMessage()); } @Override public void updatePlayerKeyword(TregminePlayer player) throws DAOException { updateProperty(player, "keyword", player.getKeyword()); } @Override public void updatePlayTime(TregminePlayer player) throws DAOException { int playTime = player.getPlayTime() + player.getTimeOnline(); updateProperty(player, "playtime", String.valueOf(playTime)); } private void updateProperty(TregminePlayer player, String key, boolean value) throws DAOException { updateProperty(player, key, String.valueOf(value)); } private void updateProperty(TregminePlayer player, String key, int value) throws DAOException { updateProperty(player, key, String.valueOf(value)); } @Override public void updateProperty(TregminePlayer player, String key, String value) throws DAOException { String sqlInsert = "REPLACE INTO player_property (player_id, " + "property_key, property_value) VALUE (?, ?, ?)"; if (value == null) { return; } try (PreparedStatement stmt = conn.prepareStatement(sqlInsert)) { stmt.setInt(1, player.getId()); stmt.setString(2, key); stmt.setString(3, value); stmt.execute(); } catch (SQLException e) { throw new DAOException(sqlInsert, e); } } }
package org.caleydo.view.idbrowser.internal.model; import gleem.linalg.Vec2f; import java.util.List; import java.util.Set; import org.caleydo.core.data.collection.EDimension; import org.caleydo.core.data.collection.table.NumericalTable; import org.caleydo.core.data.collection.table.Table; import org.caleydo.core.data.datadomain.ATableBasedDataDomain; import org.caleydo.core.data.datadomain.DataSupportDefinitions; import org.caleydo.core.data.perspective.table.TableDoubleLists; import org.caleydo.core.data.perspective.table.TablePerspective; import org.caleydo.core.util.color.Color; import org.caleydo.core.util.function.ADoubleList; import org.caleydo.core.util.function.AdvancedDoubleStatistics; import org.caleydo.core.util.function.ArrayDoubleList; import org.caleydo.core.util.function.DoubleStatistics; import org.caleydo.core.util.function.IDoubleList; import org.caleydo.core.view.opengl.canvas.EDetailLevel; import org.caleydo.core.view.opengl.layout2.GLElement; import org.caleydo.core.view.opengl.layout2.GLElementAccessor; import org.caleydo.core.view.opengl.layout2.GLGraphics; import org.caleydo.core.view.opengl.layout2.IGLElementContext; import org.caleydo.core.view.opengl.layout2.IGLElementParent; import org.caleydo.view.histogram.v2.ListBoxAndWhiskersElement; import org.caleydo.vis.lineup.model.ARankColumnModel; import org.caleydo.vis.lineup.model.IRow; import org.caleydo.vis.lineup.model.mixin.IRankableColumnMixin; import org.caleydo.vis.lineup.ui.detail.ValueElement; import com.google.common.collect.Lists; /** * @author Samuel Gratzl * */ public class BoxPlotRankTableModel extends ADataDomainRankTableModel implements IRankableColumnMixin { private double min; private double max; /** * @param d * @param dim */ public BoxPlotRankTableModel(ATableBasedDataDomain d, EDimension dim) { super(d, dim); assert DataSupportDefinitions.numericalTables.apply(d); final NumericalTable table = (NumericalTable) d.getTable(); this.min = table.getMin(); this.max = table.getMax(); } public BoxPlotRankTableModel(TablePerspective t, EDimension dim) { super(t, dim); DoubleStatistics stats = DoubleStatistics.of(TableDoubleLists.asRawList(t)); this.min = stats.getMin(); this.max = stats.getMax(); } /** * @param distributionRankTableModel */ public BoxPlotRankTableModel(BoxPlotRankTableModel clone) { super(clone); this.min = clone.min; this.max = clone.max; } @Override public ARankColumnModel clone() { return new BoxPlotRankTableModel(this); } @Override public String getValue(IRow row) { AdvancedDoubleStatistics stats = getStats(row); if (stats == null) return ""; StringBuilder b = new StringBuilder(); b.append("min: ").append(stats.getMin()).append(" max: ").append(stats.getMax()); return b.toString(); } AdvancedDoubleStatistics getStats(IRow row) { if (cache.containsKey(row.getIndex())) return (AdvancedDoubleStatistics) cache.get(row.getIndex()); AdvancedDoubleStatistics c = computeStats((IIDRow) row); cache.put(row.getIndex(), c); return c; } @Override public int compare(IRow o1, IRow o2) { AdvancedDoubleStatistics s1 = getStats(o1); AdvancedDoubleStatistics s2 = getStats(o2); if (s1 == s2) return 0; if (s1 == null) return 1; if (s2 == null) return -1; double sd1 = Math.abs(s1.getSd()); double sd2 = Math.abs(s2.getSd()); return Double.compare(sd1, sd2); } @Override public void orderByMe() { getParent().orderBy(this); } /** * @param row * @return */ private AdvancedDoubleStatistics computeStats(IIDRow row) { Set<Object> ids = row.get(getIDType()); if (ids == null || ids.isEmpty()) return null; final Table table = d.getTable(); final int size = others.size() * ids.size(); final List<Object> ids_l = Lists.newArrayList(ids); return AdvancedDoubleStatistics.of(new ADoubleList() { @Override public double getPrimitive(int index) { Integer oIndex = others.get(index / ids_l.size()); Object iIndex = ids_l.get(index % ids_l.size()); Object r; if (dim.isHorizontal()) { r = table.getRaw((Integer) iIndex, oIndex); } else { r = table.getRaw(oIndex, (Integer) iIndex); } if (r instanceof Number) return ((Number) r).doubleValue(); return Double.NaN; } @Override public int size() { return size; } }); } @Override public ValueElement createValue() { return new MyValueElement(); } private class MyValueElement extends ValueElement implements IGLElementParent { private final ListBoxAndWhiskersElement content; private AdvancedDoubleStatistics old = null; public MyValueElement() { IDoubleList l = new ArrayDoubleList(new double[0]); content = new ListBoxAndWhiskersElement(l, EDetailLevel.LOW, EDimension.RECORD, false, false, d.getLabel(), Color.LIGHT_GRAY); } @Override public String getTooltip() { AdvancedDoubleStatistics stats = updateStats(); if (stats == null) return null; return content.getTooltip(); } @Override protected void renderImpl(GLGraphics g, float w, float h) { if (h < 1) return; AdvancedDoubleStatistics stats = updateStats(); if (stats == null) return; content.render(g); } private AdvancedDoubleStatistics updateStats() { AdvancedDoubleStatistics stats = getStats(getRow()); if (stats != old) { content.setData(stats, min, max); this.old = stats; } return stats; } @Override protected void init(IGLElementContext context) { super.init(context); if (content != null) { GLElementAccessor.setParent(content, this); GLElementAccessor.init(content, context); } } @Override protected void takeDown() { if (content != null) GLElementAccessor.takeDown(content); super.takeDown(); } @Override protected boolean hasPickAbles() { return true; } @Override public void layout(int deltaTimeMs) { super.layout(deltaTimeMs); if (content != null) content.layout(deltaTimeMs); } @Override protected void layoutImpl(int deltaTimeMs) { if (content != null) { Vec2f size = getSize(); content.setBounds(0, 0, size.x(), size.y()); } super.layoutImpl(deltaTimeMs); } @Override public boolean moved(GLElement child) { return false; } } }
package org.eclipse.emf.emfstore.client.test.server; import org.eclipse.emf.emfstore.client.model.ServerInfo; import org.eclipse.emf.emfstore.client.model.Usersession; import org.eclipse.emf.emfstore.client.model.Workspace; import org.eclipse.emf.emfstore.client.model.WorkspaceManager; import org.eclipse.emf.emfstore.client.model.connectionmanager.AbstractSessionProvider; import org.eclipse.emf.emfstore.client.model.util.EMFStoreCommand; import org.eclipse.emf.emfstore.client.test.SetupHelper; import org.eclipse.emf.emfstore.server.exceptions.AccessControlException; import org.eclipse.emf.emfstore.server.exceptions.EmfStoreException; import org.junit.Assert; /** * A session provider implementation meant to be used by any tests. * * @author emueller */ public final class TestSessionProvider extends AbstractSessionProvider { private static Usersession usersession; /** * Initializes the singleton statically. */ private static class SingletonHolder { public static final TestSessionProvider INSTANCE = new TestSessionProvider(); } /** * Returns the singleton instance. * * @return the singleton instance */ public static TestSessionProvider getInstance() { return SingletonHolder.INSTANCE; } /** * Returns the default {@link Usersession}. * * @return the default user session * @throws AccessControlException if login fails * @throws EmfStoreException if anything else fails */ public Usersession getDefaultUsersession() throws AccessControlException, EmfStoreException { new EMFStoreCommand() { @Override protected void doRun() { try { usersession.logIn(); } catch (AccessControlException e) { Assert.fail(); } catch (EmfStoreException e) { Assert.fail(); } } }.run(false); return usersession; } public TestSessionProvider() { final Workspace workspace = WorkspaceManager.getInstance().getCurrentWorkspace(); usersession = org.eclipse.emf.emfstore.client.model.ModelFactory.eINSTANCE.createUsersession(); usersession.setServerInfo(SetupHelper.getServerInfo()); usersession.setUsername("super"); usersession.setPassword("super"); new EMFStoreCommand() { @Override protected void doRun() { workspace.getUsersessions().add(usersession); } }.run(false); workspace.save(); } @Override public Usersession provideUsersession(ServerInfo serverInfo) throws EmfStoreException { if (!usersession.isLoggedIn()) { usersession.logIn(); } return usersession; } @Override public void login(Usersession usersession) throws EmfStoreException { usersession.logIn(); } }
package org.codice.nitf; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import difflib.Delta; import difflib.DiffUtils; import difflib.Patch; import org.codice.nitf.filereader.ImageCompression; import org.codice.nitf.filereader.ImageCoordinatePair; import org.codice.nitf.filereader.ImageCoordinatesRepresentation; import org.codice.nitf.filereader.NitfDataExtensionSegment; import org.codice.nitf.filereader.NitfHeaderReader; import org.codice.nitf.filereader.NitfImageSegment; import org.codice.nitf.filereader.NitfSecurityClassification; import org.codice.nitf.filereader.Tre; import org.codice.nitf.filereader.TreCollection; import org.codice.nitf.filereader.TreEntry; import org.codice.nitf.filereader.TreGroup; public class FileComparison { static final String OUR_OUTPUT_EXTENSION = ".OURS.txt"; static final String THEIR_OUTPUT_EXTENSION = ".THEIRS.txt"; public static void main( String[] args ) { if (args.length == 0) { System.out.println("No file provided, not comparing"); return; } for (String filename : args) { System.out.println("Dumping output of " + filename); compareOneFile(filename); } } private static void compareOneFile(String filename) { generateGdalMetadata(filename); generateOurMetadata(filename); compareMetadataFiles(filename); } private static void generateOurMetadata(String filename) { NitfHeaderReader header = null; try { header = new NitfHeaderReader(new FileInputStream(filename)); } catch (ParseException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } NitfImageSegment segment1 = null; if (header.getNumberOfImageSegments() >= 1) { segment1 = header.getImageSegment(1); } NitfDataExtensionSegment des1 = null; if (header.getNumberOfDataExtensionSegments() >= 1) { des1 = header.getDataExtensionSegment(1); } BufferedWriter out = null; try { FileWriter fstream = new FileWriter(filename + OUR_OUTPUT_EXTENSION); out = new BufferedWriter(fstream); out.write("Driver: NITF/National Imagery Transmission Format\n"); out.write("Files: " + filename + "\n"); if (segment1 == null) { out.write(String.format("Size is 1, 1\n")); } else { out.write(String.format("Size is %d, %d\n", segment1.getNumberOfColumns(), segment1.getNumberOfRows())); } if ((segment1 == null) || (segment1.getImageCoordinatesRepresentation() == ImageCoordinatesRepresentation.NONE)) { out.write("Coordinate System is `'\n"); } else { out.write("Coordinate System is:\n"); out.write("GEOGCS[\"WGS 84\",\n"); out.write(" DATUM[\"WGS_1984\",\n"); out.write(" SPHEROID[\"WGS 84\",6378137,298.257223563,\n"); out.write(" AUTHORITY[\"EPSG\",\"7030\"]],\n"); out.write(" TOWGS84[0,0,0,0,0,0,0],\n"); out.write(" AUTHORITY[\"EPSG\",\"6326\"]],\n"); out.write(" PRIMEM[\"Greenwich\",0,\n"); out.write(" AUTHORITY[\"EPSG\",\"8901\"]],\n"); out.write(" UNIT[\"degree\",0.0174532925199433,\n"); out.write(" AUTHORITY[\"EPSG\",\"9108\"]],\n"); out.write(" AUTHORITY[\"EPSG\",\"4326\"]]\n"); } out.write("Metadata:\n"); TreeMap <String, String> metadata = new TreeMap<String, String>(); metadata.put("NITF_CLEVEL", String.format("%02d", header.getComplexityLevel())); metadata.put("NITF_ENCRYP", "0"); metadata.put("NITF_FBKGC", (String.format("%3d,%3d,%3d", (int)(header.getFileBackgroundColourRed() & 0xFF), (int)(header.getFileBackgroundColourGreen() & 0xFF), (int)(header.getFileBackgroundColourBlue() & 0xFF)))); metadata.put("NITF_FDT", new SimpleDateFormat("yyyyMMddHHmmss").format(header.getFileDateTime())); switch (header.getFileType()) { case NSIF_ONE_ZERO: metadata.put("NITF_FHDR", "NSIF01.00"); break; case NITF_TWO_ZERO: metadata.put("NITF_FHDR", "NITF02.00"); break; case NITF_TWO_ONE: metadata.put("NITF_FHDR", "NITF02.10"); break; } metadata.put("NITF_FSCATP", header.getFileSecurityMetadata().getClassificationAuthorityType()); metadata.put("NITF_FSCAUT", header.getFileSecurityMetadata().getClassificationAuthority()); metadata.put("NITF_FSCLAS", header.getFileSecurityMetadata().getSecurityClassification().getTextEquivalent()); metadata.put("NITF_FSCLSY", header.getFileSecurityMetadata().getSecurityClassificationSystem()); metadata.put("NITF_FSCLTX", header.getFileSecurityMetadata().getClassificationText()); metadata.put("NITF_FSCODE", header.getFileSecurityMetadata().getCodewords()); metadata.put("NITF_FSCOP", header.getFileSecurityMetadata().getFileCopyNumber()); metadata.put("NITF_FSCPYS", header.getFileSecurityMetadata().getFileNumberOfCopies()); metadata.put("NITF_FSCRSN", header.getFileSecurityMetadata().getClassificationReason()); metadata.put("NITF_FSCTLH", header.getFileSecurityMetadata().getControlAndHandling()); metadata.put("NITF_FSCTLN", header.getFileSecurityMetadata().getSecurityControlNumber()); metadata.put("NITF_FSDCDT", header.getFileSecurityMetadata().getDeclassificationDate()); metadata.put("NITF_FSDCTP", header.getFileSecurityMetadata().getDeclassificationType()); metadata.put("NITF_FSDCXM", header.getFileSecurityMetadata().getDeclassificationExemption()); metadata.put("NITF_FSDG", header.getFileSecurityMetadata().getDowngrade()); metadata.put("NITF_FSDGDT", header.getFileSecurityMetadata().getDowngradeDate()); metadata.put("NITF_FSREL", header.getFileSecurityMetadata().getReleaseInstructions()); metadata.put("NITF_FSSRDT", header.getFileSecurityMetadata().getSecuritySourceDate()); metadata.put("NITF_FTITLE", header.getFileTitle()); metadata.put("NITF_ONAME", header.getOriginatorsName()); metadata.put("NITF_OPHONE", header.getOriginatorsPhoneNumber()); metadata.put("NITF_OSTAID", header.getOriginatingStationId()); metadata.put("NITF_STYPE", header.getStandardType()); TreCollection treCollection = header.getTREsRawStructure(); addOldStyleMetadata(metadata, treCollection); if (segment1 != null) { metadata.put("NITF_ABPP", String.format("%02d", segment1.getActualBitsPerPixelPerBand())); metadata.put("NITF_CCS_COLUMN", String.format("%d", segment1.getImageLocationColumn())); metadata.put("NITF_CCS_ROW", String.format("%d", segment1.getImageLocationRow())); metadata.put("NITF_IALVL", String.format("%d", segment1.getImageAttachmentLevel())); metadata.put("NITF_IC", segment1.getImageCompression().getTextEquivalent()); metadata.put("NITF_ICAT", segment1.getImageCategory().getTextEquivalent()); if (segment1.getImageCoordinatesRepresentation() == ImageCoordinatesRepresentation.NONE) { metadata.put("NITF_ICORDS", ""); } else { metadata.put("NITF_ICORDS", segment1.getImageCoordinatesRepresentation().getTextEquivalent()); } metadata.put("NITF_IDATIM", new SimpleDateFormat("yyyyMMddHHmmss").format(segment1.getImageDateTime())); metadata.put("NITF_IDLVL", String.format("%d", segment1.getImageDisplayLevel())); if (segment1.getImageCoordinatesRepresentation() == ImageCoordinatesRepresentation.DECIMALDEGREES) { metadata.put("NITF_IGEOLO", String.format("%+07.3f%+08.3f%+07.3f%+08.3f%+07.3f%+08.3f%+07.3f%+08.3f", segment1.getImageCoordinates().getCoordinate00().getLatitude(), segment1.getImageCoordinates().getCoordinate00().getLongitude(), segment1.getImageCoordinates().getCoordinate0MaxCol().getLatitude(), segment1.getImageCoordinates().getCoordinate0MaxCol().getLongitude(), segment1.getImageCoordinates().getCoordinateMaxRowMaxCol().getLatitude(), segment1.getImageCoordinates().getCoordinateMaxRowMaxCol().getLongitude(), segment1.getImageCoordinates().getCoordinateMaxRow0().getLatitude(), segment1.getImageCoordinates().getCoordinateMaxRow0().getLongitude())); } else if (segment1.getImageCoordinatesRepresentation() == ImageCoordinatesRepresentation.GEOGRAPHIC) { metadata.put("NITF_IGEOLO", String.format("%s%s%s%s", makeGeoString(segment1.getImageCoordinates().getCoordinate00()), makeGeoString(segment1.getImageCoordinates().getCoordinate0MaxCol()), makeGeoString(segment1.getImageCoordinates().getCoordinateMaxRowMaxCol()), makeGeoString(segment1.getImageCoordinates().getCoordinateMaxRow0()))); } metadata.put("NITF_IID1", segment1.getImageIdentifier1()); metadata.put("NITF_IID2", segment1.getImageIdentifier2()); if (segment1.getImageIdentifier2().endsWith(".LF2")) { // TODO: this is a quick hack - should be generalised and maybe moved into main code metadata.put("NITF_SERIES_ABBREVIATION", "LFC-FR (Day)"); metadata.put("NITF_SERIES_NAME", "Low Flying Chart (Day) - Host Nation"); } metadata.put("NITF_ILOC_COLUMN", String.format("%d", segment1.getImageLocationColumn())); metadata.put("NITF_ILOC_ROW", String.format("%d", segment1.getImageLocationRow())); metadata.put("NITF_IMAG", segment1.getImageMagnification()); if (segment1.getNumberOfImageComments() > 0) { StringBuilder commentBuilder = new StringBuilder(); for (int i = 0; i < segment1.getNumberOfImageComments(); ++i) { commentBuilder.append(String.format("%-80s", segment1.getImageCommentZeroBase(i))); } metadata.put("NITF_IMAGE_COMMENTS", commentBuilder.toString()); } metadata.put("NITF_IMODE", segment1.getImageMode().getTextEquivalent()); metadata.put("NITF_IREP", segment1.getImageRepresentation().getTextEquivalent()); metadata.put("NITF_ISCATP", segment1.getSecurityMetadata().getClassificationAuthorityType()); metadata.put("NITF_ISCAUT", segment1.getSecurityMetadata().getClassificationAuthority()); metadata.put("NITF_ISCLAS", segment1.getSecurityMetadata().getSecurityClassification().getTextEquivalent()); metadata.put("NITF_ISCLSY", segment1.getSecurityMetadata().getSecurityClassificationSystem()); metadata.put("NITF_ISCLTX", segment1.getSecurityMetadata().getClassificationText()); metadata.put("NITF_ISCODE", segment1.getSecurityMetadata().getCodewords()); metadata.put("NITF_ISCRSN", segment1.getSecurityMetadata().getClassificationReason()); metadata.put("NITF_ISCTLH", segment1.getSecurityMetadata().getControlAndHandling()); metadata.put("NITF_ISCTLN", segment1.getSecurityMetadata().getSecurityControlNumber()); metadata.put("NITF_ISDCDT", segment1.getSecurityMetadata().getDeclassificationDate()); metadata.put("NITF_ISDCTP", segment1.getSecurityMetadata().getDeclassificationType()); metadata.put("NITF_ISDCXM", segment1.getSecurityMetadata().getDeclassificationExemption()); metadata.put("NITF_ISDG", segment1.getSecurityMetadata().getDowngrade()); metadata.put("NITF_ISDGDT", segment1.getSecurityMetadata().getDowngradeDate()); metadata.put("NITF_ISORCE", segment1.getImageSource()); metadata.put("NITF_ISREL", segment1.getSecurityMetadata().getReleaseInstructions()); metadata.put("NITF_ISSRDT", segment1.getSecurityMetadata().getSecuritySourceDate()); metadata.put("NITF_PJUST", segment1.getPixelJustification().getTextEquivalent()); metadata.put("NITF_PVTYPE", segment1.getPixelValueType().getTextEquivalent()); if (segment1.getImageTargetId().length() > 0) { metadata.put("NITF_TGTID", String.format("%17s", segment1.getImageTargetId())); } else { metadata.put("NITF_TGTID", ""); } treCollection = segment1.getTREsRawStructure(); addOldStyleMetadata(metadata, treCollection); } for (String key : metadata.keySet()) { out.write(String.format(" %s=%s\n", key, metadata.get(key))); } if ((header.getTREsRawStructure().hasTREs()) || ((segment1 != null) && (segment1.getTREsRawStructure().hasTREs())) || ((des1 != null) && (des1.getTREsRawStructure().hasTREs()))) { out.write("Metadata (xml:TRE):\n"); out.write("<tres>\n"); treCollection = header.getTREsRawStructure(); for (Tre tre : treCollection.getTREs()) { outputThisTre(out, tre, "file"); } if (segment1 != null) { treCollection = segment1.getTREsRawStructure(); for (Tre tre : treCollection.getTREs()) { outputThisTre(out, tre, "image"); } } if (des1 != null) { treCollection = des1.getTREsRawStructure(); for (Tre tre : treCollection.getTREs()) { outputThisTre(out, tre, "des TRE_OVERFLOW"); } } out.write("</tres>\n\n"); } if (segment1 != null) { switch (segment1.getImageCompression()) { case JPEG: case JPEGMASK: out.write("Image Structure Metadata:\n"); out.write(" COMPRESSION=JPEG\n"); break; case BILEVEL: case BILEVELMASK: case DOWNSAMPLEDJPEG: out.write("Image Structure Metadata:\n"); out.write(" COMPRESSION=BILEVEL\n"); break; case LOSSLESSJPEG: out.write("Image Structure Metadata:\n"); out.write(" COMPRESSION=LOSSLESS JPEG\n"); break; case JPEG2000: case JPEG2000MASK: out.write("Image Structure Metadata:\n"); out.write(" COMPRESSION=JPEG2000\n"); break; } } if (header.getNumberOfImageSegments() > 1) { out.write("Subdatasets:\n"); for (int i = 0; i < header.getNumberOfImageSegments(); ++i) { out.write(String.format(" SUBDATASET_%d_NAME=NITF_IM:%d:%s\n", i+1, i, filename)); out.write(String.format(" SUBDATASET_%d_DESC=Image %d of %s\n", i+1, i+1, filename)); } } TreeMap <String, String> rpc = new TreeMap<String, String>(); if (segment1 != null) { // Walk the segment1 TRE collection and add RPC entries here treCollection = segment1.getTREsRawStructure(); for (Tre tre : treCollection.getTREs()) { if (tre.getName().equals("RPC00B")) { for (TreEntry entry : tre.getEntries()) { if (entry.getName().equals("SUCCESS")) { continue; } if (entry.getName().equals("ERR_BIAS") || entry.getName().equals("ERR_RAND")) { continue; } if (entry.getFieldValue() != null) { if (entry.getName().equals("LONG_OFF") || entry.getName().equals("LONG_SCALE") || entry.getName().equals("LAT_OFF") || entry.getName().equals("LAT_SCALE")) { Double rpcValue = Double.parseDouble(entry.getFieldValue()); rpc.put(entry.getName(), rpcValue.toString()); } else { Integer rpcValue = Integer.parseInt(entry.getFieldValue()); rpc.put(entry.getName(), rpcValue.toString()); } } else if ((entry.getGroups() != null) && (entry.getGroups().size() > 0)) { StringBuilder builder = new StringBuilder(); for (TreGroup group : entry.getGroups()) { for (TreEntry groupEntry : group.getEntries()) { try { double fieldVal = Double.parseDouble(groupEntry.getFieldValue()); builder.append(cleanupNumberString(fieldVal)); builder.append(" "); } catch (NumberFormatException e) { builder.append(String.format("%s ", groupEntry.getFieldValue())); } } } rpc.put(entry.getName(), builder.toString()); } } try { double longOff = Double.parseDouble(tre.getFieldValue("LONG_OFF")); double longScale = Double.parseDouble(tre.getFieldValue("LONG_SCALE")); double longMin = longOff - (longScale / 2.0); double longMax = longOff + (longScale / 2.0); rpc.put("MAX_LONG", cleanupNumberString(longMax)); rpc.put("MIN_LONG", cleanupNumberString(longMin)); double latOff = Double.parseDouble(tre.getFieldValue("LAT_OFF")); double latScale = Double.parseDouble(tre.getFieldValue("LAT_SCALE")); double latMin = latOff - (latScale / 2.0); double latMax = latOff + (latScale / 2.0); rpc.put("MAX_LAT", cleanupNumberString(latMax)); rpc.put("MIN_LAT", cleanupNumberString(latMin)); } catch (ParseException e) { e.printStackTrace(); } } } } if (rpc.keySet().size() > 0) { out.write("RPC Metadata:\n"); for (String tagname : rpc.keySet()) { out.write(String.format(" %s=%s\n", tagname, rpc.get(tagname))); } } out.close(); } catch (IOException e) { e.printStackTrace(); } } static private String cleanupNumberString(double fieldVal) { if (fieldVal == (int)fieldVal) { return String.format("%d", (int)fieldVal); } String naiveString = String.format("%.16g", fieldVal); if (naiveString.contains("e-")) { return naiveString.replaceAll("\\.?0*e", "e"); } else if (naiveString.contains(".")) { return naiveString.replaceAll("\\.?0*$", ""); } return naiveString; } private static void addOldStyleMetadata(TreeMap <String, String> metadata, TreCollection treCollection) { for (Tre tre : treCollection.getTREs()) { if (tre.getPrefix() != null) { // if it has a prefix, its probably an old-style NITF metadata field List<TreEntry> entries = tre.getEntries(); for (TreEntry entry: entries) { metadata.put(tre.getPrefix() + entry.getName(), entry.getFieldValue().trim()); } } else if ("ICHIPB".equals(tre.getName())) { // special case List<TreEntry> entries = tre.getEntries(); for (TreEntry entry: entries) { if ("XFRM_FLAG".equals(entry.getName())) { // GDAL skips this one continue; } BigDecimal value = new BigDecimal(entry.getFieldValue().trim()).stripTrailingZeros(); if ("ANAMRPH_CORR".equals(entry.getName())) { // Special case for GDAL metadata.put("ICHIP_ANAMORPH_CORR", value.toPlainString()); } else { metadata.put("ICHIP_" + entry.getName(), value.toPlainString()); } } } } } private static void outputThisTre(BufferedWriter out, Tre tre, String location) throws IOException { doIndent(out, 1); out.write("<tre name=\"" + tre.getName().trim() + "\" location=\"" + location + "\">\n"); for (TreEntry entry : tre.getEntries()) { outputThisEntry(out, entry, 2); } doIndent(out, 1); out.write("</tre>\n"); } private static void outputThisEntry(BufferedWriter out, TreEntry entry, int indentLevel) throws IOException { if (entry.getFieldValue() != null) { doIndent(out, indentLevel); out.write("<field name=\"" + entry.getName() + "\" value=\"" + entry.getFieldValue().trim() + "\" />\n"); } if ((entry.getGroups() != null) && (entry.getGroups().size() > 0)) { doIndent(out, indentLevel); out.write("<repeated name=\"" + entry.getName() + "\" number=\"" + entry.getGroups().size() + "\">\n"); int i = 0; for (TreGroup group : entry.getGroups()) { doIndent(out, indentLevel + 1); out.write(String.format("<group index=\"%d\">\n", i)); for (TreEntry groupEntry : group.getEntries()) { outputThisEntry(out, groupEntry, indentLevel + 2); } doIndent(out, indentLevel + 1); out.write(String.format("</group>\n")); i = i + 1; } doIndent(out, indentLevel); out.write("</repeated>\n"); } } private static void doIndent(BufferedWriter out, int indentLevel) throws IOException { for (int i = 0; i < indentLevel; ++i) { out.write(" "); } } // This is ugly - feel free to fix it any time. private static String makeGeoString(ImageCoordinatePair coords) { double latitude = coords.getLatitude(); double longitude = coords.getLongitude(); String northSouth = "N"; if (latitude < 0.0) { northSouth = "S"; latitude = Math.abs(latitude); } String eastWest = "E"; if (longitude < 0.0) { eastWest = "W"; longitude = Math.abs(longitude); } int latDegrees = (int)Math.floor(latitude); double minutesAndSecondsPart = (latitude -latDegrees) * 60; int latMinutes = (int)Math.floor(minutesAndSecondsPart); double secondsPart = (minutesAndSecondsPart - latMinutes) * 60; int latSeconds = (int)Math.round(secondsPart); if (latSeconds == 60) { latMinutes++; latSeconds = 0; } if (latMinutes == 60) { latDegrees++; latMinutes = 0; } int lonDegrees = (int)Math.floor(longitude); minutesAndSecondsPart = (longitude - lonDegrees) * 60; int lonMinutes = (int)Math.floor(minutesAndSecondsPart); secondsPart = (minutesAndSecondsPart - lonMinutes) * 60; int lonSeconds = (int)Math.round(secondsPart); if (lonSeconds == 60) { lonMinutes++; lonSeconds = 0; } if (lonMinutes == 60) { lonDegrees++; lonMinutes = 0; } return String.format("%02d%02d%02d%s%03d%02d%02d%s", latDegrees, latMinutes, latSeconds, northSouth, lonDegrees, lonMinutes, lonSeconds, eastWest); } private static void generateGdalMetadata(String filename) { try { ProcessBuilder processBuilder = new ProcessBuilder("gdalinfo", "-mdd", "xml:TRE", filename); processBuilder.environment().put("NITF_OPEN_UNDERLYING_DS", "NO"); Process process = processBuilder.start(); BufferedWriter out = null; try { FileWriter fstream = new FileWriter(filename + THEIR_OUTPUT_EXTENSION); out = new BufferedWriter(fstream); } catch (IOException e) { e.printStackTrace(); } BufferedReader infoOutputReader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"), 1000000); boolean done = false; try { do { do { String line = infoOutputReader.readLine(); if (line == null) { done = true; break; } if (line.startsWith("Origin = (")) { // System.out.println("Filtering on Origin"); continue; } if (line.startsWith("Pixel Size = (")) { // System.out.println("Filtering on Pixel Size"); continue; } if (line.startsWith("Corner Coordinates:")) { // System.out.println("Exiting on Corner Coordinates"); done = true; break; } if (line.startsWith("Band 1 Block=")) { // System.out.println("Exiting on Band 1 Block"); done = true; break; } out.write(line + "\n"); } while (infoOutputReader.ready() && (!done)); Thread.sleep(100); } while (!done); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } out.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static void compareMetadataFiles(String filename) { List<String> theirs = fileToLines(filename + THEIR_OUTPUT_EXTENSION); List<String> ours = fileToLines(filename + OUR_OUTPUT_EXTENSION); Patch patch = DiffUtils.diff(theirs, ours); if (patch.getDeltas().size() > 0) { for (Delta delta: patch.getDeltas()) { System.out.println(delta); } System.out.println(" * Done"); } else { new File(filename + THEIR_OUTPUT_EXTENSION).delete(); new File(filename + OUR_OUTPUT_EXTENSION).delete(); } } private static List<String> fileToLines(String filename) { List<String> lines = new LinkedList<String>(); String line = ""; try { BufferedReader in = new BufferedReader(new FileReader(filename)); while ((line = in.readLine()) != null) { lines.add(line); } } catch (IOException e) { e.printStackTrace(); } return lines; } }
package itemrender.client; import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.client.registry.KeyBindingRegistry; import cpw.mods.fml.common.TickType; import cpw.mods.fml.relauncher.ReflectionHelper; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import itemrender.client.rendering.FBOHelper; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiInventory; import net.minecraft.client.renderer.GLAllocation; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.entity.Render; import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.client.settings.KeyBinding; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.EnumMovingObjectType; import net.minecraftforge.client.ForgeHooksClient; import org.lwjgl.BufferUtils; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL32; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.nio.IntBuffer; import java.util.EnumSet; @SideOnly(Side.CLIENT) public class KeybindRenderEntity extends KeyBindingRegistry.KeyHandler { private static KeyBinding[] keyBindings = new KeyBinding[]{new KeyBinding("Render Entity", Keyboard.KEY_L)}; private static boolean[] repeatings = new boolean[]{false}; public FBOHelper fbo; private String filenameSuffix = ""; public KeybindRenderEntity(int textureSize, String filename_suffix) { super(keyBindings, repeatings); fbo = new FBOHelper(textureSize); filenameSuffix = filename_suffix; } @Override public void keyDown(EnumSet<TickType> types, KeyBinding kb, boolean tickEnd, boolean isRepeat) { if(!tickEnd) return; Minecraft minecraft = FMLClientHandler.instance().getClient(); if(minecraft.pointedEntityLiving != null) { EntityLivingBase current = minecraft.pointedEntityLiving; fbo.begin(); AxisAlignedBB aabb = current.boundingBox; double minX = aabb.minX - current.posX; double maxX = aabb.maxX - current.posX; double minY = aabb.minY - current.posY; double maxY = aabb.maxY - current.posY; double minZ = aabb.minZ - current.posZ; double maxZ = aabb.maxZ - current.posZ; double minBound = Math.min(minX, Math.min(minY, minZ)); double maxBound = Math.max(maxX, Math.max(maxY, maxZ)); double boundLimit = Math.max(Math.abs(minBound), Math.abs(maxBound)); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glPushMatrix(); GL11.glLoadIdentity(); GL11.glOrtho(-boundLimit*0.75, boundLimit*0.75, -boundLimit*1.25, boundLimit*0.25, -100.0, 100.0); GL11.glMatrixMode(GL11.GL_MODELVIEW); renderEntity(current); //GuiInventory.func_110423_a(0, 0, 1, 1, 1, current); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glPopMatrix(); fbo.end(); fbo.saveToFile(new File(minecraft.mcDataDir, String.format("rendered/entity_%s%s.png", EntityList.getEntityString(current), filenameSuffix))); fbo.restoreTexture(); } } private void renderEntity(EntityLivingBase entity) { GL11.glEnable(GL11.GL_COLOR_MATERIAL); GL11.glPushMatrix(); GL11.glScalef((float)(-1), (float)1, (float)1); GL11.glRotatef(180.0F, 0.0F, 0.0F, 1.0F); float f2 = entity.renderYawOffset; float f3 = entity.rotationYaw; float f4 = entity.rotationPitch; float f5 = entity.prevRotationYawHead; float f6 = entity.rotationYawHead; GL11.glRotatef(135.0F, 0.0F, 1.0F, 0.0F); RenderHelper.enableStandardItemLighting(); GL11.glRotatef(-135.0F, 0.0F, 1.0F, 0.0F); GL11.glRotatef((float)Math.toDegrees(Math.asin(Math.tan(Math.toRadians(30)))), 1.0F, 0.0F, 0.0F); GL11.glRotatef(-45, 0.0F, 1.0F, 0.0F); entity.renderYawOffset = (float)Math.atan((double)(1 / 40.0F)) * 20.0F; entity.rotationYaw = (float)Math.atan((double)(1 / 40.0F)) * 40.0F; entity.rotationPitch = -((float)Math.atan((double)(1 / 40.0F))) * 20.0F; entity.rotationYawHead = entity.rotationYaw; entity.prevRotationYawHead = entity.rotationYaw; GL11.glTranslatef(0.0F, entity.yOffset, 0.0F); RenderManager.instance.playerViewY = 180.0F; RenderManager.instance.renderEntityWithPosYaw(entity, 0.0D, 0.0D, 0.0D, 0.0F, 1.0F); entity.renderYawOffset = f2; entity.rotationYaw = f3; entity.rotationPitch = f4; entity.prevRotationYawHead = f5; entity.rotationYawHead = f6; GL11.glPopMatrix(); RenderHelper.disableStandardItemLighting(); GL11.glDisable(GL12.GL_RESCALE_NORMAL); OpenGlHelper.setActiveTexture(OpenGlHelper.lightmapTexUnit); GL11.glDisable(GL11.GL_TEXTURE_2D); OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit); } @Override public void keyUp(EnumSet<TickType> types, KeyBinding kb, boolean tickEnd) { } @Override public EnumSet<TickType> ticks() { return EnumSet.of(TickType.RENDER); } @Override public String getLabel() { return "KeyHandler"; } }
package com.planetmayo.debrief.satc.model.generator.impl.ga; import java.util.List; import org.uncommons.watchmaker.framework.FitnessEvaluator; import com.planetmayo.debrief.satc.model.contributions.BaseContribution; import com.planetmayo.debrief.satc.model.generator.IContributions; import com.planetmayo.debrief.satc.model.legs.AlteringRoute; import com.planetmayo.debrief.satc.model.legs.CoreRoute; import com.planetmayo.debrief.satc.model.legs.StraightLeg; import com.planetmayo.debrief.satc.model.legs.StraightRoute; import com.planetmayo.debrief.satc.model.states.SafeProblemSpace; import com.planetmayo.debrief.satc.util.MathUtils; import com.vividsolutions.jts.geom.Point; public class RoutesFitnessEvaluator implements FitnessEvaluator<List<StraightRoute>> { private final List<StraightLeg> legs; private final IContributions contributions; private final SafeProblemSpace problemSpace; private final boolean useAlterings; public RoutesFitnessEvaluator(List<StraightLeg> legs, boolean useAlterings, IContributions contributions, SafeProblemSpace problemSpace) { super(); this.useAlterings = useAlterings; this.legs = legs; this.contributions = contributions; this.problemSpace = problemSpace; } @Override public double getFitness(List<StraightRoute> candidate, List<? extends List<StraightRoute>> population) { int length = candidate.size(); double error = 0; boolean impossible = false; for (int i = 0; i < length; i++) { StraightRoute route = candidate.get(i); StraightLeg leg = legs.get(i); if (route.isPossible()) { if (route.getScore() == 0.) { leg.decideAchievableRoute(route); if (route.isPossible()) { error += calculateContributionsScore(route); } else { impossible = true; } } else { error += route.getScore(); } } else { impossible = true; } } if (impossible) { return Double.MAX_VALUE; } if (useAlterings) { for (int i = 0; i < candidate.size() - 1; i++) { StraightRoute prev = candidate.get(i); StraightRoute next = candidate.get(i + 1); AlteringRoute route = new AlteringRoute("", prev.getEndPoint(), prev.getEndTime(), next.getStartPoint(), next.getStartTime()); route.generateSegments(problemSpace.getBoundedStatesBetween(prev.getEndTime(), next.getStartTime())); route.constructRoute(prev, next); error += calculateContributionsScore(route); error += calculateAlteringRouteScore(route, prev, next); } } return error; } public double calculateContributionsScore(CoreRoute route) { double score = 0; for (BaseContribution contribution : contributions) { score += contribution.calculateErrorScoreFor(route); } route.setScore(score); return score; } private double calculateAlteringRouteScore(AlteringRoute route, StraightRoute previous, StraightRoute next) { return calculateCompliantSpeedError(route, previous, next) + calculateSShapeScore(route); } private double calculateCompliantSpeedError(AlteringRoute route, StraightRoute previous, StraightRoute next) { double startSpeed = previous.getSpeed(); double endSpeed = next.getSpeed(); double minAlteringSpeed = route.getMinSpeed(); double maxAlteringSpeed = route.getMaxSpeed(); double error = 0; if (route.getExtremumsCount() == 0) { error = 0; } else if (route.getExtremumsCount() == 1) { double min = Math.min(startSpeed, endSpeed); double max = Math.max(startSpeed, endSpeed); double range = max - min; double scaleFactor = 10d; if (minAlteringSpeed < min) { double diff = min - minAlteringSpeed; error += scaleFactor * Math.pow(diff - range, 2); // error += alteringSpeedError(min - minAlteringSpeed); } if (maxAlteringSpeed > max) { double diff = maxAlteringSpeed - max; error += scaleFactor * Math.pow(diff - range, 2); // error += alteringSpeedError(maxAlteringSpeed - max); } } else { error += 1.5 * alteringSpeedError(maxAlteringSpeed - minAlteringSpeed); } return error; } private double alteringSpeedError(double speedDiff) { // make this error more prominent. final double fudgeFactor = 3d; final double x = 1 + speedDiff / problemSpace.getVehicleType() .getMaxSpeed(); final double res = fudgeFactor * (x * x - 1); return res; } private double calculateSShapeScore(AlteringRoute route) { Point[] pts = route.getBezierControlPoints(); // first line start-end in parametric form: B(t1) = start * (1 - t1) + end * t1 double sx = route.getStartPoint().getX(), sy = route.getStartPoint().getY(); double ex = route.getEndPoint().getX(), ey = route.getEndPoint().getY(); // second line control point 1-control point 2 in parametric form: C(t2) = pts[0] * (1 - t2) + pts[1] * t2 double p0x = pts[0].getX(), p0y = pts[0].getY(); double p1x = pts[1].getX(), p1y = pts[1].getY(); // if this two lines intersect - we have S shape, C shape otherwise // solve linear eq system: // | Bx(t1) = Cx(t2) | sx * (1 - t1) + ex * t1 = p0x * (1-t2) + p1x * t2 // | By(t1) = Cy(t2) | sy * (1 - t1) + ey * t1 = p0y * (1-t2) + p1y * t2 if (Math.abs(ex - sx) < MathUtils.EPS) { // C shape return 0; } double c1 = (p0x - sx) / (ex - sx); double c2 = (p1x - p0x) / (ex - sx); double d = (p1y - p0y) * (sy - ey) * c2; if (Math.abs(d) < MathUtils.EPS) { // C shape return 0; } double t2 = (sy - p0y + c1 * (ey - sy)) / d; double t1 = c1 + c2 * t2; // check that two line intersect, so s-shape if (t1 >= 0 && t1 <= 1 && t2 >= 0 && t2 <= 1) { Point intersection = MathUtils.calculateBezier(t2, pts[0], pts[1], null); double a = MathUtils.calcAbsoluteValue(pts[0].getX() - intersection.getX(), pts[0].getY() - intersection.getY()); double b = MathUtils.calcAbsoluteValue(pts[1].getX() - intersection.getX(), pts[1].getY() - intersection.getY()); return Math.min(a, b); } return 0; } @Override public boolean isNatural() { return false; } }
package jade.domain.mobility; import jade.util.leap.Iterator; import jade.util.leap.List; import jade.util.leap.ArrayList; import jade.util.leap.Map; import jade.util.leap.HashMap; import jade.core.AID; import jade.core.Location; import jade.core.ContainerID; import jade.content.onto.*; import jade.content.schema.*; import jade.domain.JADEAgentManagement.*; /** @author Giovanni Rimassa - Universita` di Parma @version $Date$ $Revision$ */ /** This class represents the ontology used for JADE mobility. There is only a single instance of this class. @see jade.domain.mobility.MobilityOntology#getInstance() */ public class MobilityOntology extends Ontology implements MobilityVocabulary { public static final String NAME = "jade-mobility-ontology"; private static Ontology theInstance = new MobilityOntology(); public static Ontology getInstance() { return theInstance; } private MobilityOntology() { super(NAME, JADEManagementOntology.getInstance()); try{ // Adds the roles of the basic ontology (ACTION, AID,...) add(new ConceptSchema(MOBILE_AGENT_DESCRIPTION), MobileAgentDescription.class); add(new ConceptSchema(MOBILE_AGENT_PROFILE), MobileAgentProfile.class); add(new ConceptSchema(MOBILE_AGENT_SYSTEM), MobileAgentSystem.class); add(new ConceptSchema(MOBILE_AGENT_LANGUAGE), MobileAgentLanguage.class); add(new ConceptSchema(MOBILE_AGENT_OS), MobileAgentOS.class); add(new AgentActionSchema(CLONE), CloneAction.class); add(new AgentActionSchema(MOVE), MoveAction.class); ConceptSchema cs = (ConceptSchema)getSchema(MOBILE_AGENT_DESCRIPTION); cs.add(MOBILE_AGENT_DESCRIPTION_NAME, (ConceptSchema)getSchema(BasicOntology.AID)); cs.add(MOBILE_AGENT_DESCRIPTION_DESTINATION, (ConceptSchema)getSchema(LOCATION)); cs.add(MOBILE_AGENT_DESCRIPTION_AGENT_PROFILE, (ConceptSchema)getSchema(MOBILE_AGENT_PROFILE), ObjectSchema.OPTIONAL); cs.add(MOBILE_AGENT_DESCRIPTION_AGENT_VERSION, (PrimitiveSchema)getSchema(BasicOntology.STRING), ObjectSchema.OPTIONAL); cs.add(MOBILE_AGENT_DESCRIPTION_SIGNATURE, (PrimitiveSchema)getSchema(BasicOntology.STRING), ObjectSchema.OPTIONAL); cs = (ConceptSchema)getSchema(MOBILE_AGENT_PROFILE); cs.add(MOBILE_AGENT_PROFILE_SYSTEM, (ConceptSchema)getSchema(MOBILE_AGENT_SYSTEM), ObjectSchema.OPTIONAL); cs.add(MOBILE_AGENT_PROFILE_LANGUAGE, (ConceptSchema)getSchema(MOBILE_AGENT_LANGUAGE), ObjectSchema.OPTIONAL); cs.add(MOBILE_AGENT_PROFILE_OS, (ConceptSchema)getSchema(MOBILE_AGENT_OS)); cs = (ConceptSchema)getSchema(MOBILE_AGENT_SYSTEM); cs.add(MOBILE_AGENT_SYSTEM_NAME, (PrimitiveSchema)getSchema(BasicOntology.STRING)); cs.add(MOBILE_AGENT_SYSTEM_MAJOR_VERSION, (PrimitiveSchema)getSchema(BasicOntology.INTEGER)); cs.add(MOBILE_AGENT_SYSTEM_MINOR_VERSION, (PrimitiveSchema)getSchema(BasicOntology.INTEGER), ObjectSchema.OPTIONAL); cs.add(MOBILE_AGENT_SYSTEM_DEPENDENCIES, (PrimitiveSchema)getSchema(BasicOntology.STRING), ObjectSchema.OPTIONAL); cs = (ConceptSchema)getSchema(MOBILE_AGENT_LANGUAGE); cs.add(MOBILE_AGENT_LANGUAGE_NAME, (PrimitiveSchema)getSchema(BasicOntology.STRING)); cs.add(MOBILE_AGENT_LANGUAGE_MAJOR_VERSION, (PrimitiveSchema)getSchema(BasicOntology.INTEGER)); cs.add(MOBILE_AGENT_LANGUAGE_MINOR_VERSION, (PrimitiveSchema)getSchema(BasicOntology.INTEGER), ObjectSchema.OPTIONAL); cs.add(MOBILE_AGENT_LANGUAGE_DEPENDENCIES, (PrimitiveSchema)getSchema(BasicOntology.STRING), ObjectSchema.OPTIONAL); cs = (ConceptSchema)getSchema(MOBILE_AGENT_OS); cs.add(MOBILE_AGENT_OS_NAME, (PrimitiveSchema)getSchema(BasicOntology.STRING)); cs.add(MOBILE_AGENT_OS_MAJOR_VERSION, (PrimitiveSchema)getSchema(BasicOntology.INTEGER)); cs.add(MOBILE_AGENT_OS_MINOR_VERSION, (PrimitiveSchema)getSchema(BasicOntology.INTEGER), ObjectSchema.OPTIONAL); cs.add(MOBILE_AGENT_OS_DEPENDENCIES, (PrimitiveSchema)getSchema(BasicOntology.STRING), ObjectSchema.OPTIONAL); AgentActionSchema as = (AgentActionSchema)getSchema(MOVE); as.add(MOVE_MOBILE_AGENT_DESCRIPTION, (ConceptSchema)getSchema(MOBILE_AGENT_DESCRIPTION)); as = (AgentActionSchema)getSchema(CLONE); as.addSuperSchema((AgentActionSchema)getSchema(MOVE)); //as.add(CLONE_MOBILE_AGENT_DESCRIPTION, (ConceptSchema)getSchema(MOBILE_AGENT_DESCRIPTION)); as.add(CLONE_NEW_NAME, (PrimitiveSchema)getSchema(BasicOntology.STRING)); } catch(OntologyException oe) { oe.printStackTrace(); } } }
package ru.job4j; public class Podstr { public static boolean contains(String originString, String testString) { boolean verify = true; String[] massCharacterOfOriginString = originString.split(""); String[] massCharacterOfTestString = testString.split(""); for(int i = 0; i < massCharacterOfOriginString.length - massCharacterOfTestString.length + 1; i++) { if(!massCharacterOfOriginString[i].equals(massCharacterOfTestString[0])) { continue; } for(int j = 0; j < massCharacterOfTestString.length; j++) { if(!massCharacterOfOriginString[j + i].equals(massCharacterOfTestString[j])) { break; } else if(j == massCharacterOfTestString.length - 1) { System.out.println("this strin " + testString + " is substring. It's TRUE!"); return verify; } } } return verify = false; } } /* public class Podstr { public static boolean contains(String originString, String testString) { boolean verify = true; int counter = 0; int counterJ = 0; String[] massCharacterOfOriginString = originString.split(""); String[] massCharacterOfTestString = testString.split(""); for(int i = 0; i < massCharacterOfOriginString.length; i++) { for(int j = counterJ; j < massCharacterOfTestString.length; j++) { if(massCharacterOfOriginString[i].equals(massCharacterOfTestString[j])) { counter++; counterJ++; if(counter == massCharacterOfTestString.length) { verify = true; } break; } else { counter = 0; counterJ = 0; break; } } } if(counter != massCharacterOfTestString.length) { verify = false; } return verify; } } */
package org.ddd4j.value.collection; import static java.util.Objects.requireNonNull; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; @FunctionalInterface public interface Seq<E> extends Iterable<E> { @FunctionalInterface interface Extender<E> { Seq<E> apply(Supplier<? extends Stream<? extends E>> other); default Seq<E> array(E[] entries) { return apply(Arrays.asList(entries)::stream); } default Seq<E> collection(Collection<? extends E> entries) { return apply(new ArrayList<>(entries)::stream); } default Seq<E> entry(E entry) { return apply(Collections.singleton(entry)::stream); } default Seq<E> iterable(Iterable<? extends E> iterable) { List<E> list = new ArrayList<>(); iterable.forEach(list::add); return apply(list::stream); } default Seq<E> seq(Seq<? extends E> seq) { return apply(requireNonNull(seq)::stream); } } class Filtered<E, T> { private static class Contains<T> implements Supplier<Predicate<T>> { private final Function<? super T, ?> keyMapper; public Contains(Function<? super T, ?> keyMapper) { this.keyMapper = requireNonNull(keyMapper); } @Override public Predicate<T> get() { return new Predicate<T>() { private final Set<Object> visited = new HashSet<>(); @Override public boolean test(T t) { return visited.add(keyMapper.apply(t)); } }; } } private static class Match<T> implements Supplier<Predicate<T>> { private final Predicate<? super T> predicate; private final boolean predicateOutcome; public Match(Predicate<? super T> predicate, boolean predicateOutcome) { this.predicate = requireNonNull(predicate); this.predicateOutcome = predicateOutcome; } @Override public Predicate<T> get() { return new Predicate<T>() { private boolean switched = false; @Override public boolean test(T t) { if (!switched) { switched = predicateOutcome ^ predicate.test(t); } return switched ? !predicateOutcome : predicateOutcome; } }; } } public static <E> Filtered<E, E> on(Seq<E> seq) { return new Filtered<>(seq, Function.identity(), t -> true); } private final Seq<E> sequence; private final Function<? super E, ? extends T> mapping; private final Predicate<T> filter; public Filtered(Seq<E> sequence, Function<? super E, ? extends T> mapping, Predicate<T> predicate) { this.sequence = requireNonNull(sequence); this.mapping = requireNonNull(mapping); this.filter = requireNonNull(predicate); } void apply(Seq<E> seq, Function<? super E, ? extends T> childMapping, Predicate<T> childFilter) { } public Filtered<E, T> by(Predicate<? super T> predicate) { // TODO Auto-generated method stub return null; } public <X> Filtered<E, X> byType(Class<X> type) { return matches(type::isInstance).where(type::cast); } public Seq<E> distinct() { return distinct(Function.identity()); } public Seq<E> distinct(Function<? super E, ?> keyMapper) { return matches(new Contains<>(keyMapper)); } public Seq<E> limitUntil(Predicate<? super E> predicate) { return limitWhile(predicate.negate()); } public Seq<E> limitWhile(Predicate<? super E> predicate) { return matches(new Match<>(predicate, true)); } public Filtered<E, T> matches(Predicate<? super T> predicate) { return new Filtered<>(sequence, mapping, filter.and(predicate)); } public Filtered<E, T> matches(Supplier<Predicate<? super T>> predicateSupplier) { // TODO return () ->; } public Seq<E> skipUntil(Predicate<? super E> predicate) { return matches(new Match<>(predicate, false)); } public Seq<E> skipWhile(Predicate<? super E> predicate) { return skipUntil(predicate.negate()); } @Override public Stream<E> stream() { return sequence.stream().filter(e -> filter.test(mapping.apply(e))); } public <X> Filtered<E, X> where(Function<? super T, ? extends X> expression) { return new Filtered<>(sequence, mapping.andThen(expression), t -> true); } public <X> Filtered<E, Seq<X>> whereArray(Function<? super T, X[]> mapper) { return whereStream(mapper.andThen(Stream::of)); } public <X> Filtered<E, Seq<X>> whereCollection(Function<? super T, Collection<X>> mapper) { return whereStream(mapper.andThen(Collection::stream)); } public Filtered<E, T> whereRecursive(Function<? super T, Stream<? extends T>> mapper) { // TODO return null; } public <X> Filtered<E, Seq<X>> whereStream(Function<? super T, Stream<X>> mapper) { requireNonNull(mapper); return where(t -> () -> mapper.apply(t)); } } @FunctionalInterface interface Mapper<E> { default <X> Seq<X> flat(Function<? super E, ? extends Seq<? extends X>> mapper) { return flatStream(mapper.andThen(Seq::stream)); } default <X> Seq<X> flatArray(Function<? super E, X[]> mapper) { return flatStream(mapper.andThen(Stream::of)); } default <X> Seq<X> flatCollection(Function<? super E, ? extends Collection<? extends X>> mapper) { return flatStream(mapper.andThen(Collection::stream)); } default <X> Seq<X> flatStream(Function<? super E, ? extends Stream<? extends X>> mapper) { requireNonNull(mapper); return () -> sequence().stream().flatMap(mapper); } default Seq<E> recursively(Function<? super E, ? extends Seq<E>> mapper) { return sequence().append().seq(flat(mapper).map().recursively(mapper)); } default Seq<E> recursivelyArray(Function<? super E, E[]> mapper) { return sequence().append().seq(flatArray(mapper).map().recursivelyArray(mapper)); } default Seq<E> recursivelyCollection(Function<? super E, ? extends Collection<E>> mapper) { return sequence().append().seq(flatCollection(mapper).map().recursivelyCollection(mapper)); } default Seq<E> recursivelyStream(Function<? super E, ? extends Stream<E>> mapper) { return sequence().append().seq(flatStream(mapper).map().recursivelyStream(mapper)); } Seq<E> sequence(); default <X> Seq<X> to(Function<? super E, ? extends X> mapper) { requireNonNull(mapper); return () -> sequence().stream().map(mapper); } default E[] toArray(IntFunction<E[]> generator) { return sequence().stream().toArray(generator); } default List<E> toList() { return sequence().stream().collect(Collectors.toList()); } } static <E> Seq<E> concat(Supplier<? extends Stream<? extends E>> a, Supplier<? extends Stream<? extends E>> b) { if (Seq.of(a).isEmpty()) { return Seq.ofAny(b); } else if (Seq.of(b).isEmpty()) { return Seq.ofAny(a); } else { return () -> Stream.concat(a.get(), b.get()); } } static <E> Seq<E> empty() { return Stream::empty; } static <E> Seq<E> of(Supplier<? extends Stream<E>> streamSupplier) { return requireNonNull(streamSupplier)::get; } @SuppressWarnings("unchecked") static <E> Seq<E> ofAny(Supplier<? extends Stream<? extends E>> streamSupplier) { return (Seq<E>) of(streamSupplier); } default Extender<E> append() { return o -> concat(this::stream, o); } default Extender<Object> appendAny() { return o -> concat(this::stream, o); } default String asString() { return map().toList().toString(); } default <X> Seq<X> cast(Class<X> type) { return cast(type, true); } default <X> Seq<X> cast(Class<X> type, boolean failFast) { if (failFast && !stream().allMatch(type::isInstance)) { throw new ClassCastException("Could not cast " + this + " to " + type); } else { return map(type::cast); } } default Seq<E> compact() { return map().toList()::stream; } default <X> boolean contains(Class<X> type) { return contains(type::isInstance); } default <X> boolean contains(Class<X> type, Predicate<? super X> predicate) { return stream().filter(type::isInstance).map(type::cast).anyMatch(predicate); } default <X> boolean contains(Object element) { return contains(element::equals); } default <X> boolean contains(Predicate<? super E> predicate) { return stream().anyMatch(predicate); } default Filtered<E, E> filter() { return Filtered.on(this); } default Seq<E> filter(Predicate<? super E> predicate) { requireNonNull(predicate); return () -> stream().filter(predicate); } default <T> Optional<T> fold(Function<? super E, ? extends T> creator, BiFunction<? super T, ? super E, ? extends T> mapper) { Optional<T> identity = head().map(creator); return tail().fold(identity, (o, e) -> o.map(t -> mapper.apply(t, e))); } default <T> T fold(T identity, BiFunction<? super T, ? super E, ? extends T> mapper) { T result = identity; for (E element : this) { result = mapper.apply(result, element); } return result; } default Optional<E> get(long index) { return stream().skip(index).findFirst(); } default Optional<E> head() { return stream().findFirst(); } default boolean isEmpty() { return size() == 0L; } default boolean isNotEmpty() { return !isEmpty(); } @Override default Iterator<E> iterator() { return stream().iterator(); } default Optional<E> last() { return this.<E> fold(Function.identity(), (t, e) -> e); } default Mapper<E> map() { return () -> this; } default <X> Seq<X> map(Function<? super E, ? extends X> mapper) { requireNonNull(mapper); return () -> stream().map(mapper); } default Extender<E> prepend() { return o -> concat(o, this::stream); } default Extender<Object> prependAny() { return o -> concat(o, this::stream); } default Seq<E> reverse() { List<E> result = map().toList(); Collections.reverse(result); return result::stream; } default long size() { return stream().spliterator().getExactSizeIfKnown(); } Stream<E> stream(); default Seq<E> tail() { return new Seq<E>() { @Override public long size() { // skipped stream have no size :( long size = Seq.this.size(); if (size == 0) { return 0; } else if (size < 0) { return -1; } else { return size - 1; } } @Override public Stream<E> stream() { return Seq.this.stream().skip(1L); } }; } }
package com.sun.facelets.compiler; import java.io.IOException; import javax.el.ELException; import javax.faces.component.UIComponentBase; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import com.sun.facelets.el.ELAdaptor; import com.sun.facelets.el.ELText; /** * @author Jacob Hookom * @version $Id: UIText.java,v 1.6 2005-09-30 22:20:55 jhook Exp $ */ final class UIText extends UILeaf { private final ELText txt; private final String alias; public UIText(String alias, ELText txt) { this.txt = txt; this.alias = alias; } public String getFamily() { return null; } public void encodeBegin(FacesContext context) throws IOException { ResponseWriter out = context.getResponseWriter(); try { txt.write(out, ELAdaptor.getELContext(context)); } catch (ELException e) { throw new ELException(this.alias + ": " + e.getMessage(), e.getCause()); } catch (Exception e) { throw new ELException(this.alias + ": " + e.getMessage(), e); } } public String getRendererType() { return null; } public boolean getRendersChildren() { return true; } public String toString() { return this.txt.toString(); } }
package org.devnull.matchmaking; import java.util.Comparator; /** * <p> * Representation of a player. * </p> * <p> * As indicated in the challenge description, feel free to augment the Player * class in any way that you feel will improve your final matchmaking solution. * <strong>Do NOT remove the name, wins, or losses fields.</strong> Also note * that if you make any of these changes, you are responsible for updating the * {@link SampleData} such that it provides a useful data set to exercise your * solution. * </p> */ public class Player implements java.io.Serializable { /** Generated by the serialver utility */ private static final long serialVersionUID = 894794257911209475L; public static final Comparator<Player> NAME_COMPARATOR = new NameComparator(); private static class NameComparator implements Comparator<Player>, java.io.Serializable { /** Generated by the serialver utility */ private static final long serialVersionUID = 2884307583578905718L; public int compare(final Player p1, final Player p2) { return p1.name.compareTo(p2.name); } } private final String name; private final long wins; private final long losses; public Player(String name, long wins, long losses) { // The same as java.util.Objects#requireNonNull(T) if (name == null) throw new NullPointerException(); this.name = name; this.wins = wins; this.losses = losses; } public String getName() { return name; } public long getWins() { return wins; } public long getLosses() { return losses; } @Override public int hashCode() { // The same as java.util.Objects#hash(Object...) return ( ( (1 * 31) + this.name.hashCode() ) * 31 + ((int)(this.wins ^ (this.wins >>> 32))) ) * 31 + ((int)(this.losses ^ (this.losses >>> 32))); } @Override public boolean equals(final Object obj) { if (obj == null) return false; if (obj == this) return true; // Note: Do NOT use "instanceof" here // Java equality sucks, use Scala! if (obj.getClass() != Player.class) return false; final Player p = (Player) obj; return this.name.equals(p.name) && this.wins == p.wins && this.losses == p.losses; } @Override public String toString() { // TODO: Should use Apache Commons StringEscapeUtils to escape this.name here, // but let's assume there are no special characters for simplicity. return new StringBuilder("[Player: \"name\": \"") .append(this.name) .append("\", \"wins\": ") .append(this.wins) .append(", \"losses\": ") .append(this.losses) .append("]") .toString(); } public static final void main(final String... args) { assert new Player("Kenji", 321, 123).hashCode() == new Player("Kenji", 321, 123).hashCode(); assert new Player("Kenji", 321, 123).equals(new Player("Kenji", 321, 123)); assert !new Player("Kenji", 321, 123).equals(new Player("kenji", 321, 123)); assert !new Player("Kenji", 321, 123).equals(new Player("Kenji", 432, 123)); assert !new Player("Kenji", 321, 123).equals(new Player("kenji", 321, 234)); assert new Player("Kenji", 321, 123).toString().equals("[Player: \"name\": \"Kenji\", \"wins\": 321, \"losses\": 123]"); assert NAME_COMPARATOR.compare(new Player("Kenji", 321, 123), new Player("Kenji", 432, 234)) == 0; assert NAME_COMPARATOR.compare(new Player("Kenji", 321, 123), new Player("kenji", 432, 234)) < 0; assert NAME_COMPARATOR.compare(new Player("kenji", 321, 123), new Player("Kenji", 432, 234)) > 0; } }
package picocli; import org.junit.Ignore; import org.junit.Test; import picocli.CommandLine.Command; import picocli.CommandLine.Parameters; import static org.junit.Assert.*; import static picocli.CommandLine.ScopeType.INHERIT; public class Issue1471 { public CommandLine getTestCommandLine(ParentTestCommand parentCommand, TestCommand testCommand, CommandLine.IFactory factory) { CommandLine commandLine = new CommandLine(parentCommand, factory); commandLine.addSubcommand(testCommand); return commandLine; } @Command(name = "parentTestCommand", mixinStandardHelpOptions = true, scope = INHERIT) static class ParentTestCommand { } @Command(name = "parentTestCommand", mixinStandardHelpOptions = true, scope = INHERIT, subcommands = TestCommand.class) static class ParentTestCommand2 { } @Command(name = "sorteotest") static class TestCommand { @Command(name = "entertest", description = "Start participating in a giveaway") void enter(@Parameters(arity = "1") String sentenceType, @Parameters(arity = "1") String tweetUrl) { System.out.println("entering giveaway"); } } @Ignore @Test public void testIssue1741_subcommandAddedProgrammatically() { CommandLine commandLine = getTestCommandLine(new ParentTestCommand(), new TestCommand(), CommandLine.defaultFactory()); assertEquals(0, commandLine.execute("sorteotest", "entertest", "sequenceType", "url")); } @Test public void testIssue1741_staticHierarchy() { CommandLine commandLine = new CommandLine(new ParentTestCommand2()); assertEquals(0, commandLine.execute("sorteotest", "entertest", "sequenceType", "url")); } }
// Inner class for a Namespace node. package org.jaxen.dom; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.jaxen.pattern.Pattern; /** * Extension DOM2 node type for a Namespace Declaration. * * <p>This class implements the DOM2 {@link Node} interface to * allow Namespace declarations to be included in the result * set of an XPath selectNodes operation, even though DOM2 does * not model Namespace declarations as separate nodes.</p> * * <p>While all of the methods are implemented with reasonable * defaults, there will be some unexpected surprises, so users are * advised to test for NamespaceNodes and filter them out from the * result sets as early as possible:</p> * * <ol> * * <li>The {@link #getNodeType} method returns {@link #NAMESPACE_NODE}, * which is not one of the usual DOM2 node types. Generic code may * fall unexpectedly out of switch statements, for example.</li> * * <li>The {@link #getOwnerDocument} method returns the owner document * of the parent node, but that owner document will know nothing about * the Namespace node.</p> * * <li>The {@link #isSupported} method always returns false.</li> * * </ol> * * <p>All attempts to modify a NamespaceNode will fail with a {@link * DOMException} ({@link * DOMException#NO_MODIFICATION_ALLOWED_ERR}).</p> * * <p>This class has only protected constructors, so that it can be * instantiated only by {@link DocumentNavigator}.</p> * * @author David Megginson * @see DocumentNavigator */ public class NamespaceNode implements Node { // Constants. /** * Constant: this is a NamespaceNode. * * @see #getNodeType */ public final static short NAMESPACE_NODE = Pattern.NAMESPACE_NODE; // Protected Constructors. /** * Constructor. * * @param parent The DOM node to which the Namespace is attached. * @param uri The Namespace URI as a string. */ NamespaceNode (Node parent, String name, String value) { this.parent = parent; this.name = name; this.value = value; } /** * Constructor. * * @param parent The DOM node to which the Namespace is attached. * @param attribute The DOM attribute object containing the * Namespace declaration. */ NamespaceNode (Node parent, Node attribute) { String name = attribute.getNodeName(); if (name.equals("xmlns")) this.name = ""; else this.name = name.substring(6); // the part after "xmlns:" this.parent = parent; this.value = attribute.getNodeValue(); } // Implementation of org.w3c.dom.Node. /** * Get the Namespace prefix. * * @return The Namespace prefix, or "" for the default Namespace. */ public String getNodeName () { return name; } /** * Get the Namespace URI. * * @return The Namespace URI. */ public String getNodeValue () { return value; } /** * Change the Namespace URI (always fails). * * @param value The new URI. * @exception DOMException always thrown. */ public void setNodeValue (String value) throws DOMException { no_mods(); } /** * Get the node type. * * @return Always {@link #NAMESPACE_NODE}. */ public short getNodeType () { return NAMESPACE_NODE; } /** * Get the parent node. * * <p>This method returns the element that was queried for Namespaces * in effect, <em>not</em> necessarily the actual element containing * the Namespace declaration.</p> * * @return The parent node (not null). */ public Node getParentNode () { return parent; } /** * Get the list of child nodes. * * @return An empty node list. */ public NodeList getChildNodes () { return new EmptyNodeList(); } /** * Get the first child node. * * @return Always null. */ public Node getFirstChild () { return null; } /** * Get the last child node. * * @return Always null. */ public Node getLastChild () { return null; } /** * Get the previous sibling node. * * @return Always null. */ public Node getPreviousSibling () { return null; } /** * Get the next sibling node. * * @return Always null. */ public Node getNextSibling () { return null; } /** * Get the attribute nodes. * * @return Always null. */ public NamedNodeMap getAttributes () { return null; } /** * Get the owner document. * * @return The owner document <em>of the parent node</em>. */ public Document getOwnerDocument () { // FIXME: this could cause confusion return (parent == null ? null : parent.getOwnerDocument()); } /** * Insert a new child node (always fails). * * @exception DOMException always thrown. * @see Node#insertBefore */ public Node insertBefore (Node newChild, Node refChild) throws DOMException { no_mods(); return null; } /** * Replace a child node (always fails). * * @exception DOMException always thrown. * @see Node#replaceChild */ public Node replaceChild (Node newChild, Node oldChild) throws DOMException { no_mods(); return null; } /** * Remove a child node (always fails). * * @exception DOMException always thrown. * @see Node#removeChild */ public Node removeChild (Node oldChild) throws DOMException { no_mods(); return null; } /** * Append a new child node (always fails). * * @exception DOMException always thrown. * @see Node#appendChild */ public Node appendChild (Node newChild) throws DOMException { no_mods(); return null; } /** * Test for child nodes. * * @return Always false. */ public boolean hasChildNodes () { return false; } /** * Create a copy of this node. * * @param deep Make a deep copy (no effect, since Namespace nodes * don't have children). * @return A new copy of this Namespace node. */ public Node cloneNode (boolean deep) { return new NamespaceNode(parent, name, value); } /** * Normalize the text descendants of this node. * * <p>This method has no effect, since Namespace nodes have no * descendants.</p> */ public void normalize () { // no op } /** * Test if a DOM2 feature is supported. * * @param feature The feature name. * @param version The feature version. * @return Always false. */ public boolean isSupported (String feature, String version) { return false; } /** * Get the Namespace URI for this node. * * <p>Namespace declarations are not themselves * Namespace-qualified.</p> * * @return Always null. */ public String getNamespaceURI () { return null; } /** * Get the Namespace prefix for this node. * * <p>Namespace declarations are not themselves * Namespace-qualified.</p> * * @return Always null. */ public String getPrefix () { return null; } /** * Change the Namespace prefix for this node (always fails). * * @param prefix The new prefix. * @exception DOMException always thrown. */ public void setPrefix (String prefix) throws DOMException { no_mods(); } /** * Get the local name for this node. * * @return Always null. */ public String getLocalName () { return name; } /** * Test if this node has attributes. * * @return Always false. */ public boolean hasAttributes () { return false; } /** * Throw a NO_MODIFICATION_ALLOWED_ERR DOMException. * * @exception DOMException always thrown. */ private void no_mods () throws DOMException { throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, "Namespace node may not be modified"); } // Override default methods from java.lang.Object. /** * Generate a hash code for a Namespace node. * * <p>The hash code is the sum of the hash codes of the parent node, * name, and value.</p> * * @return A hash code for this node. */ public int hashCode () { return hashCode(parent) + hashCode(name) + hashCode(value); } /** * Test for equivalence with another object. * * <p>Two Namespace nodes are considered equivalent if their parents, * names, and values are equal.</p> * * @param o The object to test for equality. * @return true if the object is equivalent to this node, false * otherwise. */ public boolean equals (Object o) { if (o == this) return true; else if (o == null) return false; else if (o instanceof NamespaceNode) { NamespaceNode ns = (NamespaceNode)o; return (equals(parent, ns.getParentNode()) && equals(name, ns.getNodeName()) && equals(value, ns.getNodeValue())); } else { return false; } } /** * Helper method for generating a hash code. * * @param o The object for generating a hash code (possibly null). * @return The object's hash code, or 0 if the object is null. * @see java.lang.Object#hashCode */ private int hashCode (Object o) { return (o == null ? 0 : o.hashCode()); } /** * Helper method for comparing two objects. * * @param a The first object to compare (possibly null). * @param b The second object to compare (possibly null). * @return true if the objects are equivalent or are both null. * @see java.lang.Object#equals */ private boolean equals (Object a, Object b) { return ((a == null && b == null) || (a != null && a.equals(b))); } // Internal state. private Node parent; private String name; private String value; // Inner class: empty node list. /** * A node list with no members. * * <p>This class is necessary for the {@link Node#getChildNodes} * method, which must return an empty node list rather than * null when there are no children.</p> */ class EmptyNodeList implements NodeList { /** * @see NodeList#getLength */ public int getLength () { return 0; } /** * @see NodeList#item */ public Node item(int index) { return null; } } } // end of Namespace.java
package unluac.decompile; import java.util.Collections; import java.util.LinkedList; import java.util.List; import unluac.decompile.block.AlwaysLoop; import unluac.decompile.block.Block; import unluac.decompile.block.Break; import unluac.decompile.block.ForBlock; import unluac.decompile.block.NewElseEndBlock; import unluac.decompile.block.NewIfThenElseBlock; import unluac.decompile.block.NewIfThenEndBlock; import unluac.decompile.block.NewRepeatBlock; import unluac.decompile.block.NewSetBlock; import unluac.decompile.block.NewWhileBlock; import unluac.decompile.block.OuterBlock; import unluac.decompile.block.TForBlock; import unluac.decompile.condition.AndCondition; import unluac.decompile.condition.BinaryCondition; import unluac.decompile.condition.Condition; import unluac.decompile.condition.OrCondition; import unluac.decompile.condition.RegisterSetCondition; import unluac.decompile.condition.SetCondition; import unluac.decompile.condition.TestCondition; import unluac.parse.LFunction; public class ControlFlowHandler { public static boolean verbose = false; private static class Branch implements Comparable<Branch> { private static enum Type { comparison, //comparisonset, test, testset, finalset, jump; } public Branch previous; public Branch next; public int line; public int target; public Type type; public Condition cond; public int targetFirst; public int targetSecond; public boolean inverseValue; public Branch(int line, Type type, Condition cond, int targetFirst, int targetSecond) { this.line = line; this.type = type; this.cond = cond; this.targetFirst = targetFirst; this.targetSecond = targetSecond; this.inverseValue = false; this.target = -1; } @Override public int compareTo(Branch other) { return this.line - other.line; } } private static class State { public LFunction function; public Registers r; public Code code; public Branch begin_branch; public Branch end_branch; public Branch[] branches; public boolean[] reverse_targets; public int[] resolved; public List<Block> blocks; } public static List<Block> process(Decompiler d, Registers r) { State state = new State(); state.function = d.function; state.r = r; state.code = d.code; find_reverse_targets(state); find_branches(state); combine_branches(state); resolve_lines(state); initialize_blocks(state); find_fixed_blocks(state); find_while_loops(state); find_repeat_loops(state); find_break_statements(state); //unredirect_branches(state); //find_blocks(state); find_if_blocks(state); find_set_blocks(state); find_jump_blocks(state); Collections.sort(state.blocks); // DEBUG: print branches stuff /* Branch b = state.begin_branch; while(b != null) { System.out.println("Branch at " + b.line); System.out.println("\tcondition: " + b.cond); b = b.next; } */ return state.blocks; } private static void find_reverse_targets(State state) { Code code = state.code; boolean[] reverse_targets = state.reverse_targets = new boolean[state.code.length + 1]; for(int line = 1; line <= code.length; line++) { if(code.op(line) == Op.JMP) { int target = code.target(line); if(target <= line) { reverse_targets[target] = true; } } } } private static void resolve_lines(State state) { int[] resolved = new int[state.code.length + 1]; for(int line = 1; line <= state.code.length; line++) { int r = line; Branch b = state.branches[line]; while(b != null && b.type == Branch.Type.jump) { r = b.targetSecond; b = state.branches[r]; } resolved[line] = r; } state.resolved = resolved; } private static int find_loadboolblock(State state, int target) { int loadboolblock = -1; if(state.code.op(target) == Op.LOADBOOL) { if(state.code.C(target) != 0) { loadboolblock = target; } else if(target - 1 >= 1 && state.code.op(target - 1) == Op.LOADBOOL && state.code.C(target - 1) != 0) { loadboolblock = target - 1; } } return loadboolblock; } private static void handle_loadboolblock(State state, boolean[] skip, int loadboolblock, Condition c, int line, int target) { int loadboolvalue = state.code.B(target); int final_line = -1; if(loadboolblock - 1 >= 1 && state.code.op(loadboolblock - 1) == Op.JMP && state.code.target(loadboolblock - 1) == loadboolblock + 2) { skip[loadboolblock - 1] = true; final_line = loadboolblock - 2; } boolean inverse = false; if(loadboolvalue == 1) { inverse = true; c = c.inverse(); } Branch b; if(line + 2 == loadboolblock) { b = new Branch(line, Branch.Type.finalset, c, line + 2, loadboolblock + 2); } else { b = new Branch(line, Branch.Type.testset, c, line + 2, loadboolblock + 2); } b.target = state.code.A(loadboolblock); b.inverseValue = inverse; insert_branch(state, b); if(final_line >= line + 2 && state.branches[final_line] == null) { c = new SetCondition(final_line, get_target(state, final_line)); b = new Branch(final_line, Branch.Type.finalset, c, final_line, loadboolblock + 2); b.target = state.code.A(loadboolblock); insert_branch(state, b); } } private static void find_branches(State state) { Code code = state.code; state.branches = new Branch[state.code.length + 1]; boolean[] skip = new boolean[code.length + 1]; for(int line = 1; line <= code.length; line++) { if(!skip[line]) { switch(code.op(line)) { case EQ: case LT: case LE: { BinaryCondition.Operator op = BinaryCondition.Operator.EQ; if(code.op(line) == Op.LT) op = BinaryCondition.Operator.LT; if(code.op(line) == Op.LE) op = BinaryCondition.Operator.LE; int left = code.B(line); int right = code.C(line); int target = code.target(line + 1); Condition c = new BinaryCondition(op, line, left, right); if(code.A(line) == 1) { c = c.inverse(); } int loadboolblock = find_loadboolblock(state, target); if(loadboolblock >= 1) { handle_loadboolblock(state, skip, loadboolblock, c, line, target); } else { Branch b = new Branch(line, Branch.Type.comparison, c, line + 2, target); if(code.A(line) == 1) { b.inverseValue = true; } insert_branch(state, b); } skip[line + 1] = true; break; } case TEST: { Condition c = new TestCondition(line, code.A(line)); if(code.C(line) != 0) c = c.inverse(); int target = code.target(line + 1); int loadboolblock = find_loadboolblock(state, target); if(loadboolblock >= 1) { handle_loadboolblock(state, skip, loadboolblock, c, line, target); } else { Branch b = new Branch(line, Branch.Type.test, c, line + 2, target); b.target = code.A(line); if(code.C(line) != 0) b.inverseValue = true; insert_branch(state, b); } skip[line + 1] = true; break; } case TESTSET: { Condition c = new TestCondition(line, code.B(line)); int target = code.target(line + 1); Branch b = new Branch(line, Branch.Type.testset, c, line + 2, target); b.target = code.A(line); if(code.C(line) != 0) b.inverseValue = true; skip[line + 1] = true; insert_branch(state, b); int final_line = target - 1; if(state.branches[final_line] == null) { int loadboolblock = find_loadboolblock(state, target - 2); if(loadboolblock == -1) { if(line + 2 == target) { c = new RegisterSetCondition(line, get_target(state, line)); //c = new SetCondition(line - 1, get_target(state, line)); final_line = final_line + 1; } else { c = new SetCondition(final_line, get_target(state, final_line)); } b = new Branch(final_line, Branch.Type.finalset, c, target, target); b.target = code.A(line); insert_branch(state, b); } } break; } case JMP: { int target = code.target(line); Branch b = new Branch(line, Branch.Type.jump, null, target, target); insert_branch(state, b); break; } } } } link_branches(state); } private static void combine_branches(State state) { Branch b; b = state.end_branch; while(b != null) { b = combine_left(state, b).previous; } /* b = state.end_branch; while(b != null) { Branch result = combine_right(state, b); if(result != null) { b = result; if(b.next != null) { b = b.next; } } else { b = b.previous; } } */ } private static void unredirect_branches(State state) { // There is more complication here int[] redirect = new int[state.code.length + 1]; Branch b = state.end_branch; while(b != null) { if(b.type == Branch.Type.jump) { if(redirect[b.targetFirst] == 0) { redirect[b.targetFirst] = b.line; } else { int temp = b.targetFirst; b.targetFirst = b.targetSecond = redirect[temp]; redirect[temp] = b.line; } } b = b.previous; } b = state.begin_branch; while(b != null) { if(b.type != Branch.Type.jump) { if(redirect[b.targetSecond] != 0) { // Hack-ish -- redirect can't extend the scope boolean skip = false; if(b.targetSecond > b.line & redirect[b.targetSecond] > b.targetSecond) skip = true; if(!skip) { //System.out.println("Redirected to " + redirct[b.targetSecond] + " from " + b.targetSecond); //if(redirect[b.targetSecond] < b.targetSecond) b.targetSecond = redirect[b.targetSecond]; } } } b = b.next; } } private static void initialize_blocks(State state) { state.blocks = new LinkedList<Block>(); } private static void find_fixed_blocks(State state) { List<Block> blocks = state.blocks; Registers r = state.r; Code code = state.code; Op tforTarget = state.function.header.version.getTForTarget(); blocks.add(new OuterBlock(state.function, state.code.length)); Branch b = state.begin_branch; while(b != null) { if(b.type == Branch.Type.jump) { int line = b.line; int target = b.targetFirst; if(code.op(target) == tforTarget) { int A = code.A(target); int C = code.C(target); if(C == 0) throw new IllegalStateException(); r.setInternalLoopVariable(A, target, line + 1); //TODO: end? r.setInternalLoopVariable(A + 1, target, line + 1); r.setInternalLoopVariable(A + 2, target, line + 1); for(int index = 1; index <= C; index++) { r.setExplicitLoopVariable(A + 2 + index, line, target + 2); //TODO: end? } remove_branch(state, state.branches[line]); remove_branch(state, state.branches[target + 1]); blocks.add(new TForBlock(state.function, line + 1, target + 2, A, C, r)); } break; } b = b.next; } for(int line = 1; line <= code.length; line++) { switch(code.op(line)) { case FORPREP: { int target = code.target(line); blocks.add(new ForBlock(state.function, line + 1, target + 1, code.A(line), r)); r.setInternalLoopVariable(code.A(line), line, target + 1); r.setInternalLoopVariable(code.A(line) + 1, line, target + 1); r.setInternalLoopVariable(code.A(line) + 2, line, target + 1); r.setExplicitLoopVariable(code.A(line) + 3, line, target + 1); break; } } } } private static void unredirect(State state, int begin, int end, int line, int target) { Branch b = state.begin_branch; while(b != null) { if(b.line >= begin && b.line < end && b.targetSecond == target) { b.targetSecond = line; if(b.targetFirst == target) { b.targetFirst = line; } } b = b.next; } } private static void find_while_loops(State state) { List<Block> blocks = state.blocks; Registers r = state.r; Branch j = state.end_branch; while(j != null) { if(j.type == Branch.Type.jump && j.targetFirst < j.line) { int line = j.targetFirst; int loopback = line; int end = j.line + 1; Branch b = state.begin_branch; while(b != null) { if(is_conditional(b) && b.line >= loopback && b.line < j.line && b.targetSecond == end) { break; } b = b.next; } if(b != null) { boolean reverse = state.reverse_targets[loopback]; state.reverse_targets[loopback] = false; for(int l = loopback; l < b.line; l++) { if(is_statement(state, l)) { //System.err.println("not while " + l); b = null; break; } } state.reverse_targets[loopback] = reverse; } Block loop; if(b != null) { remove_branch(state, b); //System.err.println("while " + b.targetFirst + " " + b.targetSecond); loop = new NewWhileBlock(state.function, r, b.cond, b.targetFirst, b.targetSecond); unredirect(state, loopback, end, j.line, loopback); } else { loop = new AlwaysLoop(state.function, loopback, end); unredirect(state, loopback, end, j.line, loopback); } remove_branch(state, j); blocks.add(loop); } j = j.previous; } } private static void find_repeat_loops(State state) { List<Block> blocks = state.blocks; Branch b = state.begin_branch; while(b != null) { if(is_conditional(b)) { if(b.targetSecond < b.targetFirst) { Block block = new NewRepeatBlock(state.function, state.r, b.cond, b.targetSecond, b.targetFirst); remove_branch(state, b); blocks.add(block); } } b = b.next; } } private static void find_if_blocks(State state) { List<Block> blocks = state.blocks; Branch b = state.begin_branch; while(b != null) { if(is_conditional(b)) { // else? Block enclosing; enclosing = enclosing_unprotected_block(state, b.line); if(enclosing != null && !enclosing.contains(b.targetSecond)) { if(b.targetSecond == enclosing.getUnprotectedTarget()) { b.targetSecond = enclosing.getUnprotectedLine(); } } Branch tail = b.targetSecond >= 1 ? state.branches[b.targetSecond - 1] : null; if(tail != null && !is_conditional(tail)) { enclosing = enclosing_unprotected_block(state, tail.line); if(enclosing != null && !enclosing.contains(tail.targetSecond)) { if(tail.targetSecond == state.resolved[enclosing.getUnprotectedTarget()]) { tail.targetSecond = enclosing.getUnprotectedLine(); } } //System.err.println("else end " + b.targetFirst + " " + b.targetSecond + " " + tail.targetSecond + " enclosing " + (enclosing != null ? enclosing.begin : -1) + " " + + (enclosing != null ? enclosing.end : -1)); state.blocks.add(new NewIfThenElseBlock(state.function, state.r, b.cond, b.targetFirst, b.targetSecond, tail.targetSecond)); if(b.targetSecond != tail.targetSecond) { state.blocks.add(new NewElseEndBlock(state.function, b.targetSecond, tail.targetSecond)); } // else "empty else" case remove_branch(state, tail); } else { //System.err.println("if end " + b.targetFirst + " " + b.targetSecond); state.blocks.add(new NewIfThenEndBlock(state.function, state.r, b.cond, b.targetFirst, b.targetSecond)); } remove_branch(state, b); } b = b.next; } } private static void find_set_blocks(State state) { List<Block> blocks = state.blocks; Branch b = state.begin_branch; while(b != null) { if(is_assignment(b) || b.type == Branch.Type.finalset) { Block block = new NewSetBlock(state.function, b.cond, b.target, b.line, b.targetFirst, b.targetSecond, false, state.r); blocks.add(block); remove_branch(state, b); } b = b.next; } } private static void find_jump_blocks(State state) { List<Block> blocks = state.blocks; Branch b = state.begin_branch; while(b != null) { if(b.type == Branch.Type.jump) { Block block = new Break(state.function, b.line, b.targetFirst); blocks.add(block); remove_branch(state, b); } b = b.next; } } private static Block enclosing_breakable_block(State state, int line) { Block enclosing = null; for(Block block : state.blocks) { if(block.contains(line) && block.breakable()) { if(enclosing == null || enclosing.contains(block)) { enclosing = block; } } } return enclosing; } private static Block enclosing_unprotected_block(State state, int line) { Block enclosing = null; for(Block block : state.blocks) { if(block.contains(line) && block.isUnprotected()) { if(enclosing == null || enclosing.contains(block)) { enclosing = block; } } } return enclosing; } private static Block enclosing_block(State state, Block inner) { Block enclosing = null; for(Block block : state.blocks) { if(block != inner && block.contains(inner) && block.breakable()) { if(enclosing == null || enclosing.contains(block)) { enclosing = block; } } } return enclosing; } private static void unredirect_break(State state, int line, Block enclosing) { Branch b = state.begin_branch; while(b != null) { /* ??? if(is_conditional(b) && enclosing_block(state, b.line) == enclosing && b.targetFirst <= line && b.targetSecond == enclosing.end) { b.targetSecond = line; if(b.targetFirst == enclosing.end) { b.targetFirst = line; } } */ Block breakable = enclosing_breakable_block(state, b.line); if(breakable != null && b.type == Branch.Type.jump && enclosing_block(state, breakable) == enclosing && b.targetFirst == enclosing.end) { b.targetFirst = line; b.targetSecond = line; } b = b.next; } } private static void find_break_statements(State state) { List<Block> blocks = state.blocks; Branch b = state.end_branch; LinkedList<Branch> breaks = new LinkedList<Branch>(); while(b != null) { if(b.type == Branch.Type.jump) { int line = b.line; Block enclosing = enclosing_breakable_block(state, line); if(enclosing != null && b.targetFirst == enclosing.end) { Break block = new Break(state.function, b.line, b.targetFirst); unredirect_break(state, line, enclosing); blocks.add(block); //breaks.add(b); breaks.addFirst(b); } } b = b.previous; } //TODO: conditional breaks (Lua 5.2) [conflicts with unredirection] b = state.begin_branch; while(b != null) { if(is_conditional(b)) { Block enclosing = enclosing_breakable_block(state, b.line); if(enclosing != null && b.targetSecond >= enclosing.end) { for(Branch br : breaks) { if(br.line >= b.targetFirst && br.line < b.targetSecond && br.line < enclosing.end) { Branch tbr = br; while(b.targetSecond != tbr.targetSecond) { Branch next = state.branches[tbr.targetSecond]; if(next != null && next.type == Branch.Type.jump) { tbr = next; // TODO: guard against infinite loop } else { break; } } if(b.targetSecond == tbr.targetSecond) { b.targetSecond = br.line; } } } } } b = b.next; } for(Branch br : breaks) { remove_branch(state, br); } } private static void find_blocks(State state) { List<Block> blocks = state.blocks; Code code = state.code; Branch b = state.begin_branch; while(b != null) { if(is_conditional(b)) { // Conditional branches decompile to if, while, or repeat boolean has_tail = false; int tail_line = b.targetSecond - 1; int tail_target = 0; if(tail_line >= 1 && code.op(tail_line) == Op.JMP) { Branch tail_branch = state.branches[tail_line]; if(tail_branch != null && tail_branch.type == Branch.Type.jump) { has_tail = true; tail_target = tail_branch.targetFirst; } } if(b.targetSecond >= b.targetFirst) { if(has_tail) { if(tail_target > tail_line) { // If -- then -- else //System.out.println("If -- then -- else"); //System.out.println("\t" + b.line + "\t" + b.cond.toString()); NewIfThenElseBlock block = new NewIfThenElseBlock(state.function, state.r, b.cond, b.targetFirst, b.targetSecond, tail_target); NewElseEndBlock block2 = new NewElseEndBlock(state.function, b.targetSecond, tail_target); block.partner = block2; block2.partner = block; //System.out.println("else -- end " + block2.begin + " " + block2.end); remove_branch(state, state.branches[tail_line]); blocks.add(block); blocks.add(block2); } else { if(tail_target <= b.line) { // While //System.out.println("While"); //System.out.println("\t" + b.line + "\t" + b.cond.toString()); Block block = new NewWhileBlock(state.function, state.r, b.cond, b.targetFirst, b.targetSecond); blocks.add(block); } else { // If -- then (tail is from an inner loop) //System.out.println("If -- then"); //System.out.println("\t" + b.line + "\t" + b.cond.toString()); Block block = new NewIfThenEndBlock(state.function, state.r, b.cond, b.targetFirst, b.targetSecond); blocks.add(block); } } } else { // If -- then //System.out.println("If -- then"); //System.out.println("\t" + b.line + "\t" + b.cond.toString() + "\t" + b.targetFirst + "\t" + b.targetSecond); int begin = b.targetFirst; int end = b.targetSecond; if(begin == end) { begin = end - 1; } Block block = new NewIfThenEndBlock(state.function, state.r, b.cond, begin, end); blocks.add(block); } } else { // Repeat //System.out.println("Repeat " + b.targetSecond + " .. " + b.targetFirst); //System.out.println("\t" + b.line + "\t" + b.cond.toString()); Block block = new NewRepeatBlock(state.function, state.r, b.cond, b.targetSecond, b.targetFirst); blocks.add(block); } } else if(is_assignment(b) || b.type == Branch.Type.finalset) { Block block = new NewSetBlock(state.function, b.cond, b.target, b.line, b.targetFirst, b.targetSecond, false, state.r); blocks.add(block); //System.out.println("Assign block " + b.line); } else if(b.type == Branch.Type.jump) { Block block = new Break(state.function, b.line, b.targetFirst); blocks.add(block); } b = b.next; } Collections.sort(blocks); } private static boolean is_conditional(Branch b) { return b.type == Branch.Type.comparison || b.type == Branch.Type.test; } private static boolean is_conditional(Branch b, int r) { return b.type == Branch.Type.comparison || b.type == Branch.Type.test && b.target != r; } private static boolean is_assignment(Branch b) { return b.type == Branch.Type.testset; } private static boolean is_assignment(Branch b, int r) { return b.type == Branch.Type.testset || b.type == Branch.Type.test && b.target == r; } private static boolean adjacent(State state, Branch branch0, Branch branch1) { if(branch0 == null || branch1 == null) { return false; } else { boolean adjacent = branch0.targetFirst <= branch1.line; if(adjacent) { for(int line = branch0.targetFirst; line < branch1.line; line++) { if(is_statement(state, line)) { if(verbose) System.out.println("Found statement at " + line + " between " + branch0.line + " and " + branch1.line); adjacent = false; break; } } adjacent = adjacent && !state.reverse_targets[branch1.line]; } return adjacent; } } private static Branch combine_left(State state, Branch branch1) { if(is_conditional(branch1)) { return combine_conditional(state, branch1); } else { return combine_assignment(state, branch1); } } private static Branch combine_conditional(State state, Branch branch1) { Branch branch0 = branch1.previous; if(adjacent(state, branch0, branch1) && is_conditional(branch0) && is_conditional(branch1)) { int branch0TargetSecond = branch0.targetSecond; if(state.code.op(branch1.targetFirst) == Op.JMP && state.code.target(branch1.targetFirst) == branch0TargetSecond) { // Handle redirected target branch0TargetSecond = branch1.targetFirst; } if(branch0TargetSecond == branch1.targetFirst) { // Combination if not branch0 or branch1 then branch0 = combine_conditional(state, branch0); Condition c = new OrCondition(branch0.cond.inverse(), branch1.cond); Branch branchn = new Branch(branch0.line, Branch.Type.comparison, c, branch1.targetFirst, branch1.targetSecond); branchn.inverseValue = branch1.inverseValue; if(verbose) System.err.println("conditional or " + branchn.line); replace_branch(state, branch0, branch1, branchn); return combine_conditional(state, branchn); } else if(branch0TargetSecond == branch1.targetSecond) { // Combination if branch0 and branch1 then branch0 = combine_conditional(state, branch0); Condition c = new AndCondition(branch0.cond, branch1.cond); Branch branchn = new Branch(branch0.line, Branch.Type.comparison, c, branch1.targetFirst, branch1.targetSecond); branchn.inverseValue = branch1.inverseValue; if(verbose) System.err.println("conditional and " + branchn.line); replace_branch(state, branch0, branch1, branchn); return combine_conditional(state, branchn); } } return branch1; } private static Branch combine_assignment(State state, Branch branch1) { Branch branch0 = branch1.previous; if(adjacent(state, branch0, branch1)) { int register = branch1.target; //System.err.println("blah " + branch1.line + " " + branch0.line); if(is_conditional(branch0) && is_assignment(branch1)) { //System.err.println("bridge cand " + branch1.line + " " + branch0.line); if(branch0.targetSecond == branch1.targetFirst) { boolean inverse = branch0.inverseValue; if(verbose) System.err.println("bridge " + (inverse ? "or" : "and") + " " + branch1.line + " " + branch0.line); branch0 = combine_conditional(state, branch0); if(inverse != branch0.inverseValue) throw new IllegalStateException(); Condition c; if(inverse) { //System.err.println("bridge or " + branch0.line + " " + branch0.inverseValue); c = new OrCondition(branch0.cond.inverse(), branch1.cond); } else { //System.err.println("bridge and " + branch0.line + " " + branch0.inverseValue); c = new AndCondition(branch0.cond, branch1.cond); } Branch branchn = new Branch(branch0.line, branch1.type, c, branch1.targetFirst, branch1.targetSecond); branchn.inverseValue = branch1.inverseValue; branchn.target = register; replace_branch(state, branch0, branch1, branchn); return combine_assignment(state, branchn); } else if(branch0.targetSecond == branch1.targetSecond) { /* Condition c = new AndCondition(branch0.cond, branch1.cond); Branch branchn = new Branch(branch0.line, Branch.Type.comparison, c, branch1.targetFirst, branch1.targetSecond); replace_branch(state, branch0, branch1, branchn); return branchn; */ } } if(is_assignment(branch0, register) && is_assignment(branch1) && branch0.inverseValue == branch1.inverseValue) { if(branch0.type == Branch.Type.test && branch0.inverseValue) { branch0.cond = branch0.cond.inverse(); // inverse has been double handled; undo it } if(branch0.targetSecond == branch1.targetSecond) { Condition c; //System.err.println("preassign " + branch1.line + " " + branch0.line + " " + branch0.targetSecond); boolean inverse = branch0.inverseValue; if(verbose) System.err.println("assign " + (inverse ? "or" : "and") + " " + branch1.line + " " + branch0.line); branch0 = combine_assignment(state, branch0); if(inverse != branch0.inverseValue) throw new IllegalStateException(); if(branch0.inverseValue) { //System.err.println("assign and " + branch1.line + " " + branch0.line); c = new OrCondition(branch0.cond, branch1.cond); } else { //System.err.println("assign or " + branch1.line + " " + branch0.line); c = new AndCondition(branch0.cond, branch1.cond); } Branch branchn = new Branch(branch0.line, branch1.type, c, branch1.targetFirst, branch1.targetSecond); branchn.inverseValue = branch1.inverseValue; branchn.target = register; replace_branch(state, branch0, branch1, branchn); return combine_assignment(state, branchn); } } if(is_assignment(branch0, register) && branch1.type == Branch.Type.finalset) { if(branch0.targetSecond == branch1.targetSecond) { if(branch0.type == Branch.Type.test && branch0.inverseValue) { branch0.cond = branch0.cond.inverse(); // inverse has been double handled; undo it } Condition c; //System.err.println("final preassign " + branch1.line + " " + branch0.line); boolean inverse = branch0.inverseValue; if(verbose) System.err.println("final assign " + (inverse ? "or" : "and") + " " + branch1.line + " " + branch0.line); branch0 = combine_assignment(state, branch0); if(inverse != branch0.inverseValue) throw new IllegalStateException(); if(branch0.inverseValue) { //System.err.println("final assign or " + branch1.line + " " + branch0.line); c = new OrCondition(branch0.cond, branch1.cond); } else { //System.err.println("final assign and " + branch1.line + " " + branch0.line); c = new AndCondition(branch0.cond, branch1.cond); } Branch branchn = new Branch(branch0.line, Branch.Type.finalset, c, branch1.targetFirst, branch1.targetSecond); branchn.target = register; replace_branch(state, branch0, branch1, branchn); return combine_assignment(state, branchn); } } } return branch1; } private static void replace_branch(State state, Branch branch0, Branch branch1, Branch branchn) { state.branches[branch0.line] = null; state.branches[branch1.line] = null; branchn.previous = branch0.previous; if(branchn.previous == null) { state.begin_branch = branchn; } else { branchn.previous.next = branchn; } branchn.next = branch1.next; if(branchn.next == null) { state.end_branch = branchn; } else { branchn.next.previous = branchn; } state.branches[branchn.line] = branchn; } private static void remove_branch(State state, Branch b) { state.branches[b.line] = null; Branch prev = b.previous; Branch next = b.next; if(prev != null) { prev.next = next; } else { state.begin_branch = next; } if(next != null) { next.previous = prev; } else { state.end_branch = prev; } } private static void insert_branch(State state, Branch b) { state.branches[b.line] = b; } private static void link_branches(State state) { Branch previous = null; for(int index = 0; index < state.branches.length; index++) { Branch b = state.branches[index]; if(b != null) { b.previous = previous; if(previous != null) { previous.next = b; } else { state.begin_branch = b; } previous = b; } } state.end_branch = previous; } /** * Returns the target register of the instruction at the given * line or -1 if the instruction does not have a unique target. * * TODO: this probably needs a more careful pass */ private static int get_target(State state, int line) { Code code = state.code; switch(code.op(line)) { case MOVE: case LOADK: case LOADBOOL: case GETUPVAL: case GETTABUP: case GETGLOBAL: case GETTABLE: case NEWTABLE: case ADD: case SUB: case MUL: case DIV: case MOD: case POW: case UNM: case NOT: case LEN: case CONCAT: case CLOSURE: case TESTSET: return code.A(line); case LOADNIL: if(code.A(line) == code.B(line)) { return code.A(line); } else { return -1; } case SETGLOBAL: case SETUPVAL: case SETTABUP: case SETTABLE: case JMP: case TAILCALL: case RETURN: case FORLOOP: case FORPREP: case TFORCALL: case TFORLOOP: case CLOSE: return -1; case SELF: return -1; case EQ: case LT: case LE: case TEST: case SETLIST: return -1; case CALL: { int a = code.A(line); int c = code.C(line); if(c == 2) { return a; } else { return -1; } } case VARARG: { int a = code.A(line); int b = code.B(line); if(b == 1) { return a; } else { return -1; } } default: throw new IllegalStateException(); } } private static boolean is_statement(State state, int line) { if(state.reverse_targets[line]) return true; Registers r = state.r; int testRegister = -1; Code code = state.code; switch(code.op(line)) { case MOVE: case LOADK: case LOADBOOL: case GETUPVAL: case GETTABUP: case GETGLOBAL: case GETTABLE: case NEWTABLE: case ADD: case SUB: case MUL: case DIV: case MOD: case POW: case UNM: case NOT: case LEN: case CONCAT: case CLOSURE: return r.isLocal(code.A(line), line) || code.A(line) == testRegister; case LOADNIL: for(int register = code.A(line); register <= code.B(line); register++) { if(r.isLocal(register, line)) { return true; } } return false; case SETGLOBAL: case SETUPVAL: case SETTABUP: case SETTABLE: case JMP: case TAILCALL: case RETURN: case FORLOOP: case FORPREP: case TFORCALL: case TFORLOOP: case CLOSE: return true; case SELF: return r.isLocal(code.A(line), line) || r.isLocal(code.A(line) + 1, line); case EQ: case LT: case LE: case TEST: case TESTSET: case SETLIST: return false; case CALL: { int a = code.A(line); int c = code.C(line); if(c == 1) { return true; } if(c == 0) c = r.registers - a + 1; for(int register = a; register < a + c - 1; register++) { if(r.isLocal(register, line)) { return true; } } return (c == 2 && a == testRegister); } case VARARG: { int a = code.A(line); int b = code.B(line); if(b == 0) b = r.registers - a + 1; for(int register = a; register < a + b - 1; register++) { if(r.isLocal(register, line)) { return true; } } return false; } default: throw new IllegalStateException("Illegal opcode: " + code.op(line)); } } // static only private ControlFlowHandler() { } }
package org.devocative.wickomp; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.request.IRequestParameters; import org.apache.wicket.request.Response; import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.util.string.StringValue; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /* * Some useful annotations: * * @JsonIgnore * * @JsonInclude(JsonInclude.Include.NON_NULL) * * @JsonRawValue * * @JsonProperty("<as property name>") * * @JsonValue */ public class WebUtil { public static String toJson(Object obj) { StringWriter sw = new StringWriter(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true); try { mapper.writeValue(sw, obj); } catch (IOException e) { throw new RuntimeException(e); } return sw.toString(); } public static <T> T fromJson(String json, Class<T> cls) { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); try { return mapper.readValue(json, cls); } catch (IOException e) { throw new RuntimeException(e); } } public static <T> T fromJson(String json, TypeReference<T> typeReference) { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); try { return mapper.readValue(json, typeReference); } catch (IOException e) { throw new RuntimeException(e); } } public static void writeJQueryCall(String script, boolean decorateWithInit) { AjaxRequestTarget target = RequestCycle.get().find(AjaxRequestTarget.class); if (target != null) { target.appendJavaScript(script); } else { Response response = RequestCycle.get().getResponse(); if (decorateWithInit) { response.write(String.format("<script>$(function(){%s});</script>", script)); } else { response.write(String.format("<script>%s</script>", script)); } } } public static Map<String, List<String>> toMap(IRequestParameters parameters, boolean lowercaseParam) { Map<String, List<String>> result = new HashMap<>(); for (String param : parameters.getParameterNames()) { List<String> values = new ArrayList<>(); for (StringValue stringValue : parameters.getParameterValues(param)) { values.add(stringValue.toString()); } if (lowercaseParam) { param = param.toLowerCase(); } if (result.containsKey(param)) { result.get(param).addAll(values); } else { result.put(param, values); } } return result; } }
package net.sf.jabref.groups; import java.awt.*; import java.awt.event.*; import java.util.*; import java.util.regex.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.undo.AbstractUndoableEdit; import net.sf.jabref.*; import net.sf.jabref.search.*; import antlr.collections.AST; import com.jgoodies.forms.builder.DefaultFormBuilder; import com.jgoodies.forms.layout.*; /** * Dialog for creating or modifying groups. Operates directly on the Vector * containing group information. */ class GroupDialog extends JDialog { private static final int INDEX_EXPLICITGROUP = 0; private static final int INDEX_KEYWORDGROUP = 1; private static final int INDEX_SEARCHGROUP = 2; private static final int TEXTFIELD_LENGTH = 30; // for all types private JTextField m_name = new JTextField(TEXTFIELD_LENGTH); private JRadioButton m_explicitRadioButton = new JRadioButton(Globals .lang("Statically group entries by manual assignment")); private JRadioButton m_keywordsRadioButton = new JRadioButton( Globals.lang("Dynamically group entries by searching a field for a keyword")); private JRadioButton m_searchRadioButton = new JRadioButton(Globals .lang("Dynamically group entries by a free-form search expression")); private JRadioButton m_independentButton = new JRadioButton( // JZTODO lyrics "Independent group: When selected, view only this group's entries"); private JRadioButton m_intersectionButton = new JRadioButton( // JZTODO lyrics "Refine supergroup: When selected, view entries contained in both this group and its supergroup"); private JRadioButton m_unionButton = new JRadioButton( // JZTODO lyrics "Include subgroups: When selected, view entries contained in this group or its subgroups"); // for KeywordGroup private JTextField m_kgSearchField = new JTextField(TEXTFIELD_LENGTH); private FieldTextField m_kgSearchTerm = new FieldTextField("keywords", "", false); private JCheckBox m_kgCaseSensitive = new JCheckBox(Globals .lang("Case sensitive")); private JCheckBox m_kgRegExp = new JCheckBox(Globals .lang("Regular Expression")); // for SearchGroup private JTextField m_sgSearchExpression = new JTextField(TEXTFIELD_LENGTH); private JCheckBox m_sgCaseSensitive = new JCheckBox(Globals .lang("Case sensitive")); private JCheckBox m_sgRegExp = new JCheckBox(Globals .lang("Regular Expression")); // for all types private JButton m_ok = new JButton(Globals.lang("Ok")); private JButton m_cancel = new JButton(Globals.lang("Cancel")); private JPanel m_optionsPanel = new JPanel(); private JLabel m_description = new JLabel() { public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); // width must be smaller than width of enclosing JScrollPane // to prevent a horizontal scroll bar d.width = 1; return d; } }; private boolean m_okPressed = false; private final JabRefFrame m_parent; private final BasePanel m_basePanel; private AbstractGroup m_resultingGroup; private AbstractUndoableEdit m_undoAddPreviousEntires = null; private final AbstractGroup m_editedGroup; private CardLayout m_optionsLayout = new CardLayout(); /** * Shows a group add/edit dialog. * * @param jabrefFrame * The parent frame. * @param defaultField * The default grouping field. * @param editedGroup * The group being edited, or null if a new group is to be * created. */ public GroupDialog(JabRefFrame jabrefFrame, BasePanel basePanel, AbstractGroup editedGroup) { super(jabrefFrame, Globals.lang("Edit group"), true); m_basePanel = basePanel; m_parent = jabrefFrame; m_editedGroup = editedGroup; // set default values (overwritten if editedGroup != null) m_kgSearchField.setText(jabrefFrame.prefs().get("groupsDefaultField")); // configure elements ButtonGroup groupType = new ButtonGroup(); groupType.add(m_explicitRadioButton); groupType.add(m_keywordsRadioButton); groupType.add(m_searchRadioButton); ButtonGroup groupHierarchy = new ButtonGroup(); groupHierarchy.add(m_independentButton); groupHierarchy.add(m_intersectionButton); groupHierarchy.add(m_unionButton); m_description.setVerticalAlignment(JLabel.TOP); getRootPane().setDefaultButton(m_ok); // build individual layout cards for each group m_optionsPanel.setLayout(m_optionsLayout); // ... for explicit group m_optionsPanel.add(new JPanel(), "" + INDEX_EXPLICITGROUP); // ... for keyword group FormLayout layoutKG = new FormLayout( "right:pref, 4dlu, fill:1dlu:grow, 2dlu, left:pref"); DefaultFormBuilder builderKG = new DefaultFormBuilder(layoutKG); builderKG.append(Globals.lang("Field")); builderKG.append(m_kgSearchField, 3); builderKG.nextLine(); builderKG.append(Globals.lang("Keyword")); builderKG.append(m_kgSearchTerm); builderKG.append(new FieldContentSelector(m_parent, m_basePanel, this, m_kgSearchTerm, m_basePanel.metaData(), null, true)); builderKG.nextLine(); builderKG.append(m_kgCaseSensitive, 3); builderKG.nextLine(); builderKG.append(m_kgRegExp, 3); m_optionsPanel.add(builderKG.getPanel(), "" + INDEX_KEYWORDGROUP); // ... for search group FormLayout layoutSG = new FormLayout("right:pref, 4dlu, fill:1dlu:grow"); DefaultFormBuilder builderSG = new DefaultFormBuilder(layoutSG); builderSG.append(Globals.lang("Search expression")); builderSG.append(m_sgSearchExpression); builderSG.nextLine(); builderSG.append(m_sgCaseSensitive, 3); builderSG.nextLine(); builderSG.append(m_sgRegExp, 3); m_optionsPanel.add(builderSG.getPanel(), "" + INDEX_SEARCHGROUP); // ... for buttons panel FormLayout layoutBP = new FormLayout("pref, 4dlu, pref", "p"); layoutBP.setColumnGroups(new int[][] { { 1, 3 } }); DefaultFormBuilder builderBP = new DefaultFormBuilder(layoutBP); builderBP.append(m_ok); builderBP.add(m_cancel); // create layout FormLayout layoutAll = new FormLayout( "right:pref, 4dlu, fill:600px, 4dlu, fill:pref", "p, 3dlu, p, 3dlu, p, 0dlu, p, 0dlu, p, 3dlu, p, 3dlu, p, " + "0dlu, p, 0dlu, p, 3dlu, p, 3dlu, " + "p, 3dlu, p, 3dlu, top:80dlu, 9dlu, p, , 9dlu, p"); DefaultFormBuilder builderAll = new DefaultFormBuilder(layoutAll); builderAll.setDefaultDialogBorder(); builderAll.appendSeparator(Globals.lang("General")); builderAll.nextLine(); builderAll.nextLine(); builderAll.append(Globals.lang("Name")); builderAll.append(m_name); builderAll.nextLine(); builderAll.nextLine(); builderAll.append(m_explicitRadioButton, 5); builderAll.nextLine(); builderAll.nextLine(); builderAll.append(m_keywordsRadioButton, 5); builderAll.nextLine(); builderAll.nextLine(); builderAll.append(m_searchRadioButton, 5); builderAll.nextLine(); builderAll.nextLine(); builderAll.appendSeparator("Hierarchical Context"); // JZTODO lyrics builderAll.nextLine(); builderAll.nextLine(); builderAll.append(m_independentButton, 5); builderAll.nextLine(); builderAll.nextLine(); builderAll.append(m_intersectionButton, 5); builderAll.nextLine(); builderAll.nextLine(); builderAll.append(m_unionButton, 5); builderAll.nextLine(); builderAll.nextLine(); builderAll.appendSeparator(Globals.lang("Options")); builderAll.nextLine(); builderAll.nextLine(); builderAll.append(m_optionsPanel, 5); builderAll.nextLine(); builderAll.nextLine(); builderAll.appendSeparator(Globals.lang("Description")); builderAll.nextLine(); builderAll.nextLine(); JScrollPane sp = new JScrollPane(m_description, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) { public Dimension getPreferredSize() { return getMaximumSize(); } }; builderAll.append(sp, 5); builderAll.nextLine(); builderAll.nextLine(); builderAll.appendSeparator(); builderAll.nextLine(); builderAll.nextLine(); CellConstraints cc = new CellConstraints(); builderAll.add(builderBP.getPanel(), cc.xyw(builderAll.getColumn(), builderAll.getRow(), 5, "center, fill")); Container cp = getContentPane(); cp.setLayout(new BoxLayout(cp, BoxLayout.Y_AXIS)); cp.add(builderAll.getPanel()); pack(); setResizable(false); updateComponents(); setLayoutForSelectedGroup(); Util.placeDialog(this, m_parent); // add listeners ItemListener radioButtonItemListener = new ItemListener() { public void itemStateChanged(ItemEvent e) { setLayoutForSelectedGroup(); updateComponents(); } }; m_explicitRadioButton.addItemListener(radioButtonItemListener); m_keywordsRadioButton.addItemListener(radioButtonItemListener); m_searchRadioButton.addItemListener(radioButtonItemListener); m_cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); m_ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { m_okPressed = true; if (m_explicitRadioButton.isSelected()) { if (m_editedGroup instanceof ExplicitGroup) { // keep assignments from possible previous ExplicitGroup m_resultingGroup = m_editedGroup.deepCopy(); m_resultingGroup.setName(m_name.getText().trim()); m_resultingGroup.setHierarchicalContext(getContext()); } else { m_resultingGroup = new ExplicitGroup(m_name.getText() .trim(), getContext()); if (m_editedGroup != null) addPreviousEntries(); } } else if (m_keywordsRadioButton.isSelected()) { // regex is correct, otherwise OK would have been disabled // therefore I don't catch anything here m_resultingGroup = new KeywordGroup( m_name.getText().trim(), m_kgSearchField.getText() .trim(), m_kgSearchTerm.getText().trim(), m_kgCaseSensitive.isSelected(), m_kgRegExp .isSelected(), getContext()); if ((m_editedGroup instanceof ExplicitGroup || m_editedGroup instanceof SearchGroup) && m_resultingGroup.supportsAdd()) { addPreviousEntries(); } } else if (m_searchRadioButton.isSelected()) { try { // regex is correct, otherwise OK would have been // disabled // therefore I don't catch anything here m_resultingGroup = new SearchGroup(m_name.getText() .trim(), m_sgSearchExpression.getText().trim(), m_sgCaseSensitive.isSelected(), m_sgRegExp .isSelected(), getContext()); } catch (Exception e1) { // should never happen } } dispose(); } }); CaretListener caretListener = new CaretListener() { public void caretUpdate(CaretEvent e) { updateComponents(); } }; ItemListener itemListener = new ItemListener() { public void itemStateChanged(ItemEvent e) { updateComponents(); } }; m_name.addCaretListener(caretListener); m_kgSearchField.addCaretListener(caretListener); m_kgSearchTerm.addCaretListener(caretListener); m_kgCaseSensitive.addItemListener(itemListener); m_kgRegExp.addItemListener(itemListener); m_sgSearchExpression.addCaretListener(caretListener); m_sgRegExp.addItemListener(itemListener); m_sgCaseSensitive.addItemListener(itemListener); // configure for current type if (editedGroup instanceof KeywordGroup) { KeywordGroup group = (KeywordGroup) editedGroup; m_name.setText(group.getName()); m_kgSearchField.setText(group.getSearchField()); m_kgSearchTerm.setText(group.getSearchExpression()); m_kgCaseSensitive.setSelected(group.isCaseSensitive()); m_kgRegExp.setSelected(group.isRegExp()); m_keywordsRadioButton.setSelected(true); setContext(editedGroup.getHierarchicalContext()); } else if (editedGroup instanceof SearchGroup) { SearchGroup group = (SearchGroup) editedGroup; m_name.setText(group.getName()); m_sgSearchExpression.setText(group.getSearchExpression()); m_sgCaseSensitive.setSelected(group.isCaseSensitive()); m_sgRegExp.setSelected(group.isRegExp()); m_searchRadioButton.setSelected(true); setContext(editedGroup.getHierarchicalContext()); } else if (editedGroup instanceof ExplicitGroup) { m_name.setText(editedGroup.getName()); m_explicitRadioButton.setSelected(true); setContext(editedGroup.getHierarchicalContext()); } else { // creating new group -> defaults! m_explicitRadioButton.setSelected(true); setContext(AbstractGroup.INDEPENDENT); } } public boolean okPressed() { return m_okPressed; } public AbstractGroup getResultingGroup() { return m_resultingGroup; } private void setLayoutForSelectedGroup() { if (m_explicitRadioButton.isSelected()) m_optionsLayout.show(m_optionsPanel, String .valueOf(INDEX_EXPLICITGROUP)); else if (m_keywordsRadioButton.isSelected()) m_optionsLayout.show(m_optionsPanel, String .valueOf(INDEX_KEYWORDGROUP)); else if (m_searchRadioButton.isSelected()) m_optionsLayout.show(m_optionsPanel, String .valueOf(INDEX_SEARCHGROUP)); } private void updateComponents() { // all groups need a name boolean okEnabled = m_name.getText().trim().length() > 0; if (!okEnabled) { setDescription(Globals.lang("Please enter a name for the group.")); m_ok.setEnabled(false); return; } String s1, s2; if (m_keywordsRadioButton.isSelected()) { s1 = m_kgSearchField.getText().trim(); okEnabled = okEnabled && s1.matches("\\w+"); s2 = m_kgSearchTerm.getText().trim(); okEnabled = okEnabled && s2.length() > 0; if (!okEnabled) { setDescription(Globals .lang("Please enter the field to search (e.g. <b>keywords</b>) and the keyword to search it for (e.g. <b>electrical</b>).")); } else { if (m_kgRegExp.isSelected()) { try { Pattern.compile(s2); setDescription(KeywordGroup.getDescriptionForPreview(s1, s2, m_kgCaseSensitive.isSelected(), m_kgRegExp .isSelected())); } catch (Exception e) { okEnabled = false; setDescription(formatRegExException(s2, e)); } } else { setDescription(KeywordGroup.getDescriptionForPreview(s1, s2, m_kgCaseSensitive.isSelected(), m_kgRegExp .isSelected())); } } setNameFontItalic(true); } else if (m_searchRadioButton.isSelected()) { s1 = m_sgSearchExpression.getText().trim(); okEnabled = okEnabled & s1.length() > 0; if (!okEnabled) { setDescription(Globals .lang("Please enter a search term. For example, to search all fields for <b>Smith</b>, enter%c<p>" + "<tt>smith</tt><p>" + "To search the field <b>Author</b> for <b>Smith</b> and the field <b>Title</b> for <b>electrical</b>, enter%c<p>" + "<tt>author%esmith and title%eelectrical</tt>")); } else { AST ast = SearchExpressionParser .checkSyntax(s1, m_sgCaseSensitive.isSelected(), m_sgRegExp.isSelected()); setDescription(SearchGroup.getDescriptionForPreview(s1, ast, m_sgCaseSensitive.isSelected(), m_sgRegExp.isSelected())); if (m_sgRegExp.isSelected()) { try { Pattern.compile(s1); } catch (Exception e) { okEnabled = false; setDescription(formatRegExException(s1, e)); } } } setNameFontItalic(true); } else if (m_explicitRadioButton.isSelected()) { setDescription(ExplicitGroup.getDescriptionForPreview()); setNameFontItalic(false); } m_ok.setEnabled(okEnabled); } /** * This is used when a group is converted and the new group supports * explicit adding of entries: All entries that match the previous group are * added to the new group. */ private void addPreviousEntries() { // JZTODO lyrics... int i = JOptionPane.showConfirmDialog(m_basePanel.frame(), Globals .lang("Assign the original group's entries to this group?"), Globals.lang("Change of Grouping Method"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (i == JOptionPane.NO_OPTION) return; BibtexEntry entry; Vector vec = new Vector(); for (Iterator it = m_basePanel.database().getEntries().iterator(); it .hasNext();) { entry = (BibtexEntry) it.next(); if (m_editedGroup.contains(entry)) vec.add(entry); } if (vec.size() > 0) { BibtexEntry[] entries = new BibtexEntry[vec.size()]; vec.toArray(entries); if (!Util.warnAssignmentSideEffects(new AbstractGroup[]{m_resultingGroup}, entries, m_basePanel.getDatabase(), this)) return; // the undo information for a conversion to an ExplicitGroup is // contained completely in the UndoableModifyGroup object. if (!(m_resultingGroup instanceof ExplicitGroup)) m_undoAddPreviousEntires = m_resultingGroup.add(entries); } } protected void setDescription(String description) { m_description.setText("<html>" + description + "</html>"); } protected String formatRegExException(String regExp, Exception e) { String s = Globals.lang( "The regular expression <b>%0</b> is invalid%c", regExp) + "<p><tt>" + e.getMessage().replaceAll("\\n", "<br>") + "</tt>"; if (!(e instanceof PatternSyntaxException)) return s; int lastNewline = s.lastIndexOf("<br>"); int hat = s.lastIndexOf("^"); if (lastNewline >= 0 && hat >= 0 && hat > lastNewline) return s.substring(0, lastNewline + 4) + s.substring(lastNewline + 4).replaceAll(" ", "&nbsp;"); return s; } /** * Returns an undo object for adding the edited group's entries to the new * group, or null if this did not occur. */ public AbstractUndoableEdit getUndoForAddPreviousEntries() { return m_undoAddPreviousEntires; } /** Sets the font of the name entry field. */ protected void setNameFontItalic(boolean italic) { Font f = m_name.getFont(); if (f.isItalic() != italic) { f = f.deriveFont(italic ? Font.ITALIC : Font.PLAIN); m_name.setFont(f); } } /** * Returns the int representing the selected hierarchical group context. */ protected int getContext() { if (m_independentButton.isSelected()) return AbstractGroup.INDEPENDENT; if (m_intersectionButton.isSelected()) return AbstractGroup.REFINING; if (m_unionButton.isSelected()) return AbstractGroup.INCLUDING; return AbstractGroup.INDEPENDENT; // default } protected void setContext(int context) { switch (context) { case AbstractGroup.REFINING: m_intersectionButton.setSelected(true); return; case AbstractGroup.INCLUDING: m_unionButton.setSelected(true); return; case AbstractGroup.INDEPENDENT: default: m_independentButton.setSelected(true); return; } } }
package org.dynmap.bukkit; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.Future; import org.bukkit.ChatColor; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockBurnEvent; import org.bukkit.event.block.BlockFadeEvent; import org.bukkit.event.block.BlockFormEvent; import org.bukkit.event.block.BlockFromToEvent; import org.bukkit.event.block.BlockGrowEvent; import org.bukkit.event.block.BlockPhysicsEvent; import org.bukkit.event.block.BlockPistonExtendEvent; import org.bukkit.event.block.BlockPistonRetractEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.BlockRedstoneEvent; import org.bukkit.event.block.BlockSpreadEvent; import org.bukkit.event.block.LeavesDecayEvent; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerBedLeaveEvent; import org.bukkit.event.player.PlayerChatEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.world.ChunkPopulateEvent; import org.bukkit.event.world.SpawnChangeEvent; import org.bukkit.event.world.StructureGrowEvent; import org.bukkit.event.world.WorldLoadEvent; import org.bukkit.event.world.WorldUnloadEvent; import org.bukkit.material.MaterialData; import org.bukkit.material.Tree; import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionDefault; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import org.dynmap.DynmapAPI; import org.dynmap.DynmapChunk; import org.dynmap.DynmapCore; import org.dynmap.DynmapLocation; import org.dynmap.DynmapWebChatEvent; import org.dynmap.DynmapWorld; import org.dynmap.Log; import org.dynmap.MapManager; import org.dynmap.MapType; import org.dynmap.PlayerList; import org.dynmap.bukkit.permissions.BukkitPermissions; import org.dynmap.bukkit.permissions.NijikokunPermissions; import org.dynmap.bukkit.permissions.OpPermissions; import org.dynmap.bukkit.permissions.PEXPermissions; import org.dynmap.bukkit.permissions.PermBukkitPermissions; import org.dynmap.bukkit.permissions.PermissionProvider; import org.dynmap.bukkit.permissions.bPermPermissions; import org.dynmap.common.BiomeMap; import org.dynmap.common.DynmapCommandSender; import org.dynmap.common.DynmapPlayer; import org.dynmap.common.DynmapServerInterface; import org.dynmap.common.DynmapListenerManager.EventType; import org.dynmap.hdmap.HDMap; import org.dynmap.markers.MarkerAPI; import org.dynmap.utils.MapChunkCache; public class DynmapPlugin extends JavaPlugin implements DynmapAPI { private DynmapCore core; private PermissionProvider permissions; private String version; public SnapshotCache sscache; private boolean has_spout = false; public PlayerList playerList; private MapManager mapManager; public static DynmapPlugin plugin; public SpoutPluginBlocks spb; public PluginManager pm; private Metrics metrics; private class BukkitEnableCoreCallback extends DynmapCore.EnableCoreCallbacks { @Override public void configurationLoaded() { /* Check for Spout */ if(detectSpout()) { if(core.configuration.getBoolean("spout/enabled", true)) { has_spout = true; Log.info("Detected Spout"); spb = new SpoutPluginBlocks(); spb.processSpoutBlocks(DynmapPlugin.this, core); } else { Log.info("Detected Spout - Support Disabled"); } } if(!has_spout) { /* If not, clean up old spout texture, if needed */ File st = new File(core.getDataFolder(), "renderdata/spout-texture.txt"); if(st.exists()) st.delete(); } } } private static class BlockToCheck { Location loc; int typeid; byte data; String trigger; }; private LinkedList<BlockToCheck> blocks_to_check = null; private LinkedList<BlockToCheck> blocks_to_check_accum = new LinkedList<BlockToCheck>(); public DynmapPlugin() { plugin = this; } /** * Server access abstraction class */ public class BukkitServer implements DynmapServerInterface { /* Chunk load handling */ private Object loadlock = new Object(); private int chunks_in_cur_tick = 0; private long cur_tick; @Override public void scheduleServerTask(Runnable run, long delay) { getServer().getScheduler().scheduleSyncDelayedTask(DynmapPlugin.this, run, delay); } @Override public DynmapPlayer[] getOnlinePlayers() { Player[] players = getServer().getOnlinePlayers(); DynmapPlayer[] dplay = new DynmapPlayer[players.length]; for(int i = 0; i < players.length; i++) dplay[i] = new BukkitPlayer(players[i]); return dplay; } @Override public void reload() { PluginManager pluginManager = getServer().getPluginManager(); pluginManager.disablePlugin(DynmapPlugin.this); pluginManager.enablePlugin(DynmapPlugin.this); } @Override public DynmapPlayer getPlayer(String name) { Player p = getServer().getPlayerExact(name); if(p != null) { return new BukkitPlayer(p); } return null; } @Override public Set<String> getIPBans() { return getServer().getIPBans(); } @Override public <T> Future<T> callSyncMethod(Callable<T> task) { return getServer().getScheduler().callSyncMethod(DynmapPlugin.this, task); } @Override public String getServerName() { return getServer().getServerName(); } @Override public boolean isPlayerBanned(String pid) { OfflinePlayer p = getServer().getOfflinePlayer(pid); if((p != null) && p.isBanned()) return true; return false; } @Override public String stripChatColor(String s) { return ChatColor.stripColor(s); } private Set<EventType> registered = new HashSet<EventType>(); @Override public boolean requestEventNotification(EventType type) { if(registered.contains(type)) return true; switch(type) { case WORLD_LOAD: case WORLD_UNLOAD: /* Already called for normal world activation/deactivation */ break; case WORLD_SPAWN_CHANGE: pm.registerEvents(new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onSpawnChange(SpawnChangeEvent evt) { DynmapWorld w = new BukkitWorld(evt.getWorld()); core.listenerManager.processWorldEvent(EventType.WORLD_SPAWN_CHANGE, w); } }, DynmapPlugin.this); break; case PLAYER_JOIN: case PLAYER_QUIT: /* Already handled */ break; case PLAYER_BED_LEAVE: pm.registerEvents(new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onPlayerBedLeave(PlayerBedLeaveEvent evt) { DynmapPlayer p = new BukkitPlayer(evt.getPlayer()); core.listenerManager.processPlayerEvent(EventType.PLAYER_BED_LEAVE, p); } }, DynmapPlugin.this); break; case PLAYER_CHAT: try { Class.forName("org.bukkit.event.player.AsyncPlayerChatEvent"); pm.registerEvents(new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onPlayerChat(AsyncPlayerChatEvent evt) { if(evt.isCancelled()) return; final Player p = evt.getPlayer(); final String msg = evt.getMessage(); getServer().getScheduler().scheduleSyncDelayedTask(DynmapPlugin.this, new Runnable() { public void run() { DynmapPlayer dp = null; if(p != null) dp = new BukkitPlayer(p); core.listenerManager.processChatEvent(EventType.PLAYER_CHAT, dp, msg); } }); } }, DynmapPlugin.this); } catch (ClassNotFoundException cnfx) { pm.registerEvents(new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onPlayerChat(PlayerChatEvent evt) { if(evt.isCancelled()) return; DynmapPlayer p = null; if(evt.getPlayer() != null) p = new BukkitPlayer(evt.getPlayer()); core.listenerManager.processChatEvent(EventType.PLAYER_CHAT, p, evt.getMessage()); } }, DynmapPlugin.this); } break; case BLOCK_BREAK: pm.registerEvents(new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onBlockBreak(BlockBreakEvent evt) { if(evt.isCancelled()) return; Block b = evt.getBlock(); if(b == null) return; /* Work around for stupid mods.... */ Location l = b.getLocation(); core.listenerManager.processBlockEvent(EventType.BLOCK_BREAK, b.getType().getId(), BukkitWorld.normalizeWorldName(l.getWorld().getName()), l.getBlockX(), l.getBlockY(), l.getBlockZ()); } }, DynmapPlugin.this); break; case SIGN_CHANGE: pm.registerEvents(new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onSignChange(SignChangeEvent evt) { if(evt.isCancelled()) return; Block b = evt.getBlock(); Location l = b.getLocation(); String[] lines = evt.getLines(); /* Note: changes to this change event - intentional */ DynmapPlayer dp = null; Player p = evt.getPlayer(); if(p != null) dp = new BukkitPlayer(p); core.listenerManager.processSignChangeEvent(EventType.SIGN_CHANGE, b.getType().getId(), BukkitWorld.normalizeWorldName(l.getWorld().getName()), l.getBlockX(), l.getBlockY(), l.getBlockZ(), lines, dp); } }, DynmapPlugin.this); break; default: Log.severe("Unhandled event type: " + type); return false; } registered.add(type); return true; } @Override public boolean sendWebChatEvent(String source, String name, String msg) { DynmapWebChatEvent evt = new DynmapWebChatEvent(source, name, msg); getServer().getPluginManager().callEvent(evt); return ((evt.isCancelled() == false) && (evt.isProcessed() == false)); } @Override public void broadcastMessage(String msg) { getServer().broadcastMessage(msg); } @Override public String[] getBiomeIDs() { BiomeMap[] b = BiomeMap.values(); String[] bname = new String[b.length]; for(int i = 0; i < bname.length; i++) bname[i] = b[i].toString(); return bname; } @Override public double getCacheHitRate() { return sscache.getHitRate(); } @Override public void resetCacheStats() { sscache.resetStats(); } @Override public DynmapWorld getWorldByName(String wname) { World w = getServer().getWorld(wname); /* FInd world */ if(w != null) { return new BukkitWorld(w); } return null; } @Override public DynmapPlayer getOfflinePlayer(String name) { OfflinePlayer op = getServer().getOfflinePlayer(name); if(op != null) { return new BukkitPlayer(op); } return null; } @Override public Set<String> checkPlayerPermissions(String player, Set<String> perms) { OfflinePlayer p = getServer().getOfflinePlayer(player); if(p.isBanned()) return new HashSet<String>(); Set<String> rslt = permissions.hasOfflinePermissions(player, perms); if (rslt == null) { rslt = new HashSet<String>(); if(p.isOp()) { rslt.addAll(perms); } } return rslt; } @Override public boolean checkPlayerPermission(String player, String perm) { OfflinePlayer p = getServer().getOfflinePlayer(player); if(p.isBanned()) return false; return permissions.hasOfflinePermission(player, perm); } /** * Render processor helper - used by code running on render threads to request chunk snapshot cache from server/sync thread */ @Override public MapChunkCache createMapChunkCache(DynmapWorld w, List<DynmapChunk> chunks, boolean blockdata, boolean highesty, boolean biome, boolean rawbiome) { MapChunkCache c = w.getChunkCache(chunks); if(w.visibility_limits != null) { for(MapChunkCache.VisibilityLimit limit: w.visibility_limits) { c.setVisibleRange(limit); } c.setHiddenFillStyle(w.hiddenchunkstyle); c.setAutoGenerateVisbileRanges(w.do_autogenerate); } if(w.hidden_limits != null) { for(MapChunkCache.VisibilityLimit limit: w.hidden_limits) { c.setHiddenRange(limit); } c.setHiddenFillStyle(w.hiddenchunkstyle); } if(c.setChunkDataTypes(blockdata, biome, highesty, rawbiome) == false) { Log.severe("CraftBukkit build does not support biome APIs"); } if(chunks.size() == 0) { /* No chunks to get? */ c.loadChunks(0); return c; } final MapChunkCache cc = c; while(!cc.isDoneLoading()) { synchronized(loadlock) { long now = System.currentTimeMillis(); if(cur_tick != (now/50)) { /* New tick? */ chunks_in_cur_tick = mapManager.getMaxChunkLoadsPerTick(); cur_tick = now/50; } } Future<Boolean> f = core.getServer().callSyncMethod(new Callable<Boolean>() { public Boolean call() throws Exception { boolean exhausted; synchronized(loadlock) { if(chunks_in_cur_tick > 0) chunks_in_cur_tick -= cc.loadChunks(chunks_in_cur_tick); exhausted = (chunks_in_cur_tick == 0); } return exhausted; } }); Boolean delay; try { delay = f.get(); } catch (Exception ix) { Log.severe(ix); return null; } if((delay != null) && delay.booleanValue()) { try { Thread.sleep(25); } catch (InterruptedException ix) {} } } return c; } @Override public int getMaxPlayers() { return getServer().getMaxPlayers(); } @Override public int getCurrentPlayers() { return getServer().getOnlinePlayers().length; } } /** * Player access abstraction class */ public class BukkitPlayer extends BukkitCommandSender implements DynmapPlayer { private Player player; private OfflinePlayer offplayer; public BukkitPlayer(Player p) { super(p); player = p; offplayer = p.getPlayer(); } public BukkitPlayer(OfflinePlayer p) { super(null); offplayer = p; } @Override public boolean isConnected() { return offplayer.isOnline(); } @Override public String getName() { return offplayer.getName(); } @Override public String getDisplayName() { if(player != null) return player.getDisplayName(); else return offplayer.getName(); } @Override public boolean isOnline() { return offplayer.isOnline(); } @Override public DynmapLocation getLocation() { if(player == null) { return null; } Location loc = player.getEyeLocation(); // Use eye location, since we show head return toLoc(loc); } @Override public String getWorld() { if(player == null) { return null; } World w = player.getWorld(); if(w != null) return BukkitWorld.normalizeWorldName(w.getName()); return null; } @Override public InetSocketAddress getAddress() { if(player != null) return player.getAddress(); return null; } @Override public boolean isSneaking() { if(player != null) return player.isSneaking(); return false; } @Override public int getHealth() { if(player != null) return player.getHealth(); else return 0; } @Override public int getArmorPoints() { if(player != null) return Armor.getArmorPoints(player); else return 0; } @Override public DynmapLocation getBedSpawnLocation() { Location loc = offplayer.getBedSpawnLocation(); if(loc != null) { return toLoc(loc); } return null; } @Override public long getLastLoginTime() { return offplayer.getLastPlayed(); } @Override public long getFirstLoginTime() { return offplayer.getFirstPlayed(); } } /* Handler for generic console command sender */ public class BukkitCommandSender implements DynmapCommandSender { private CommandSender sender; public BukkitCommandSender(CommandSender send) { sender = send; } @Override public boolean hasPrivilege(String privid) { if(sender != null) return permissions.has(sender, privid); return false; } @Override public void sendMessage(String msg) { if(sender != null) sender.sendMessage(msg); } @Override public boolean isConnected() { if(sender != null) return true; return false; } @Override public boolean isOp() { if(sender != null) return sender.isOp(); else return false; } } @Override public void onEnable() { pm = this.getServer().getPluginManager(); PluginDescriptionFile pdfFile = this.getDescription(); version = pdfFile.getVersion(); /* Set up player login/quit event handler */ registerPlayerLoginListener(); Map<String, Boolean> perdefs = new HashMap<String, Boolean>(); List<Permission> pd = plugin.getDescription().getPermissions(); for(Permission p : pd) { perdefs.put(p.getName(), p.getDefault() == PermissionDefault.TRUE); } permissions = PEXPermissions.create(getServer(), "dynmap"); if (permissions == null) permissions = bPermPermissions.create(getServer(), "dynmap", perdefs); if (permissions == null) permissions = PermBukkitPermissions.create(getServer(), "dynmap", perdefs); if (permissions == null) permissions = NijikokunPermissions.create(getServer(), "dynmap"); if (permissions == null) permissions = BukkitPermissions.create("dynmap", perdefs); if (permissions == null) permissions = new OpPermissions(new String[] { "fullrender", "cancelrender", "radiusrender", "resetstats", "reload", "purgequeue", "pause", "ips-for-id", "ids-for-ip", "add-id-for-ip", "del-id-for-ip" }); /* Get and initialize data folder */ File dataDirectory = this.getDataFolder(); if(dataDirectory.exists() == false) dataDirectory.mkdirs(); /* Get MC version */ String bukkitver = getServer().getVersion(); String mcver = "1.0.0"; int idx = bukkitver.indexOf("(MC: "); if(idx > 0) { mcver = bukkitver.substring(idx+5); idx = mcver.indexOf(")"); if(idx > 0) mcver = mcver.substring(0, idx); } /* Instantiate core */ if(core == null) core = new DynmapCore(); /* Inject dependencies */ core.setPluginVersion(version); core.setMinecraftVersion(mcver); core.setDataFolder(dataDirectory); core.setServer(new BukkitServer()); /* Enable core */ if(!core.enableCore(new BukkitEnableCoreCallback())) { this.setEnabled(false); return; } playerList = core.playerList; sscache = new SnapshotCache(core.getSnapShotCacheSize()); /* Get map manager from core */ mapManager = core.getMapManager(); /* Initialized the currently loaded worlds */ for (World world : getServer().getWorlds()) { BukkitWorld w = new BukkitWorld(world); if(core.processWorldLoad(w)) /* Have core process load first - fire event listeners if good load after */ core.listenerManager.processWorldEvent(EventType.WORLD_LOAD, w); } /* Register our update trigger events */ registerEvents(); /* Submit metrics to mcstats.org */ initMetrics(); Log.info("Enabled"); } @Override public void onDisable() { if (metrics != null) { metrics = null; } /* Disable core */ core.disableCore(); if(sscache != null) { sscache.cleanup(); sscache = null; } Log.info("Disabled"); } @Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { DynmapCommandSender dsender; if(sender instanceof Player) { dsender = new BukkitPlayer((Player)sender); } else { dsender = new BukkitCommandSender(sender); } return core.processCommand(dsender, cmd.getName(), commandLabel, args); } @Override public final MarkerAPI getMarkerAPI() { return core.getMarkerAPI(); } @Override public final boolean markerAPIInitialized() { return core.markerAPIInitialized(); } @Override public final boolean sendBroadcastToWeb(String sender, String msg) { return core.sendBroadcastToWeb(sender, msg); } @Override public final int triggerRenderOfVolume(String wid, int minx, int miny, int minz, int maxx, int maxy, int maxz) { return core.triggerRenderOfVolume(wid, minx, miny, minz, maxx, maxy, maxz); } @Override public final int triggerRenderOfBlock(String wid, int x, int y, int z) { return core.triggerRenderOfBlock(wid, x, y, z); } @Override public final void setPauseFullRadiusRenders(boolean dopause) { core.setPauseFullRadiusRenders(dopause); } @Override public final boolean getPauseFullRadiusRenders() { return core.getPauseFullRadiusRenders(); } @Override public final void setPauseUpdateRenders(boolean dopause) { core.setPauseUpdateRenders(dopause); } @Override public final boolean getPauseUpdateRenders() { return core.getPauseUpdateRenders(); } @Override public final void setPlayerVisiblity(String player, boolean is_visible) { core.setPlayerVisiblity(player, is_visible); } @Override public final boolean getPlayerVisbility(String player) { return core.getPlayerVisbility(player); } @Override public final void postPlayerMessageToWeb(String playerid, String playerdisplay, String message) { core.postPlayerMessageToWeb(playerid, playerdisplay, message); } @Override public final void postPlayerJoinQuitToWeb(String playerid, String playerdisplay, boolean isjoin) { core.postPlayerJoinQuitToWeb(playerid, playerdisplay, isjoin); } @Override public final String getDynmapCoreVersion() { return core.getDynmapCoreVersion(); } @Override public final int triggerRenderOfVolume(Location l0, Location l1) { int x0 = l0.getBlockX(), y0 = l0.getBlockY(), z0 = l0.getBlockZ(); int x1 = l1.getBlockX(), y1 = l1.getBlockY(), z1 = l1.getBlockZ(); return core.triggerRenderOfVolume(BukkitWorld.normalizeWorldName(l0.getWorld().getName()), Math.min(x0, x1), Math.min(y0, y1), Math.min(z0, z1), Math.max(x0, x1), Math.max(y0, y1), Math.max(z0, z1)); } @Override public final void setPlayerVisiblity(Player player, boolean is_visible) { core.setPlayerVisiblity(player.getName(), is_visible); } @Override public final boolean getPlayerVisbility(Player player) { return core.getPlayerVisbility(player.getName()); } @Override public final void postPlayerMessageToWeb(Player player, String message) { core.postPlayerMessageToWeb(player.getName(), player.getDisplayName(), message); } @Override public void postPlayerJoinQuitToWeb(Player player, boolean isjoin) { core.postPlayerJoinQuitToWeb(player.getName(), player.getDisplayName(), isjoin); } @Override public String getDynmapVersion() { return version; } private static DynmapLocation toLoc(Location l) { return new DynmapLocation(DynmapWorld.normalizeWorldName(l.getWorld().getName()), l.getBlockX(), l.getBlockY(), l.getBlockZ()); } private void registerPlayerLoginListener() { Listener pl = new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onPlayerJoin(PlayerJoinEvent evt) { DynmapPlayer dp = new BukkitPlayer(evt.getPlayer()); core.listenerManager.processPlayerEvent(EventType.PLAYER_JOIN, dp); } @EventHandler(priority=EventPriority.MONITOR) public void onPlayerQuit(PlayerQuitEvent evt) { DynmapPlayer dp = new BukkitPlayer(evt.getPlayer()); core.listenerManager.processPlayerEvent(EventType.PLAYER_QUIT, dp); } }; pm.registerEvents(pl, this); } private class BlockCheckHandler implements Runnable { public void run() { BlockToCheck btt; while(blocks_to_check.isEmpty() != true) { btt = blocks_to_check.pop(); Location loc = btt.loc; World w = loc.getWorld(); if(!w.isChunkLoaded(loc.getBlockX()>>4, loc.getBlockZ()>>4)) continue; int bt = w.getBlockTypeIdAt(loc); /* Avoid stationary and moving water churn */ if(bt == 9) bt = 8; if(btt.typeid == 9) btt.typeid = 8; if((bt != btt.typeid) || (btt.data != w.getBlockAt(loc).getData())) { String wn = BukkitWorld.normalizeWorldName(w.getName()); sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), btt.trigger); } } blocks_to_check = null; /* Kick next run, if one is needed */ startIfNeeded(); } public void startIfNeeded() { if((blocks_to_check == null) && (blocks_to_check_accum.isEmpty() == false)) { /* More pending? */ blocks_to_check = blocks_to_check_accum; blocks_to_check_accum = new LinkedList<BlockToCheck>(); getServer().getScheduler().scheduleSyncDelayedTask(DynmapPlugin.this, this, 10); } } } private BlockCheckHandler btth = new BlockCheckHandler(); private void checkBlock(Block b, String trigger) { BlockToCheck btt = new BlockToCheck(); btt.loc = b.getLocation(); btt.typeid = b.getTypeId(); btt.data = b.getData(); btt.trigger = trigger; blocks_to_check_accum.add(btt); /* Add to accumulator */ btth.startIfNeeded(); } private boolean onplace; private boolean onbreak; private boolean onblockform; private boolean onblockfade; private boolean onblockspread; private boolean onblockfromto; private boolean onblockphysics; private boolean onleaves; private boolean onburn; private boolean onpiston; private boolean onplayerjoin; private boolean onplayermove; private boolean ongeneratechunk; private boolean onexplosion; private boolean onstructuregrow; private boolean onblockgrow; private boolean onblockredstone; private void registerEvents() { // To trigger rendering. onplace = core.isTrigger("blockplaced"); onbreak = core.isTrigger("blockbreak"); onleaves = core.isTrigger("leavesdecay"); onburn = core.isTrigger("blockburn"); onblockform = core.isTrigger("blockformed"); onblockfade = core.isTrigger("blockfaded"); onblockspread = core.isTrigger("blockspread"); onblockfromto = core.isTrigger("blockfromto"); onblockphysics = core.isTrigger("blockphysics"); onpiston = core.isTrigger("pistonmoved"); onblockfade = core.isTrigger("blockfaded"); onblockredstone = core.isTrigger("blockredstone"); if(onplace) { Listener placelistener = new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onBlockPlace(BlockPlaceEvent event) { if(event.isCancelled()) return; Location loc = event.getBlock().getLocation(); String wn = BukkitWorld.normalizeWorldName(loc.getWorld().getName()); sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockplace"); } }; pm.registerEvents(placelistener, this); } if(onbreak) { Listener breaklistener = new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onBlockBreak(BlockBreakEvent event) { if(event.isCancelled()) return; Block b = event.getBlock(); if(b == null) return; /* Stupid mod workaround */ Location loc = b.getLocation(); String wn = BukkitWorld.normalizeWorldName(loc.getWorld().getName()); sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockbreak"); } }; pm.registerEvents(breaklistener, this); } if(onleaves) { Listener leaveslistener = new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onLeavesDecay(LeavesDecayEvent event) { if(event.isCancelled()) return; Location loc = event.getBlock().getLocation(); String wn = BukkitWorld.normalizeWorldName(loc.getWorld().getName()); sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); if(onleaves) { mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "leavesdecay"); } } }; pm.registerEvents(leaveslistener, this); } if(onburn) { Listener burnlistener = new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onBlockBurn(BlockBurnEvent event) { if(event.isCancelled()) return; Location loc = event.getBlock().getLocation(); String wn = BukkitWorld.normalizeWorldName(loc.getWorld().getName()); sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); if(onburn) { mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockburn"); } } }; pm.registerEvents(burnlistener, this); } if(onblockphysics) { Listener physlistener = new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onBlockPhysics(BlockPhysicsEvent event) { if(event.isCancelled()) return; Block b = event.getBlock(); Material m = b.getType(); if(m == null) return; switch(m) { case STATIONARY_WATER: case WATER: case STATIONARY_LAVA: case LAVA: case GRAVEL: case SAND: checkBlock(b, "blockphysics"); break; default: break; } } }; pm.registerEvents(physlistener, this); } if(onblockfromto) { Listener fromtolistener = new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onBlockFromTo(BlockFromToEvent event) { if(event.isCancelled()) return; Block b = event.getBlock(); Material m = b.getType(); if((m != Material.WOOD_PLATE) && (m != Material.STONE_PLATE) && (m != null)) checkBlock(b, "blockfromto"); b = event.getToBlock(); m = b.getType(); if((m != Material.WOOD_PLATE) && (m != Material.STONE_PLATE) && (m != null)) checkBlock(b, "blockfromto"); } }; pm.registerEvents(fromtolistener, this); } if(onpiston) { Listener pistonlistener = new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onBlockPistonRetract(BlockPistonRetractEvent event) { if(event.isCancelled()) return; Block b = event.getBlock(); Location loc = b.getLocation(); BlockFace dir; try { dir = event.getDirection(); } catch (ClassCastException ccx) { dir = BlockFace.NORTH; } String wn = BukkitWorld.normalizeWorldName(loc.getWorld().getName()); int x = loc.getBlockX(), y = loc.getBlockY(), z = loc.getBlockZ(); sscache.invalidateSnapshot(wn, x, y, z); if(onpiston) mapManager.touch(wn, x, y, z, "pistonretract"); for(int i = 0; i < 2; i++) { x += dir.getModX(); y += dir.getModY(); z += dir.getModZ(); sscache.invalidateSnapshot(wn, x, y, z); mapManager.touch(wn, x, y, z, "pistonretract"); } } @EventHandler(priority=EventPriority.MONITOR) public void onBlockPistonExtend(BlockPistonExtendEvent event) { if(event.isCancelled()) return; Block b = event.getBlock(); Location loc = b.getLocation(); BlockFace dir; try { dir = event.getDirection(); } catch (ClassCastException ccx) { dir = BlockFace.NORTH; } String wn = BukkitWorld.normalizeWorldName(loc.getWorld().getName()); int x = loc.getBlockX(), y = loc.getBlockY(), z = loc.getBlockZ(); sscache.invalidateSnapshot(wn, x, y, z); if(onpiston) mapManager.touch(wn, x, y, z, "pistonretract"); for(int i = 0; i < 1+event.getLength(); i++) { x += dir.getModX(); y += dir.getModY(); z += dir.getModZ(); sscache.invalidateSnapshot(wn, x, y, z); mapManager.touch(wn, x, y, z, "pistonretract"); } } }; pm.registerEvents(pistonlistener, this); } if(onblockspread) { Listener spreadlistener = new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onBlockSpread(BlockSpreadEvent event) { if(event.isCancelled()) return; Location loc = event.getBlock().getLocation(); String wn = BukkitWorld.normalizeWorldName(loc.getWorld().getName()); sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockspread"); } }; pm.registerEvents(spreadlistener, this); } if(onblockform) { Listener formlistener = new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onBlockForm(BlockFormEvent event) { if(event.isCancelled()) return; Location loc = event.getBlock().getLocation(); String wn = BukkitWorld.normalizeWorldName(loc.getWorld().getName()); sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockform"); } }; pm.registerEvents(formlistener, this); } if(onblockfade) { Listener fadelistener = new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onBlockFade(BlockFadeEvent event) { if(event.isCancelled()) return; Location loc = event.getBlock().getLocation(); String wn = BukkitWorld.normalizeWorldName(loc.getWorld().getName()); sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockfade"); } }; pm.registerEvents(fadelistener, this); } onblockgrow = core.isTrigger("blockgrow"); if(onblockgrow) { try { Class.forName("org.bukkit.event.block.BlockGrowEvent"); Listener growTrigger = new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onBlockGrow(BlockGrowEvent event) { if(event.isCancelled()) return; Location loc = event.getBlock().getLocation(); String wn = BukkitWorld.normalizeWorldName(loc.getWorld().getName()); sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockgrow"); } }; pm.registerEvents(growTrigger, this); } catch (ClassNotFoundException cnfx) { /* Pre-R5 - no grow event yet */ } } if(onblockredstone) { Listener redstoneTrigger = new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onBlockRedstone(BlockRedstoneEvent event) { Location loc = event.getBlock().getLocation(); String wn = BukkitWorld.normalizeWorldName(loc.getWorld().getName()); sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockredstone"); } }; pm.registerEvents(redstoneTrigger, this); } /* Register player event trigger handlers */ Listener playerTrigger = new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onPlayerJoin(PlayerJoinEvent event) { if(onplayerjoin) { Location loc = event.getPlayer().getLocation(); mapManager.touch(BukkitWorld.normalizeWorldName(loc.getWorld().getName()), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "playerjoin"); } } }; onplayerjoin = core.isTrigger("playerjoin"); onplayermove = core.isTrigger("playermove"); pm.registerEvents(playerTrigger, this); if(onplayermove) { Listener playermove = new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onPlayerMove(PlayerMoveEvent event) { Location loc = event.getPlayer().getLocation(); mapManager.touch(BukkitWorld.normalizeWorldName(loc.getWorld().getName()), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "playermove"); } }; pm.registerEvents(playermove, this); Log.warning("playermove trigger enabled - this trigger can cause excessive tile updating: use with caution"); } /* Register entity event triggers */ Listener entityTrigger = new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onEntityExplode(EntityExplodeEvent event) { Location loc = event.getLocation(); String wname = BukkitWorld.normalizeWorldName(loc.getWorld().getName()); int minx, maxx, miny, maxy, minz, maxz; minx = maxx = loc.getBlockX(); miny = maxy = loc.getBlockY(); minz = maxz = loc.getBlockZ(); /* Calculate volume impacted by explosion */ List<Block> blocks = event.blockList(); for(Block b: blocks) { Location l = b.getLocation(); int x = l.getBlockX(); if(x < minx) minx = x; if(x > maxx) maxx = x; int y = l.getBlockY(); if(y < miny) miny = y; if(y > maxy) maxy = y; int z = l.getBlockZ(); if(z < minz) minz = z; if(z > maxz) maxz = z; } sscache.invalidateSnapshot(wname, minx, miny, minz, maxx, maxy, maxz); if(onexplosion) { mapManager.touchVolume(wname, minx, miny, minz, maxx, maxy, maxz, "entityexplode"); } } }; onexplosion = core.isTrigger("explosion"); pm.registerEvents(entityTrigger, this); /* Register world event triggers */ Listener worldTrigger = new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onWorldLoad(WorldLoadEvent event) { core.updateConfigHashcode(); BukkitWorld w = new BukkitWorld(event.getWorld()); if(core.processWorldLoad(w)) /* Have core process load first - fire event listeners if good load after */ core.listenerManager.processWorldEvent(EventType.WORLD_LOAD, w); } @EventHandler(priority=EventPriority.MONITOR) public void onWorldUnload(WorldUnloadEvent event) { core.updateConfigHashcode(); DynmapWorld w = core.getWorld(BukkitWorld.normalizeWorldName(event.getWorld().getName())); if(w != null) core.listenerManager.processWorldEvent(EventType.WORLD_UNLOAD, w); } @EventHandler(priority=EventPriority.MONITOR) public void onStructureGrow(StructureGrowEvent event) { Location loc = event.getLocation(); String wname = BukkitWorld.normalizeWorldName(loc.getWorld().getName()); int minx, maxx, miny, maxy, minz, maxz; minx = maxx = loc.getBlockX(); miny = maxy = loc.getBlockY(); minz = maxz = loc.getBlockZ(); /* Calculate volume impacted by explosion */ List<BlockState> blocks = event.getBlocks(); for(BlockState b: blocks) { int x = b.getX(); if(x < minx) minx = x; if(x > maxx) maxx = x; int y = b.getY(); if(y < miny) miny = y; if(y > maxy) maxy = y; int z = b.getZ(); if(z < minz) minz = z; if(z > maxz) maxz = z; } sscache.invalidateSnapshot(wname, minx, miny, minz, maxx, maxy, maxz); if(onstructuregrow) { mapManager.touchVolume(wname, minx, miny, minz, maxx, maxy, maxz, "structuregrow"); } } }; onstructuregrow = core.isTrigger("structuregrow"); // To link configuration to real loaded worlds. pm.registerEvents(worldTrigger, this); ongeneratechunk = core.isTrigger("chunkgenerated"); if(ongeneratechunk) { Listener chunkTrigger = new Listener() { @EventHandler(priority=EventPriority.MONITOR) public void onChunkPopulate(ChunkPopulateEvent event) { Chunk c = event.getChunk(); /* Touch extreme corners */ int x = c.getX() << 4; int z = c.getZ() << 4; mapManager.touchVolume(BukkitWorld.normalizeWorldName(event.getWorld().getName()), x, 0, z, x+15, 128, z+16, "chunkpopulate"); } }; pm.registerEvents(chunkTrigger, this); } } private boolean detectSpout() { Plugin p = this.getServer().getPluginManager().getPlugin("Spout"); if(p != null) { return p.isEnabled(); } return false; } public boolean hasSpout() { return has_spout; } @Override public void assertPlayerInvisibility(String player, boolean is_invisible, String plugin_id) { core.assertPlayerInvisibility(player, is_invisible, plugin_id); } @Override public void assertPlayerInvisibility(Player player, boolean is_invisible, Plugin plugin) { core.assertPlayerInvisibility(player.getName(), is_invisible, plugin.getDescription().getName()); } @Override public void assertPlayerVisibility(String player, boolean is_visible, String plugin_id) { core.assertPlayerVisibility(player, is_visible, plugin_id); } @Override public void assertPlayerVisibility(Player player, boolean is_visible, Plugin plugin) { core.assertPlayerVisibility(player.getName(), is_visible, plugin.getDescription().getName()); } @Override public boolean setDisableChatToWebProcessing(boolean disable) { return core.setDisableChatToWebProcessing(disable); } @Override public boolean testIfPlayerVisibleToPlayer(String player, String player_to_see) { return core.testIfPlayerVisibleToPlayer(player, player_to_see); } @Override public boolean testIfPlayerInfoProtected() { return core.testIfPlayerInfoProtected(); } private void initMetrics() { try { metrics = new Metrics(this); Metrics.Graph features = metrics.createGraph("Features Used"); features.addPlotter(new Metrics.Plotter("Internal Web Server") { @Override public int getValue() { if (!core.configuration.getBoolean("disable-webserver", false)) return 1; return 0; } }); features.addPlotter(new Metrics.Plotter("Spout") { @Override public int getValue() { if(plugin.has_spout) return 1; return 0; } }); features.addPlotter(new Metrics.Plotter("Login Security") { @Override public int getValue() { if(core.configuration.getBoolean("login-enabled", false)) return 1; return 0; } }); features.addPlotter(new Metrics.Plotter("Player Info Protected") { @Override public int getValue() { if(core.player_info_protected) return 1; return 0; } }); Metrics.Graph maps = metrics.createGraph("Map Data"); maps.addPlotter(new Metrics.Plotter("Worlds") { @Override public int getValue() { if(core.mapManager != null) return core.mapManager.getWorlds().size(); return 0; } }); maps.addPlotter(new Metrics.Plotter("Maps") { @Override public int getValue() { int cnt = 0; if(core.mapManager != null) { for(DynmapWorld w :core.mapManager.getWorlds()) { cnt += w.maps.size(); } } return cnt; } }); maps.addPlotter(new Metrics.Plotter("HD Maps") { @Override public int getValue() { int cnt = 0; if(core.mapManager != null) { for(DynmapWorld w :core.mapManager.getWorlds()) { for(MapType mt : w.maps) { if(mt instanceof HDMap) { cnt++; } } } } return cnt; } }); metrics.start(); } catch (IOException e) { // Failed to submit the stats :-( } } }
package net.sf.jabref.groups; import java.awt.Container; import java.awt.event.*; import java.io.StringReader; import java.util.regex.Pattern; import javax.swing.*; import javax.swing.event.*; import antlr.*; import net.sf.jabref.*; import net.sf.jabref.gui.*; import net.sf.jabref.gui.components.*; import net.sf.jabref.search.*; /** * Dialog for creating or modifying groups. Operates directly on the Vector * containing group information. */ class GroupDialog extends JDialog { private static final int INDEX_KEYWORDGROUP = 0; private static final int INDEX_SEARCHGROUP = 1; private static final int INDEX_EXPLICITGROUP = 2; private static final int TEXTFIELD_LENGTH = 30; // for all types private JTextField m_name = new JTextField(TEXTFIELD_LENGTH); private JLabel m_nameLabel = new JLabel(Globals.lang("Group name") + ":"); // for KeywordGroup private JTextField m_kgSearchExpression = new JTextField(TEXTFIELD_LENGTH); private JTextField m_searchField = new JTextField(TEXTFIELD_LENGTH); private JLabel m_keywordLabel = new JLabel(Globals.lang("Search term") + ":"); private JLabel m_searchFieldLabel = new JLabel(Globals .lang("Field to search") + ":"); private JPanel m_keywordGroupPanel; // for SearchGroup private JTextField m_sgSearchExpression = new JTextField(TEXTFIELD_LENGTH); private JCheckBox m_caseSensitive = new JCheckBox("Case sensitive"); private JCheckBox m_isRegExp = new JCheckBox("Regular Expression"); private JLabel m_searchExpressionLabel = new JLabel("Search expression:"); private JPanel m_searchGroupPanel; private JLabel m_searchType = new JLabel("Plaintext Search"); private JCheckBox m_searchAllFields = new JCheckBox("Search All Fields"); private JCheckBox m_searchRequiredFields = new JCheckBox("Search Required Fields"); private JCheckBox m_searchOptionalFields = new JCheckBox("Search Optional Fields"); private JCheckBox m_searchGeneralFields = new JCheckBox("Search General Fields"); private SearchExpressionParser m_parser; // JZTODO: translations... // for all types private DefaultComboBoxModel m_types = new DefaultComboBoxModel(); private JLabel m_typeLabel = new JLabel("Assign entries based on:"); private JComboBox m_typeSelector = new JComboBox(); private JButton m_ok = new JButton(Globals.lang("Ok")); private JButton m_cancel = new JButton(Globals.lang("Cancel")); private JPanel m_mainPanel; private boolean m_okPressed = false; private final JabRefFrame m_parent; private final BasePanel m_basePanel; private AbstractGroup m_resultingGroup; private final AbstractGroup m_editedGroup; /** * Shows a group add/edit dialog. * * @param jabrefFrame * The parent frame. * @param defaultField * The default grouping field. * @param editedGroup * The group being edited, or null if a new group is to be * created. */ public GroupDialog(JabRefFrame jabrefFrame, BasePanel basePanel, AbstractGroup editedGroup) { super(jabrefFrame, Globals.lang("Edit group"), true); m_basePanel = basePanel; m_parent = jabrefFrame; m_editedGroup = editedGroup; // set default values (overwritten if editedGroup != null) m_searchField.setText(jabrefFrame.prefs().get("groupsDefaultField")); // configure elements m_types.addElement("Keywords"); m_types.addElement("Search Expression"); m_types.addElement("Explicit"); m_typeSelector.setModel(m_types); // create layout m_mainPanel = new JPanelYBoxPreferredWidth(); JPanel namePanel = new JPanelXBoxPreferredHeight(); namePanel.add(m_nameLabel); namePanel.add(Box.createHorizontalGlue()); namePanel.add(new JPanelXBoxPreferredSize(m_name)); JPanel typePanel = new JPanelXBoxPreferredHeight(); typePanel.add(m_typeLabel); typePanel.add(Box.createHorizontalGlue()); typePanel.add(new JPanelXBoxPreferredSize(m_typeSelector)); // ...for keyword group m_keywordGroupPanel = new JPanelYBox(); JPanel kgField = new JPanelXBoxPreferredHeight(); kgField.add(m_searchFieldLabel); kgField.add(Box.createHorizontalGlue()); kgField.add(new JPanelXBoxPreferredSize(m_searchField)); JPanel kgExpression = new JPanelXBoxPreferredHeight(); kgExpression.add(m_keywordLabel); kgExpression.add(Box.createHorizontalGlue()); kgExpression.add(new JPanelXBoxPreferredSize(m_kgSearchExpression)); m_keywordGroupPanel.add(kgField); m_keywordGroupPanel.add(kgExpression); m_keywordGroupPanel.add(Box.createVerticalGlue()); // ...for search group m_searchGroupPanel = new JPanelYBox(); JPanel sgExpression = new JPanelXBoxPreferredHeight(); sgExpression.add(m_searchExpressionLabel); sgExpression.add(Box.createHorizontalGlue()); sgExpression.add(new JPanelXBoxPreferredSize(m_sgSearchExpression)); JPanel sgSearchType = new JPanelXBoxPreferredHeight(m_searchType); sgSearchType.add(Box.createHorizontalGlue()); JPanel sgCaseSensitive = new JPanelXBoxPreferredHeight(m_caseSensitive); JPanel sgRegExp = new JPanelXBoxPreferredHeight(m_isRegExp); JPanel sgAll = new JPanelXBoxPreferredHeight(m_searchAllFields); JPanel sgReq = new JPanelXBoxPreferredHeight(m_searchRequiredFields); JPanel sgOpt = new JPanelXBoxPreferredHeight(m_searchOptionalFields); JPanel sgGen = new JPanelXBoxPreferredHeight(m_searchGeneralFields); sgCaseSensitive.add(Box.createHorizontalGlue()); sgRegExp.add(Box.createHorizontalGlue()); sgAll.add(Box.createHorizontalGlue()); sgReq.add(Box.createHorizontalGlue()); sgOpt.add(Box.createHorizontalGlue()); sgGen.add(Box.createHorizontalGlue()); m_searchGroupPanel.add(sgExpression); m_searchGroupPanel.add(sgSearchType); m_searchGroupPanel.add(sgCaseSensitive); m_searchGroupPanel.add(sgRegExp); m_searchGroupPanel.add(sgAll); m_searchGroupPanel.add(sgReq); m_searchGroupPanel.add(sgOpt); m_searchGroupPanel.add(sgGen); m_searchGroupPanel.add(Box.createVerticalGlue()); m_mainPanel.add(namePanel); m_mainPanel.add(typePanel); JPanel buttons = new JPanelXBoxPreferredHeight(); buttons.add(m_ok); buttons.add(Box.createHorizontalStrut(5)); buttons.add(m_cancel); Container cp = getContentPane(); cp.setLayout(new BoxLayout(cp, BoxLayout.Y_AXIS)); cp.add(m_mainPanel); cp.add(Box.createVerticalGlue()); cp.add(buttons); // add listeners m_typeSelector.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { setLayoutForGroup(m_typeSelector.getSelectedIndex()); updateComponents(); } }); m_cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); m_ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { m_okPressed = true; switch (m_typeSelector.getSelectedIndex()) { case INDEX_EXPLICITGROUP: if (m_editedGroup instanceof ExplicitGroup) { // keep assignments from possible previous ExplicitGroup m_resultingGroup = m_editedGroup.deepCopy(); m_resultingGroup.setName(m_name.getText().trim()); } else { m_resultingGroup = new ExplicitGroup(m_name.getText() .trim(),m_basePanel.database()); } break; case INDEX_KEYWORDGROUP: // regex is correct, otherwise OK would have been disabled // therefore I don't catch anything here m_resultingGroup = new KeywordGroup( m_name.getText().trim(), m_searchField.getText() .trim(), m_kgSearchExpression.getText() .trim()); break; case INDEX_SEARCHGROUP: try { // regex is correct, otherwise OK would have been // disabled // therefore I don't catch anything here m_resultingGroup = new SearchGroup(m_name.getText() .trim(), m_sgSearchExpression.getText().trim(), m_caseSensitive.isSelected(), m_isRegExp .isSelected(), m_searchAllFields .isSelected(), m_searchRequiredFields .isSelected(), m_searchOptionalFields .isSelected(), m_searchGeneralFields .isSelected()); } catch (Exception e1) { // should never happen } break; } dispose(); } }); CaretListener caretListener = new CaretListener() { public void caretUpdate(CaretEvent e) { updateComponents(); } }; ItemListener itemListener = new ItemListener() { public void itemStateChanged(ItemEvent e) { updateComponents(); } }; m_name.addCaretListener(caretListener); m_searchField.addCaretListener(caretListener); m_kgSearchExpression.addCaretListener(caretListener); m_sgSearchExpression.addCaretListener(caretListener); m_isRegExp.addItemListener(itemListener); m_caseSensitive.addItemListener(itemListener); m_searchAllFields.addItemListener(itemListener); m_searchRequiredFields.addItemListener(itemListener); m_searchOptionalFields.addItemListener(itemListener); m_searchGeneralFields.addItemListener(itemListener); // configure for current type if (editedGroup instanceof KeywordGroup) { KeywordGroup group = (KeywordGroup) editedGroup; m_name.setText(group.getName()); m_searchField.setText(group.getSearchField()); m_kgSearchExpression.setText(group.getSearchExpression()); m_typeSelector.setSelectedIndex(INDEX_KEYWORDGROUP); } else if (editedGroup instanceof SearchGroup) { SearchGroup group = (SearchGroup) editedGroup; m_name.setText(group.getName()); m_sgSearchExpression.setText(group.getSearchExpression()); m_caseSensitive.setSelected(group.isCaseSensitive()); m_isRegExp.setSelected(group.isRegExp()); m_searchAllFields.setSelected(group.searchAllFields()); m_searchRequiredFields.setSelected(group.searchRequiredFields()); m_searchOptionalFields.setSelected(group.searchOptionalFields()); m_searchGeneralFields.setSelected(group.searchGeneralFields()); m_typeSelector.setSelectedIndex(INDEX_SEARCHGROUP); } else if (editedGroup instanceof ExplicitGroup) { m_name.setText(editedGroup.getName()); m_typeSelector.setSelectedIndex(INDEX_EXPLICITGROUP); } pack(); setSize(350, 300); setResizable(false); updateComponents(); setLayoutForGroup(m_typeSelector.getSelectedIndex()); Util.placeDialog(this, m_parent); } public boolean okPressed() { return m_okPressed; } public AbstractGroup getResultingGroup() { return m_resultingGroup; } private void setLayoutForGroup(int index) { switch (index) { case INDEX_KEYWORDGROUP: m_mainPanel.remove(m_searchGroupPanel); m_mainPanel.add(m_keywordGroupPanel); validate(); repaint(); break; case INDEX_SEARCHGROUP: m_mainPanel.remove(m_keywordGroupPanel); m_mainPanel.add(m_searchGroupPanel); validate(); repaint(); break; case INDEX_EXPLICITGROUP: m_mainPanel.remove(m_searchGroupPanel); m_mainPanel.remove(m_keywordGroupPanel); validate(); repaint(); break; } } private void updateComponents() { // all groups need a name boolean okEnabled = m_name.getText().trim().length() > 0; String s; switch (m_typeSelector.getSelectedIndex()) { case INDEX_KEYWORDGROUP: s = m_searchField.getText().trim(); okEnabled = okEnabled && s.length() > 0 && s.indexOf(' ') < 0; s = m_kgSearchExpression.getText().trim(); okEnabled = okEnabled && s.length() > 0; try { Pattern.compile(s); } catch (Exception e) { okEnabled = false; } break; case INDEX_SEARCHGROUP: s = m_sgSearchExpression.getText().trim(); okEnabled = okEnabled & s.length() > 0; m_parser = new SearchExpressionParser(new SearchExpressionLexer( new StringReader(s))); m_parser.caseSensitive = m_caseSensitive.isSelected(); m_parser.regex = m_isRegExp.isSelected(); boolean advancedSearch = false; try { m_parser.searchExpression(); advancedSearch = true; } catch (Exception e) { // advancedSearch remains false; } m_searchType.setText(advancedSearch ? "Advanced Search":"Plaintext Search"); m_searchAllFields.setEnabled(!advancedSearch); m_searchRequiredFields.setEnabled(!advancedSearch && !m_searchAllFields.isSelected()); m_searchOptionalFields.setEnabled(!advancedSearch && !m_searchAllFields.isSelected()); m_searchGeneralFields.setEnabled(!advancedSearch && !m_searchAllFields.isSelected()); validate(); break; case INDEX_EXPLICITGROUP: break; } m_ok.setEnabled(okEnabled); } }
package org.eclipse.oomph.setup.internal.installer; import org.eclipse.oomph.p2.P2Factory; import org.eclipse.oomph.p2.Repository; import org.eclipse.oomph.p2.core.Agent; import org.eclipse.oomph.p2.core.P2Util; import org.eclipse.oomph.p2.core.Profile; import org.eclipse.oomph.p2.core.ProfileTransaction; import org.eclipse.oomph.p2.core.ProfileTransaction.CommitContext; import org.eclipse.oomph.p2.core.ProfileTransaction.Resolution; import org.eclipse.oomph.setup.User; import org.eclipse.oomph.setup.internal.core.SetupTaskPerformer; import org.eclipse.oomph.setup.p2.impl.P2TaskImpl; import org.eclipse.oomph.setup.ui.AbstractSetupDialog; import org.eclipse.oomph.setup.ui.SetupUIPlugin; import org.eclipse.oomph.setup.ui.UnsignedContentDialog; import org.eclipse.oomph.setup.ui.wizards.ConfirmationPage; import org.eclipse.oomph.setup.ui.wizards.ProgressPage; import org.eclipse.oomph.setup.ui.wizards.SetupWizard; import org.eclipse.oomph.setup.ui.wizards.SetupWizard.Installer; import org.eclipse.oomph.setup.ui.wizards.SetupWizardDialog; import org.eclipse.oomph.ui.UICallback; import org.eclipse.oomph.util.Confirmer; import org.eclipse.oomph.util.IOUtil; import org.eclipse.oomph.util.IRunnable; import org.eclipse.oomph.util.Pair; import org.eclipse.oomph.util.PropertiesUtil; import org.eclipse.emf.common.util.EList; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.p2.engine.IProfile; import org.eclipse.equinox.p2.engine.IProfileRegistry; import org.eclipse.equinox.p2.engine.IProvisioningPlan; import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.metadata.Version; import org.eclipse.equinox.p2.query.QueryUtil; import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IPageChangedListener; import org.eclipse.jface.dialogs.PageChangedEvent; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.util.List; import java.util.Map; import java.util.Properties; /** * @author Eike Stepper */ public final class InstallerDialog extends SetupWizardDialog implements IPageChangedListener { private static final String PROP_INSTALLER_UPDATE_URL = "oomph.installer.update.url"; private static final String DEFAULT_INSTALLER_UPDATE_URL = "http://download.eclipse.org/oomph/products/repository"; public static final String INSTALLER_UPDATE_URL = PropertiesUtil.getProperty(PROP_INSTALLER_UPDATE_URL, DEFAULT_INSTALLER_UPDATE_URL).replace('\\', '/'); public static final int RETURN_RESTART = -4; private final boolean restarted; private ToolItem updateToolItem; private boolean updateSearching; private Resolution updateResolution; private IStatus updateError; private Link versionLink; public InstallerDialog(Shell parentShell, boolean restarted) { super(parentShell, new SetupWizard.Installer()); this.restarted = restarted; addPageChangedListener(this); } public Installer getInstaller() { return (Installer)getWizard(); } public void pageChanged(PageChangedEvent event) { if (event.getSelectedPage() instanceof ConfirmationPage) { updateSearching = false; updateResolution = null; updateError = null; setUpdateIcon(0); SetupTaskPerformer performer = getInstaller().getPerformer(); performer.getBundles().add(SetupInstallerPlugin.INSTANCE.getBundle()); } } @Override protected Control createHelpControl(Composite parent) { Control helpControl = super.createHelpControl(parent); setProductVersionLink(parent); return helpControl; } @Override protected void createToolItemsForToolBar(ToolBar toolBar) { createToolItem(toolBar, "install_prefs_proxy", "Network proxy settings").addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Dialog dialog = new ProxyPreferenceDialog(getShell()); dialog.open(); } }); createToolItem(toolBar, "install_prefs_ssh2", "SSH2 settings").addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Dialog dialog = new SSH2PreferenceDialog(getShell()); dialog.open(); } }); updateToolItem = createToolItem(toolBar, "install_update0", "Update"); updateToolItem.setDisabledImage(SetupInstallerPlugin.INSTANCE.getSWTImage("install_searching0")); updateToolItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { selfUpdate(); } }); } protected final ToolItem createToolItem(ToolBar toolBar, String iconPath, String toolTip) { ToolItem toolItem = new ToolItem(toolBar, SWT.PUSH); if (iconPath == null) { toolItem.setText(toolTip); } else { Image image = SetupInstallerPlugin.INSTANCE.getSWTImage(iconPath); toolItem.setImage(image); toolItem.setToolTipText(toolTip); } return toolItem; } private void selfUpdate() { updateError = null; setUpdateIcon(0); if (updateResolution == null) { initUpdateSearch(); } else { final UICallback callback = new UICallback(getShell(), AbstractSetupDialog.SHELL_TEXT); callback.runInProgressDialog(false, new IRunnable() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { updateResolution.commit(monitor); callback.execInUI(true, new Runnable() { public void run() { callback.information(false, "Updates were installed. Press OK to restart."); close(); setReturnCode(RETURN_RESTART); } }); } catch (CoreException ex) { updateError = ex.getStatus(); } finally { updateResolution = null; setUpdateIcon(0); } } }); } } private void initUpdateSearch() { updateSearching = true; Thread updateIconSetter = new UpdateIconSetter(); updateIconSetter.start(); Thread updateSearcher = new UpdateSearcher(); updateSearcher.start(); } private void setUpdateIcon(final int icon) { updateToolItem.getDisplay().asyncExec(new Runnable() { public void run() { if (updateToolItem == null || updateToolItem.isDisposed()) { return; } try { if (updateSearching) { updateToolItem.setToolTipText("Checking for updates..."); updateToolItem.setDisabledImage(SetupInstallerPlugin.INSTANCE.getSWTImage("install_searching" + icon + "")); updateToolItem.setEnabled(false); } else if (updateError != null) { StringBuilder builder = new StringBuilder(); formatStatus(builder, "", updateError); updateToolItem.setToolTipText(builder.toString()); updateToolItem.setImage(SetupInstallerPlugin.INSTANCE.getSWTImage("install_error")); updateToolItem.setEnabled(true); } else if (updateResolution != null) { updateToolItem.setToolTipText("Install available updates"); updateToolItem.setImage(SetupInstallerPlugin.INSTANCE.getSWTImage("install_update" + icon + "")); updateToolItem.setEnabled(true); } else { updateToolItem.setToolTipText("No updates available"); updateToolItem.setDisabledImage(SetupInstallerPlugin.INSTANCE.getSWTImage("install_update_disabled")); updateToolItem.setEnabled(false); } } catch (Exception ex) { // Ignore } } private void formatStatus(StringBuilder builder, String indent, IStatus status) { if (builder.length() != 0) { builder.append('\n'); } builder.append(indent); builder.append(status.getMessage()); for (IStatus child : status.getChildren()) { formatStatus(builder, indent + " ", child); } } }); } private void setProductVersionLink(Composite parent) { GridLayout parentLayout = (GridLayout)parent.getLayout(); parentLayout.numColumns++; parentLayout.horizontalSpacing = 10; versionLink = new Link(parent, SWT.NO_FOCUS); versionLink.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER | GridData.VERTICAL_ALIGN_CENTER)); versionLink.setToolTipText("About"); Thread thread = new ProductVersionSetter(); thread.start(); } /** * @author Eike Stepper */ private final class ProductVersionSetter extends Thread { private boolean selfHosting; public ProductVersionSetter() { super("Product Version Setter"); } @Override public void run() { try { final String version = getProductVersion(); if (version != null) { if (selfHosting) { updateSearching = false; setUpdateIcon(0); } else if (!restarted) { initUpdateSearch(); } versionLink.getDisplay().asyncExec(new Runnable() { public void run() { try { versionLink.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { new AboutDialog(getShell(), version).open(); } }); versionLink.setText("<a>" + version + "</a>"); //$NON-NLS-1$ versionLink.getParent().layout(); } catch (Exception ex) { SetupInstallerPlugin.INSTANCE.log(ex); } } }); } } catch (Exception ex) { SetupInstallerPlugin.INSTANCE.log(ex); } } private String getProductVersion() { Agent agent = P2Util.getAgentManager().getCurrentAgent(); IProfile profile = agent.getProfileRegistry().getProfile(IProfileRegistry.SELF); if (profile == null || "SelfHostingProfile".equals(profile.getProfileId())) { selfHosting = true; return "Self Hosting"; } String buildID = null; InputStream source = null; try { URL url = SetupInstallerPlugin.INSTANCE.getBundle().getResource("about.mappings"); if (url != null) { source = url.openStream(); Properties properties = new Properties(); properties.load(source); buildID = (String)properties.get("0"); if (buildID != null && buildID.startsWith("$")) { buildID = null; } } } catch (IOException ex) { //$FALL-THROUGH$ } finally { IOUtil.closeSilent(source); } for (IInstallableUnit iu : P2Util.asIterable(profile.query(QueryUtil.createIUQuery(SetupUIPlugin.INSTALLER_PRODUCT_ID), null))) { String label; Version version = iu.getVersion(); if (buildID != null && version.getSegmentCount() > 3) { label = version.getSegment(0) + "." + version.getSegment(1) + "." + version.getSegment(2); } else { label = version.toString(); } if (buildID != null) { label += " Build " + buildID; } return label; } return null; } } /** * @author Eike Stepper */ private final class UpdateIconSetter extends Thread { public UpdateIconSetter() { super("Update Icon Setter"); } @Override public void run() { try { for (int i = 0; updateSearching || updateResolution != null; i = ++i % 20) { if (updateToolItem == null || updateToolItem.isDisposed()) { return; } int icon = i > 7 ? 0 : i; setUpdateIcon(icon); sleep(80); } setUpdateIcon(0); } catch (Exception ex) { SetupInstallerPlugin.INSTANCE.log(ex); } } } /** * @author Eike Stepper */ private final class UpdateSearcher extends Thread { public UpdateSearcher() { super("Update Searcher"); } @Override public void run() { try { Agent agent = P2Util.getAgentManager().getCurrentAgent(); Profile profile = agent.getCurrentProfile(); ProfileTransaction transaction = profile.change(); EList<Repository> repositories = transaction.getProfileDefinition().getRepositories(); final boolean firstTime = repositories.isEmpty(); if (firstTime) { repositories.add(P2Factory.eINSTANCE.createRepository(InstallerDialog.INSTALLER_UPDATE_URL)); } CommitContext commitContext = new CommitContext() { private IProvisioningPlan provisioningPlan; @Override public boolean handleProvisioningPlan(IProvisioningPlan provisioningPlan, Map<IInstallableUnit, DeltaType> iuDeltas, Map<IInstallableUnit, Map<String, Pair<Object, Object>>> propertyDeltas, List<IMetadataRepository> metadataRepositories) throws CoreException { if (firstTime && iuDeltas.isEmpty() && propertyDeltas.size() <= 1) { // Cancel if only the repository addition would be committed. return false; } this.provisioningPlan = provisioningPlan; return true; } @Override public Confirmer getUnsignedContentConfirmer() { User user = getInstaller().getUser(); P2TaskImpl.processLicenses(provisioningPlan, ProgressPage.LICENSE_CONFIRMER, user, true, new NullProgressMonitor()); provisioningPlan = null; return UnsignedContentDialog.createUnsignedContentConfirmer(user, true); } }; updateResolution = transaction.resolve(commitContext, null); } catch (CoreException ex) { updateError = ex.getStatus(); } finally { updateSearching = false; } } } }