answer
stringlengths
17
10.2M
package com.google.gwt.eclipse.wtp; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.UUID; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.debug.core.DebugEvent; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.IDebugEventSetListener; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchConfigurationType; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.debug.core.ILaunchManager; import org.eclipse.debug.core.IStreamListener; import org.eclipse.debug.core.model.IProcess; import org.eclipse.debug.core.model.IStreamMonitor; import org.eclipse.debug.core.model.RuntimeProcess; import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.eclipse.wst.server.core.IModule; import org.eclipse.wst.server.core.IModule2; import org.eclipse.wst.server.core.IServer; import org.eclipse.wst.server.core.ServerPort; import org.eclipse.wst.server.core.ServerUtil; import org.eclipse.wst.server.core.model.IURLProvider; import org.osgi.framework.BundleContext; import com.google.appengine.eclipse.wtp.server.GaeServer; import com.google.gwt.eclipse.core.launch.GWTLaunchConstants; import com.google.gwt.eclipse.core.launch.GwtSuperDevModeLaunchConfiguration; import com.google.gwt.eclipse.core.launch.util.GwtSuperDevModeCodeServerLaunchUtil; import com.google.gwt.eclipse.core.properties.GWTProjectProperties; import com.google.gwt.eclipse.oophm.model.LaunchConfiguration; import com.google.gwt.eclipse.oophm.model.WebAppDebugModel; import com.google.gwt.eclipse.wtp.utils.GwtFacetUtils; /** * Google GWT WTP plug-in life-cycle. */ public final class GwtWtpPlugin extends AbstractUIPlugin { public static final String PLUGIN_ID = "com.google.gwt.eclipse.wtp"; public static final String USE_MAVEN_DEPS_PROPERTY_NAME = PLUGIN_ID + ".useMavenDependencies"; private static GwtWtpPlugin INSTANCE; private static final String LOCAL_URL = "http: private static HashSet<String[]> commandsToExecuteAtExit = new HashSet<String[]>(); private static List<String> launchUrls = new ArrayList<String>(); public static IStatus createErrorStatus(String mess, Exception e) { return new Status(IStatus.ERROR, PLUGIN_ID, -1, mess, e); } public static GwtWtpPlugin getInstance() { return INSTANCE; } public static void logMessage(String msg) { msg = msg == null ? "GWT" : "GWT: " + msg; Status status = new Status(IStatus.INFO, PLUGIN_ID, 1, msg, null); getInstance().getLog().log(status); } public static void logError(String msg) { logError(msg, null); } public static void logError(String msg, Throwable e) { msg = msg == null ? "GWT Error" : "GWT: " + msg; Status status = new Status(IStatus.ERROR, PLUGIN_ID, 1, msg, e); getInstance().getLog().log(status); } public static void logMessage(Throwable e) { logError(null, e); } private IDebugEventSetListener processListener; private IStreamListener consoleStreamListener; /** * Observe the console to notify SDM has launched */ private IStreamMonitor streamMonitor; public GwtWtpPlugin() { INSTANCE = this; } /** * When a Server runtime server is started and terminated, and the project has a GWT Facet, start and stop the GWT * Super Dev Mode Code Server with runtime server. * * TODO if sdm starts, start the wtp server? <br/> * TODO if the sdm server stops on its own, stop the wtp server? */ @Override public void start(BundleContext context) throws Exception { super.start(context); // Observe launch events, that are for the WTP server processListener = new IDebugEventSetListener() { @Override public void handleDebugEvents(DebugEvent[] events) { if (events != null) { processProcessorEvents(events); } } }; DebugPlugin.getDefault().addDebugEventListener(processListener); } protected void processProcessorEvents(DebugEvent[] events) { for (int i = 0; i < events.length; i++) { try { processLauncherEvent(events[i]); } catch (CoreException e) { e.printStackTrace(); } } } private void processLauncherEvent(DebugEvent event) throws CoreException { if (!(event.getSource() instanceof RuntimeProcess)) { return; } RuntimeProcess runtimeProcess = (RuntimeProcess) event.getSource(); ILaunch launch = runtimeProcess.getLaunch(); ILaunchConfiguration launchConfig = launch.getLaunchConfiguration(); if (launchConfig == null) { return; } ILaunchConfigurationType launchType = launchConfig.getType(); ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); ILaunchConfigurationType sdmCodeServerType = launchManager .getLaunchConfigurationType(GwtSuperDevModeLaunchConfiguration.TYPE_ID); if (launchType.equals(sdmCodeServerType) && event.getKind() == DebugEvent.CREATE) { // Start: Observe the console for SDM launching processSdmCodeServerLauncher(event); } else if (launchType.equals(sdmCodeServerType) && event.getKind() == DebugEvent.TERMINATE) { // Stop: Observe the console for SDM terminating processSdmCodeServerTerminate(event); } else { if (event.getKind() == DebugEvent.CREATE) { // Start: Delineate event for Server Launching and then possibly launch SDM posiblyLaunchGwtSuperDevModeCodeServer(event); } else if (event.getKind() == DebugEvent.TERMINATE) { // Stop: Delineate event for Server Launching and then possibly terminate SDM possiblyTerminateLaunchConfiguration(event); } } } private void processSdmCodeServerTerminate(DebugEvent event) { if (streamMonitor == null) { return; } streamMonitor.removeListener(consoleStreamListener); } private void processSdmCodeServerLauncher(DebugEvent event) { RuntimeProcess runtimeProcess = (RuntimeProcess) event.getSource(); final ILaunch launch = runtimeProcess.getLaunch(); IProcess[] processes = launch.getProcesses(); final IProcess process = processes[0]; // Look for the links in the sdm console output consoleStreamListener = new IStreamListener() { @Override public void streamAppended(String text, IStreamMonitor monitor) { displayCodeServerUrlInDevMode(launch, text); } }; // Listen to Console output streamMonitor = process.getStreamsProxy().getOutputStreamMonitor(); streamMonitor.addListener(consoleStreamListener); } // TODO fire gwt sdm start/stop event private void addServerUrlsToDevModeView(ILaunch launch) { IServer server = getServerFromLaunchConfig(launch); if (server == null) { logMessage("posiblyLaunchGwtSuperDevModeCodeServer: No WTP server found."); return; } IModule[] modules = server.getModules(); if (modules == null || modules.length == 0) { return; } IModule rootMod = modules[0]; if (rootMod == null) { return; } // First clear the previous urls, before adding new ones launchUrls.clear(); String host = server.getHost(); ServerPort[] ports = null; try { ports = server.getServerPorts(new NullProgressMonitor()); } catch (Exception e1) { } // Add server urls to DevModeViewer if (ports != null) { for (ServerPort port : ports) { String baseUrl = String.format(LOCAL_URL, host, port.getPort()); String path = getPath(server, rootMod); String fullUrl = baseUrl + path; launchUrls.add(fullUrl); } } // TODO extract, consider a plugin that does this, that adds the appengine dashboard url // TODO or possibly do a extension query // Add App Engine url to DevModeView // See OpenLocalAdminConsoleHandler if (server.getName().contains("Google")) { GaeServer gaeServer = GaeServer.getGaeServer(server); String gaeHost = server.getHost(); ServerPort gaePort = gaeServer.getMainPort(); String gaeUrl = String.format("http://%s:%s/_ah/admin", gaeHost, gaePort.getPort()); launchUrls.add(gaeUrl); } } private String getPath(IServer server, IModule rootMod) { URL url = ((IURLProvider) server.loadAdapter(IURLProvider.class, null)).getModuleRootURL(rootMod); String surl = ""; try { surl = url.toURI().getPath().toString(); } catch (URISyntaxException e) { } return surl; } private void displayCodeServerUrlInDevMode(final ILaunch launch, String text) { if (!text.contains("http")) { return; } String url = text.replaceAll(".*(http.*).*?", "$1").trim(); if (url.matches(".*/")) { url = url.substring(0, url.length() - 1); launchUrls.add(url); } // Dev Mode View, add url LaunchConfiguration lc = WebAppDebugModel.getInstance().addOrReturnExistingLaunchConfiguration(launch, "", null); lc.setLaunchUrls(launchUrls); } private IServer getServerFromLaunchConfig(ILaunch launch) { ILaunchConfiguration launchConfig = launch.getLaunchConfiguration(); if (launchConfig == null) { return null; } IServer server = null; try { server = ServerUtil.getServer(launchConfig); } catch (CoreException e) { logError("getServerFromLaunchConfig: Getting the WTP server error.", e); return null; } return server; } protected void possiblyTerminateLaunchConfiguration(DebugEvent event) { logMessage("posiblyTerminateGwtSuperDevModeCodeServer: Stopping GWT Super Dev Mode Code Server."); RuntimeProcess serverRuntimeProcess = (RuntimeProcess) event.getSource(); ILaunch serverLaunch = serverRuntimeProcess.getLaunch(); if (serverLaunch == null) { return; } ILaunchConfiguration serverLaunchConfig = serverLaunch.getLaunchConfiguration(); if (serverLaunchConfig == null) { return; } ILaunchConfigurationType serverType = null; try { serverType = serverLaunchConfig.getType(); } catch (CoreException e) { logError("possiblyRemoveLaunchConfiguration: Could not retrieve the launch config type.", e); } String serverLaunchId; try { serverLaunchId = serverLaunchConfig.getAttribute(GWTLaunchConstants.SUPERDEVMODE_LAUNCH_ID, "NoId"); } catch (CoreException e1) { serverLaunchId = "NoId"; } try { ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); ILaunchConfigurationType sdmcodeServerType = launchManager .getLaunchConfigurationType(GwtSuperDevModeLaunchConfiguration.TYPE_ID); ILaunch[] launches = launchManager.getLaunches(); if (launches == null || launches.length == 0) { logMessage("possiblyRemoveLaunchConfiguration: Launches is empty or null. Can't find the GWT sdm launch config"); return; } for (ILaunch launch : launches) { ILaunchConfiguration launchConfig = launch.getLaunchConfiguration(); String launcherId = launchConfig.getAttribute(GWTLaunchConstants.SUPERDEVMODE_LAUNCH_ID, (String) null); // If its the sdm code server if (sdmcodeServerType.equals(serverType)) { // TODO ? remove listener on console } else if (!sdmcodeServerType.equals(serverType) && sdmcodeServerType.equals(launch.getLaunchConfiguration().getType()) && serverLaunchId.equals(launcherId)) { // Skip if it's the Super Dev Mode Code Server terminating, so it // doesn't // Terminate if the server terminated and they both have the same // launcher id. launch.terminate(); } } } catch (CoreException e) { logError("possiblyRemoveLaunchConfiguration: Couldn't stop the Super Dev Mode Code Server.", e); } } private String setLauncherIdToWtpRunTimeLaunchConfig(ILaunchConfiguration launchConfig) { String launcherId = getLaunchId(); logMessage("setLauncherIdToWtpRunTimeLaunchConfig: Adding server launcherId id=" + getLaunchId()); try { ILaunchConfigurationWorkingCopy launchConfigWorkingCopy = launchConfig.getWorkingCopy(); launchConfigWorkingCopy.setAttribute(GWTLaunchConstants.SUPERDEVMODE_LAUNCH_ID, launcherId); launchConfigWorkingCopy.doSave(); } catch (CoreException e) { logError("posiblyLaunchGwtSuperDevModeCodeServer: Couldn't add server Launcher Id attribute.", e); } return launcherId; } private String getLaunchId() { return UUID.randomUUID().toString(); } /** * Possibly start the GWT Super Dev Mode CodeServer. <br/> * <br/> * This starts as separate process, which allows for custom args modification. It adds a launcher id to both processes * for reference. 1. Get it from classic launch config 2. Get it from server VM properties */ protected void posiblyLaunchGwtSuperDevModeCodeServer(DebugEvent event) { RuntimeProcess runtimeProcess = (RuntimeProcess) event.getSource(); ILaunch launch = runtimeProcess.getLaunch(); ILaunchConfiguration launchConfig = launch.getLaunchConfiguration(); String launchMode = launch.getLaunchMode(); IServer server = null; try { server = ServerUtil.getServer(launchConfig); } catch (CoreException e) { logError("posiblyLaunchGwtSuperDevModeCodeServer: Could get the WTP server.", e); return; } if (server == null) { logMessage("posiblyLaunchGwtSuperDevModeCodeServer: No WTP server found."); return; } IProject project = getProject(server); if (project == null) { logMessage("posiblyLaunchGwtSuperDevModeCodeServer: Couldn't find project."); return; } // If the sync is off, ignore stopping the server if (GWTProjectProperties.getFacetSyncCodeServer(project) != null && GWTProjectProperties.getFacetSyncCodeServer(project) == false) { logMessage("posiblyLaunchGwtSuperDevModeCodeServer: GWT Facet project properties, the code server sync is off."); return; } if (!GwtFacetUtils.hasGwtFacet(project)) { logMessage("posiblyLaunchGwtSuperDevModeCodeServer: Does not have a GWT Facet."); return; } if (GWTProjectProperties.getFacetSyncCodeServer(project) != null && GWTProjectProperties.getFacetSyncCodeServer(project) == false) { logMessage("posiblyLaunchGwtSuperDevModeCodeServer: GWT Facet project properties, the code server sync is off."); return; } /** * Get the war output path for the `-launcherDir` in SDM launcher */ String launcherDir = null; // Get the the war output path from classic launch configuration working directory // Also used GaeServerBehaviour.setupLaunchConfig(...) try { launcherDir = launchConfig.getAttribute(IJavaLaunchConfigurationConstants.ATTR_WORKING_DIRECTORY, (String) null); } catch (CoreException e) { logMessage("posiblyLaunchGwtSuperDevModeCodeServer: Couldn't get working directory from launchConfig IJavaLaunchConfigurationConstants.ATTR_WORKING_DIRECTORY."); } // Get the war output path from Server VM properties for working directory if (launcherDir == null || launcherDir.isEmpty()) { launcherDir = getLauncherDirFromServerLaunchConfigAttributes(server, launchConfig); } // Exit on error if (launcherDir == null || launcherDir.isEmpty()) { logError("posiblyLaunchGwtSuperDevModeCodeServer: No -launcherDir arg is available, EXITING. launcherDir=" + launcherDir); return; } // Add server urls to DevMode view for easy clicking on addServerUrlsToDevModeView(launch); // LauncherId used to reference and terminate the the process String launcherId = setLauncherIdToWtpRunTimeLaunchConfig(launchConfig); logMessage("posiblyLaunchGwtSuperDevModeCodeServer: Launching GWT Super Dev Mode CodeServer. launcherId=" + launcherId + " launcherDir=" + launcherDir); // Just in case if (launchMode == null) { launchMode = "run"; } if (launcherId == null) { logMessage("posiblyLaunchGwtSuperDevModeCodeServer: No launcherId."); } // Creates ore launches an existing Super Dev Mode Code Server process GwtSuperDevModeCodeServerLaunchUtil.launch(project, launchMode, launcherDir, launcherId); } /** * Try to get the war output path from server launch config. * * @param server * is the server launcher * @param serverLaunchConfig * server launcher config * @return string path to the output war */ private String getLauncherDirFromServerLaunchConfigAttributes(IServer server, ILaunchConfiguration serverLaunchConfig) { if (server == null || serverLaunchConfig == null) { return null; } // First get wtp.deploy from the server attributes Map<String, Object> launchConfigAttributes = null; try { launchConfigAttributes = serverLaunchConfig.getAttributes(); } catch (CoreException e) { logError( "posiblyLaunchGwtSuperDevModeCodeServer > getLauncherDirFromServerLaunchConfigAttributes: can't find launcher directory in ATTR_VM_ARGUMENTS.", e); } // Get the vm arguments in the launch configs vm args String vmArgsString = (String) launchConfigAttributes.get("org.eclipse.jdt.launching.VM_ARGUMENTS"); if (vmArgsString == null || vmArgsString.isEmpty()) { logMessage("posiblyLaunchGwtSuperDevModeCodeServer > getLauncherDirFromServerLaunchConfigAttributes: can't get org.eclipse.jdt.launching.VM_ARGUMENTS from the launch config."); return null; } // Create an array from the vm args string String[] vmArgsArray = DebugPlugin.parseArguments(vmArgsString); if (vmArgsArray == null || vmArgsString.isEmpty()) { logMessage("posiblyLaunchGwtSuperDevModeCodeServer > getLauncherDirFromServerLaunchConfigAttributes: can't parse vm args into an array."); return null; } String wtpDeployArg = null; for (int i = 0; i < vmArgsArray.length; i++) { String arg = vmArgsArray[i]; if (arg != null && arg.startsWith("-Dwtp.deploy")) { wtpDeployArg = arg.replaceFirst("-Dwtp.deploy=", ""); wtpDeployArg = wtpDeployArg.replace("\"", "").trim(); break; } } if (wtpDeployArg == null || wtpDeployArg.isEmpty()) { logMessage("posiblyLaunchGwtSuperDevModeCodeServer > getLauncherDirFromServerLaunchConfigAttributes: can't get \"-Dwtp.deploy=\" (w/no spaces) arg from vm args list."); return null; } // Next get the server project deploy name or deploy context relative path String launcherDir = null; String deployName = null; IModule[] modules = server.getModules(); if (modules != null && modules.length > 0) { if (modules.length > 0) { logMessage("posiblyLaunchGwtSuperDevModeCodeServer > getLauncherDirFromServerLaunchConfigAttributes: launcherDir will use the first module for the deploy path."); } IModule2 module = (IModule2) modules[0]; deployName = module.getProperty(IModule2.PROP_DEPLOY_NAME); if (deployName == null) { logMessage("posiblyLaunchGwtSuperDevModeCodeServer > getLauncherDirFromServerLaunchConfigAttributes: Couldn't get the deploy path for the module."); } else { launcherDir = wtpDeployArg + File.separator + deployName; } } else { logMessage("posiblyLaunchGwtSuperDevModeCodeServer > getLauncherDirFromServerLaunchConfigAttributes: the modules are empty, add a wtp module."); } if (launcherDir == null) { logMessage("posiblyLaunchGwtSuperDevModeCodeServer > getLauncherDirFromServerLaunchConfigAttributes: couldn't construct the launcherDir Path from server launch config."); logMessage("posiblyLaunchGwtSuperDevModeCodeServer > getLauncherDirFromServerLaunchConfigAttributes: wtpDeployArg=" + wtpDeployArg); logMessage("posiblyLaunchGwtSuperDevModeCodeServer > getLauncherDirFromServerLaunchConfigAttributes: wtpDeployArg=" + deployName); } logMessage("posiblyLaunchGwtSuperDevModeCodeServer > getLauncherDirFromServerLaunchConfigAttributes: Success, found the launcherDir=" + launcherDir); return launcherDir; } private IProject getProject(IServer server) { IModule[] modules = server.getModules(); if (modules == null || modules.length == 0) { return null; } return modules[0].getProject(); } @Override public void stop(BundleContext v) throws Exception { DebugPlugin.getDefault().removeDebugEventListener(processListener); for (String[] command : commandsToExecuteAtExit) { try { logError(">>> " + command[0], null); BufferedReader input = new BufferedReader(new InputStreamReader(Runtime.getRuntime().exec(command) .getInputStream())); String line = null; while ((line = input.readLine()) != null) { logError(">>> " + line, null); } input.close(); } catch (Throwable ex) { logMessage("Error executing process:\n" + ex); } } super.stop(v); } }
package org.jetbrains.plugins.groovy.intentions.base; import com.intellij.codeInsight.CodeInsightUtilBase; import com.intellij.codeInsight.template.Template; import com.intellij.codeInsight.template.TemplateBuilder; import com.intellij.codeInsight.template.TemplateManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiType; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.annotator.intentions.QuickfixUtil; import org.jetbrains.plugins.groovy.lang.editor.template.expressions.ChooseTypeExpression; import org.jetbrains.plugins.groovy.lang.editor.template.expressions.ParameterNameExpression; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrMemberOwner; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement; import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint; public class IntentionUtils { public static void replaceExpression(@NotNull String newExpression, @NotNull GrExpression expression) throws IncorrectOperationException { final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(expression.getProject()); final GrExpression newCall = factory.createExpressionFromText(newExpression); final PsiElement insertedElement = expression.replaceWithExpression(newCall, true); } public static GrStatement replaceStatement( @NonNls @NotNull String newStatement, @NonNls @NotNull GrStatement statement) throws IncorrectOperationException { final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(statement.getProject()); final GrStatement newCall = (GrStatement) factory.createTopElementFromText(newStatement); return statement.replaceWithStatement(newCall); } public static void createTemplateForMethod(PsiType[] argTypes, ChooseTypeExpression[] paramTypesExpressions, GrMethod method, GrMemberOwner owner, TypeConstraint[] constraints, boolean isConstructor) { Project project = owner.getProject(); GrTypeElement typeElement = method.getReturnTypeElementGroovy(); ChooseTypeExpression expr = new ChooseTypeExpression(constraints, PsiManager.getInstance(project)); TemplateBuilder builder = new TemplateBuilder(method); if (!isConstructor) { assert typeElement != null; builder.replaceElement(typeElement, expr); } GrParameter[] parameters = method.getParameterList().getParameters(); assert parameters.length == argTypes.length; for (int i = 0; i < parameters.length; i++) { GrParameter parameter = parameters[i]; GrTypeElement parameterTypeElement = parameter.getTypeElementGroovy(); builder.replaceElement(parameterTypeElement, paramTypesExpressions[i]); builder.replaceElement(parameter.getNameIdentifierGroovy(), new ParameterNameExpression()); } GrOpenBlock body = method.getBlock(); assert body != null; PsiElement lbrace = body.getLBrace(); assert lbrace != null; builder.setEndVariableAfter(lbrace); method = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(method); Template template = builder.buildTemplate(); Editor newEditor = QuickfixUtil.positionCursor(project, owner.getContainingFile(), method); TextRange range = method.getTextRange(); newEditor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset()); TemplateManager manager = TemplateManager.getInstance(project); manager.startTemplate(newEditor, template); } }
package com.vaadin.terminal.gwt.client.ui; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Stack; import com.google.gwt.dom.client.NodeList; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.dom.client.FocusHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.event.dom.client.KeyDownHandler; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwt.event.dom.client.KeyPressHandler; import com.google.gwt.event.logical.shared.CloseEvent; import com.google.gwt.event.logical.shared.CloseHandler; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.DeferredCommand; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.HasHTML; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.Widget; import com.vaadin.terminal.gwt.client.ApplicationConnection; import com.vaadin.terminal.gwt.client.BrowserInfo; import com.vaadin.terminal.gwt.client.ContainerResizedListener; import com.vaadin.terminal.gwt.client.Paintable; import com.vaadin.terminal.gwt.client.TooltipInfo; import com.vaadin.terminal.gwt.client.UIDL; import com.vaadin.terminal.gwt.client.Util; import com.vaadin.terminal.gwt.client.VTooltip; public class VMenuBar extends SimpleFocusablePanel implements Paintable, CloseHandler<PopupPanel>, ContainerResizedListener, KeyPressHandler, KeyDownHandler, FocusHandler, SubPartAware { // The hierarchy of VMenuBar is a bit weird as VMenuBar is the Paintable, // used for the root menu but also used for the sub menus. /** Set the CSS class name to allow styling. */ public static final String CLASSNAME = "v-menubar"; /** For server connections **/ protected String uidlId; protected ApplicationConnection client; protected final VMenuBar hostReference = this; protected String submenuIcon = null; protected CustomMenuItem moreItem = null; // Only used by the root menu bar protected VMenuBar collapsedRootItems; // Construct an empty command to be used when the item has no command // associated protected static final Command emptyCommand = null; /** Widget fields **/ protected boolean subMenu; protected ArrayList<CustomMenuItem> items; protected Element containerElement; protected VOverlay popup; protected VMenuBar visibleChildMenu; protected boolean menuVisible = false; protected VMenuBar parentMenu; protected CustomMenuItem selected; private Timer layoutTimer; private Timer focusDelayTimer; private boolean enabled = true; public VMenuBar() { // Create an empty horizontal menubar this(false, null); // Navigation is only handled by the root bar addFocusHandler(this); /* * Firefox auto-repeat works correctly only if we use a key press * handler, other browsers handle it correctly when using a key down * handler */ if (BrowserInfo.get().isGecko()) { addKeyPressHandler(this); } else { addKeyDownHandler(this); } } public VMenuBar(boolean subMenu, VMenuBar parentMenu) { items = new ArrayList<CustomMenuItem>(); popup = null; visibleChildMenu = null; containerElement = getElement(); if (!subMenu) { setStyleName(CLASSNAME); } else { setStyleName(CLASSNAME + "-submenu"); this.parentMenu = parentMenu; } this.subMenu = subMenu; sinkEvents(Event.ONCLICK | Event.ONMOUSEOVER | Event.ONMOUSEOUT | Event.ONLOAD); sinkEvents(VTooltip.TOOLTIP_EVENTS); } @Override protected void onDetach() { super.onDetach(); if (!subMenu) { setSelected(null); hideChildren(); menuVisible = false; } } @Override public void setWidth(String width) { Util.setWidthExcludingPaddingAndBorder(this, width, 0); if (!subMenu) { // Only needed for root level menu hideChildren(); setSelected(null); menuVisible = false; } } /** * This method must be implemented to update the client-side component from * UIDL data received from server. * * This method is called when the page is loaded for the first time, and * every time UI changes in the component are received from the server. */ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { // This call should be made first. Ensure correct implementation, // and let the containing layout manage caption, etc. if (client.updateComponent(this, uidl, true)) { return; } enabled = !uidl.getBooleanAttribute("disabled"); // For future connections this.client = client; uidlId = uidl.getId(); // Empty the menu every time it receives new information if (!getItems().isEmpty()) { clearItems(); } UIDL options = uidl.getChildUIDL(0); // FIXME remove in version 7 if (options.hasAttribute("submenuIcon")) { submenuIcon = client.translateVaadinUri(uidl.getChildUIDL(0) .getStringAttribute("submenuIcon")); } else { submenuIcon = null; } if (uidl.hasAttribute("width")) { UIDL moreItemUIDL = options.getChildUIDL(0); StringBuffer itemHTML = new StringBuffer(); if (moreItemUIDL.hasAttribute("icon")) { itemHTML.append("<img src=\"" + client.translateVaadinUri(moreItemUIDL .getStringAttribute("icon")) + "\" class=\"" + Icon.CLASSNAME + "\" alt=\"\" />"); } String moreItemText = moreItemUIDL.getStringAttribute("text"); if ("".equals(moreItemText)) { moreItemText = "&#x25BA;"; } itemHTML.append(moreItemText); moreItem = new CustomMenuItem(itemHTML.toString(), emptyCommand); collapsedRootItems = new VMenuBar(true, (VMenuBar) client.getPaintable(uidlId)); moreItem.setSubMenu(collapsedRootItems); moreItem.addStyleName(CLASSNAME + "-more-menuitem"); } UIDL uidlItems = uidl.getChildUIDL(1); Iterator<Object> itr = uidlItems.getChildIterator(); Stack<Iterator<Object>> iteratorStack = new Stack<Iterator<Object>>(); Stack<VMenuBar> menuStack = new Stack<VMenuBar>(); VMenuBar currentMenu = this; while (itr.hasNext()) { UIDL item = (UIDL) itr.next(); CustomMenuItem currentItem = null; String itemText = item.getStringAttribute("text"); final int itemId = item.getIntAttribute("id"); boolean itemHasCommand = item.hasAttribute("command"); // Construct html from the text and the optional icon StringBuffer itemHTML = new StringBuffer(); Command cmd = null; if (item.hasAttribute("separator")) { itemHTML.append("<span>---</span>"); } else { // Add submenu indicator if (item.getChildCount() > 0) { // FIXME For compatibility reasons: remove in version 7 String bgStyle = ""; if (submenuIcon != null) { bgStyle = " style=\"background-image: url(" + submenuIcon + "); text-indent: -999px; width: 1em;\""; } itemHTML.append("<span class=\"" + CLASSNAME + "-submenu-indicator\"" + bgStyle + ">&#x25BA;</span>"); } itemHTML.append("<span class=\"" + CLASSNAME + "-menuitem-caption\">"); if (item.hasAttribute("icon")) { itemHTML.append("<img src=\"" + client.translateVaadinUri(item .getStringAttribute("icon")) + "\" class=\"" + Icon.CLASSNAME + "\" alt=\"\" />"); } itemHTML.append(Util.escapeHTML(itemText) + "</span>"); if (itemHasCommand) { // Construct a command that fires onMenuClick(int) with the // item's id-number cmd = new Command() { public void execute() { hostReference.onMenuClick(itemId); } }; } } currentItem = currentMenu.addItem(itemHTML.toString(), cmd); currentItem.updateFromUIDL(item, client); if (item.getChildCount() > 0) { menuStack.push(currentMenu); iteratorStack.push(itr); itr = item.getChildIterator(); currentMenu = new VMenuBar(true, currentMenu); if (uidl.hasAttribute("style")) { for (String style : uidl.getStringAttribute("style").split( " ")) { currentMenu.addStyleDependentName(style); } } currentItem.setSubMenu(currentMenu); } while (!itr.hasNext() && !iteratorStack.empty()) { itr = iteratorStack.pop(); currentMenu = menuStack.pop(); } }// while iLayout(false); }// updateFromUIDL /** * This is called by the items in the menu and it communicates the * information to the server * * @param clickedItemId * id of the item that was clicked */ public void onMenuClick(int clickedItemId) { // Cancel the focus event handling since focus was gained by // clicking an item. if (focusDelayTimer != null || subMenu) { focusDelayTimer.cancel(); } // Updating the state to the server can not be done before // the server connection is known, i.e., before updateFromUIDL() // has been called. if (uidlId != null && client != null) { // Communicate the user interaction parameters to server. This call // will initiate an AJAX request to the server. client.updateVariable(uidlId, "clickedId", clickedItemId, true); } } /** Widget methods **/ /** * Returns a list of items in this menu */ public List<CustomMenuItem> getItems() { return items; } /** * Remove all the items in this menu */ public void clearItems() { Element e = getContainerElement(); while (DOM.getChildCount(e) > 0) { DOM.removeChild(e, DOM.getChild(e, 0)); } items.clear(); } /** * Returns the containing element of the menu * * @return */ @Override public Element getContainerElement() { return containerElement; } /** * Add a new item to this menu * * @param html * items text * @param cmd * items command * @return the item created */ public CustomMenuItem addItem(String html, Command cmd) { CustomMenuItem item = new CustomMenuItem(html, cmd); addItem(item); return item; } /** * Add a new item to this menu * * @param item */ public void addItem(CustomMenuItem item) { if (items.contains(item)) { return; } DOM.appendChild(getContainerElement(), item.getElement()); item.setParentMenu(this); item.setSelected(false); items.add(item); } public void addItem(CustomMenuItem item, int index) { if (items.contains(item)) { return; } DOM.insertChild(getContainerElement(), item.getElement(), index); item.setParentMenu(this); item.setSelected(false); items.add(index, item); } /** * Remove the given item from this menu * * @param item */ public void removeItem(CustomMenuItem item) { if (items.contains(item)) { int index = items.indexOf(item); DOM.removeChild(getContainerElement(), DOM.getChild(getContainerElement(), index)); items.remove(index); } } /* * @see * com.google.gwt.user.client.ui.Widget#onBrowserEvent(com.google.gwt.user * .client.Event) */ @Override public void onBrowserEvent(Event e) { super.onBrowserEvent(e); // Handle onload events (icon loaded, size changes) if (DOM.eventGetType(e) == Event.ONLOAD) { VMenuBar parent = getParentMenu(); if (parent != null) { // The onload event for an image in a popup should be sent to // the parent, which owns the popup parent.iconLoaded(); } else { // Onload events for images in the root menu are handled by the // root menu itself iconLoaded(); } return; } Element targetElement = DOM.eventGetTarget(e); CustomMenuItem targetItem = null; for (int i = 0; i < items.size(); i++) { CustomMenuItem item = items.get(i); if (DOM.isOrHasChild(item.getElement(), targetElement)) { targetItem = item; } } // Handle tooltips if (targetItem == null && client != null) { // Handle root menubar tooltips client.handleTooltipEvent(e, this); } else if (targetItem != null) { // Handle item tooltips targetItem.onBrowserEvent(e); } if (targetItem != null) { switch (DOM.eventGetType(e)) { case Event.ONCLICK: if (isEnabled() && targetItem.isEnabled()) { itemClick(targetItem); } if (subMenu) { // Prevent moving keyboard focus to child menus VMenuBar parent = parentMenu; while (parent.getParentMenu() != null) { parent = parent.getParentMenu(); } parent.setFocus(true); } break; case Event.ONMOUSEOVER: if (isEnabled() && targetItem.isEnabled()) { itemOver(targetItem); } break; case Event.ONMOUSEOUT: itemOut(targetItem); break; } } else if (subMenu && DOM.eventGetType(e) == Event.ONCLICK && subMenu) { // Prevent moving keyboard focus to child menus VMenuBar parent = parentMenu; while (parent.getParentMenu() != null) { parent = parent.getParentMenu(); } parent.setFocus(true); } } private boolean isEnabled() { return enabled; } private void iconLoaded() { if (layoutTimer == null) { layoutTimer = new Timer() { @Override public void run() { layoutTimer = null; iLayout(true); } }; } layoutTimer.schedule(100); } /** * When an item is clicked * * @param item */ public void itemClick(CustomMenuItem item) { if (item.getCommand() != null) { setSelected(null); if (visibleChildMenu != null) { visibleChildMenu.hideChildren(); } hideParents(true); menuVisible = false; DeferredCommand.addCommand(item.getCommand()); } else { if (item.getSubMenu() != null && item.getSubMenu() != visibleChildMenu) { setSelected(item); showChildMenu(item); menuVisible = true; } else if (!subMenu) { setSelected(null); hideChildren(); menuVisible = false; } } } /** * When the user hovers the mouse over the item * * @param item */ public void itemOver(CustomMenuItem item) { if ((subMenu || menuVisible) && !item.isSeparator()) { setSelected(item); } if (menuVisible && visibleChildMenu != item.getSubMenu() && popup != null) { popup.hide(); } if (menuVisible && item.getSubMenu() != null && visibleChildMenu != item.getSubMenu()) { showChildMenu(item); } } /** * When the mouse is moved away from an item * * @param item */ public void itemOut(CustomMenuItem item) { if (visibleChildMenu != item.getSubMenu()) { hideChildMenu(item); setSelected(null); } else if (visibleChildMenu == null) { setSelected(null); } } /** * Shows the child menu of an item. The caller must ensure that the item has * a submenu. * * @param item */ public void showChildMenu(CustomMenuItem item) { final int shadowSpace = 10; popup = new VOverlay(true, false, true); popup.setStyleName(CLASSNAME + "-popup"); popup.setWidget(item.getSubMenu()); popup.addCloseHandler(this); popup.addAutoHidePartner(item.getElement()); int left = 0; int top = 0; if (subMenu) { left = item.getParentMenu().getAbsoluteLeft() + item.getParentMenu().getOffsetWidth(); top = item.getAbsoluteTop(); } else { left = item.getAbsoluteLeft(); top = item.getParentMenu().getAbsoluteTop() + item.getParentMenu().getOffsetHeight(); } popup.setPopupPosition(left, top); item.getSubMenu().onShow(); visibleChildMenu = item.getSubMenu(); item.getSubMenu().setParentMenu(this); popup.show(); if (left + popup.getOffsetWidth() >= RootPanel.getBodyElement() .getOffsetWidth() - shadowSpace) { if (subMenu) { left = item.getParentMenu().getAbsoluteLeft() - popup.getOffsetWidth() - shadowSpace; } else { left = RootPanel.getBodyElement().getOffsetWidth() - popup.getOffsetWidth() - shadowSpace; } // Accommodate space for shadow if (left < shadowSpace) { left = shadowSpace; } popup.setPopupPosition(left, top); } // IE7 really tests one's patience sometimes // Part of a fix to correct #3850 if (BrowserInfo.get().isIE7()) { popup.getElement().getStyle().setProperty("zoom", ""); DeferredCommand.addCommand(new Command() { public void execute() { if (popup == null) { // The child menu can be hidden before this command is // run. return; } if (popup.getElement().getStyle().getProperty("width") == null || popup.getElement().getStyle() .getProperty("width") == "") { popup.setWidth(popup.getOffsetWidth() + "px"); } popup.getElement().getStyle().setProperty("zoom", "1"); } }); } } /** * Hides the submenu of an item * * @param item */ public void hideChildMenu(CustomMenuItem item) { if (visibleChildMenu != null && !(visibleChildMenu == item.getSubMenu())) { popup.hide(); } } /** * When the menu is shown. */ public void onShow() { // remove possible previous selection if (selected != null) { selected.setSelected(false); selected = null; } menuVisible = true; } /** * Listener method, fired when this menu is closed */ public void onClose(CloseEvent<PopupPanel> event) { hideChildren(); if (event.isAutoClosed()) { hideParents(true); menuVisible = false; } visibleChildMenu = null; popup = null; } /** * Recursively hide all child menus */ public void hideChildren() { if (visibleChildMenu != null) { visibleChildMenu.hideChildren(); popup.hide(); } } /** * Recursively hide all parent menus */ public void hideParents(boolean autoClosed) { if (visibleChildMenu != null) { popup.hide(); setSelected(null); menuVisible = !autoClosed; } if (getParentMenu() != null) { getParentMenu().hideParents(autoClosed); } } /** * Returns the parent menu of this menu, or null if this is the top-level * menu * * @return */ public VMenuBar getParentMenu() { return parentMenu; } /** * Set the parent menu of this menu * * @param parent */ public void setParentMenu(VMenuBar parent) { parentMenu = parent; } /** * Returns the currently selected item of this menu, or null if nothing is * selected * * @return */ public CustomMenuItem getSelected() { return selected; } /** * Set the currently selected item of this menu * * @param item */ public void setSelected(CustomMenuItem item) { // If we had something selected, unselect if (item != selected && selected != null) { selected.setSelected(false); } // If we have a valid selection, select it if (item != null) { item.setSelected(true); } selected = item; } /** * * A class to hold information on menu items * */ private class CustomMenuItem extends Widget implements HasHTML { private ApplicationConnection client; protected String html = null; protected Command command = null; protected VMenuBar subMenu = null; protected VMenuBar parentMenu = null; protected boolean enabled = true; protected boolean isSeparator = false; public CustomMenuItem(String html, Command cmd) { // We need spans to allow inline-block in IE setElement(DOM.createSpan()); setHTML(html); setCommand(cmd); setSelected(false); setStyleName(CLASSNAME + "-menuitem"); sinkEvents(VTooltip.TOOLTIP_EVENTS); // Sink the onload event for an icon (if it exists). The onload // events are handled by the parent VMenuBar. NodeList<com.google.gwt.dom.client.Element> imgElements = getElement() .getElementsByTagName("img"); for (int i = 0; i < imgElements.getLength(); i++) { DOM.sinkEvents((Element) imgElements.getItem(i), Event.ONLOAD); } } public void setSelected(boolean selected) { if (selected && !isSeparator) { addStyleDependentName("selected"); } else { removeStyleDependentName("selected"); } } /* * setters and getters for the fields */ public void setSubMenu(VMenuBar subMenu) { this.subMenu = subMenu; } public VMenuBar getSubMenu() { return subMenu; } public void setParentMenu(VMenuBar parentMenu) { this.parentMenu = parentMenu; } public VMenuBar getParentMenu() { return parentMenu; } public void setCommand(Command command) { this.command = command; } public Command getCommand() { return command; } public String getHTML() { return html; } public void setHTML(String html) { this.html = html; DOM.setInnerHTML(getElement(), html); if (BrowserInfo.get().isIE6() && client != null) { // Find possible icon element final NodeList<com.google.gwt.dom.client.Element> imgs = getElement() .getElementsByTagName("IMG"); if (imgs.getLength() > 0) { client.addPngFix((Element) imgs.getItem(0).cast()); } } } public String getText() { return html; } public void setText(String text) { setHTML(Util.escapeHTML(text)); } public void setEnabled(boolean enabled) { this.enabled = enabled; if (enabled) { removeStyleDependentName("disabled"); } else { addStyleDependentName("disabled"); } } public boolean isEnabled() { return enabled; } private void setSeparator(boolean separator) { isSeparator = separator; if (separator) { setStyleName(CLASSNAME + "-separator"); } else { setStyleName(CLASSNAME + "-menuitem"); setEnabled(enabled); } } public boolean isSeparator() { return isSeparator; } public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { this.client = client; setSeparator(uidl.hasAttribute("separator")); setEnabled(!uidl.hasAttribute("disabled")); if (uidl.hasAttribute("style")) { String itemStyle = uidl.getStringAttribute("style"); addStyleDependentName(itemStyle); } if (uidl.hasAttribute("description")) { String description = uidl.getStringAttribute("description"); TooltipInfo info = new TooltipInfo(description); VMenuBar root = findRootMenu(); client.registerTooltip(root, this, info); } } @Override public void onBrowserEvent(Event event) { super.onBrowserEvent(event); if (client != null) { client.handleTooltipEvent(event, findRootMenu(), this); } } private VMenuBar findRootMenu() { VMenuBar menubar = getParentMenu(); // Traverse up until root menu is found while (menubar.getParentMenu() != null) { menubar = menubar.getParentMenu(); } return menubar; } } /** * @author Jouni Koivuviita / IT Mill Ltd. */ private int paddingWidth = -1; public void iLayout() { iLayout(false); } public void iLayout(boolean iconLoadEvent) { // Only collapse if there is more than one item in the root menu and the // menu has an explicit size if ((getItems().size() > 1 || (collapsedRootItems != null && collapsedRootItems .getItems().size() > 0)) && getElement().getStyle().getProperty("width") != null && moreItem != null) { // Measure the width of the "more" item final boolean morePresent = getItems().contains(moreItem); addItem(moreItem); final int moreItemWidth = moreItem.getOffsetWidth(); if (!morePresent) { removeItem(moreItem); } // Measure available space if (paddingWidth == -1) { int widthBefore = getElement().getClientWidth(); getElement().getStyle().setProperty("padding", "0"); paddingWidth = widthBefore - getElement().getClientWidth(); getElement().getStyle().setProperty("padding", ""); } String overflow = ""; if (BrowserInfo.get().isIE6()) { // IE6 cannot measure available width correctly without // overflow:hidden overflow = getElement().getStyle().getProperty("overflow"); getElement().getStyle().setProperty("overflow", "hidden"); } int availableWidth = getElement().getClientWidth() - paddingWidth; if (BrowserInfo.get().isIE6()) { // IE6 cannot measure available width correctly without // overflow:hidden getElement().getStyle().setProperty("overflow", overflow); } int diff = availableWidth - getConsumedWidth(); removeItem(moreItem); if (diff < 0) { // Too many items: collapse last items from root menu final int widthNeeded = moreItemWidth - diff; int widthReduced = 0; while (widthReduced < widthNeeded && getItems().size() > 0) { // Move last root menu item to collapsed menu CustomMenuItem collapse = getItems().get( getItems().size() - 1); widthReduced += collapse.getOffsetWidth(); removeItem(collapse); collapsedRootItems.addItem(collapse, 0); } } else if (collapsedRootItems.getItems().size() > 0) { // Space available for items: expand first items from collapsed // menu int widthAvailable = diff + moreItemWidth; int widthGrowth = 0; while (widthAvailable > widthGrowth) { // Move first item from collapsed menu to the root menu CustomMenuItem expand = collapsedRootItems.getItems() .get(0); collapsedRootItems.removeItem(expand); addItem(expand); widthGrowth += expand.getOffsetWidth(); if (collapsedRootItems.getItems().size() > 0) { widthAvailable -= moreItemWidth; } if (widthGrowth > widthAvailable) { removeItem(expand); collapsedRootItems.addItem(expand, 0); } else { widthAvailable = diff; } } } if (collapsedRootItems.getItems().size() > 0) { addItem(moreItem); } } // If a popup is open we might need to adjust the shadow as well if an // icon shown in that popup was loaded if (popup != null) { // Forces a recalculation of the shadow size popup.show(); } if (iconLoadEvent) { // Size have changed if the width is undefined Util.notifyParentOfSizeChange(this, false); } } private int getConsumedWidth() { int w = 0; for (CustomMenuItem item : getItems()) { if (!collapsedRootItems.getItems().contains(item)) { w += item.getOffsetWidth(); } } return w; } /* * (non-Javadoc) * * @see * com.google.gwt.event.dom.client.KeyPressHandler#onKeyPress(com.google * .gwt.event.dom.client.KeyPressEvent) */ public void onKeyPress(KeyPressEvent event) { if (handleNavigation(event.getNativeEvent().getKeyCode(), event.isControlKeyDown() || event.isMetaKeyDown(), event.isShiftKeyDown())) { event.preventDefault(); } } /* * (non-Javadoc) * * @see * com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt * .event.dom.client.KeyDownEvent) */ public void onKeyDown(KeyDownEvent event) { if (handleNavigation(event.getNativeEvent().getKeyCode(), event.isControlKeyDown() || event.isMetaKeyDown(), event.isShiftKeyDown())) { event.preventDefault(); } } /** * Get the key that moves the selection upwards. By default it is the up * arrow key but by overriding this you can change the key to whatever you * want. * * @return The keycode of the key */ protected int getNavigationUpKey() { return KeyCodes.KEY_UP; } /** * Get the key that moves the selection downwards. By default it is the down * arrow key but by overriding this you can change the key to whatever you * want. * * @return The keycode of the key */ protected int getNavigationDownKey() { return KeyCodes.KEY_DOWN; } /** * Get the key that moves the selection left. By default it is the left * arrow key but by overriding this you can change the key to whatever you * want. * * @return The keycode of the key */ protected int getNavigationLeftKey() { return KeyCodes.KEY_LEFT; } /** * Get the key that moves the selection right. By default it is the right * arrow key but by overriding this you can change the key to whatever you * want. * * @return The keycode of the key */ protected int getNavigationRightKey() { return KeyCodes.KEY_RIGHT; } /** * Get the key that selects a menu item. By default it is the Enter key but * by overriding this you can change the key to whatever you want. * * @return */ protected int getNavigationSelectKey() { return KeyCodes.KEY_ENTER; } /** * Get the key that closes the menu. By default it is the escape key but by * overriding this yoy can change the key to whatever you want. * * @return */ protected int getCloseMenuKey() { return KeyCodes.KEY_ESCAPE; } /** * Handles the keyboard events handled by the MenuBar * * @param event * The keyboard event received * @return true iff the navigation event was handled */ public boolean handleNavigation(int keycode, boolean ctrl, boolean shift) { // If tab or shift+tab close menus if (keycode == KeyCodes.KEY_TAB) { setSelected(null); hideChildren(); menuVisible = false; return false; } if (ctrl || shift || !isEnabled()) { // Do not handle tab key, nor ctrl keys return false; } if (keycode == getNavigationLeftKey()) { if (getSelected() == null) { // If nothing is selected then select the last item setSelected(items.get(items.size() - 1)); if (getSelected().isSeparator() || !getSelected().isEnabled()) { handleNavigation(keycode, ctrl, shift); } } else if (visibleChildMenu == null && getParentMenu() == null) { // If this is the root menu then move to the right int idx = items.indexOf(getSelected()); if (idx > 0) { setSelected(items.get(idx - 1)); } else { setSelected(items.get(items.size() - 1)); } if (getSelected().isSeparator() || !getSelected().isEnabled()) { handleNavigation(keycode, ctrl, shift); } } else if (visibleChildMenu != null) { // Redirect all navigation to the submenu visibleChildMenu.handleNavigation(keycode, ctrl, shift); } else if (getParentMenu().getParentMenu() == null) { // Get the root menu VMenuBar root = getParentMenu(); root.getSelected().getSubMenu().setSelected(null); root.hideChildren(); // Get the root menus items and select the previous one int idx = root.getItems().indexOf(root.getSelected()); idx = idx > 0 ? idx : root.getItems().size(); CustomMenuItem selected = root.getItems().get(--idx); while (selected.isSeparator() || !selected.isEnabled()) { idx = idx > 0 ? idx : root.getItems().size(); selected = root.getItems().get(--idx); } root.setSelected(selected); root.showChildMenu(selected); VMenuBar submenu = selected.getSubMenu(); // Select the first item in the newly open submenu submenu.setSelected(submenu.getItems().get(0)); } else { getParentMenu().getSelected().getSubMenu().setSelected(null); getParentMenu().hideChildren(); } return true; } else if (keycode == getNavigationRightKey()) { if (getSelected() == null) { // If nothing is selected then select the first item setSelected(items.get(0)); if (getSelected().isSeparator() || !getSelected().isEnabled()) { handleNavigation(keycode, ctrl, shift); } } else if (visibleChildMenu == null && getParentMenu() == null) { // If this is the root menu then move to the right int idx = items.indexOf(getSelected()); if (idx < items.size() - 1) { setSelected(items.get(idx + 1)); } else { setSelected(items.get(0)); } if (getSelected().isSeparator() || !getSelected().isEnabled()) { handleNavigation(keycode, ctrl, shift); } } else if (visibleChildMenu == null && getSelected().getSubMenu() != null) { // If the item has a submenu then show it and move the selection // there showChildMenu(getSelected()); menuVisible = true; visibleChildMenu.handleNavigation(keycode, ctrl, shift); } else if (visibleChildMenu == null) { // Get the root menu VMenuBar root = getParentMenu(); while (root.getParentMenu() != null) { root = root.getParentMenu(); } // Hide the submenu root.hideChildren(); // Get the root menus items and select the next one int idx = root.getItems().indexOf(root.getSelected()); idx = idx < root.getItems().size() - 1 ? idx : -1; CustomMenuItem selected = root.getItems().get(++idx); while (selected.isSeparator() || !selected.isEnabled()) { idx = idx < root.getItems().size() - 1 ? idx : -1; selected = root.getItems().get(++idx); } root.setSelected(selected); root.showChildMenu(selected); VMenuBar submenu = selected.getSubMenu(); // Select the first item in the newly open submenu submenu.setSelected(submenu.getItems().get(0)); } else if (visibleChildMenu != null) { // Redirect all navigation to the submenu visibleChildMenu.handleNavigation(keycode, ctrl, shift); } return true; } else if (keycode == getNavigationUpKey()) { if (getSelected() == null) { // If nothing is selected then select the last item setSelected(items.get(items.size() - 1)); if (getSelected().isSeparator() || !getSelected().isEnabled()) { handleNavigation(keycode, ctrl, shift); } } else if (visibleChildMenu != null) { // Redirect all navigation to the submenu visibleChildMenu.handleNavigation(keycode, ctrl, shift); } else { // Select the previous item if possible or loop to the last item int idx = items.indexOf(getSelected()); if (idx > 0) { setSelected(items.get(idx - 1)); } else { setSelected(items.get(items.size() - 1)); } if (getSelected().isSeparator() || !getSelected().isEnabled()) { handleNavigation(keycode, ctrl, shift); } } return true; } else if (keycode == getNavigationDownKey()) { if (getSelected() == null) { // If nothing is selected then select the first item setSelected(items.get(0)); if (getSelected().isSeparator() || !getSelected().isEnabled()) { handleNavigation(keycode, ctrl, shift); } } else if (visibleChildMenu == null && getParentMenu() == null) { // If this is the root menu the show the child menu with arrow // down showChildMenu(getSelected()); menuVisible = true; visibleChildMenu.handleNavigation(keycode, ctrl, shift); } else if (visibleChildMenu != null) { // Redirect all navigation to the submenu visibleChildMenu.handleNavigation(keycode, ctrl, shift); } else { // Select the next item if possible or loop to the first item int idx = items.indexOf(getSelected()); if (idx < items.size() - 1) { setSelected(items.get(idx + 1)); } else { setSelected(items.get(0)); } if (getSelected().isSeparator() || !getSelected().isEnabled()) { handleNavigation(keycode, ctrl, shift); } } return true; } else if (keycode == getCloseMenuKey()) { setSelected(null); hideChildren(); menuVisible = false; } else if (keycode == getNavigationSelectKey()) { if (visibleChildMenu != null) { // Redirect all navigation to the submenu visibleChildMenu.handleNavigation(keycode, ctrl, shift); menuVisible = false; } else if (visibleChildMenu == null && getSelected().getSubMenu() != null) { // If the item has a submenu then show it and move the selection // there showChildMenu(getSelected()); menuVisible = true; visibleChildMenu.handleNavigation(keycode, ctrl, shift); } else { Command command = getSelected().getCommand(); if (command != null) { command.execute(); } setSelected(null); hideParents(true); } } return false; } /* * (non-Javadoc) * * @see * com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event * .dom.client.FocusEvent) */ public void onFocus(FocusEvent event) { /* * Delay the action so a mouse click can cancel the blur event if needed */ focusDelayTimer = new Timer() { @Override public void run() { if (getSelected() == null) { // If nothing is selected then select the first item setSelected(items.get(0)); } } }; focusDelayTimer.schedule(100); } private final String SUBPART_PREFIX = "item"; public Element getSubPartElement(String subPart) { int index = Integer .parseInt(subPart.substring(SUBPART_PREFIX.length())); CustomMenuItem item = getItems().get(index); return item.getElement(); } public String getSubPartName(Element subElement) { if (!getElement().isOrHasChild(subElement)) { return null; } Element menuItemRoot = subElement; while (menuItemRoot != null && menuItemRoot.getParentElement() != null && menuItemRoot.getParentElement() != getElement()) { menuItemRoot = menuItemRoot.getParentElement().cast(); } // "menuItemRoot" is now the root of the menu item final int itemCount = getItems().size(); for (int i = 0; i < itemCount; i++) { if (getItems().get(i).getElement() == menuItemRoot) { String name = SUBPART_PREFIX + i; return name; } } return null; } }
package com.webdude.algorithms; import java.math.BigInteger; import java.util.Scanner; public class ExtraLongFactorials { private static BigInteger one = BigInteger.valueOf(1); public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println(calcFactorial(in.nextBigInteger())); } public static BigInteger calcFactorial(BigInteger input) { if (input.equals(one)) { return one; } return input.multiply(calcFactorial(input.subtract(one))); } }
package com.whoshuu.artbox.component; import org.jbox2d.collision.shapes.CircleShape; import org.jbox2d.collision.shapes.EdgeShape; import org.jbox2d.collision.shapes.PolygonShape; import org.jbox2d.common.Vec2; import org.jbox2d.dynamics.Body; import org.jbox2d.dynamics.BodyDef; import org.jbox2d.dynamics.BodyType; import org.jbox2d.dynamics.FixtureDef; import org.json.JSONException; import org.json.JSONObject; import com.whoshuu.artbox.GameContext; import com.whoshuu.artbox.artemis.utils.JSONComponent; public class BodyComponent extends JSONComponent { public BodyComponent() { this.body = null; } public BodyComponent(Body body) { this.body = body; } public Body getBody() { return this.body; } @Override public void fromJSON(JSONObject json, float x, float y, float angle) throws JSONException { /* * "type": "com.whoshuu.artbox.component.BodyComponent" * ... */ BodyDef def = new BodyDef(); def.type = json.optString("bodytype", "dynamic").equals("dynamic") ? BodyType.DYNAMIC : BodyType.STATIC; def.position.set(x, y); def.angle = angle; def.fixedRotation = !json.optBoolean("rotate", true); this.body = GameContext.get().getPhysics().createBody(def); if (body != null) { // Set shape, density, friction, and restitution FixtureDef fixture = new FixtureDef(); JSONObject jsonShape = json.getJSONObject("shape"); String shape = jsonShape.optString("type", "circle"); if (shape.equals("circle")) { CircleShape circle = new CircleShape(); circle.setRadius((float) jsonShape.optDouble("radius", 1.0)); fixture.shape = circle; } else if (shape.equals("edge")) { EdgeShape edge = new EdgeShape(); edge.set(new Vec2(0, 0), new Vec2((float) jsonShape.optDouble("x2", 1.0) - def.position.x, (float) jsonShape.optDouble("y2", 1.0) - def.position.y)); fixture.shape = edge; } else if (shape.equals("box")) { PolygonShape box = new PolygonShape(); box.setAsBox((float) (jsonShape.optDouble("w", 2.0) / 2.0), (float) (jsonShape.optDouble("h", 2.0) / 2.0)); fixture.shape = box; } else if (shape.equals("polygon")) { // TODO } else if (shape.equals("chain")) { // TODO } fixture.density = (float) json.optDouble("density", 1.0); fixture.friction = (float) json.optDouble("friction", 1.0); fixture.restitution = (float) json.optDouble("restitution", 1.0); this.body.createFixture(fixture); } } private Body body; }
package net.langleystudios.avro.ecore; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import net.langleystudios.avro.AvroEMFConverter; import org.apache.avro.Schema; import org.apache.avro.file.CodecFactory; import org.apache.avro.file.DataFileStream; import org.apache.avro.file.DataFileWriter; import org.apache.avro.io.DatumReader; import org.apache.avro.io.DatumWriter; import org.apache.avro.io.DecoderFactory; import org.apache.avro.io.EncoderFactory; import org.apache.avro.io.JsonDecoder; import org.apache.avro.io.JsonEncoder; import org.apache.avro.specific.SpecificData; import org.apache.avro.specific.SpecificDatumWriter; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.impl.ResourceImpl; public class AvroResource extends ResourceImpl { /** * A load or save option that when set to Boolean.TRUE, directs the resource * to produce or consume a binary resource encoded by Avro */ public final static String OPTION_AVRO_BINARY = "AVRO_BINARY"; /** * A save option that when set to Boolean.TRUE, directs the resource * to produce a compressed resource encoded by Avro. The resource compression * is automatically determined for loading. */ public final static String OPTION_AVRO_ZIP = "AVRO_ZIP"; /** * A key used for storing a list of package URIs as metadata in the * Avro file. */ public final static String AVRO_PACKAGE_LIST = "AVRO_PACKAGE_LIST"; private ClassLoader loader = null; private AvroEMFConverter converter = null; public AvroResource() { super(); } public AvroResource(URI uri) { super(uri); } public void setClassLoader(ClassLoader loader) { this.loader = loader; } public void setConverter(AvroEMFConverter converter) { this.converter = converter; } @Override protected void doLoad(InputStream inputStream, Map<?, ?> options) throws IOException { // Compression is read from the file metadata if binary // Object zipOption = options.get(Resource.OPTION_ZIP); Object binaryOption = null; if (options != null) { binaryOption = options.get(OPTION_AVRO_BINARY); } SpecificData sData = new SpecificData(loader); Schema unionSchema = converter.getSchema(); DatumReader<Object> reader = sData.createDatumReader(unionSchema); // If the binary option is not set, use Json encoding if (!Boolean.TRUE.equals(binaryOption)) { JsonDecoder decoder = DecoderFactory.get().jsonDecoder(unionSchema, inputStream); try { Object object = reader.read(null, decoder); while (object != null) { EObject obj = converter.convertAvroObject(object); this.getContents().add(obj); reader.read(null, decoder); } } catch (EOFException eof) { // Find a way to read without relying on an exception to stop } } else // Use binary encoding with the DataFileStream { DataFileStream<Object> dataStream = new DataFileStream<Object>( inputStream, reader); for (Object object : dataStream) { EObject obj = converter.convertAvroObject(object); this.getContents().add(obj); } } } @Override protected void doSave(OutputStream outputStream, Map<?, ?> options) throws IOException { Error error = null; Exception exception = null; // Bail early if we have nothing to save if (this.contents == null && this.contents.size() == 0) { return; } // Create a union schema using only the EObjects that are in contents // and build a list of unique URIs for the packages List<Schema> schemaList = new ArrayList<Schema>(); List<String> uriList = new ArrayList<String>(); for (EObject eobject : this.contents) { Schema schema = converter.getSchema(eobject); if (schema != null) { schemaList.add(schema); } String uri = eobject.eClass().getEPackage().getNsURI(); if(!uriList.contains(uri)) { uriList.add(uri); } } Schema unionSchema = Schema.createUnion(schemaList); DatumWriter<Object> writer = new SpecificDatumWriter<Object>( unionSchema); // Build the package list StringBuilder builder = new StringBuilder(); if(uriList.size() > 0) { builder.append(uriList.get(0)); for(int i = 1; i < uriList.size(); i++) { builder.append(","); builder.append(uriList.get(i)); } } Object zipOption = null; Object binaryOption = null; if (options != null) { zipOption = options.get(OPTION_AVRO_ZIP); binaryOption = options.get(OPTION_AVRO_BINARY); } if (Boolean.TRUE.equals(binaryOption)) { DataFileWriter<Object> fileWriter = null; try { fileWriter = new DataFileWriter<Object>(writer); fileWriter.setMeta(AVRO_PACKAGE_LIST, builder.toString()); // Check to see if we're using compression if (Boolean.TRUE.equals(zipOption)) { fileWriter.setCodec(CodecFactory.deflateCodec(9)); } fileWriter.create(unionSchema, outputStream); for (EObject eobject : this.contents) { Object o = converter.convertEObject(eobject); fileWriter.append(o); } } catch (Exception exc) { exception = exc; } catch (Error err) { error = err; } finally { if (fileWriter != null) { fileWriter.flush(); } } } else { JsonEncoder encoder = EncoderFactory.get().jsonEncoder(unionSchema, outputStream); try { for (EObject eobject : this.contents) { Object o = converter.convertEObject(eobject); writer.write(o, encoder); } } catch (Exception exc) { exception = exc; } catch (Error err) { error = err; } finally { if (encoder != null) { encoder.flush(); } } } // Re-throw any exceptions as IOExceptions if (exception != null) { throw new IOException(exception); } else if (error != null) { throw new IOException(error); } } protected void doTempSave(OutputStream outputStream, Map<?, ?> options) throws IOException { Error error = null; Exception exception = null; // Bail early if we have nothing to save if (this.contents == null && this.contents.size() == 0) { return; } // Create a union schema using only the EObjects that are in contents List<Schema> schemaList = new ArrayList<Schema>(); for (EObject eobject : this.contents) { Schema schema = converter.getSchema(eobject); if (schema != null) { schemaList.add(schema); } } Schema unionSchema = Schema.createUnion(schemaList); DataFileWriter<Object> fileWriter = null; try { DatumWriter<Object> writer = new SpecificDatumWriter<Object>( unionSchema); fileWriter = new DataFileWriter<Object>(writer); fileWriter.setCodec(CodecFactory.deflateCodec(9)); fileWriter.create(unionSchema, outputStream); for (EObject eobject : this.contents) { Object o = converter.convertEObject(eobject); fileWriter.append(o); } } catch (Exception exc) { exception = exc; } catch (Error err) { error = err; } finally { if (fileWriter != null) { fileWriter.close(); } } if (exception != null) { throw new IOException(exception); } else if (error != null) { throw new IOException(error); } } }
package org.jkiss.dbeaver.ext.oracle.oci; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.core.DBeaverCore; import org.jkiss.dbeaver.utils.WinRegistry; import org.jkiss.utils.CommonUtils; import org.jkiss.utils.IOUtils; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; public class OCIUtils { static final Log log = LogFactory.getLog(OCIUtils.class); public static final String WIN_REG_ORACLE = "SOFTWARE\\ORACLE"; public static final String WIN_REG_ORA_HOME = "ORACLE_HOME"; public static final String WIN_REG_ORA_HOME_NAME = "ORACLE_HOME_NAME"; public static final String VAR_ORA_HOME = "ORA_HOME"; public static final String VAR_ORACLE_HOME = "ORACLE_HOME"; public static final String VAR_TNS_ADMIN = "TNS_ADMIN"; public static final String VAR_PATH = "PATH"; public static final String TNSNAMES_FILE_NAME = "tnsnames.ora"; public static final String TNSNAMES_FILE_PATH = "network/admin/"; //public static final String DRIVER_NAME_OCI = "oracle_oci"; /** * A list of Oracle client homes found in the system. * The first one is always a current Oracle home (from PATH) */ private static final List<OracleHomeDescriptor> oraHomes = new ArrayList<OracleHomeDescriptor>(); private static boolean oraHomesSearched = false; /* static { findOraHomes(); } */ public static List<OracleHomeDescriptor> getOraHomes() { checkOraHomes(); return oraHomes; } private static boolean checkOraHomes() { if (!oraHomesSearched) { findOraHomes(); oraHomesSearched = true; } return !oraHomes.isEmpty(); } public static OracleHomeDescriptor getOraHome(String oraHome) { if (CommonUtils.isEmpty(oraHome) || !checkOraHomes()) { return null; } for (OracleHomeDescriptor home : oraHomes) { // file name case insensitivity on Windows platform if (equalsFileName(home.getHomeId(), oraHome)) { return home; } } return null; } public static OracleHomeDescriptor getOraHomeByName(String oraHomeName) { if (CommonUtils.isEmpty(oraHomeName) || !checkOraHomes()) { return null; } for (OracleHomeDescriptor home : oraHomes) { // file name case insensitivity on Windows platform if (equalsFileName(home.getDisplayName(), oraHomeName)) { return home; } } return null; } private static boolean equalsFileName(String file1, String file2) { if (DBeaverCore.getInstance().getLocalSystem().isWindows()) { return file1.equalsIgnoreCase(file2); } else { return file1.equals(file2); } } public static OracleHomeDescriptor addOraHome(String oraHome) throws DBException { if (CommonUtils.isEmpty(oraHome)) { return null; } oraHome = CommonUtils.removeTrailingSlash(oraHome); boolean contains = false; for (OracleHomeDescriptor home : oraHomes) { // file name case insensitivity on Windows platform if (equalsFileName(home.getHomeId(), oraHome)) { contains = true; break; } } if (!contains) { OracleHomeDescriptor homeDescriptor = new OracleHomeDescriptor(oraHome); oraHomes.add(0, homeDescriptor); return homeDescriptor; } return null; } /** * Searches Oracle home locations. */ private static void findOraHomes() { // read system environment variables String path = System.getenv(VAR_PATH); if (path != null) { for (String token : path.split(System.getProperty("path.separator"))) { if (token.toLowerCase().contains("oracle")) { token = CommonUtils.removeTrailingSlash(token); if (token.toLowerCase().endsWith("bin")) { String oraHome = token.substring(0, token.length() - 3); try { addOraHome(oraHome); } catch (DBException ex) { log.warn("Wrong Oracle client home " + oraHome, ex); } } } } } String oraHome = System.getenv(VAR_ORA_HOME); if (oraHome == null) { oraHome = System.getenv(VAR_ORACLE_HOME); } if (oraHome != null) { try { addOraHome(oraHome); } catch (DBException ex) { log.warn("Wrong Oracle client home " + oraHome, ex); } } // find Oracle homes in Windows registry if (DBeaverCore.getInstance().getLocalSystem().isWindows()) { try { List<String> oracleKeys = WinRegistry.readStringSubKeys(WinRegistry.HKEY_LOCAL_MACHINE, WIN_REG_ORACLE); if (oracleKeys != null) { for (String oracleKey : oracleKeys) { Map<String, String> valuesMap = WinRegistry.readStringValues(WinRegistry.HKEY_LOCAL_MACHINE, WIN_REG_ORACLE + "\\" + oracleKey); if (valuesMap != null) { for (String key : valuesMap.keySet()) { if (WIN_REG_ORA_HOME.equals(key)) { try { oraHome = valuesMap.get(key); addOraHome(oraHome); } catch (DBException ex) { log.warn("Wrong Oracle client home " + oraHome, ex); } break; } } } } } } catch (IllegalAccessException e) { log.warn("Error reading Windows registry", e); } catch (InvocationTargetException e) { log.warn("Error reading Windows registry", e); } } } public static String readWinRegistry(String oraHome, String name) { if (DBeaverCore.getInstance().getLocalSystem().isWindows()) { try { List<String> oracleKeys = WinRegistry.readStringSubKeys(WinRegistry.HKEY_LOCAL_MACHINE, WIN_REG_ORACLE); if (oracleKeys != null) { for (String oracleKey : oracleKeys) { String home = WinRegistry.readString(WinRegistry.HKEY_LOCAL_MACHINE, WIN_REG_ORACLE + "\\" + oracleKey, WIN_REG_ORA_HOME); if (oraHome.equals(home)) { String value = WinRegistry.readString(WinRegistry.HKEY_LOCAL_MACHINE, WIN_REG_ORACLE + "\\" + oracleKey, name); if (value != null) { return value; } } } } } catch (IllegalAccessException e) { log.warn("Error reading Windows registry", e); } catch (InvocationTargetException e) { log.warn("Error reading Windows registry", e); } } return null; } /* public static boolean isOciDriver(DBPDriver driver) { return DRIVER_NAME_OCI.equals(driver.getId()); } */ /** * Returns an installed Oracle client full version * @return oracle version */ public static String getFullOraVersion(String oraHome, boolean isInstantClient) { String sqlplus = (isInstantClient ? CommonUtils.makeDirectoryName(oraHome) : CommonUtils.makeDirectoryName(oraHome) + "bin/") + "sqlplus -version"; try { Process p = Runtime.getRuntime().exec(sqlplus); try { BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); try { String line; while ((line = input.readLine()) != null) { if (line.startsWith("SQL*Plus: Release ")) { return line.substring(18, line.indexOf(" ", 19)); } } } finally { IOUtils.close(input); } } finally { p.destroy(); } } catch (Exception ex) { log.warn("Error reading Oracle client version from " + sqlplus, ex); } return null; } /** * Reads TNS names from a specified Oracle home or system variable TNS_ADMIN. */ public static List<String> readTnsNames(@Nullable File oraHome, boolean checkTnsAdmin) { File tnsNamesFile = null; if (checkTnsAdmin) { String tnsAdmin = System.getenv(VAR_TNS_ADMIN); if (tnsAdmin != null) { tnsNamesFile = new File (CommonUtils.removeTrailingSlash(tnsAdmin) + "/" + TNSNAMES_FILE_NAME); } } if ((tnsNamesFile == null || !tnsNamesFile.exists()) && oraHome != null) { tnsNamesFile = new File (oraHome, TNSNAMES_FILE_PATH + TNSNAMES_FILE_NAME); } if (tnsNamesFile != null && tnsNamesFile.exists()) { return parseTnsNames(tnsNamesFile.getAbsolutePath()); } else { return Collections.emptyList(); } } /** * Reads TNS names from a specified file. */ public static List<String> parseTnsNames(String tnsnamesPath) { ArrayList<String> aliases = new ArrayList<String>(); File tnsnamesOra = new File (tnsnamesPath); if (tnsnamesOra.exists()) { try { BufferedReader reader = new BufferedReader(new FileReader(tnsnamesOra)); String line; while ((line = reader.readLine()) != null) { if (!line.isEmpty() && !line.startsWith(" ") && !line.startsWith("#") && line.contains("=")) { aliases.add(line.substring(0, line.indexOf("="))); } } } catch (FileNotFoundException e) { // do nothing } catch (IOException e) { // do nothing } } else { // do nothing } Collections.sort(aliases); return aliases; } public static boolean isInstantClient(String oraHome) { File root = new File(System.mapLibraryName(CommonUtils.makeDirectoryName(oraHome) + "oci")); File bin = new File(System.mapLibraryName(CommonUtils.makeDirectoryName(oraHome) + "bin/" + "oci")); return root.exists() && !bin.exists(); } }
package org.lockss.plugin.ingenta; import java.io.*; import org.lockss.util.*; import org.lockss.filter.html.HtmlNodeFilters; import org.lockss.test.*; /** * This class tests the IngentaJouranlPluginHtmlFilterFactory. * @author phil * */ public class TestIngentaJournalHtmlFilterFactory extends LockssTestCase { private IngentaJournalHtmlFilterFactory fact; private MockArchivalUnit mau; public void setUp() throws Exception { super.setUp(); fact = new IngentaJournalHtmlFilterFactory(); } // block tags from IngentaJouranlHtmlFilterFactory String blockIds[][] = new String[][] { // only tests the constructed tag rather than actual example from page // Filter out <div id="header">...</div> {"div", "id", "header"}, // Filter out <div id="footerarea">...</div> {"div", "id", "footerarea"}, // Filter out <div id="rightnavbar">...</div> {"div", "id", "rightnavbar"}, // Filter out <div class="article-pager">...</div> {"div", "class", "article-pager"}, // Filter out <div id="purchaseexpand"...>...</div> {"div", "id", "purchaseexpand"}, // Filter out <div id="moredetails">...</div> {"div", "id", "moredetails"}, // Filter out <div id="moreLikeThis">...</div> {"div", "id", "moreLikeThis"}, // filter out <div class="heading"> that encloses a statement with // the number of references and the number that can be referenced: // number of reference links won't be the same because not all // the referenced articles are available at a given institution. {"div", "class", "heading"}, // filter out <div class="advertisingbanner[ clear]"> that encloses // GA_googleFillSlot("TopLeaderboard") & GA_googleFillSlot("Horizontal_banner") {"div", "class", "advertisingbanner"}, {"div", "class", "advertisingbanner clear"}, // filter out <li class="data"> that encloses a reference for the // article: reference links won't be the same because not all // the referenced articles are available at a given institution. {"li", "class", "data"}, // institution-specific subscription link section {"div", "id", "subscribe-links"}, // Filter out <div id="links">...</div> {"div", "id", "links"}, // Filter out <div id="footer">...</div> {"div", "id", "footer"}, // Filter out <div id="top-ad-alignment">...</div> {"div", "id", "top-ad-alignment"}, // Filter out <div id="top-ad">...</div> {"div", "id", "top-ad"}, // Filter out <div id="ident">...</div> {"div", "id", "ident"}, // Filter out <div id="ad">...</div> {"div", "id", "ad"}, // Filter out <div id="vertical-ad">...</div> {"div", "id", "vertical-ad"}, // Filter out <div class="right-col-download">...</div> {"div", "class", "right-col-download"}, // Filter out <div id="cart-navbar">...</div> {"div", "id", "cart-navbar"}, // Filter out <div id="baynote-recommendations">...</div> {"div", "id", "baynote-recommendations"}, // Filter out <div id="bookmarks-container">...</div> {"div", "id", "bookmarks-container"}, // Filter out <div id="llb">...</div> {"div", "id", "llb"}, // Filter out <a href="...">...</a> where the href value includes "exitTargetId" as a parameter {"a", "href", "foo?exitTargetId=bar"}, {"a", "href", "foo?parm=value&exitTargetId=bar"}, // Icon on article reference page {"span", "class", "access-icon"}, }; // single tags from IngentaJouranlHtmlFilterFactory String[][] tagIds = new String[][] { // filter out <link rel="stylesheet" href="..."> because Ingenta has // bad habit of adding a version number to the CSS file name {"link", "rel", "stylesheet"}, // Filter out <input name="exitTargetId"> {"input", "name", "exitTargetId"}, }; public void testTagFiltering() throws Exception { // common filtered html results String filteredHtml = "<!DOCTYPE HTML PUBLIC \"- + "<html lang=\"en\"> <head> <body> " + "</body> </html> "; // html for block tags String blockHtml = "<!DOCTYPE HTML PUBLIC \"- + "<html lang=\"en\">\n<head>\n<body>\n" + "<%s %s=\"%s\">\n" + "chicken chicken chicken...\n" + "</%s>\n" + "</body>\n</html>\n\n\n"; // test block tag ID filtering for (String[] id : blockIds) { InputStream htmlIn = fact.createFilteredInputStream(mau, new StringInputStream(String.format(blockHtml, id[0],id[1],id[2],id[0])), Constants.DEFAULT_ENCODING); assertEquals(filteredHtml, StringUtil.fromInputStream(htmlIn)); } // html for single tags String tagHtml = "<!DOCTYPE HTML PUBLIC \"- + "<html lang=\"en\">\n<head>\n<body>\n" + "<%s %s=\"%s\">\n" + "</body>\n</html>\n\n\n"; // test single tag ID filtering for (String[] id : tagIds) { InputStream htmlIn = fact.createFilteredInputStream(mau, new StringInputStream(String.format(tagHtml, id[0],id[1],id[2])), Constants.DEFAULT_ENCODING); assertEquals(filteredHtml, StringUtil.fromInputStream(htmlIn)); } } //test AdvertisingBannerHtml with explicit tests private static final String AdvertisingBannerHtml = "<p>The chickens were decidedly cold.</p>" + "<div class=\"advertisingbanner\"> " + "<script type='text/javascript'>" + "GA_googleFillSlot(\"TopLeaderboard\"); </script>" + "<script type='text/javascript'>" + "GA_googleFillSlot(\"Horizontal_banner\"); </script>" + "</div>"; private static final String AdvertisingBannerHtmlFiltered = "<p>The chickens were decidedly cold.</p>" ; //test span rust with explicit tests private static final String HeadingMacfixHtml = "<p>The chickens were decidedly cold.</p>" + "<div class=\"heading-macfix\"> " + "<span class=\"rust\"> 2" + "</span> references have been identified for this article, " + "of which <span class=\"rust\">2</span> have matches and can be" + "accessed below </div>"; private static final String HeadingMacfixHtmlFiltered = "<p>The chickens were decidedly cold.</p>" ; public void testFilterAdvertising() throws Exception { InputStream inA; inA = fact.createFilteredInputStream(mau, new StringInputStream(AdvertisingBannerHtml), Constants.DEFAULT_ENCODING); assertEquals(AdvertisingBannerHtmlFiltered,StringUtil.fromInputStream(inA)); } //test some straight html strings with explicit tests private static final String expireChecksumHtml = "<p>The chickens were decidedly cold.</p>" + "<p xmlns:f=\"http: "<a name=\"g002\"></a>" + "<div class=\"figure\">" + "<div class=\"image\">" + "<a class=\"table-popup\" href=\"javascript:popupImage('s4-ft1401-0065-g002.gif.html?expires=1355962274&id=72080579&titleid=6312&accname=Stanford+University&checksum=FA59636C74DD0E40E92BA6EFECB866E7')\">" + "<img alt=\"Figure 1\" border=\"0\" src=\"s4-ft1401-0065-g002_thmb.gif\">" + "<p>Figure 1<br>Click to view</p>" + "</a>" + "</div>" + "<div class=\"caption\">" + "<span class=\"captionLabel\"><span class=\"label\">The Chickens.</span></span>" + "</div>"; // NOTE - the two following lines below: // "<p>Figure 1<br>Click to view</p>" + // need to be included in the filtered result because // the <a> tag hashing will stop when it finds an embedded composite tag, // (in this case, <p>). Once we update the daemon to allow modifying this in a subclass // then we'll need to make the change for this plugin & update this test. // HOWEVER - this still solves the hash problems since the item to remove is // before the <p> tag private static final String expireChecksumFiltered = "<p>The chickens were decidedly cold.</p>" + "<p xmlns:f=\"http: "<a name=\"g002\"></a>" + "<div class=\"figure\">" + "<div class=\"image\">" + "<p>Figure 1<br>Click to view</p>" + "</a>" + "</div>" + "<div class=\"caption\">" + "<span class=\"captionLabel\"><span class=\"label\">The Chickens.</span></span>" + "</div>"; public void testFiltering() throws Exception { InputStream inA; inA = fact.createFilteredInputStream(mau, new StringInputStream(expireChecksumHtml), Constants.DEFAULT_ENCODING); assertEquals(expireChecksumFiltered,StringUtil.fromInputStream(inA)); } private static final String onClickExitTargetID = "<div class=\"left-col-download\">View now:</div>" + "<div class=\"right-col-download contain\">" + "<span class=\"orangebutton\">" + "<span class=\"orangeleftside icbutton\">" + "<a onclick=\"javascript:popup('/search/download?pub=infobike%3a%2f%2flse%2fjtep%2f2001%2f00000035%2f00000001%2fart00001&mimetype=" + "application%2fpdf&exitTargetId=1371686277240','dowloadWindow','900','800')\" title=\"PDF download of Editorial\" class=\"no-underl" + "ine contain\" >PDF" + "</a></span></span>" + "</div>"; private static final String onClickExitTargetIDFiltered = "<div class=\"left-col-download\">View now:</div>" + "<div class=\"right-col-download contain\">" + "<span class=\"orangebutton\">" + "<span class=\"orangeleftside icbutton\">" + "</span></span>" + "</div>"; public void testonClickFiltering() throws Exception { InputStream inA; inA = fact.createFilteredInputStream(mau, new StringInputStream(onClickExitTargetID), Constants.DEFAULT_ENCODING); assertEquals(onClickExitTargetIDFiltered,StringUtil.fromInputStream(inA)); } }
package org.apache.jmeter.gui.util; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import javax.swing.JTextField; public class JDateField extends JTextField { private final static DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); /* * The following array must agree with dateFormat * * It is used to translate the positions in the buffer * to the values used by the Calendar class for the field id. * * Current format: * MM/DD/YYYY HH:MM:SS * 01234567890123456789 * ^buffer positions */ private static int fieldPositions [] = { Calendar.YEAR, Calendar.YEAR, Calendar.YEAR, Calendar.YEAR, Calendar.YEAR, Calendar.MONTH, Calendar.MONTH, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.DAY_OF_MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR_OF_DAY, Calendar.HOUR_OF_DAY, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.MINUTE, Calendar.MINUTE, Calendar.SECOND, Calendar.SECOND, Calendar.SECOND // end }; /** * Create a DateField with the specified date. */ public JDateField(Date date) { super(20); this.addKeyListener(new KeyFocus()); this.addFocusListener(new FocusClass()); String myString = dateFormat.format(date); setText(myString); } /** * Set the date to the Date mask control. */ public void setDate(Date date) { setText(dateFormat.format(date)); } /** * Get the date from the Date mask control. */ public Date getDate() { try { return dateFormat.parse(getText()); } catch (ParseException e) { return new Date(); } } /* * Convert position in buffer to Calendar type * Assumes that pos >=0 (which is true for getCaretPosition()) */ private static int posToField(int pos){ if (pos >= fieldPositions.length) { // if beyond the end pos = fieldPositions.length - 1; // then set to the end } return fieldPositions[pos]; } /** * Converts a date/time to a calendar using the defined format */ private static Calendar parseDate(String datetime) { Calendar c = Calendar.getInstance(); try { Date dat = dateFormat.parse(datetime); c.setTime(dat); } catch (ParseException e) { //Do nothing; the current time will be returned } return c; } /* * Update the current field. The addend is only expected to be +1/-1, * but other values will work. * N.B. the roll() method only supports changes by a single unit - up or down */ private void update(int addend, boolean shifted){ Calendar c = parseDate(getText()); int pos = getCaretPosition(); int field = posToField(pos); if (shifted){ c.roll(field,true); } else { c.add(field,addend); } String newDate =dateFormat.format(c.getTime()); setText(newDate); if (pos > newDate.length()) pos = newDate.length(); setCaretPosition(pos);// Restore position } /** * @author T.Elanjchezhiyan * @version $Revision$ */ class KeyFocus extends KeyAdapter { KeyFocus() { } public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_UP) { update(1,e.isShiftDown()); } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { update(-1,e.isShiftDown()); } } } /** * @author T.Elanjchezhiyan * @version $Revision$ */ class FocusClass implements FocusListener { FocusClass() { } public void focusGained(FocusEvent e) { } public void focusLost(FocusEvent e) { try { dateFormat.parse(getText()); } catch (ParseException e1) { requestFocus(); } } } }
package de.lmu.ifi.dbs.elki.algorithm.outlier; import java.util.ArrayList; import java.util.Collections; import java.util.List; import de.lmu.ifi.dbs.elki.algorithm.DistanceBasedAlgorithm; import de.lmu.ifi.dbs.elki.data.DatabaseObject; import de.lmu.ifi.dbs.elki.database.AssociationID; import de.lmu.ifi.dbs.elki.database.Database; import de.lmu.ifi.dbs.elki.distance.DoubleDistance; import de.lmu.ifi.dbs.elki.result.AnnotationsFromDatabase; import de.lmu.ifi.dbs.elki.result.MultiResult; import de.lmu.ifi.dbs.elki.result.OrderingFromAssociation; import de.lmu.ifi.dbs.elki.utilities.Description; import de.lmu.ifi.dbs.elki.utilities.QueryResult; import de.lmu.ifi.dbs.elki.utilities.optionhandling.DoubleParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.IntParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID; import de.lmu.ifi.dbs.elki.utilities.optionhandling.ParameterException; import de.lmu.ifi.dbs.elki.utilities.optionhandling.PatternParameter; import de.lmu.ifi.dbs.elki.utilities.pairs.ComparablePair; /** * Fast Outlier Detection Using the "Local Correlation Integral". * * Exact implementation only, not aLOCI. * * Outlier detection using multiple epsilon neighborhoods. * * Based on: * S. Papadimitriou, H. Kitagawa, P. B. Gibbons and C. Faloutsos: * LOCI: Fast Outlier Detection Using the Local Correlation Integral. * In: Proc. 19th IEEE Int. Conf. on Data Engineering (ICDE '03), Bangalore, India, 2003. * * @author Erich Schubert * * @param <O> */ public class LOCI<O extends DatabaseObject> extends DistanceBasedAlgorithm<O, DoubleDistance, MultiResult> { /** * OptionID for {@link #RMAX_PARAM} */ public static final OptionID RMAX_ID = OptionID.getOrCreateOptionID( "loci.rmax", "The maximum radius of the neighborhood to be considered." ); /** * OptionID for {@link #NMIN_PARAM} */ public static final OptionID NMIN_ID = OptionID.getOrCreateOptionID( "loci.nmin", "Minimum neighborhood size to be considered." ); /** * OptionID for {@link #ALPHA_PARAM} */ public static final OptionID ALPHA_ID = OptionID.getOrCreateOptionID( "loci.alpha", "Scaling factor for averaging neighborhood" ); /** * Parameter to specify the maximum radius of the neighborhood to be considered, * must be suitable to the distance function specified. * <p>Key: {@code -loci.rmax} </p> */ private final PatternParameter RMAX_PARAM = new PatternParameter(RMAX_ID); /** * Holds the value of {@link #RMAX_PARAM}. */ private String rmax; /** * Parameter to specify the minimum neighborhood size * <p>Key: {@code -loci.alpha} </p> */ private final IntParameter NMIN_PARAM = new IntParameter(NMIN_ID, null, 20); /** * Holds the value of {@link #NMIN_PARAM}. */ private double nmin; /** * Parameter to specify the averaging neighborhood scaling * <p>Key: {@code -loci.alpha} </p> */ private final DoubleParameter ALPHA_PARAM = new DoubleParameter(ALPHA_ID); /** * Holds the value of {@link #ALPHA_PARAM}. */ private double alpha; /** * Provides the result of the algorithm. */ MultiResult result; /** * Constructor, adding options to option handler. */ public LOCI() { super(); // maximum query range addOption(RMAX_PARAM); // minimum neighborhood size addOption(NMIN_PARAM); // scaling factor for averaging range addOption(ALPHA_PARAM); } /** * Calls the super method * and sets additionally the values of the parameter * {@link #RMAX_PARAM}, {@link #NMIN_PARAM} and {@link #ALPHA_PARAM} */ @Override public String[] setParameters(String[] args) throws ParameterException { String[] remainingParameters = super.setParameters(args); // maximum query radius rmax = RMAX_PARAM.getValue(); // minimum neighborhood size nmin = NMIN_PARAM.getValue(); // averaging range scaling alpha = ALPHA_PARAM.getValue(); return remainingParameters; } /** * Runs the algorithm in the timed evaluation part. */ @Override protected MultiResult runInTime(Database<O> database) throws IllegalStateException { getDistanceFunction().setDatabase(database, isVerbose(), isTime()); // LOCI preprocessing step for (Integer id : database.getIDs()) { List<QueryResult<DoubleDistance>> neighbors = database.rangeQuery(id, rmax, getDistanceFunction()); // build list of critical distances ArrayList<ComparablePair<Double,Integer>> cdist = new ArrayList<ComparablePair<Double,Integer>>(neighbors.size() * 2); { int i = 0; for (QueryResult<DoubleDistance> r : neighbors) { cdist.add(new ComparablePair<Double,Integer>(r.getDistance().getValue(), i)); cdist.add(new ComparablePair<Double,Integer>(r.getDistance().getValue() / alpha, null)); i++; } } Collections.sort(cdist); // fill the gaps to have fast lookups of number of neighbors at a given distance. int lastk = 0; for (ComparablePair<Double,Integer> c : cdist) { if (c.second == null) c.second = lastk; else lastk = c.second; } database.associate(AssociationID.LOCI_CRITICALDIST, id, cdist); } // LOCI main step for (Integer id : database.getIDs()) { double maxmdefnorm = 0.0; double maxnormr = 0; List<ComparablePair<Double,Integer>> cdist = database.getAssociation(AssociationID.LOCI_CRITICALDIST, id); for (ComparablePair<Double,Integer> c : cdist) { double alpha_r = alpha * c.first; // compute n(p_i, \alpha * r) from list int n_alphar = 0; for (ComparablePair<Double,Integer> c2 : cdist) { if (c2.first <= alpha_r) n_alphar=c2.second; else break; } // compute \hat{n}(p_i, r, \alpha) double nhat_r_alpha = 0.0; double sigma_nhat_r_alpha = 0.0; // note that the query range is c.first List<QueryResult<DoubleDistance>> rneighbors = database.rangeQuery(id, Double.toString(c.first), getDistanceFunction()); if (rneighbors.size() < nmin) continue; for (QueryResult<DoubleDistance> rn : rneighbors) { List<ComparablePair<Double,Integer>> rncdist = database.getAssociation(AssociationID.LOCI_CRITICALDIST, rn.getID()); int rn_alphar = 0; for (ComparablePair<Double,Integer> c2 : rncdist) { if (c2.first <= alpha_r) rn_alphar=c2.second; else break; } nhat_r_alpha = nhat_r_alpha + rn_alphar; sigma_nhat_r_alpha = sigma_nhat_r_alpha + (rn_alphar * rn_alphar); } // finalize average and deviation nhat_r_alpha = nhat_r_alpha / rneighbors.size(); sigma_nhat_r_alpha = Math.sqrt(sigma_nhat_r_alpha / rneighbors.size() - nhat_r_alpha * nhat_r_alpha); double mdef = 1.0 - (n_alphar / nhat_r_alpha); double sigmamdef = sigma_nhat_r_alpha / nhat_r_alpha; double mdefnorm = mdef / sigmamdef; if (mdefnorm > maxmdefnorm) { maxmdefnorm = mdefnorm; maxnormr = c.first; } } // TODO: when nmin was never fulfilled, the values will remain 0. database.associate(AssociationID.LOCI_MDEF_NORM, id, maxmdefnorm); database.associate(AssociationID.LOCI_MDEF_CRITICAL_RADIUS, id, maxnormr); } AnnotationsFromDatabase<O, Double> res1 = new AnnotationsFromDatabase<O, Double>(database); res1.addAssociation("MDEF_NORM", AssociationID.LOCI_MDEF_NORM); res1.addAssociation("LOCI_RADIUS", AssociationID.LOCI_MDEF_CRITICAL_RADIUS); OrderingFromAssociation<Double, O> res2 = new OrderingFromAssociation<Double, O>(database, AssociationID.LOCI_MDEF_NORM, true); result = new MultiResult(); result.addResult(res1); result.addResult(res2); return result; } /** * Get algorithm description. */ public Description getDescription() { return new Description( "LOCI", "Fast Outlier Detection Using the Local Correlation Integral", "Algorithm to compute outliers based on the Local Correlation Integral", "S. Papadimitriou, H. Kitagawa, P. B. Gibbons and C. Faloutsos: " + "LOCI: Fast Outlier Detection Using the Local Correlation Integral. " + "In: Proc. 19th IEEE Int. Conf. on Data Engineering (ICDE '03), Bangalore, India, 2003."); } /** * Return result. */ public MultiResult getResult() { return result; } }
package de.superioz.mcuc.scenes; import de.superioz.mcuc.Main; import de.superioz.mcuc.PremiumChecker; import de.superioz.mcuc.UsernameVerifier; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.ProgressIndicator; import javafx.scene.control.TextField; import javafx.scene.paint.Color; import java.util.Timer; import java.util.TimerTask; public class FunctionController { // variables public Main app; // FXML variables @FXML private TextField textField; @FXML private Label resultLabel; @FXML private ProgressIndicator progressIndicator; // setting main to use public void setMain(Main main){ this.app = main; } /* checking if username is premium */ @FXML public void handleCheckUsername(){ String givenName = textField.getText(); if(givenName.isEmpty()){ this.app.showError("Falsche Eingabe!", "Das Textfeld darf nicht leer bleiben, sonst kann nicht überprüft werden, ob der Spieler wirklich ein Premium User ist. Drücke 'Ok' um zur Applikation zurück zu kehren."); return; } else if(!(UsernameVerifier.verifyUsername(givenName, this.app))){ return; } progressIndicator.setVisible(true); final boolean[] isPremium = {false}; // setting timer to fade in text and chec the username in other thread Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { isPremium[0] = PremiumChecker.checkUsername(givenName, app); // setting progress unvisible progressIndicator.setVisible(false); Platform.runLater(() -> { // setting the result label resultLabel.setVisible(true); setResultLabel(isPremium[0]); }); } }, 60*25); // setting timer to timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { Platform.runLater(() -> resultLabel.setVisible(false)); } }, 60*100); } public void setResultLabel(boolean isPremium){ if(isPremium){ resultLabel.setText("Der Username ist bereits vergeben."); resultLabel.setTextFill(Color.RED); } else{ resultLabel.setText("Der Username ist noch frei."); resultLabel.setTextFill(Color.GREEN); } } }
package edu.mit.streamjit.impl.compiler2; import com.google.common.base.Function; import static com.google.common.base.Preconditions.checkState; import com.google.common.collect.FluentIterable; import com.google.common.collect.HashBasedTable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.ImmutableTable; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import com.google.common.collect.Range; import com.google.common.collect.Sets; import com.google.common.collect.Table; import com.google.common.primitives.Ints; import com.google.common.primitives.Primitives; import com.google.common.reflect.TypeResolver; import com.google.common.reflect.TypeToken; import edu.mit.streamjit.api.DuplicateSplitter; import edu.mit.streamjit.api.IllegalStreamGraphException; import edu.mit.streamjit.api.Input; import edu.mit.streamjit.api.Joiner; import edu.mit.streamjit.api.Output; import edu.mit.streamjit.api.RoundrobinJoiner; import edu.mit.streamjit.api.RoundrobinSplitter; import edu.mit.streamjit.api.Splitter; import edu.mit.streamjit.api.StreamCompilationFailedException; import edu.mit.streamjit.api.StreamCompiler; import edu.mit.streamjit.api.WeightedRoundrobinJoiner; import edu.mit.streamjit.api.WeightedRoundrobinSplitter; import edu.mit.streamjit.api.Worker; import edu.mit.streamjit.impl.blob.Blob; import edu.mit.streamjit.impl.blob.Blob.Token; import edu.mit.streamjit.impl.blob.Buffer; import edu.mit.streamjit.impl.blob.DrainData; import edu.mit.streamjit.impl.blob.PeekableBuffer; import edu.mit.streamjit.impl.common.Configuration; import edu.mit.streamjit.impl.common.Configuration.IntParameter; import edu.mit.streamjit.impl.common.Configuration.SwitchParameter; import edu.mit.streamjit.impl.common.InputBufferFactory; import edu.mit.streamjit.impl.common.OutputBufferFactory; import edu.mit.streamjit.impl.common.Workers; import edu.mit.streamjit.impl.compiler.Schedule; import edu.mit.streamjit.impl.compiler2.Compiler2BlobHost.DrainInstruction; import edu.mit.streamjit.impl.compiler2.Compiler2BlobHost.ReadInstruction; import edu.mit.streamjit.impl.compiler2.Compiler2BlobHost.WriteInstruction; import edu.mit.streamjit.test.Benchmark; import edu.mit.streamjit.test.Benchmarker; import edu.mit.streamjit.test.apps.fmradio.FMRadio; import edu.mit.streamjit.util.CollectionUtils; import edu.mit.streamjit.util.bytecode.methodhandles.Combinators; import static edu.mit.streamjit.util.bytecode.methodhandles.LookupUtils.findStatic; import edu.mit.streamjit.util.Pair; import edu.mit.streamjit.util.ReflectionUtils; import edu.mit.streamjit.util.bytecode.Module; import edu.mit.streamjit.util.bytecode.ModuleClassLoader; import edu.mit.streamjit.util.bytecode.methodhandles.ProxyFactory; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; 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.NavigableSet; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * * @author Jeffrey Bosboom <jbosboom@csail.mit.edu> * @since 9/22/2013 */ public class Compiler2 { public static final ImmutableSet<Class<?>> REMOVABLE_WORKERS = ImmutableSet.<Class<?>>of( RoundrobinSplitter.class, WeightedRoundrobinSplitter.class, DuplicateSplitter.class, RoundrobinJoiner.class, WeightedRoundrobinJoiner.class); public static final ImmutableSet<IndexFunctionTransformer> INDEX_FUNCTION_TRANSFORMERS = ImmutableSet.<IndexFunctionTransformer>of( new IdentityIndexFunctionTransformer() // new ArrayifyIndexFunctionTransformer(false), // new ArrayifyIndexFunctionTransformer(true) ); public static final RemovalStrategy REMOVAL_STRATEGY = new BitsetRemovalStrategy(); public static final FusionStrategy FUSION_STRATEGY = new BitsetFusionStrategy(); public static final UnboxingStrategy UNBOXING_STRATEGY = new BitsetUnboxingStrategy(); public static final AllocationStrategy ALLOCATION_STRATEGY = new SubsetBiasAllocationStrategy(8); public static final StorageStrategy INTERNAL_STORAGE_STRATEGY = new TuneInternalStorageStrategy(); public static final StorageStrategy EXTERNAL_STORAGE_STRATEGY = new TuneExternalStorageStrategy(); public static final SwitchingStrategy SWITCHING_STRATEGY = SwitchingStrategy.tunePerWorker(); private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup(); private static final AtomicInteger PACKAGE_NUMBER = new AtomicInteger(); private final ImmutableSet<Worker<?, ?>> workers; private final ImmutableSet<ActorArchetype> archetypes; private final NavigableSet<Actor> actors; private ImmutableSortedSet<ActorGroup> groups; private ImmutableSortedSet<WorkerActor> actorsToBeRemoved; private final Configuration config; private final int maxNumCores; private final DrainData initialState; /** * If the blob is the entire graph, this is the overall input; else null. */ private final Input<?> overallInput; /** * If the blob is the entire graph, this is the overall output; else null. */ private final Output<?> overallOutput; private Buffer overallInputBuffer, overallOutputBuffer; private ImmutableMap<Token, Buffer> precreatedBuffers; private final ImmutableMap<Token, ImmutableList<Object>> initialStateDataMap; private final Set<Storage> storage; private ImmutableMap<ActorGroup, Integer> externalSchedule; private final Module module = new Module(); private final ModuleClassLoader classloader = new ModuleClassLoader(module); private final String packageName = "compiler"+PACKAGE_NUMBER.getAndIncrement(); private ImmutableMap<ActorGroup, Integer> initSchedule; /** * For each token in the blob, the number of items live on that edge after * the init schedule, without regard to removals. (We could recover this * information from Actor.inputSlots when we're creating drain instructions, * but storing it simplifies the code and permits asserting we didn't lose * any items.) */ private ImmutableMap<Token, Integer> postInitLiveness; /** * ConcreteStorage instances used during initialization (bound into the * initialization code). */ private ImmutableMap<Storage, ConcreteStorage> initStorage; /** * ConcreteStorage instances used during the steady-state (bound into the * steady-state code). */ private ImmutableMap<Storage, ConcreteStorage> steadyStateStorage; /** * Code to run the initialization schedule. (Initialization is * single-threaded.) */ private MethodHandle initCode; /** * Code to run the steady state schedule. The blob host takes care of * filling/flushing buffers, adjusting storage and the global barrier. */ private ImmutableList<MethodHandle> steadyStateCode; private final List<ReadInstruction> initReadInstructions = new ArrayList<>(); private final List<WriteInstruction> initWriteInstructions = new ArrayList<>(); private final List<Runnable> migrationInstructions = new ArrayList<>(); private final List<ReadInstruction> readInstructions = new ArrayList<>(); private final List<WriteInstruction> writeInstructions = new ArrayList<>(); private final List<DrainInstruction> drainInstructions = new ArrayList<>(); public Compiler2(Set<Worker<?, ?>> workers, Configuration config, int maxNumCores, DrainData initialState, Input<?> input, Output<?> output) { this.workers = ImmutableSet.copyOf(workers); Map<Class<?>, ActorArchetype> archetypesBuilder = new HashMap<>(); Map<Worker<?, ?>, WorkerActor> workerActors = new HashMap<>(); for (Worker<?, ?> w : workers) { @SuppressWarnings("unchecked") Class<? extends Worker<?, ?>> wClass = (Class<? extends Worker<?, ?>>)w.getClass(); if (archetypesBuilder.get(wClass) == null) archetypesBuilder.put(wClass, new ActorArchetype(wClass, module)); WorkerActor actor = new WorkerActor(w, archetypesBuilder.get(wClass)); workerActors.put(w, actor); } this.archetypes = ImmutableSet.copyOf(archetypesBuilder.values()); Map<Token, TokenActor> tokenActors = new HashMap<>(); Table<Actor, Actor, Storage> storageTable = HashBasedTable.create(); int[] inputTokenId = new int[]{Integer.MIN_VALUE}, outputTokenId = new int[]{Integer.MAX_VALUE}; for (WorkerActor a : workerActors.values()) a.connect(ImmutableMap.copyOf(workerActors), tokenActors, storageTable, inputTokenId, outputTokenId); this.actors = new TreeSet<>(); this.actors.addAll(workerActors.values()); this.actors.addAll(tokenActors.values()); this.storage = new HashSet<>(storageTable.values()); this.config = config; this.maxNumCores = maxNumCores; this.initialState = initialState; ImmutableMap.Builder<Token, ImmutableList<Object>> initialStateDataMapBuilder = ImmutableMap.builder(); if (initialState != null) { for (Table.Cell<Actor, Actor, Storage> cell : storageTable.cellSet()) { Token tok; if (cell.getRowKey() instanceof TokenActor) tok = ((TokenActor)cell.getRowKey()).token(); else if (cell.getColumnKey() instanceof TokenActor) tok = ((TokenActor)cell.getColumnKey()).token(); else tok = new Token(((WorkerActor)cell.getRowKey()).worker(), ((WorkerActor)cell.getColumnKey()).worker()); ImmutableList<Object> data = initialState.getData(tok); if (data != null && !data.isEmpty()) { initialStateDataMapBuilder.put(tok, data); cell.getValue().initialData().add(Pair.make(data, MethodHandles.identity(int.class))); } } } this.initialStateDataMap = initialStateDataMapBuilder.build(); this.overallInput = input; this.overallOutput = output; } public Blob compile() { findRemovals(); fuse(); schedule(); // identityRemoval(); splitterRemoval(); joinerRemoval(); inferTypes(); unbox(); generateArchetypalCode(); createBuffers(); createInitCode(); createSteadyStateCode(); return instantiateBlob(); } private void findRemovals() { ImmutableSortedSet.Builder<WorkerActor> builder = ImmutableSortedSet.naturalOrder(); next_worker: for (WorkerActor a : Iterables.filter(actors, WorkerActor.class)) { if (!REMOVABLE_WORKERS.contains(a.worker().getClass())) continue; for (Storage s : a.outputs()) if (!s.initialData().isEmpty()) continue next_worker; for (Storage s : a.inputs()) if (!s.initialData().isEmpty()) continue next_worker; if (!REMOVAL_STRATEGY.remove(a, config)) continue; builder.add(a); } this.actorsToBeRemoved = builder.build(); } /** * Fuses actors into groups as directed by the configuration. */ private void fuse() { List<ActorGroup> actorGroups = new ArrayList<>(); for (Actor a : actors) actorGroups.add(ActorGroup.of(a)); //Fuse as much as possible. just_fused: do { try_fuse: for (Iterator<ActorGroup> it = actorGroups.iterator(); it.hasNext();) { ActorGroup g = it.next(); if (g.isTokenGroup()) continue try_fuse; for (ActorGroup pg : g.predecessorGroups()) if (pg.isTokenGroup()) continue try_fuse; if (g.isPeeking() || g.predecessorGroups().size() > 1) continue try_fuse; for (Storage s : g.inputs()) if (!s.initialData().isEmpty()) continue try_fuse; //We are assuming FusionStrategies are all happy to work //group-by-group. If later we want to make all decisions at //once, we'll refactor existing FusionStrategies to inherit from //a base class containing this loop. if (!FUSION_STRATEGY.fuseUpward(g, config)) continue try_fuse; ActorGroup gpred = Iterables.getOnlyElement(g.predecessorGroups()); ActorGroup fusedGroup = ActorGroup.fuse(g, gpred); it.remove(); actorGroups.remove(gpred); actorGroups.add(fusedGroup); continue just_fused; } break; } while (true); this.groups = ImmutableSortedSet.copyOf(actorGroups); Boolean reportFusion = (Boolean)config.getExtraData("reportFusion"); if (reportFusion != null && reportFusion) { for (ActorGroup g : groups) { if (g.isTokenGroup()) continue; List<Integer> list = new ArrayList<>(); for (Actor a : g.actors()) list.add(a.id()); System.out.println(com.google.common.base.Joiner.on(' ').join(list)); } System.out.flush(); System.exit(0); } } /** * Computes each group's internal schedule and the external schedule. */ private void schedule() { for (ActorGroup g : groups) internalSchedule(g); externalSchedule(); initSchedule(); } private void externalSchedule() { Schedule.Builder<ActorGroup> scheduleBuilder = Schedule.builder(); scheduleBuilder.addAll(groups); for (ActorGroup g : groups) { for (Storage e : g.outputs()) { Actor upstream = Iterables.getOnlyElement(e.upstream()); Actor downstream = Iterables.getOnlyElement(e.downstream()); ActorGroup other = downstream.group(); int upstreamAdjust = g.schedule().get(upstream); int downstreamAdjust = other.schedule().get(downstream); scheduleBuilder.connect(g, other) .push(e.push() * upstreamAdjust) .pop(e.pop() * downstreamAdjust) .peek(e.peek() * downstreamAdjust) .bufferExactly(0); } } int multiplier = config.getParameter("multiplier", IntParameter.class).getValue(); scheduleBuilder.multiply(multiplier); try { externalSchedule = scheduleBuilder.build().getSchedule(); } catch (Schedule.ScheduleException ex) { throw new StreamCompilationFailedException("couldn't find external schedule; mult = "+multiplier, ex); } } /** * Computes the internal schedule for the given group. */ private void internalSchedule(ActorGroup g) { Schedule.Builder<Actor> scheduleBuilder = Schedule.builder(); scheduleBuilder.addAll(g.actors()); for (Actor a : g.actors()) scheduleBuilder.executeAtLeast(a, 1); for (Storage s : g.internalEdges()) { scheduleBuilder.connect(Iterables.getOnlyElement(s.upstream()), Iterables.getOnlyElement(s.downstream())) .push(s.push()) .pop(s.pop()) .peek(s.peek()) .bufferExactly(0); } try { Schedule<Actor> schedule = scheduleBuilder.build(); g.setSchedule(schedule.getSchedule()); } catch (Schedule.ScheduleException ex) { throw new StreamCompilationFailedException("couldn't find internal schedule for group "+g+"\n"+scheduleBuilder.toString(), ex); } } private void initSchedule() { Schedule.Builder<ActorGroup> scheduleBuilder = Schedule.builder(); scheduleBuilder.addAll(groups); for (Storage s : storage) { if (s.isInternal()) continue; Actor upstream = Iterables.getOnlyElement(s.upstream()), downstream = Iterables.getOnlyElement(s.downstream()); int upstreamAdjust = upstream.group().schedule().get(upstream); int downstreamAdjust = downstream.group().schedule().get(downstream); int throughput, excessPeeks; //TODO: avoid double-buffering token groups here? if (actorsToBeRemoved.contains(downstream) && false) throughput = excessPeeks = 0; else { throughput = s.push() * upstreamAdjust * externalSchedule.get(upstream.group()); excessPeeks = Math.max(s.peek() - s.pop(), 0); } int initialDataSize = Iterables.getOnlyElement(s.initialData(), new Pair<>(ImmutableList.<Object>of(), (MethodHandle)null)).first.size(); scheduleBuilder.connect(upstream.group(), downstream.group()) .push(s.push() * upstreamAdjust) .pop(s.pop() * downstreamAdjust) .peek(s.peek() * downstreamAdjust) .bufferAtLeast(throughput + excessPeeks - initialDataSize); } IntParameter initBufferingCostParam = config.getParameter("InitBufferingCost", IntParameter.class); int initBufferCost = initBufferingCostParam.getValue(), fireCost = initBufferingCostParam.getMax() - initBufferCost; scheduleBuilder.costs(fireCost, initBufferCost); try { Schedule<ActorGroup> schedule = scheduleBuilder.build(); this.initSchedule = schedule.getSchedule(); } catch (Schedule.ScheduleException ex) { throw new StreamCompilationFailedException("couldn't find init schedule", ex); } ImmutableMap.Builder<Token, Integer> postInitLivenessBuilder = ImmutableMap.builder(); for (Storage s : storage) { if (s.isInternal()) continue; Actor upstream = Iterables.getOnlyElement(s.upstream()), downstream = Iterables.getOnlyElement(s.downstream()); int upstreamExecutions = upstream.group().schedule().get(upstream) * initSchedule.get(upstream.group()); int downstreamExecutions = downstream.group().schedule().get(downstream) * initSchedule.get(downstream.group()); int liveItems = s.push() * upstreamExecutions - s.pop() * downstreamExecutions + s.initialDataIndices().size(); assert liveItems >= 0 : s; int index = downstream.inputs().indexOf(s); assert index != -1; Token token; if (downstream instanceof WorkerActor) { Worker<?, ?> w = ((WorkerActor)downstream).worker(); token = downstream.id() == 0 ? Token.createOverallInputToken(w) : new Token(Workers.getPredecessors(w).get(index), w); } else token = ((TokenActor)downstream).token(); for (int i = 0; i < liveItems; ++i) downstream.inputSlots(index).add(StorageSlot.live(token, i)); postInitLivenessBuilder.put(token, liveItems); } this.postInitLiveness = postInitLivenessBuilder.build(); int initScheduleSize = 0; for (int i : initSchedule.values()) initScheduleSize += i; // System.out.println("init schedule size "+initScheduleSize); int totalBuffering = 0; for (int i : postInitLiveness.values()) totalBuffering += i; // System.out.println("total items buffered "+totalBuffering); } private void splitterRemoval() { for (WorkerActor splitter : actorsToBeRemoved) { if (!(splitter.worker() instanceof Splitter)) continue; List<MethodHandle> transfers = splitterTransferFunctions(splitter); Storage survivor = Iterables.getOnlyElement(splitter.inputs()); //Remove all instances of splitter, not just the first. survivor.downstream().removeAll(ImmutableList.of(splitter)); MethodHandle Sin = Iterables.getOnlyElement(splitter.inputIndexFunctions()); List<StorageSlot> drainInfo = splitter.inputSlots(0); for (int i = 0; i < splitter.outputs().size(); ++i) { Storage victim = splitter.outputs().get(i); MethodHandle t = transfers.get(i); for (Actor a : victim.downstream()) { List<Storage> inputs = a.inputs(); List<MethodHandle> inputIndices = a.inputIndexFunctions(); for (int j = 0; j < inputs.size(); ++j) if (inputs.get(j).equals(victim)) { inputs.set(j, survivor); survivor.downstream().add(a); inputIndices.set(j, MethodHandles.filterReturnValue(inputIndices.get(j), t)); if (splitter.push(i) > 0) for (int idx = 0, q = a.translateInputIndex(j, idx); q < drainInfo.size(); ++idx, q = a.translateInputIndex(j, idx)) { a.inputSlots(j).add(drainInfo.get(q)); drainInfo.set(q, drainInfo.get(q).duplify()); } inputIndices.set(j, MethodHandles.filterReturnValue(inputIndices.get(j), Sin)); } } for (Pair<ImmutableList<Object>, MethodHandle> item : victim.initialData()) survivor.initialData().add(new Pair<>(item.first, MethodHandles.filterReturnValue(item.second, t))); storage.remove(victim); } removeActor(splitter); assert consistency(); } } /** * Returns transfer functions for the given splitter. * * A splitter has one transfer function for each output that maps logical * output indices to logical input indices (representing the splitter's * distribution pattern). * @param a an actor * @return transfer functions, or null */ private List<MethodHandle> splitterTransferFunctions(WorkerActor a) { assert REMOVABLE_WORKERS.contains(a.worker().getClass()) : a.worker().getClass(); if (a.worker() instanceof RoundrobinSplitter || a.worker() instanceof WeightedRoundrobinSplitter) { int[] weights = new int[a.outputs().size()]; for (int i = 0; i < weights.length; ++i) weights[i] = a.push(i); return roundrobinTransferFunctions(weights); } else if (a.worker() instanceof DuplicateSplitter) { return Collections.nCopies(a.outputs().size(), MethodHandles.identity(int.class)); } else throw new AssertionError(); } private void joinerRemoval() { for (WorkerActor joiner : actorsToBeRemoved) { if (!(joiner.worker() instanceof Joiner)) continue; List<MethodHandle> transfers = joinerTransferFunctions(joiner); Storage survivor = Iterables.getOnlyElement(joiner.outputs()); //Remove all instances of joiner, not just the first. survivor.upstream().removeAll(ImmutableList.of(joiner)); MethodHandle Jout = Iterables.getOnlyElement(joiner.outputIndexFunctions()); for (int i = 0; i < joiner.inputs().size(); ++i) { Storage victim = joiner.inputs().get(i); MethodHandle t = transfers.get(i); MethodHandle t2 = MethodHandles.filterReturnValue(t, Jout); for (Actor a : victim.upstream()) { List<Storage> outputs = a.outputs(); List<MethodHandle> outputIndices = a.outputIndexFunctions(); for (int j = 0; j < outputs.size(); ++j) if (outputs.get(j).equals(victim)) { outputs.set(j, survivor); outputIndices.set(j, MethodHandles.filterReturnValue(outputIndices.get(j), t2)); survivor.upstream().add(a); } } for (Pair<ImmutableList<Object>, MethodHandle> item : victim.initialData()) survivor.initialData().add(new Pair<>(item.first, MethodHandles.filterReturnValue(item.second, t2))); storage.remove(victim); } //Linearize drain info from the joiner's inputs. int maxIdx = 0; for (int i = 0; i < joiner.inputs().size(); ++i) { MethodHandle t = transfers.get(i); for (int idx = 0; idx < joiner.inputSlots(i).size(); ++idx) try { maxIdx = Math.max(maxIdx, (int)t.invokeExact(joiner.inputSlots(i).size()-1)); } catch (Throwable ex) { throw new AssertionError("Can't happen! transfer function threw?", ex); } } List<StorageSlot> linearizedInput = new ArrayList<>(Collections.nCopies(maxIdx+1, StorageSlot.hole())); for (int i = 0; i < joiner.inputs().size(); ++i) { MethodHandle t = transfers.get(i); for (int idx = 0; idx < joiner.inputSlots(i).size(); ++idx) try { linearizedInput.set((int)t.invokeExact(idx), joiner.inputSlots(i).get(idx)); } catch (Throwable ex) { throw new AssertionError("Can't happen! transfer function threw?", ex); } joiner.inputSlots(i).clear(); joiner.inputSlots(i).trimToSize(); } if (!linearizedInput.isEmpty()) { for (Actor a : survivor.downstream()) for (int j = 0; j < a.inputs().size(); ++j) if (a.inputs().get(j).equals(survivor)) for (int idx = 0, q = a.translateInputIndex(j, idx); q < linearizedInput.size(); ++idx, q = a.translateInputIndex(j, idx)) { StorageSlot slot = linearizedInput.get(q); a.inputSlots(j).add(slot); linearizedInput.set(q, slot.duplify()); } } // System.out.println("removed "+joiner); removeActor(joiner); assert consistency(); } } private List<MethodHandle> joinerTransferFunctions(WorkerActor a) { assert REMOVABLE_WORKERS.contains(a.worker().getClass()) : a.worker().getClass(); if (a.worker() instanceof RoundrobinJoiner || a.worker() instanceof WeightedRoundrobinJoiner) { int[] weights = new int[a.inputs().size()]; for (int i = 0; i < weights.length; ++i) weights[i] = a.pop(i); return roundrobinTransferFunctions(weights); } else throw new AssertionError(); } private List<MethodHandle> roundrobinTransferFunctions(int[] weights) { int[] weightPrefixSum = new int[weights.length + 1]; for (int i = 1; i < weightPrefixSum.length; ++i) weightPrefixSum[i] = weightPrefixSum[i-1] + weights[i-1]; int N = weightPrefixSum[weightPrefixSum.length-1]; //t_x(i) = N(i/w[x]) + sum_0_x-1{w} + (i mod w[x]) //where the first two terms select a "window" and the third is the //index into that window. ImmutableList.Builder<MethodHandle> transfer = ImmutableList.builder(); for (int x = 0; x < weights.length; ++x) transfer.add(MethodHandles.insertArguments(ROUNDROBIN_TRANSFER_FUNCTION, 0, weights[x], weightPrefixSum[x], N)); return transfer.build(); } private final MethodHandle ROUNDROBIN_TRANSFER_FUNCTION = findStatic(LOOKUP, "_roundrobinTransferFunction"); //TODO: build this directly out of MethodHandles? private static int _roundrobinTransferFunction(int weight, int prefixSum, int N, int i) { //assumes nonnegative indices return N*(i/weight) + prefixSum + (i % weight); } /** * Removes an Actor from this compiler's data structures. The Actor should * already have been unlinked from the graph (no incoming edges); this takes * care of removing it from the actors set, its actor group (possibly * removing the group if it's now empty), and the schedule. * @param a the actor to remove */ private void removeActor(Actor a) { assert actors.contains(a) : a; actors.remove(a); ActorGroup g = a.group(); g.remove(a); if (g.actors().isEmpty()) { groups = ImmutableSortedSet.copyOf(Sets.difference(groups, ImmutableSet.of(g))); externalSchedule = ImmutableMap.copyOf(Maps.difference(externalSchedule, ImmutableMap.of(g, 0)).entriesOnlyOnLeft()); initSchedule = ImmutableMap.copyOf(Maps.difference(initSchedule, ImmutableMap.of(g, 0)).entriesOnlyOnLeft()); } } private boolean consistency() { Set<Storage> usedStorage = new HashSet<>(); for (Actor a : actors) { usedStorage.addAll(a.inputs()); usedStorage.addAll(a.outputs()); } if (!storage.equals(usedStorage)) { Set<Storage> unused = Sets.difference(storage, usedStorage); Set<Storage> untracked = Sets.difference(usedStorage, storage); throw new AssertionError(String.format("inconsistent storage:%n\tunused: %s%n\tuntracked:%s%n", unused, untracked)); } return true; } //<editor-fold defaultstate="collapsed" desc="Unimplemented optimization stuff"> // /** // * Removes Identity instances from the graph, unless doing so would make the // * graph empty. // */ // private void identityRemoval() { // //TODO: remove from group, possibly removing the group if it becomes empty // for (Iterator<Actor> iter = actors.iterator(); iter.hasNext();) { // if (actors.size() == 1) // break; // Actor actor = iter.next(); // if (!actor.archetype().workerClass().equals(Identity.class)) // continue; // iter.remove(); // assert actor.predecessors().size() == 1 && actor.successors().size() == 1; // Object upstream = actor.predecessors().get(0), downstream = actor.successors().get(0); // if (upstream instanceof Actor) // replace(((Actor)upstream).successors(), actor, downstream); // if (downstream instanceof Actor) // replace(((Actor)downstream).predecessors(), actor, upstream); // //No index function changes required for Identity actors. // private static int replace(List<Object> list, Object target, Object replacement) { // int replacements = 0; // for (int i = 0; i < list.size(); ++i) // if (Objects.equals(list.get(0), target)) { // list.set(i, replacement); // ++replacements; // return replacements; //</editor-fold> /** * Performs type inference to replace type variables with concrete types. * For now, we only care about wrapper types. */ public void inferTypes() { while (inferUpward() || inferDownward()); } private boolean inferUpward() { boolean changed = false; //For each storage, if a reader's input type is a final type, all //writers' output types must be that final type. (Wrappers are final, //so this works for wrappers, and maybe detects errors related to other //types.) for (Storage s : storage) { Set<TypeToken<?>> finalInputTypes = new HashSet<>(); for (Actor a : s.downstream()) if (Modifier.isFinal(a.inputType().getRawType().getModifiers())) finalInputTypes.add(a.inputType()); if (finalInputTypes.isEmpty()) continue; if (finalInputTypes.size() > 1) throw new IllegalStreamGraphException("Type mismatch among readers: "+s.downstream()); TypeToken<?> inputType = finalInputTypes.iterator().next(); for (Actor a : s.upstream()) if (!a.outputType().equals(inputType)) { TypeToken<?> oldOutputType = a.outputType(); TypeResolver resolver = new TypeResolver().where(oldOutputType.getType(), inputType.getType()); TypeToken<?> newOutputType = TypeToken.of(resolver.resolveType(oldOutputType.getType())); if (!oldOutputType.equals(newOutputType)) { a.setOutputType(newOutputType); // System.out.println("inferUpward: inferred "+a+" output type: "+oldOutputType+" -> "+newOutputType); changed = true; } TypeToken<?> oldInputType = a.inputType(); TypeToken<?> newInputType = TypeToken.of(resolver.resolveType(oldInputType.getType())); if (!oldInputType.equals(newInputType)) { a.setInputType(newInputType); // System.out.println("inferUpward: inferred "+a+" input type: "+oldInputType+" -> "+newInputType); changed = true; } } } return changed; } private boolean inferDownward() { boolean changed = false; //For each storage, find the most specific common type among all the //writers' output types, then if it's final, unify with any variable or //wildcard reader input type. (We only unify if final to avoid removing //a type variable too soon. We could also refine concrete types like //Object to a more specific subclass.) for (Storage s : storage) { Set<? extends TypeToken<?>> commonTypes = null; for (Actor a : s.upstream()) if (commonTypes == null) commonTypes = a.outputType().getTypes(); else commonTypes = Sets.intersection(commonTypes, a.outputType().getTypes()); if (commonTypes.isEmpty()) throw new IllegalStreamGraphException("No common type among writers: "+s.upstream()); TypeToken<?> mostSpecificType = commonTypes.iterator().next(); if (!Modifier.isFinal(mostSpecificType.getRawType().getModifiers())) continue; for (Actor a : s.downstream()) { TypeToken<?> oldInputType = a.inputType(); //TODO: this isn't quite right? if (!ReflectionUtils.containsVariableOrWildcard(oldInputType.getType())) continue; TypeResolver resolver = new TypeResolver().where(oldInputType.getType(), mostSpecificType.getType()); TypeToken<?> newInputType = TypeToken.of(resolver.resolveType(oldInputType.getType())); if (!oldInputType.equals(newInputType)) { a.setInputType(newInputType); // System.out.println("inferDownward: inferred "+a+" input type: "+oldInputType+" -> "+newInputType); changed = true; } TypeToken<?> oldOutputType = a.outputType(); TypeToken<?> newOutputType = TypeToken.of(resolver.resolveType(oldOutputType.getType())); if (!oldOutputType.equals(newOutputType)) { a.setOutputType(newOutputType); // System.out.println("inferDownward: inferred "+a+" output type: "+oldOutputType+" -> "+newOutputType); changed = true; } } } return changed; } /** * Unboxes storage types and Actor input and output types. */ private void unbox() { for (Storage s : storage) { if (isUnboxable(s.contentType()) && UNBOXING_STRATEGY.unboxStorage(s, config)) { TypeToken<?> contents = s.contentType(); Class<?> type = contents.unwrap().getRawType(); s.setType(type); // if (!s.type().equals(contents.getRawType())) // System.out.println("unboxed "+s+" to "+type); } } for (WorkerActor a : Iterables.filter(actors, WorkerActor.class)) { if (isUnboxable(a.inputType()) && UNBOXING_STRATEGY.unboxInput(a, config)) { TypeToken<?> oldType = a.inputType(); a.setInputType(oldType.unwrap()); // if (!a.inputType().equals(oldType)) // System.out.println("unboxed input of "+a+": "+oldType+" -> "+a.inputType()); } if (isUnboxable(a.outputType()) && UNBOXING_STRATEGY.unboxOutput(a, config)) { TypeToken<?> oldType = a.outputType(); a.setOutputType(oldType.unwrap()); // if (!a.outputType().equals(oldType)) // System.out.println("unboxed output of "+a+": "+oldType+" -> "+a.outputType()); } } } private boolean isUnboxable(TypeToken<?> type) { return Primitives.isWrapperType(type.getRawType()) && !type.getRawType().equals(Void.class); } private void generateArchetypalCode() { for (final ActorArchetype archetype : archetypes) { Iterable<WorkerActor> workerActors = FluentIterable.from(actors) .filter(WorkerActor.class) .filter(wa -> wa.archetype().equals(archetype)); archetype.generateCode(packageName, classloader, workerActors); for (WorkerActor wa : workerActors) wa.setStateHolder(archetype.makeStateHolder(wa)); } } /** * If we're compiling an entire graph, create the overall input and output * buffers now so we can take advantage of * PeekableBuffers/PokeableBuffers. Otherwise we must pre-init() * our read/write instructions to refer to these buffers, since they won't * be passed to the blob's installBuffers(). */ private void createBuffers() { assert (overallInput == null) == (overallOutput == null); if (overallInput == null) { this.precreatedBuffers = ImmutableMap.of(); return; } ActorGroup inputGroup = null, outputGroup = null; Token inputToken = null, outputToken = null; for (ActorGroup g : groups) if (g.isTokenGroup()) { assert g.actors().size() == 1; TokenActor ta = (TokenActor)g.actors().iterator().next(); assert g.schedule().get(ta) == 1; if (ta.isInput()) { assert inputGroup == null; inputGroup = g; inputToken = ta.token(); } if (ta.isOutput()) { assert outputGroup == null; outputGroup = g; outputToken = ta.token(); } } this.overallInputBuffer = InputBufferFactory.unwrap(overallInput).createReadableBuffer( Math.max(initSchedule.get(inputGroup), externalSchedule.get(inputGroup))); this.overallOutputBuffer = OutputBufferFactory.unwrap(overallOutput).createWritableBuffer( Math.max(initSchedule.get(outputGroup), externalSchedule.get(outputGroup))); this.precreatedBuffers = ImmutableMap.<Token, Buffer>builder() .put(inputToken, overallInputBuffer) .put(outputToken, overallOutputBuffer) .build(); } private void createInitCode() { ImmutableMap<Actor, ImmutableList<MethodHandle>> indexFxnBackup = adjustOutputIndexFunctions(Storage::initialDataIndices); this.initStorage = createStorage(false, new PeekPokeStorageFactory(InternalArrayConcreteStorage.initFactory(initSchedule))); initReadInstructions.add(new InitDataReadInstruction(initStorage, initialStateDataMap)); ImmutableMap<Storage, ConcreteStorage> internalStorage = createStorage(true, InternalArrayConcreteStorage.initFactory(initSchedule)); IndexFunctionTransformer ift = new IdentityIndexFunctionTransformer(); ImmutableTable.Builder<Actor, Integer, IndexFunctionTransformer> inputTransformers = ImmutableTable.builder(), outputTransformers = ImmutableTable.builder(); for (Actor a : Iterables.filter(actors, WorkerActor.class)) { for (int i = 0; i < a.inputs().size(); ++i) inputTransformers.put(a, i, ift); for (int i = 0; i < a.outputs().size(); ++i) outputTransformers.put(a, i, ift); } ImmutableMap.Builder<ActorGroup, Integer> unrollFactors = ImmutableMap.builder(); for (ActorGroup g : groups) unrollFactors.put(g, 1); /** * During init, all (nontoken) groups are assigned to the same Core in * topological order (via the ordering on ActorGroups). At the same * time we build the token init schedule information required by the * blob host. */ Core initCore = new Core(CollectionUtils.union(initStorage, internalStorage), (table, wa) -> Combinators.lookupswitch(table), unrollFactors.build(), inputTransformers.build(), outputTransformers.build(), new ProxyFactory(classloader, packageName+".init")); for (ActorGroup g : groups) if (!g.isTokenGroup()) initCore.allocate(g, Range.closedOpen(0, initSchedule.get(g))); else { assert g.actors().size() == 1; TokenActor ta = (TokenActor)g.actors().iterator().next(); assert g.schedule().get(ta) == 1; ConcreteStorage storage = initStorage.get(Iterables.getOnlyElement(ta.isInput() ? g.outputs() : g.inputs())); int executions = initSchedule.get(g); if (ta.isInput()) initReadInstructions.add(makeReadInstruction(ta, storage, executions)); else initWriteInstructions.add(makeWriteInstruction(ta, storage, executions)); } this.initCode = initCore.code(); restoreOutputIndexFunctions(indexFxnBackup); } private void createSteadyStateCode() { for (Actor a : actors) { for (int i = 0; i < a.outputs().size(); ++i) { Storage s = a.outputs().get(i); if (s.isInternal()) continue; int itemsWritten = a.push(i) * initSchedule.get(a.group()) * a.group().schedule().get(a); a.outputIndexFunctions().set(i, MethodHandles.filterArguments( a.outputIndexFunctions().get(i), 0, Combinators.adder(itemsWritten))); } for (int i = 0; i < a.inputs().size(); ++i) { Storage s = a.inputs().get(i); if (s.isInternal()) continue; int itemsRead = a.pop(i) * initSchedule.get(a.group()) * a.group().schedule().get(a); a.inputIndexFunctions().set(i, MethodHandles.filterArguments( a.inputIndexFunctions().get(i), 0, Combinators.adder(itemsRead))); } } for (Storage s : storage) s.computeSteadyStateRequirements(externalSchedule); this.steadyStateStorage = createStorage(false, new PeekPokeStorageFactory(EXTERNAL_STORAGE_STRATEGY.asFactory(config))); ImmutableMap<Storage, ConcreteStorage> internalStorage = createStorage(true, INTERNAL_STORAGE_STRATEGY.asFactory(config)); List<Core> ssCores = new ArrayList<>(maxNumCores); IndexFunctionTransformer ift = new IdentityIndexFunctionTransformer(); for (int i = 0; i < maxNumCores; ++i) { ImmutableTable.Builder<Actor, Integer, IndexFunctionTransformer> inputTransformers = ImmutableTable.builder(), outputTransformers = ImmutableTable.builder(); for (Actor a : Iterables.filter(actors, WorkerActor.class)) { for (int j = 0; j < a.inputs().size(); ++j) { // String name = String.format("Core%dWorker%dInput%dIndexFxnTransformer", i, a.id(), j); // SwitchParameter<IndexFunctionTransformer> param = config.getParameter(name, SwitchParameter.class, IndexFunctionTransformer.class); inputTransformers.put(a, j, ift); } for (int j = 0; j < a.outputs().size(); ++j) { // String name = String.format("Core%dWorker%dOutput%dIndexFxnTransformer", i, a.id(), j); // SwitchParameter<IndexFunctionTransformer> param = config.getParameter(name, SwitchParameter.class, IndexFunctionTransformer.class); outputTransformers.put(a, j, ift); } } ImmutableMap.Builder<ActorGroup, Integer> unrollFactors = ImmutableMap.builder(); for (ActorGroup g : groups) { if (g.isTokenGroup()) continue; IntParameter param = config.getParameter(String.format("UnrollCore%dGroup%d", i, g.id()), IntParameter.class); unrollFactors.put(g, param.getValue()); } ssCores.add(new Core(CollectionUtils.union(steadyStateStorage, internalStorage), (table, wa) -> SWITCHING_STRATEGY.createSwitch(table, wa, config), unrollFactors.build(), inputTransformers.build(), outputTransformers.build(), new ProxyFactory(classloader, packageName+".steadystate."))); } int throughputPerSteadyState = 0; for (ActorGroup g : groups) if (!g.isTokenGroup()) ALLOCATION_STRATEGY.allocateGroup(g, Range.closedOpen(0, externalSchedule.get(g)), ssCores, config); else { assert g.actors().size() == 1; TokenActor ta = (TokenActor)g.actors().iterator().next(); assert g.schedule().get(ta) == 1; ConcreteStorage storage = steadyStateStorage.get(Iterables.getOnlyElement(ta.isInput() ? g.outputs() : g.inputs())); int executions = externalSchedule.get(g); if (ta.isInput()) readInstructions.add(makeReadInstruction(ta, storage, executions)); else { writeInstructions.add(makeWriteInstruction(ta, storage, executions)); throughputPerSteadyState += executions; } } ImmutableList.Builder<MethodHandle> steadyStateCodeBuilder = ImmutableList.builder(); for (Core c : ssCores) if (!c.isEmpty()) steadyStateCodeBuilder.add(c.code()); //Provide at least one core of code, even if it doesn't do anything; the //blob host will still copy inputs to outputs. this.steadyStateCode = steadyStateCodeBuilder.build(); if (steadyStateCode.isEmpty()) this.steadyStateCode = ImmutableList.of(Combinators.nop()); createMigrationInstructions(); createDrainInstructions(); Boolean reportThroughput = (Boolean)config.getExtraData("reportThroughput"); if (reportThroughput != null && reportThroughput) { ReportThroughputInstruction rti = new ReportThroughputInstruction(throughputPerSteadyState); readInstructions.add(rti); writeInstructions.add(rti); } } private ReadInstruction makeReadInstruction(TokenActor a, ConcreteStorage cs, int count) { assert a.isInput(); Storage s = Iterables.getOnlyElement(a.outputs()); MethodHandle idxFxn = Iterables.getOnlyElement(a.outputIndexFunctions()); ReadInstruction retval; if (count == 0) retval = new NopReadInstruction(a.token()); else if (cs instanceof PeekableBufferConcreteStorage) retval = new PeekReadInstruction(a, count); else if (!s.type().isPrimitive() && cs instanceof BulkWritableConcreteStorage && contiguouslyIncreasing(idxFxn, 0, count)) { retval = new BulkReadInstruction(a, (BulkWritableConcreteStorage)cs, count); } else retval = new TokenReadInstruction(a, cs, count); // System.out.println("Made a "+retval+" for "+a.token()); retval.init(precreatedBuffers); return retval; } private WriteInstruction makeWriteInstruction(TokenActor a, ConcreteStorage cs, int count) { assert a.isOutput(); Storage s = Iterables.getOnlyElement(a.inputs()); MethodHandle idxFxn = Iterables.getOnlyElement(a.inputIndexFunctions()); WriteInstruction retval; if (count == 0) retval = new NopWriteInstruction(a.token()); else if (!s.type().isPrimitive() && cs instanceof BulkReadableConcreteStorage && contiguouslyIncreasing(idxFxn, 0, count)) { retval = new BulkWriteInstruction(a, (BulkReadableConcreteStorage)cs, count); } else retval = new TokenWriteInstruction(a, cs, count); // System.out.println("Made a "+retval+" for "+a.token()); retval.init(precreatedBuffers); return retval; } private boolean contiguouslyIncreasing(MethodHandle idxFxn, int start, int count) { try { int prev = (int)idxFxn.invokeExact(start); for (int i = start+1; i < count; ++i) { int next = (int)idxFxn.invokeExact(i); if (next != (prev + 1)) return false; prev = next; } return true; } catch (Throwable ex) { throw new AssertionError("index functions should not throw", ex); } } /** * Create migration instructions: Runnables that move live items from * initialization to steady-state storage. */ private void createMigrationInstructions() { for (Storage s : initStorage.keySet()) { ConcreteStorage init = initStorage.get(s), steady = steadyStateStorage.get(s); if (steady instanceof PeekableBufferConcreteStorage) migrationInstructions.add(new PeekMigrationInstruction( s, (PeekableBufferConcreteStorage)steady)); else migrationInstructions.add(new MigrationInstruction(s, init, steady)); } } /** * Create drain instructions, which collect live items from steady-state * storage when draining. */ private void createDrainInstructions() { Map<Token, Pair<List<ConcreteStorage>, List<Integer>>> drainReads = new HashMap<>(); for (Map.Entry<Token, Integer> e : postInitLiveness.entrySet()) drainReads.put(e.getKey(), Pair.make( new ArrayList<>(Collections.nCopies(e.getValue(), null)), Ints.asList(new int[e.getValue()]))); for (Actor a : actors) { for (int input = 0; input < a.inputs().size(); ++input) { ConcreteStorage storage = steadyStateStorage.get(a.inputs().get(input)); for (int index = 0; index < a.inputSlots(input).size(); ++index) { StorageSlot info = a.inputSlots(input).get(index); if (info.isDrainable()) { Pair<List<ConcreteStorage>, List<Integer>> dr = drainReads.get(info.token()); ConcreteStorage old = dr.first.set(info.index(), storage); assert old == null : "overwriting "+info; dr.second.set(info.index(), a.translateInputIndex(input, index)); } } } } for (Map.Entry<Token, Pair<List<ConcreteStorage>, List<Integer>>> e : drainReads.entrySet()) { List<ConcreteStorage> storages = e.getValue().first; List<Integer> indices = e.getValue().second; assert !storages.contains(null) : "lost an element from "+e.getKey()+": "+e.getValue(); if (storages.stream().anyMatch(s -> s instanceof PeekableBufferConcreteStorage)) { assert storages.stream().allMatch(s -> s instanceof PeekableBufferConcreteStorage) : "mixed peeking and not? "+e.getKey()+": "+e.getValue(); //we still create a drain instruction, but it does nothing storages.clear(); indices = Ints.asList(); } drainInstructions.add(new XDrainInstruction(e.getKey(), storages, indices)); } for (WorkerActor wa : Iterables.filter(actors, WorkerActor.class)) drainInstructions.add(wa.stateHolder()); } //<editor-fold defaultstate="collapsed" desc="Output index function adjust/restore"> /** * Adjust output index functions to avoid overwriting items in external * storage. For any actor writing to external storage, we find the * first item that doesn't hit the live index set and add that many * (making that logical item 0 for writers). * @param liveIndexExtractor a function that computes the relevant live * index set for the given external storage * @return the old output index functions, to be restored later */ private ImmutableMap<Actor, ImmutableList<MethodHandle>> adjustOutputIndexFunctions(Function<Storage, Set<Integer>> liveIndexExtractor) { ImmutableMap.Builder<Actor, ImmutableList<MethodHandle>> backup = ImmutableMap.builder(); for (Actor a : actors) { backup.put(a, ImmutableList.copyOf(a.outputIndexFunctions())); for (int i = 0; i < a.outputs().size(); ++i) { if (a.push(i) == 0) continue; //No writes -- nothing to adjust. Storage s = a.outputs().get(i); if (s.isInternal()) continue; Set<Integer> liveIndices = liveIndexExtractor.apply(s); assert liveIndices != null : s +" "+liveIndexExtractor; int offset = 0; while (liveIndices.contains(a.translateOutputIndex(i, offset))) ++offset; //Check future indices are also open (e.g., that we aren't //alternating hole/not-hole). for (int check = 0; check < 100; ++check) assert !liveIndices.contains(a.translateOutputIndex(i, offset + check)) : check; a.outputIndexFunctions().set(i, Combinators.apply(a.outputIndexFunctions().get(i), Combinators.adder(offset))); } } return backup.build(); } /** * Restores output index functions from a backup returned from * {@link #adjustOutputIndexFunctions(com.google.common.base.Function)}. * @param backup the backup to restore */ private void restoreOutputIndexFunctions(ImmutableMap<Actor, ImmutableList<MethodHandle>> backup) { for (Actor a : actors) { ImmutableList<MethodHandle> oldFxns = backup.get(a); assert oldFxns != null : "no backup for "+a; assert oldFxns.size() == a.outputIndexFunctions().size() : "backup for "+a+" is wrong size"; Collections.copy(a.outputIndexFunctions(), oldFxns); } } //</editor-fold> private ImmutableMap<Storage, ConcreteStorage> createStorage(boolean internal, StorageFactory factory) { ImmutableMap.Builder<Storage, ConcreteStorage> builder = ImmutableMap.builder(); for (Storage s : storage) if (s.isInternal() == internal) builder.put(s, factory.make(s)); return builder.build(); } /** * Creates special ConcreteStorage implementations for PeekableBuffer and * PokeableBuffer, or falls back to the given factory. */ private final class PeekPokeStorageFactory implements StorageFactory { private final StorageFactory fallback; private final boolean usePeekableBuffer; private PeekPokeStorageFactory(StorageFactory fallback) { this.fallback = fallback; SwitchParameter<Boolean> usePeekableBufferParam = config.getParameter("UsePeekableBuffer", SwitchParameter.class, Boolean.class); this.usePeekableBuffer = usePeekableBufferParam.getValue(); } @Override public ConcreteStorage make(Storage storage) { if (storage.id().isOverallInput() && overallInputBuffer instanceof PeekableBuffer && usePeekableBuffer) return PeekableBufferConcreteStorage.factory(ImmutableMap.of(storage.id(), (PeekableBuffer)overallInputBuffer)).make(storage); //TODO: PokeableBuffer return fallback.make(storage); } } private static final class MigrationInstruction implements Runnable { private final ConcreteStorage init, steady; private final int[] indicesToMigrate; private MigrationInstruction(Storage storage, ConcreteStorage init, ConcreteStorage steady) { this.init = init; this.steady = steady; Set<Integer> builder = new HashSet<>(); for (Actor a : storage.downstream()) for (int i = 0; i < a.inputs().size(); ++i) if (a.inputs().get(i).equals(storage)) for (int idx = 0; idx < a.inputSlots(i).size(); ++idx) if (a.inputSlots(i).get(idx).isLive()) builder.add(a.translateInputIndex(i, idx)); this.indicesToMigrate = Ints.toArray(builder); //TODO: we used to sort here (using ImmutableSortedSet). Does it matter? } @Override public void run() { init.sync(); for (int i : indicesToMigrate) steady.write(i, init.read(i)); steady.sync(); } } private static final class PeekMigrationInstruction implements Runnable { private final PeekableBuffer buffer; private final int itemsConsumedDuringInit; private PeekMigrationInstruction(Storage storage, PeekableBufferConcreteStorage steady) { this.buffer = steady.buffer(); this.itemsConsumedDuringInit = steady.minReadIndex(); } @Override public void run() { buffer.consume(itemsConsumedDuringInit); } } /** * The X doesn't stand for anything. I just needed a different name. */ private static final class XDrainInstruction implements DrainInstruction { private final Token token; private final ConcreteStorage[] storage; private final int[] storageSelector, index; private XDrainInstruction(Token token, List<ConcreteStorage> storages, List<Integer> indices) { assert storages.size() == indices.size() : String.format("%s %s %s", token, storages, indices); this.token = token; Set<ConcreteStorage> set = new HashSet<>(storages); this.storage = set.toArray(new ConcreteStorage[set.size()]); this.storageSelector = new int[indices.size()]; this.index = Ints.toArray(indices); for (int i = 0; i < indices.size(); ++i) storageSelector[i] = Arrays.asList(storage).indexOf(storages.get(i)); } @Override public Map<Token, Object[]> call() { Object[] data = new Object[index.length]; int idx = 0; for (int i = 0; i < index.length; ++i) data[idx++] = storage[storageSelector[i]].read(index[i]); return ImmutableMap.of(token, data); } } /** * PeekReadInstruction implements special handling for PeekableBuffer. */ private static final class PeekReadInstruction implements ReadInstruction { private final Token token; private final int count; private PeekableBuffer buffer; private PeekReadInstruction(TokenActor a, int count) { assert a.isInput() : a; this.token = a.token(); //If we "read" count new items, the maximum available index is given //by the output index function. this.count = a.translateOutputIndex(0, count); } @Override public void init(Map<Token, Buffer> buffers) { if (!buffers.containsKey(token)) return; if (buffer != null) checkState(buffers.get(token) == buffer, "reassigning %s from %s to %s", token, buffer, buffers.get(token)); this.buffer = (PeekableBuffer)buffers.get(token); } @Override public Map<Token, Integer> getMinimumBufferCapacity() { //This shouldn't matter because we've already created the buffers. return ImmutableMap.of(token, count); } @Override public boolean load() { //Ensure data is present for reading. return buffer.size() >= count; } @Override public Map<Token, Object[]> unload() { //Data is not consumed from the underlying buffer until it's //adjusted, so no work is necessary here. return ImmutableMap.of(); } } private static final class BulkReadInstruction implements ReadInstruction { private final Token token; private final BulkWritableConcreteStorage storage; private final int index, count; private Buffer buffer; private BulkReadInstruction(TokenActor a, BulkWritableConcreteStorage storage, int count) { assert a.isInput() : a; this.token = a.token(); this.storage = storage; this.index = a.translateOutputIndex(0, 0); this.count = count; } @Override public void init(Map<Token, Buffer> buffers) { if (!buffers.containsKey(token)) return; if (buffer != null) checkState(buffers.get(token) == buffer, "reassigning %s from %s to %s", token, buffer, buffers.get(token)); this.buffer = buffers.get(token); } @Override public Map<Token, Integer> getMinimumBufferCapacity() { return ImmutableMap.of(token, count); } @Override public boolean load() { if (buffer.size() < count) return false; storage.bulkWrite(buffer, index, count); storage.sync(); return true; } @Override public Map<Token, Object[]> unload() { Object[] data = new Object[count]; for (int i = index; i < count; ++i) { data[i - index] = storage.read(i); } return ImmutableMap.of(token, data); } } /** * TODO: consider using read/write handles instead of read(), write()? */ private static final class TokenReadInstruction implements ReadInstruction { private final Token token; private final MethodHandle idxFxn; private final ConcreteStorage storage; private final int count; private Buffer buffer; private TokenReadInstruction(TokenActor a, ConcreteStorage storage, int count) { assert a.isInput() : a; this.token = a.token(); this.storage = storage; this.idxFxn = Iterables.getOnlyElement(a.outputIndexFunctions()); this.count = count; } @Override public void init(Map<Token, Buffer> buffers) { if (!buffers.containsKey(token)) return; if (buffer != null) checkState(buffers.get(token) == buffer, "reassigning %s from %s to %s", token, buffer, buffers.get(token)); this.buffer = buffers.get(token); } @Override public Map<Token, Integer> getMinimumBufferCapacity() { return ImmutableMap.of(token, count); } @Override public boolean load() { Object[] data = new Object[count]; if (!buffer.readAll(data)) return false; for (int i = 0; i < data.length; ++i) { int idx; try { idx = (int)idxFxn.invokeExact(i); } catch (Throwable ex) { throw new AssertionError("Can't happen! Index functions should not throw", ex); } storage.write(idx, data[i]); } storage.sync(); return true; } @Override public Map<Token, Object[]> unload() { Object[] data = new Object[count]; for (int i = 0; i < data.length; ++i) { int idx; try { idx = (int)idxFxn.invokeExact(i); } catch (Throwable ex) { throw new AssertionError("Can't happen! Index functions should not throw", ex); } data[i] = storage.read(idx); } return ImmutableMap.of(token, data); } } /** * Doesn't read anything, but does respond to getMinimumBufferCapacity(). */ private static final class NopReadInstruction implements ReadInstruction { private final Token token; private NopReadInstruction(Token token) { this.token = token; } @Override public void init(Map<Token, Buffer> buffers) { } @Override public Map<Token, Integer> getMinimumBufferCapacity() { return ImmutableMap.of(token, 0); } @Override public boolean load() { return true; } @Override public Map<Token, Object[]> unload() { return ImmutableMap.of(); } } private static final class BulkWriteInstruction implements WriteInstruction { private final Token token; private final BulkReadableConcreteStorage storage; private final int index, count; private Buffer buffer; private int written; private BulkWriteInstruction(TokenActor a, BulkReadableConcreteStorage storage, int count) { assert a.isOutput(): a; this.token = a.token(); this.storage = storage; this.index = a.translateInputIndex(0, 0); this.count = count; } @Override public void init(Map<Token, Buffer> buffers) { if (!buffers.containsKey(token)) return; if (buffer != null) checkState(buffers.get(token) == buffer, "reassigning %s from %s to %s", token, buffer, buffers.get(token)); this.buffer = buffers.get(token); } @Override public Map<Token, Integer> getMinimumBufferCapacity() { return ImmutableMap.of(token, count); } @Override public Boolean call() { written += storage.bulkRead(buffer, index + written, count); if (written < count) return false; written = 0; return true; } } /** * TODO: consider using read handles instead of read()? */ private static final class TokenWriteInstruction implements WriteInstruction { private final Token token; private final MethodHandle idxFxn; private final ConcreteStorage storage; private final int count; private Buffer buffer; private int written; private TokenWriteInstruction(TokenActor a, ConcreteStorage storage, int count) { assert a.isOutput() : a; this.token = a.token(); this.storage = storage; this.idxFxn = Iterables.getOnlyElement(a.inputIndexFunctions()); this.count = count; } @Override public void init(Map<Token, Buffer> buffers) { if (!buffers.containsKey(token)) return; if (buffer != null) checkState(buffers.get(token) == buffer, "reassigning %s from %s to %s", token, buffer, buffers.get(token)); this.buffer = buffers.get(token); } @Override public Map<Token, Integer> getMinimumBufferCapacity() { return ImmutableMap.of(token, count); } @Override public Boolean call() { Object[] data = new Object[count]; for (int i = 0; i < count; ++i) { int idx; try { idx = (int)idxFxn.invokeExact(i); } catch (Throwable ex) { throw new AssertionError("Can't happen! Index functions should not throw", ex); } data[i] = storage.read(idx); } written += buffer.write(data, written, data.length-written); if (written < count) return false; written = 0; return true; } } /** * Doesn't write anything, but does respond to getMinimumBufferCapacity(). */ private static final class NopWriteInstruction implements WriteInstruction { private final Token token; private NopWriteInstruction(Token token) { this.token = token; } @Override public void init(Map<Token, Buffer> buffers) { } @Override public Map<Token, Integer> getMinimumBufferCapacity() { return ImmutableMap.of(token, 0); } @Override public Boolean call() { return true; } } /** * Writes initial data into init storage, or "unloads" it (just returning it * as it was in the DrainData, not actually reading the storage) if we drain * during init. (Any remaining data after init will be migrated as normal.) * There's only one of these per blob because it returns all the data, and * it should be the first initReadInstruction. */ private static final class InitDataReadInstruction implements ReadInstruction { private final ImmutableMap<ConcreteStorage, ImmutableList<Pair<ImmutableList<Object>, MethodHandle>>> toWrite; private final ImmutableMap<Token, ImmutableList<Object>> initialStateDataMap; private InitDataReadInstruction(Map<Storage, ConcreteStorage> initStorage, ImmutableMap<Token, ImmutableList<Object>> initialStateDataMap) { ImmutableMap.Builder<ConcreteStorage, ImmutableList<Pair<ImmutableList<Object>, MethodHandle>>> toWriteBuilder = ImmutableMap.builder(); for (Map.Entry<Storage, ConcreteStorage> e : initStorage.entrySet()) { Storage s = e.getKey(); if (s.isInternal()) continue; if (s.initialData().isEmpty()) continue; toWriteBuilder.put(e.getValue(), ImmutableList.copyOf(s.initialData())); } this.toWrite = toWriteBuilder.build(); this.initialStateDataMap = initialStateDataMap; } @Override public void init(Map<Token, Buffer> buffers) { } @Override public Map<Token, Integer> getMinimumBufferCapacity() { return ImmutableMap.of(); } @Override public boolean load() { for (Map.Entry<ConcreteStorage, ImmutableList<Pair<ImmutableList<Object>, MethodHandle>>> e : toWrite.entrySet()) for (Pair<ImmutableList<Object>, MethodHandle> p : e.getValue()) for (int i = 0; i < p.first.size(); ++i) { int idx; try { idx = (int)p.second.invokeExact(i); } catch (Throwable ex) { throw new AssertionError("Can't happen! Index functions should not throw", ex); } e.getKey().write(idx, p.first.get(i)); } return true; } @Override public Map<Token, Object[]> unload() { Map<Token, Object[]> r = new HashMap<>(); for (Map.Entry<Token, ImmutableList<Object>> e : initialStateDataMap.entrySet()) r.put(e.getKey(), e.getValue().toArray()); return r; } } private static final class ReportThroughputInstruction implements ReadInstruction, WriteInstruction { private static final long WARMUP_NANOS = TimeUnit.NANOSECONDS.convert(10, TimeUnit.SECONDS); private static final long TIMING_NANOS = TimeUnit.NANOSECONDS.convert(5, TimeUnit.SECONDS); private final long throughputPerSteadyState; private int steadyStates = 0; private long firstNanoTime = Long.MIN_VALUE, afterWarmupNanoTime = Long.MIN_VALUE; private ReportThroughputInstruction(long throughputPerSteadyState) { this.throughputPerSteadyState = throughputPerSteadyState; } @Override public void init(Map<Token, Buffer> buffers) {} @Override public Map<Token, Integer> getMinimumBufferCapacity() { return ImmutableMap.of(); } @Override public Map<Token, Object[]> unload() { return ImmutableMap.of(); } @Override public boolean load() { long currentTime = time(); if (firstNanoTime == Long.MIN_VALUE) firstNanoTime = currentTime; else if (afterWarmupNanoTime == Long.MIN_VALUE && currentTime - firstNanoTime > WARMUP_NANOS) afterWarmupNanoTime = currentTime; return true; } @Override public Boolean call() { if (afterWarmupNanoTime != Long.MIN_VALUE) { ++steadyStates; long currentTime = time(); long elapsed = currentTime - afterWarmupNanoTime; if (elapsed > TIMING_NANOS) { long itemsOutput = steadyStates * throughputPerSteadyState; System.out.format("%d/%d/%d/%d#%n", steadyStates, itemsOutput, elapsed, elapsed/itemsOutput); System.out.flush(); System.exit(0); } } return true; } private static long time() { // return System.currentTimeMillis()*1000000; return System.nanoTime(); } } /** * Creates the blob host. This mostly involves shuffling our state into the * form the blob host wants. * @return the blob */ public Blob instantiateBlob() { ImmutableSortedSet.Builder<Token> inputTokens = ImmutableSortedSet.naturalOrder(), outputTokens = ImmutableSortedSet.naturalOrder(); for (TokenActor ta : Iterables.filter(actors, TokenActor.class)) (ta.isInput() ? inputTokens : outputTokens).add(ta.token()); ImmutableList.Builder<MethodHandle> storageAdjusts = ImmutableList.builder(); for (ConcreteStorage s : steadyStateStorage.values()) storageAdjusts.add(s.adjustHandle()); return new Compiler2BlobHost(workers, config, inputTokens.build(), outputTokens.build(), initCode, steadyStateCode, storageAdjusts.build(), initReadInstructions, initWriteInstructions, migrationInstructions, readInstructions, writeInstructions, drainInstructions, precreatedBuffers); } public static void main(String[] args) { StreamCompiler sc; Benchmark bm; if (args.length == 3) { String benchmarkName = args[0]; int cores = Integer.parseInt(args[1]); int multiplier = Integer.parseInt(args[2]); sc = new Compiler2StreamCompiler().maxNumCores(cores).multiplier(multiplier); bm = Benchmarker.getBenchmarkByName(benchmarkName); } else { sc = new Compiler2StreamCompiler().multiplier(384).maxNumCores(4); bm = new FMRadio.FMRadioBenchmarkProvider().iterator().next(); } Benchmarker.runBenchmark(bm, sc).get(0).print(System.out); } private void printDot(String stage) { try (FileWriter fw = new FileWriter(stage+".dot"); BufferedWriter bw = new BufferedWriter(fw)) { bw.write("digraph {\n"); for (ActorGroup g : groups) { bw.write("subgraph cluster_"+Integer.toString(g.id()).replace('-', '_')+" {\n"); for (Actor a : g.actors()) bw.write(String.format("\"%s\";\n", nodeName(a))); bw.write("label = \"x"+externalSchedule.get(g)+"\";\n"); bw.write("}\n"); } for (ActorGroup g : groups) { for (Actor a : g.actors()) { for (Storage s : a.outputs()) for (Actor b : s.downstream()) bw.write(String.format("\"%s\" -> \"%s\";\n", nodeName(a), nodeName(b))); } } bw.write("}\n"); } catch (IOException ex) { ex.printStackTrace(); } } private String nodeName(Actor a) { if (a instanceof TokenActor) return (((TokenActor)a).isInput()) ? "input" : "output"; WorkerActor wa = (WorkerActor)a; String workerClassName = wa.worker().getClass().getSimpleName(); return workerClassName.replaceAll("[a-z]", "") + "@" + Integer.toString(wa.id()).replace('-', '_'); } }
package experimentalcode.remigius; import de.lmu.ifi.dbs.elki.data.DatabaseObject; import de.lmu.ifi.dbs.elki.database.AssociationID; import de.lmu.ifi.dbs.elki.database.Database; import de.lmu.ifi.dbs.elki.result.AnnotationResult; import de.lmu.ifi.dbs.elki.result.MultiResult; import de.lmu.ifi.dbs.elki.result.Result; import de.lmu.ifi.dbs.elki.result.ResultUtil; public abstract class AlgorithmAdapter<O extends DatabaseObject, T> { protected MultiResult result; protected Database<O> database; protected AssociationID<T> asID; public AlgorithmAdapter(Database<O> database, Result result){ if (result instanceof MultiResult){ this.database = database; this.result = (MultiResult)result; } else { throw new RuntimeException("No MultiResult"); } } public Database<O> getDatabase(){ return database; } public MultiResult getResult(){ return this.result; } public AssociationID<T> getAlgorithmID(){ return asID; } protected T getScore(O dbo){ return getOutlierAnnotationResult().getValueFor(dbo.getID()); } private AnnotationResult<T> getOutlierAnnotationResult(){ return ResultUtil.findAnnotationResult(result, asID); } public abstract Double getUnnormalized(O dbo); public abstract Double getNormalized(O dbo); }
package gov.nih.nci.ncicb.cadsr.loader.ui; import gov.nih.nci.ncicb.cadsr.loader.event.ReviewListener; import gov.nih.nci.ncicb.cadsr.loader.ui.event.NavigationEvent; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.*; import gov.nih.nci.ncicb.cadsr.loader.ui.util.UIUtil; import gov.nih.nci.ncicb.cadsr.domain.ValueDomain; import gov.nih.nci.ncicb.cadsr.loader.event.ElementChangeListener; import gov.nih.nci.ncicb.cadsr.loader.ui.event.NavigationListener; import gov.nih.nci.ncicb.cadsr.loader.util.StringUtil; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.FlowLayout; import java.awt.GridBagLayout; import java.beans.PropertyChangeListener; import java.util.HashMap; import java.util.Map; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; /** * Wraps the various LVD view Panels and button Panel */ public class LVDPanel extends JPanel implements Editable, NodeViewPanel{ private ValueDomainViewPanel vdViewPanel; private MapToExistingVDPanel mteVDPanel; private VDButtonPanel vdButtonPanel; private JPanel cardPanel; static final String VD_FIELDS_PANEL_KEY = "vdFieldPanel"; static final String VD_MTE_PANEL_KEY = "vdMtePanel"; private Map<String, JPanel> panelKeyMap = new HashMap<String, JPanel>(); private boolean isInitialized = false; private JPanel displayedPanel; public LVDPanel() { vdButtonPanel = new VDButtonPanel(this); } private void initUI() { isInitialized = true; cardPanel = new JPanel(); cardPanel.setLayout(new CardLayout()); cardPanel.add(vdViewPanel, VD_FIELDS_PANEL_KEY); cardPanel.add(mteVDPanel, VD_MTE_PANEL_KEY); panelKeyMap.put(VD_FIELDS_PANEL_KEY, vdViewPanel); panelKeyMap.put(VD_MTE_PANEL_KEY, mteVDPanel); setLayout(new BorderLayout()); JPanel buttonSpacedPanel = new JPanel(); buttonSpacedPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); JLabel spaceLabel = new JLabel(" "); buttonSpacedPanel.add(spaceLabel); buttonSpacedPanel.add(vdButtonPanel); JPanel editPanel = new JPanel(); editPanel.setLayout(new GridBagLayout()); UIUtil.insertInBag(editPanel, cardPanel, 0, 1); JScrollPane scrollPane = new JScrollPane(editPanel); scrollPane.getVerticalScrollBar().setUnitIncrement(30); this.add(scrollPane, BorderLayout.CENTER); this.add(buttonSpacedPanel, BorderLayout.SOUTH); vdViewPanel.addPropertyChangeListener(vdButtonPanel); mteVDPanel.addPropertyChangeListener(vdButtonPanel); } public void update(ValueDomain vd, UMLNode umlNode) { if(!isInitialized) initUI(); vdViewPanel.update(vd, umlNode); mteVDPanel.update(vd, umlNode); if(StringUtil.isEmpty(vd.getPublicId())) { switchCards(VD_FIELDS_PANEL_KEY); vdButtonPanel.update((ReviewableUMLNode)umlNode, true); } else { switchCards(VD_MTE_PANEL_KEY); vdButtonPanel.update((ReviewableUMLNode)umlNode, false); } } public void switchCards(String key) { CardLayout layout = (CardLayout)cardPanel.getLayout(); if(displayedPanel instanceof ValueDomainViewPanel) { vdViewPanel.setExpanded(false); } layout.show(cardPanel, key); displayedPanel = panelKeyMap.get(key); if(displayedPanel instanceof ValueDomainViewPanel) { vdViewPanel.setExpanded(true); } if((Editable)displayedPanel instanceof ValueDomainViewPanel) vdButtonPanel.switchButton.setEnabled(true); else if(mteVDPanel.getPubId() != null && mteVDPanel.isApplied()) vdButtonPanel.switchButton.setEnabled(false); else if(mteVDPanel.getPubId() != null) vdButtonPanel.switchButton.setEnabled(false); else vdButtonPanel.switchButton.setEnabled(true); } public void setVdViewPanel(ValueDomainViewPanel vdViewPanel) { this.vdViewPanel = vdViewPanel; } public void setMteVDPanel(MapToExistingVDPanel mteVDPanel) { this.mteVDPanel = mteVDPanel; } public void addElementChangeListener(ElementChangeListener listener){ vdViewPanel.addElementChangeListener(listener); mteVDPanel.addElementChangeListener(listener); } public void addPropertyChangeListener(PropertyChangeListener l) { super.addPropertyChangeListener(l);; vdViewPanel.addPropertyChangeListener(l); mteVDPanel.addPropertyChangeListener(l); } public void addReviewListener(ReviewListener l) { vdButtonPanel.addReviewListener(l); } public void applyPressed() throws ApplyException { if((Editable)displayedPanel instanceof MapToExistingVDPanel) if(mteVDPanel.getPubId() != null) {//Apply Button clicked after search vdButtonPanel.switchButton.setEnabled(false); mteVDPanel.setApplied(false); } else {// Apply Button clicked after clear, set all values to null for ValueDomainViewPanel vdButtonPanel.switchButton.setEnabled(true); mteVDPanel.setApplied(true); // !! TODO - REFACTOR THIS. DONT USE PUBLIC FIELDS. GURU MEDITATION. vdViewPanel.vdPrefDefValueTextField.setText(""); vdViewPanel.vdDatatypeValueCombobox.setSelectedIndex(0); vdViewPanel.tmpInvisible.setSelected(true); vdViewPanel.vdCDPublicIdJLabel.setText(""); vdViewPanel.vdCdLongNameValueJLabel.setText("Unable to lookup CD Long Name"); vdViewPanel.vdRepIdValueJLabel.setText(""); } else vdButtonPanel.switchButton.setEnabled(true); ((Editable)displayedPanel).applyPressed(); } public void addNavigationListener(NavigationListener listener) { vdButtonPanel.addNavigationListener(listener); } public void updateNode(UMLNode node) { } public void navigate(NavigationEvent event) { vdButtonPanel.navigate(event); } }
package dr.evomodel.continuous; import dr.evolution.tree.Tree; import dr.evolution.tree.NodeRef; import dr.xml.*; import dr.evomodel.tree.TreeModel; import dr.evomodel.tree.TreeStatistic; import dr.inference.model.Statistic; import dr.evolution.continuous.SphericalPolarCoordinates; /** * @author Marc Suchard * @author Philippe Lemey */ public class TreeDispersionStatistic extends Statistic.Abstract implements TreeStatistic { public static final String TREE_DISPERSION_STATISTIC = "treeDispersionStatistic"; public static final String BOOLEAN_OPTION = "greatCircleDistance"; public TreeDispersionStatistic(String name, TreeModel tree, SampledMultivariateTraitLikelihood traitLikelihood, boolean genericOption) { super(name); this.tree = tree; this.traitLikelihood = traitLikelihood; this.genericOption = genericOption; } public void setTree(Tree tree) { this.tree = (TreeModel) tree; } public Tree getTree() { return tree; } public int getDimension() { return 1; } /** * @return whatever Philippe wants */ public double getStatisticValue(int dim) { String traitName = traitLikelihood.getTraitName(); double treelength = 0; double treeDistance = 0; for (int i = 0; i < tree.getNodeCount(); i++) { NodeRef node = tree.getNode(i); double[] trait = tree.getMultivariateNodeTrait(node, traitName); if (node != tree.getRoot()) { SphericalPolarCoordinates coord1 = new SphericalPolarCoordinates(trait[0], trait[1]); double[] parentTrait = tree.getMultivariateNodeTrait(tree.getParent(node), traitName); SphericalPolarCoordinates coord2 = new SphericalPolarCoordinates(parentTrait[0], parentTrait[1]); treelength += tree.getBranchLength(node); if (genericOption) { //treeDistance += getKilometerGreatCircleDistance(trait,parentTrait); treeDistance += coord1.distance(coord2); } else { treeDistance += getNativeDistance(trait,parentTrait); } } } return treeDistance/treelength; } private double getNativeDistance(double[] location1, double[] location2) { return Math.sqrt(Math.pow((location2[0]-location1[0]),2.0)+Math.pow((location2[1]-location1[1]),2.0)); } // private double getKilometerGreatCircleDistance(double[] location1, double[] location2) { // double R = 6371; // km // double dLat = Math.toRadians(location2[0]-location1[0]); // double dLon = Math.toRadians(location2[1]-location1[1]); // double a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(Math.toRadians(location1[0])) * Math.cos(Math.toRadians(location2[0])) * Math.sin(dLon/2) * Math.sin(dLon/2); // double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); // return R * c; public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return TREE_DISPERSION_STATISTIC; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { String name = xo.getAttribute(NAME, xo.getId()); TreeModel tree = (TreeModel) xo.getChild(Tree.class); boolean option = xo.getAttribute(BOOLEAN_OPTION,false); // Default value is false SampledMultivariateTraitLikelihood traitLikelihood = (SampledMultivariateTraitLikelihood) xo.getChild(SampledMultivariateTraitLikelihood.class); return new TreeDispersionStatistic(name, tree, traitLikelihood, option); }
package edu.ucsb.cs56.projects.github.jcapi_demo; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import com.jcabi.github.RtGithub; import com.jcabi.github.Issues; import com.jcabi.github.Issue; import com.jcabi.github.Github; import com.jcabi.github.Repos; import com.jcabi.github.Repo; import com.jcabi.github.User; import com.jcabi.github.Coordinates; public class Demo1 { public static String readAllBytes(String filename) throws Exception { return new String(Files.readAllBytes(Paths.get(filename))); } public static void main(String[] args) throws Exception { String oauthToken = Demo1.readAllBytes("tokens/MostPrivileges.txt"); Github github = new RtGithub(oauthToken); System.out.println("Github=" + github); Repos repos = github.repos(); System.out.println("repos=" + repos); Repo repo = repos.get(new Coordinates.Simple("jcabi/jcabi-github")); Issues issues = repo.issues(); Issue issue = issues.get(123); User author = new Issue.Smart(issue).author(); System.out.println("author="+author); } }
package edu.wheaton.simulator.gui.screen; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; import javax.swing.ScrollPaneConstants; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import edu.wheaton.simulator.entity.Prototype; import edu.wheaton.simulator.entity.Trigger; import edu.wheaton.simulator.gui.FileMenu; import edu.wheaton.simulator.gui.Gui; import edu.wheaton.simulator.gui.SimulatorFacade; public class TriggerScreen extends Screen { private static final long serialVersionUID = 1L; /** * The screen that allows the user to edit the selected trigger */ private EditTriggerScreen edit; /** * Allows the trigger list to scroll */ private JScrollPane listScrollView; /** * The title label */ private JLabel triggerLabel; /** * The prototype whose triggers are being updated */ private Prototype prototype; /** * The list of triggers of the prototype */ private JList triggers; /** * Button that adds a trigger to the prototype */ private JButton addButton; /** * Deletes a trigger from the prototype */ private JButton deleteButton; /** * Saves the changes to the currently selected trigger */ private JButton saveButton; /** * int counter that prevents added triggers from having the same name */ private int untitledCounter = 1; public TriggerScreen(SimulatorFacade sm) { super(sm); setLayout(new GridBagLayout()); addTriggerLabel(new GridBagConstraints()); addEditLayout(new GridBagConstraints()); addListLayout(new GridBagConstraints()); addTriggerList(new GridBagConstraints()); addAddButton(new GridBagConstraints()); addDeleteButton(new GridBagConstraints()); addSaveButton(new GridBagConstraints()); } /** * Adds the JList in a scrollpane to the view * @param constraints */ private void addTriggerList(GridBagConstraints constraints) { triggers = new JList(); listScrollView.setViewportView(triggers); triggers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); triggers.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent arg0) { try{ if(triggers.getSelectedIndex() >= 0){ Trigger t = (Trigger) triggers.getSelectedValue(); edit.load(new Trigger.Builder(t, prototype), t); } }catch(Exception e){ } } }); constraints.gridx = 0; constraints.gridy = 1; constraints.gridheight = 1; constraints.gridwidth = 2; constraints.ipadx = 200; constraints.ipady = 425; constraints.insets = new Insets(0, 0, 0, 50); add(listScrollView, constraints); } /** * Title of the trigger list * @param constraints */ private void addTriggerLabel(GridBagConstraints constraints) { triggerLabel = new JLabel("Triggers:"); constraints.gridx = 0; constraints.gridy = 0; constraints.gridheight = 1; constraints.gridwidth = 1; constraints.fill = GridBagConstraints.BOTH; add(triggerLabel, constraints); } /** * Generates and adds the JScrollPane * @param constraints */ private void addListLayout(GridBagConstraints constraints) { listScrollView = new JScrollPane(null, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); constraints.gridx = 0; constraints.gridy = 1; constraints.gridheight = 1; constraints.gridwidth = 2; constraints.ipadx = 200; constraints.ipady = 425; constraints.insets = new Insets(0, 0, 0, 50); add(listScrollView, constraints); } /** * Adds the EditTriggerScreen screen to the view * @param constraints */ private void addEditLayout(GridBagConstraints constraints){ edit = new EditTriggerScreen(gm); constraints.gridx = 2; constraints.gridy = 1; constraints.gridheight = 1; constraints.gridwidth = 1; add(edit, constraints); } /** * Adds the button that allows for the addition of a new trigger to the prototype * @param constraints */ private void addAddButton(GridBagConstraints constraints){ addButton = new JButton("Add Trigger"); addButton.addActionListener(new AddTriggerListener()); constraints.gridx = 0; constraints.gridy = 2; constraints.gridheight = 1; constraints.gridwidth = 1; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.anchor = GridBagConstraints.BASELINE_LEADING; add(addButton, constraints); } /** * Adds the button that allows for the deletion of a trigger from the prototype * @param constraints */ private void addDeleteButton(GridBagConstraints constraints) { deleteButton = new JButton("Delete Trigger"); deleteButton.addActionListener(new DeleteTriggerListener()); constraints.gridx = 1; constraints.gridy = 2; constraints.gridheight = 1; constraints.gridwidth = 1; constraints.insets = new Insets(0, 0, 0, 50); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.anchor = GridBagConstraints.BASELINE_LEADING; add(deleteButton, constraints); } /** * Adds the button that allows the user to save the changes to a selected trigger * @param constraints */ private void addSaveButton(GridBagConstraints constraints) { saveButton = new JButton("Save Current Trigger"); saveButton.addActionListener(new SaveListener()); constraints.anchor = GridBagConstraints.BASELINE_TRAILING; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 0; constraints.gridy = 3; constraints.gridheight = 1; constraints.gridwidth = 2; constraints.insets = new Insets(0, 0, 0, 50); add(saveButton, constraints); } /** * Listener that adds a trigger to the prototype when the add button is pressed */ private class AddTriggerListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { // Sets default to 100 because that is the lowest possible priority and the // added trigger should appear at the end of the trigger list Trigger t = new Trigger("Untitled" + untitledCounter++, 100, null, null); edit.load(new Trigger.Builder(prototype), t); prototype.addTrigger(t); load(prototype); triggers.setSelectedIndex(triggers.getLastVisibleIndex()); } } /** * Listener that deletes the selected trigger from the prototype when the delete button is pressed */ private class DeleteTriggerListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e){ Trigger toDelete = (Trigger)triggers.getSelectedValue(); if(toDelete != null){ prototype.removeTrigger(toDelete.toString()); edit.reset(); load(prototype); } else JOptionPane.showMessageDialog(null, "No trigger selected"); } } /** * Listener that saves the changes to the selected listener to the prototype */ private class SaveListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { if(triggers.getSelectedValue() != null){ Trigger toAdd = edit.sendInfo(); if(toAdd != null){ prototype.updateTrigger(triggers.getSelectedValue().toString(), toAdd); load(prototype); edit.reset(); } } else JOptionPane.showMessageDialog(null, "You must select a trigger to save"); } } /** * Clears all information from the screen (except the untitledCounter * which is only reset when the page is reinitialized */ public void reset(){ edit.reset(); prototype = null; triggers.removeAll(); } /** * Loads the prototype trigger information to the screen * @param p, the prototype whose information is loaded */ public void load(Prototype p){ FileMenu fm = Gui.getFileMenu(); fm.setSaveSim(false); prototype = p; triggers.setListData(prototype.getTriggers().toArray()); listScrollView.setViewportView(triggers); listScrollView.updateUI(); validate(); repaint(); } @Override public void load() { FileMenu fm = Gui.getFileMenu(); fm.setSaveSim(false); } /** * Returns the updated prototype * @return The prototype with the saved trigger changes */ public Prototype sendInfo(){ return prototype; } }
/** * ViewSimScreen * * Class representing the screen that displays the grid as * the simulation runs. * * @author Willy McHie and Ian Walling * Wheaton College, CSCI 335, Spring 2013 */ package edu.wheaton.simulator.gui.screen; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.LayoutManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import edu.wheaton.simulator.gui.GeneralButtonListener; import edu.wheaton.simulator.gui.Gui; import edu.wheaton.simulator.gui.MaxSize; import edu.wheaton.simulator.gui.PrefSize; import edu.wheaton.simulator.gui.ScreenManager; import edu.wheaton.simulator.gui.SimulatorFacade; public class ViewSimScreen extends Screen { private static final long serialVersionUID = -6872689283286800861L; private GridBagConstraints c; private boolean canSpawn; private final EntityScreen entitiesScreen; private final Screen layerScreen; private final Screen globalFieldScreen; private final Screen optionsScreen; public ViewSimScreen(final SimulatorFacade gm) { super(gm); setSpawn(false); this.setLayout(new GridBagLayout()); ((GridBagLayout)this.getLayout()).columnWeights = new double[]{0, 1}; final JTabbedPane tabs = new JTabbedPane(); tabs.setMaximumSize(new Dimension(550, 550)); entitiesScreen = new EntityScreen(gm); layerScreen = new LayerScreen(gm); globalFieldScreen = new FieldScreen(gm); optionsScreen = new SetupScreen(gm); tabs.addTab("Agent", entitiesScreen); tabs.addTab("Layers", layerScreen); tabs.addTab("Global Fields", globalFieldScreen); tabs.addTab("Options", optionsScreen); tabs.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent ce) { if (tabs.getSelectedComponent().toString() == "Agent") setSpawn(true); else { setSpawn(false); } entitiesScreen.load(); layerScreen.load(); globalFieldScreen.load(); optionsScreen.load(); } }); gm.getGridPanel().addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent me) { if (getGuiManager().canSpawn()) { int standardSize = Math.min(gm.getGridPanel().getWidth() / gm.getGridWidth(), gm.getGridPanel() .getHeight() / gm.getGridHeight()); int x = me.getX() / standardSize; int y = me.getY() / standardSize; if (canSpawn) { if (gm.getAgent(x, y) == null) { gm.addAgent(entitiesScreen.getList() .getSelectedValue().toString(), x, y); } else { gm.removeAgent(x, y); } } gm.getGridPanel().repaint(); } } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { } @Override public void mouseReleased(MouseEvent arg0) { } }); c = new GridBagConstraints(); c.fill = GridBagConstraints.NONE; c.gridx = 0; c.gridy = 0; c.gridheight = 2; c.weightx = 0; c.insets = new Insets(5, 5, 5, 5); this.add(tabs, c); c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.gridx = 1; c.gridy = 0; c.ipadx = 600; c.ipady = 600; c.gridwidth = 2; c.weighty = 1; c.weightx = 1; c.insets = new Insets(5, 5, 5, 5); this.add(gm.getGridPanel(), c); c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridy = 1; c.gridwidth = 2; this.add(makeButtonPanel(), c); this.setVisible(true); } private JPanel makeButtonPanel() { ScreenManager sm = getScreenManager(); JPanel buttonPanel = Gui.makePanel((LayoutManager) null, new MaxSize( 500, 50), PrefSize.NULL, makeStartButton(), Gui.makeButton("Statistics", null, new GeneralButtonListener("Statistics", sm)), Gui.makeButton("Clear Agents", null, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { gm.clearGrid(); } }), Gui.makeButton("Fill Grid", null, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String agentName = entitiesScreen.getList().getSelectedValue().toString(); if (agentName != null) { gm.fillGrid(agentName); } } }) ); return buttonPanel; } public void setSpawn(boolean canSpawn) { this.canSpawn = canSpawn; } private JButton makeStartButton() { final JButton b = Gui.makeButton("Start", null, null); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SimulatorFacade gm = getGuiManager(); if(b.getName() == "Start" || b.getName() == "Resume"){ canSpawn = false; gm.getGridPanel().repaint(); gm.start(); b.setName("Pause"); } else{ getGuiManager().pause(); canSpawn = true; b.setName("Resume"); } } }); return b; } @Override public void load() { entitiesScreen.load(); layerScreen.load(); globalFieldScreen.load(); optionsScreen.load(); validate(); getGuiManager().getGridPanel().repaint(); } }
package edu.wustl.common.querysuite.utils; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import edu.common.dynamicextensions.domaininterface.AttributeInterface; import edu.common.dynamicextensions.domaininterface.EntityInterface; import edu.wustl.common.querysuite.queryobject.IArithmeticOperand; import edu.wustl.common.querysuite.queryobject.ICondition; import edu.wustl.common.querysuite.queryobject.IConstraints; import edu.wustl.common.querysuite.queryobject.ICustomFormula; import edu.wustl.common.querysuite.queryobject.IExpression; import edu.wustl.common.querysuite.queryobject.IExpressionAttribute; import edu.wustl.common.querysuite.queryobject.IExpressionOperand; import edu.wustl.common.querysuite.queryobject.IParameter; import edu.wustl.common.querysuite.queryobject.IParameterizedQuery; import edu.wustl.common.querysuite.queryobject.IQuery; import edu.wustl.common.querysuite.queryobject.IQueryEntity; import edu.wustl.common.querysuite.queryobject.IRule; import edu.wustl.common.querysuite.queryobject.ITerm; import edu.wustl.common.util.Collections; /** * @author chetan_patil * @created Sep 20, 2007, 12:07:59 PM */ public class QueryUtility { /** * This method returns all the selected Condition for a given query. * * @param query * @return Map of ExpressionId -> Collection of Condition */ public static Map<IExpression, Collection<ICondition>> getAllSelectedConditions(IQuery query) { Map<IExpression, Collection<ICondition>> expressionIdConditionCollectionMap = null; if (query != null) { expressionIdConditionCollectionMap = new HashMap<IExpression, Collection<ICondition>>(); IConstraints constraints = query.getConstraints(); for (IExpression expression : constraints) { for (int index = 0; index < expression.numberOfOperands(); index++) { IExpressionOperand expressionOperand = expression.getOperand(index); if (expressionOperand instanceof IRule) { IRule rule = (IRule) expressionOperand; expressionIdConditionCollectionMap.put(expression, Collections.list(rule)); } } } } return expressionIdConditionCollectionMap; } /** * This method returns the collection of all non-parameterized conditions form a given query. * * @param paramQuery parameterized query * @return collection of non-parameterized conditions */ public static Collection<ICondition> getAllNonParameteriedConditions(IParameterizedQuery paramQuery) { Map<IExpression, Collection<ICondition>> conditionsMap = getAllSelectedConditions(paramQuery); Collection<ICondition> nonParamConditions = new ArrayList<ICondition>(); for (Collection<ICondition> conditions : conditionsMap.values()) { nonParamConditions.addAll(conditions); } nonParamConditions.removeAll(getAllParameterizedConditions(paramQuery)); return nonParamConditions; } public static Collection<ICondition> getAllParameterizedConditions(IParameterizedQuery paramQuery) { Collection<ICondition> paramConditions = new ArrayList<ICondition>(); List<IParameter<?>> parameters = paramQuery.getParameters(); for (IParameter<?> parameter : parameters) { if (parameter.getParameterizedObject() instanceof ICondition) { paramConditions.add((ICondition) parameter.getParameterizedObject()); } } return paramConditions; } /** * This method returns all the attributes of the expressions involved in a * given query. * * @param query * @return Map of ExpressionId -> Collection of Attribute */ public static Map<IExpression, Collection<AttributeInterface>> getAllAttributes(IQuery query) { Map<IExpression, Collection<AttributeInterface>> expressionIdAttributeCollectionMap = null; if (query != null) { expressionIdAttributeCollectionMap = new HashMap<IExpression, Collection<AttributeInterface>>(); IConstraints constraints = query.getConstraints(); for (IExpression expression : constraints) { IQueryEntity queryEntity = expression.getQueryEntity(); EntityInterface deEntity = queryEntity.getDynamicExtensionsEntity(); Collection<AttributeInterface> attributeCollection = deEntity.getEntityAttributesForQuery(); expressionIdAttributeCollectionMap.put(expression, attributeCollection); } } return expressionIdAttributeCollectionMap; } public static Set<ICustomFormula> getCustomFormulas(IQuery query) { return getCustomFormulas(query.getConstraints()); } public static Set<ICustomFormula> getCustomFormulas(IConstraints constraints) { Set<ICustomFormula> res = new HashSet<ICustomFormula>(); for (IExpression expression : constraints) { res.addAll(getCustomFormulas(expression)); } return res; } public static Set<ICustomFormula> getCustomFormulas(IExpression expression) { Set<ICustomFormula> res = new HashSet<ICustomFormula>(); for (IExpressionOperand operand : expression) { if (operand instanceof ICustomFormula) { res.add((ICustomFormula) operand); } } return res; } public static Set<IExpression> getExpressionsInFormula(ICustomFormula formula) { Set<IExpression> res = new HashSet<IExpression>(); res.addAll(getExpressionsInTerm(formula.getLhs())); for (ITerm rhs : formula.getAllRhs()) { res.addAll(getExpressionsInTerm(rhs)); } return res; } public static Set<IExpressionAttribute> getAttributesInFormula(ICustomFormula formula) { Set<IExpressionAttribute> res = new HashSet<IExpressionAttribute>(); res.addAll(getAttributesInTerm(formula.getLhs())); for (ITerm rhs : formula.getAllRhs()) { res.addAll(getAttributesInTerm(rhs)); } return res; } public static Set<IExpression> getExpressionsInTerm(ITerm term) { Set<IExpression> res = new HashSet<IExpression>(); for (IExpressionAttribute attr : getAttributesInTerm(term)) { res.add(attr.getExpression()); } return res; } public static Set<IExpressionAttribute> getAttributesInTerm(ITerm term) { Set<IExpressionAttribute> res = new HashSet<IExpressionAttribute>(); for (IArithmeticOperand operand : term) { if (operand instanceof IExpressionAttribute) { res.add((IExpressionAttribute) operand); } } return res; } public static Set<IExpression> getContainingExpressions(IConstraints constraints, ICustomFormula formula) { Set<IExpression> res = new HashSet<IExpression>(); for (IExpression expression : constraints) { if (expression.containsOperand(formula)) { res.add(expression); } } return res; } }
package FlightScheduler; // VERTEX.JAVA // Vertex class for the multigraph // A Vertex is created with an integer identifier. Subclass // it if you want to store more complex info. // To enumerate a vertex's adjacency list, you call its adj() // method, which returns an iterator "ei" of type EdgeIterator for // the list. You can call ei.hasNext() to see if there is another // edge available, and ei.next() to get it. import java.util.*; public class Vertex { // Constructor (takes an identifier) public Vertex(int id) { _id = id; neighbors = new ArrayList<Edge>(); } // Return our identifier. public int id() { return _id; } // adj() // Return an iterator to list all of our edges. public EdgeIterator adj() { EdgeIterator a = new EdgeIterator(this); return a; } // addEdge() // Add an edge to our adjacency list. public void addEdge(Edge e) { neighbors.add(e); } // toString() // Identify us by our id. public String toString() { return "" + _id; } public class EdgeIterator { public EdgeIterator(Vertex iv) { v = iv; posn = 0; } public boolean hasNext() { return (posn < v.neighbors.size()); } public Edge next() { return v.neighbors.get(posn++); } private Vertex v; private int posn; } private int _id; private ArrayList<Edge> neighbors; public Handle handle; }
package gov.nih.nci.calab.service.common; import gov.nih.nci.calab.db.DataAccessProxy; import gov.nih.nci.calab.db.IDataAccess; import gov.nih.nci.calab.domain.Aliquot; import gov.nih.nci.calab.domain.MeasureUnit; import gov.nih.nci.calab.domain.Sample; import gov.nih.nci.calab.domain.SampleContainer; import gov.nih.nci.calab.domain.StorageElement; import gov.nih.nci.calab.dto.inventory.AliquotBean; import gov.nih.nci.calab.dto.inventory.ContainerBean; import gov.nih.nci.calab.dto.inventory.ContainerInfoBean; import gov.nih.nci.calab.dto.inventory.SampleBean; import gov.nih.nci.calab.dto.workflow.AssayBean; import gov.nih.nci.calab.service.util.CalabComparators; import gov.nih.nci.calab.service.util.CalabConstants; import gov.nih.nci.calab.service.util.CananoConstants; import gov.nih.nci.calab.service.util.PropertyReader; import gov.nih.nci.calab.service.util.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import org.apache.log4j.Logger; import org.apache.struts.util.LabelValueBean; /** * The service to return prepopulated data that are shared across different * views. * * @author zengje * */ /* CVS $Id: LookupService.java,v 1.66 2006-12-01 14:22:45 beasleyj Exp $ */ public class LookupService { private static Logger logger = Logger.getLogger(LookupService.class); /** * Retrieving all unmasked aliquots for use in views create run, use aliquot * and create aliquot. * * @return a Map between sample name and its associated unmasked aliquots * @throws Exception */ public Map<String, SortedSet<AliquotBean>> getUnmaskedSampleAliquots() throws Exception { SortedSet<AliquotBean> aliquots = null; IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Map<String, SortedSet<AliquotBean>> sampleAliquots = new HashMap<String, SortedSet<AliquotBean>>(); try { ida.open(); String hqlString = "select aliquot.id, aliquot.name, aliquot.sample.name from Aliquot aliquot where aliquot.dataStatus is null order by aliquot.name"; List results = ida.search(hqlString); for (Object obj : results) { Object[] info = (Object[]) obj; AliquotBean aliquot = new AliquotBean(StringUtils .convertToString(info[0]), StringUtils .convertToString(info[1]), CalabConstants.ACTIVE_STATUS); String sampleName = (String) info[2]; if (sampleAliquots.get(sampleName) != null) { aliquots = (SortedSet<AliquotBean>) sampleAliquots .get(sampleName); } else { aliquots = new TreeSet<AliquotBean>( new CalabComparators.AliquotBeanComparator()); sampleAliquots.put(sampleName, aliquots); } aliquots.add(aliquot); } } catch (Exception e) { logger.error("Error in retrieving all aliquot Ids and names", e); throw new RuntimeException( "Error in retrieving all aliquot Ids and names"); } finally { ida.close(); } return sampleAliquots; } /** * * @return a map between sample name and its sample containers * @throws Exception */ public Map<String, SortedSet<ContainerBean>> getAllSampleContainers() throws Exception { SortedSet<ContainerBean> containers = null; IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Map<String, SortedSet<ContainerBean>> sampleContainers = new HashMap<String, SortedSet<ContainerBean>>(); try { ida.open(); String hqlString = "select container, container.sample.name from SampleContainer container"; List results = ida.search(hqlString); for (Object obj : results) { Object[] info = (Object[]) obj; if (!(info[0] instanceof Aliquot)) { ContainerBean container = new ContainerBean( (SampleContainer) info[0]); String sampleName = (String) info[1]; if (sampleContainers.get(sampleName) != null) { containers = (SortedSet<ContainerBean>) sampleContainers .get(sampleName); } else { containers = new TreeSet<ContainerBean>( new CalabComparators.ContainerBeanComparator()); sampleContainers.put(sampleName, containers); } containers.add(container); } } } catch (Exception e) { logger.error("Error in retrieving all containers", e); throw new RuntimeException("Error in retrieving all containers"); } finally { ida.close(); } return sampleContainers; } /** * Retrieving all sample types. * * @return a list of all sample types */ public List<String> getAllSampleTypes() throws Exception { // Detail here // Retrieve data from Sample_Type table List<String> sampleTypes = new ArrayList<String>(); // sampleTypes.add(CalabConstants.OTHER); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sampleType.name from SampleType sampleType order by sampleType.name"; List results = ida.search(hqlString); for (Object obj : results) { sampleTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all sample types", e); throw new RuntimeException("Error in retrieving all sample types"); } finally { ida.close(); } return sampleTypes; } /** * * @return the default sample container information in a form of * ContainerInfoBean */ public ContainerInfoBean getSampleContainerInfo() throws Exception { List<MeasureUnit> units = getAllMeasureUnits(); List<StorageElement> storageElements = getAllRoomAndFreezers(); List<String> quantityUnits = new ArrayList<String>(); List<String> concentrationUnits = new ArrayList<String>(); List<String> volumeUnits = new ArrayList<String>(); List<String> rooms = new ArrayList<String>(); List<String> freezers = new ArrayList<String>(); for (MeasureUnit unit : units) { if (unit.getType().equalsIgnoreCase("Quantity")) { quantityUnits.add(unit.getName()); } else if (unit.getType().equalsIgnoreCase("Volume")) { volumeUnits.add(unit.getName()); } else if (unit.getType().equalsIgnoreCase("Concentration")) { concentrationUnits.add(unit.getName()); } } for (StorageElement storageElement : storageElements) { if (storageElement.getType().equalsIgnoreCase("Room")) { rooms.add((storageElement.getLocation())); } else if (storageElement.getType().equalsIgnoreCase("Freezer")) { freezers.add((storageElement.getLocation())); } } // set labs and racks to null for now ContainerInfoBean containerInfo = new ContainerInfoBean(quantityUnits, concentrationUnits, volumeUnits, null, rooms, freezers); return containerInfo; } public List<String> getAllSampleContainerTypes() throws Exception { SortedSet<String> containerTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct container.containerType from SampleContainer container order by container.containerType"; List results = ida.search(hqlString); for (Object obj : results) { containerTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all sample container types", e); throw new RuntimeException( "Error in retrieving all sample container types."); } finally { ida.close(); } containerTypes.addAll(Arrays .asList(CalabConstants.DEFAULT_CONTAINER_TYPES)); List<String> containerTypeList = new ArrayList<String>(containerTypes); return containerTypeList; } public List<String> getAllAliquotContainerTypes() throws Exception { SortedSet<String> containerTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct aliquot.containerType from Aliquot aliquot order by aliquot.containerType"; List results = ida.search(hqlString); for (Object obj : results) { containerTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all aliquot container types", e); throw new RuntimeException( "Error in retrieving all aliquot container types."); } finally { ida.close(); } containerTypes.addAll(Arrays .asList(CalabConstants.DEFAULT_CONTAINER_TYPES)); List<String> containerTypeList = new ArrayList<String>(containerTypes); return containerTypeList; } private List<MeasureUnit> getAllMeasureUnits() throws Exception { List<MeasureUnit> units = new ArrayList<MeasureUnit>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from MeasureUnit"; List results = ida.search(hqlString); for (Object obj : results) { units.add((MeasureUnit) obj); } } catch (Exception e) { logger.error("Error in retrieving all measure units", e); throw new RuntimeException("Error in retrieving all measure units."); } finally { ida.close(); } return units; } private List<StorageElement> getAllRoomAndFreezers() throws Exception { List<StorageElement> storageElements = new ArrayList<StorageElement>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from StorageElement where type in ('Room', 'Freezer')"; List results = ida.search(hqlString); for (Object obj : results) { storageElements.add((StorageElement) obj); } } catch (Exception e) { logger.error("Error in retrieving all rooms and freezers", e); throw new RuntimeException( "Error in retrieving all rooms and freezers."); } finally { ida.close(); } return storageElements; } /** * * @return the default sample container information in a form of * ContainerInfoBean */ public ContainerInfoBean getAliquotContainerInfo() throws Exception { return getSampleContainerInfo(); } /** * Get all samples in the database * * @return a list of SampleBean containing sample Ids and names DELETE */ public List<SampleBean> getAllSamples() throws Exception { List<SampleBean> samples = new ArrayList<SampleBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sample.id, sample.name from Sample sample"; List results = ida.search(hqlString); for (Object obj : results) { Object[] sampleInfo = (Object[]) obj; samples.add(new SampleBean(StringUtils .convertToString(sampleInfo[0]), StringUtils .convertToString(sampleInfo[1]))); } } catch (Exception e) { logger.error("Error in retrieving all sample IDs and names", e); throw new RuntimeException( "Error in retrieving all sample IDs and names"); } finally { ida.close(); } Collections.sort(samples, new CalabComparators.SampleBeanComparator()); return samples; } /** * Retrieve all Assay Types from the system * * @return A list of all assay type */ public List getAllAssayTypes() throws Exception { List<String> assayTypes = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select assayType.name from AssayType assayType order by assayType.executeOrder"; List results = ida.search(hqlString); for (Object obj : results) { assayTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all assay types", e); throw new RuntimeException("Error in retrieving all assay types"); } finally { ida.close(); } return assayTypes; } /** * * @return a map between assay type and its assays * @throws Exception */ public Map<String, SortedSet<AssayBean>> getAllAssayTypeAssays() throws Exception { Map<String, SortedSet<AssayBean>> assayTypeAssays = new HashMap<String, SortedSet<AssayBean>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select assay.id, assay.name, assay.assayType from Assay assay"; List results = ida.search(hqlString); SortedSet<AssayBean> assays = null; for (Object obj : results) { Object[] objArray = (Object[]) obj; AssayBean assay = new AssayBean( ((Long) objArray[0]).toString(), (String) objArray[1], (String) objArray[2]); if (assayTypeAssays.get(assay.getAssayType()) != null) { assays = (SortedSet<AssayBean>) assayTypeAssays.get(assay .getAssayType()); } else { assays = new TreeSet<AssayBean>( new CalabComparators.AssayBeanComparator()); assayTypeAssays.put(assay.getAssayType(), assays); } assays.add(assay); } } catch (Exception e) { logger.error("Error in retrieving all assay beans. ", e); throw new RuntimeException("Error in retrieving all assays beans. "); } finally { ida.close(); } return assayTypeAssays; } /** * * @return all sample sources */ public List<String> getAllSampleSources() throws Exception { List<String> sampleSources = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select source.organizationName from Source source order by source.organizationName"; List results = ida.search(hqlString); for (Object obj : results) { sampleSources.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all sample sources", e); throw new RuntimeException("Error in retrieving all sample sources"); } finally { ida.close(); } return sampleSources; } /** * * @return a map between sample source and samples with unmasked aliquots * @throws Exception */ public Map<String, SortedSet<SampleBean>> getSampleSourceSamplesWithUnmaskedAliquots() throws Exception { Map<String, SortedSet<SampleBean>> sampleSourceSamples = new HashMap<String, SortedSet<SampleBean>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct aliquot.sample from Aliquot aliquot where aliquot.dataStatus is null"; List results = ida.search(hqlString); SortedSet<SampleBean> samples = null; for (Object obj : results) { SampleBean sample = new SampleBean((Sample) obj); if (sampleSourceSamples.get(sample.getSampleSource()) != null) { // TODO need to make sample source a required field if (sample.getSampleSource().length() > 0) { samples = (SortedSet<SampleBean>) sampleSourceSamples .get(sample.getSampleSource()); } } else { samples = new TreeSet<SampleBean>( new CalabComparators.SampleBeanComparator()); if (sample.getSampleSource().length() > 0) { sampleSourceSamples.put(sample.getSampleSource(), samples); } } samples.add(sample); } } catch (Exception e) { logger.error( "Error in retrieving sample beans with unmasked aliquots ", e); throw new RuntimeException( "Error in retrieving all sample beans with unmasked aliquots. "); } finally { ida.close(); } return sampleSourceSamples; } public List<String> getAllSampleSOPs() throws Exception { List<String> sampleSOPs = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sampleSOP.name from SampleSOP sampleSOP where sampleSOP.description='sample creation'"; List results = ida.search(hqlString); for (Object obj : results) { sampleSOPs.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Sample SOPs."); throw new RuntimeException("Problem to retrieve all Sample SOPs. "); } finally { ida.close(); } return sampleSOPs; } /** * * @return all methods for creating aliquots */ public List<LabelValueBean> getAliquotCreateMethods() throws Exception { List<LabelValueBean> createMethods = new ArrayList<LabelValueBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sop.name, file.path from SampleSOP sop join sop.sampleSOPFileCollection file where sop.description='aliquot creation'"; List results = ida.search(hqlString); for (Object obj : results) { String sopName = (String) ((Object[]) obj)[0]; String sopURI = (String) ((Object[]) obj)[1]; String sopURL = (sopURI == null) ? "" : sopURI; createMethods.add(new LabelValueBean(sopName, sopURL)); } } catch (Exception e) { logger.error("Error in retrieving all sample sources", e); throw new RuntimeException("Error in retrieving all sample sources"); } finally { ida.close(); } return createMethods; } /** * * @return all source sample IDs */ public List<String> getAllSourceSampleIds() throws Exception { List<String> sourceSampleIds = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct sample.sourceSampleId from Sample sample order by sample.sourceSampleId"; List results = ida.search(hqlString); for (Object obj : results) { sourceSampleIds.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all source sample IDs", e); throw new RuntimeException( "Error in retrieving all source sample IDs"); } finally { ida.close(); } return sourceSampleIds; } public Map<String, SortedSet<String>> getAllParticleTypeParticles() throws Exception { // TODO fill in actual database query. Map<String, SortedSet<String>> particleTypeParticles = new HashMap<String, SortedSet<String>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select particle.type, particle.name from Nanoparticle particle"; List results = ida.search(hqlString); SortedSet<String> particleNames = null; for (Object obj : results) { Object[] objArray = (Object[]) obj; String particleType = (String) objArray[0]; String particleName = (String) objArray[1]; if (particleType != null) { if (particleTypeParticles.get(particleType) != null) { particleNames = (SortedSet<String>) particleTypeParticles .get(particleType); } else { particleNames = new TreeSet<String>( new CalabComparators.SortableNameComparator()); particleTypeParticles.put(particleType, particleNames); } particleNames.add(particleName); } } } catch (Exception e) { logger .error("Error in retrieving all particle type particles. ", e); throw new RuntimeException( "Error in retrieving all particle type particles. "); } finally { ida.close(); } return particleTypeParticles; } public String[] getAllParticleFunctions() { String[] functions = new String[] { "Therapeutic", "Targeting", "Diagnostic Imaging", "Diagnostic Reporting" }; return functions; } public String[] getAllCharacterizationTypes() { String[] charTypes = new String[] { "Physical Characterization", "In Vitro Characterization", "In Vivo Characterization" }; return charTypes; } public String[] getAllDendrimerCores() { String[] cores = new String[] { "Diamine", "Ethyline" }; return cores; } public String[] getAllDendrimerSurfaceGroupNames() { String[] names = new String[] { "Amine", "Carboxyl", "Hydroxyl" }; return names; } public String[] getAllDendrimerBranches() throws Exception { SortedSet<String> branches = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct dendrimer.branch from DendrimerComposition dendrimer where dendrimer.branch is not null"; List results = ida.search(hqlString); for (Object obj : results) { branches.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Dendrimer Branches."); throw new RuntimeException( "Problem to retrieve all Dendrimer Branches. "); } finally { ida.close(); } branches.addAll(Arrays .asList(CananoConstants.DEFAULT_DENDRIMER_BRANCHES)); return (String[]) branches.toArray(new String[0]); } public String[] getAllDendrimerGenerations() throws Exception { SortedSet<String> generations = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct dendrimer.generation from DendrimerComposition dendrimer where dendrimer.generation is not null "; List results = ida.search(hqlString); for (Object obj : results) { generations.add(obj.toString()); } } catch (Exception e) { logger.error("Problem to retrieve all Dendrimer Generations."); throw new RuntimeException( "Problem to retrieve all Dendrimer Generations. "); } finally { ida.close(); } generations.addAll(Arrays .asList(CananoConstants.DEFAULT_DENDRIMER_GENERATIONS)); return (String[]) generations.toArray(new String[0]); } public String[] getAllMetalCompositions() { String[] compositions = new String[] { "Gold", "Sliver", "Iron oxide" }; return compositions; } public String[] getAllPolymerInitiators() throws Exception { SortedSet<String> initiators = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct polymer.initiator from PolymerComposition polymer "; List results = ida.search(hqlString); for (Object obj : results) { initiators.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Polymer Initiator."); throw new RuntimeException( "Problem to retrieve all Polymer Initiator. "); } finally { ida.close(); } initiators.addAll(Arrays .asList(CananoConstants.DEFAULT_POLYMER_INITIATORS)); return (String[]) initiators.toArray(new String[0]); } public List<String> getAllParticleSources() throws Exception { // TODO fill in db code return getAllSampleSources(); } public String getParticleClassification(String particleType) { String key = "classification." + particleType.replaceAll(" ", "_"); String classification = PropertyReader.getProperty( CananoConstants.PARTICLE_PROPERTY, key); return classification; } /** * * @return a map between a characterization type and its child * characterizations. */ public Map<String, String[]> getCharacterizationTypeCharacterizations() { Map<String, String[]> charTypeChars = new HashMap<String, String[]>(); String[] physicalChars = new String[] { CananoConstants.PHYSICAL_COMPOSITION, CananoConstants.PHYSICAL_SIZE, CananoConstants.PHYSICAL_MOLECULAR_WEIGHT, CananoConstants.PHYSICAL_MORPHOLOGY, CananoConstants.PHYSICAL_SOLUBILITY, CananoConstants.PHYSICAL_SURFACE, CananoConstants.PHYSICAL_PURITY, CananoConstants.PHYSICAL_STABILITY, CananoConstants.PHYSICAL_FUNCTIONAL, CananoConstants.PHYSICAL_SHAPE }; charTypeChars.put("physical", physicalChars); String[] toxChars = new String[] { CananoConstants.TOXICITY_OXIDATIVE_STRESS, CananoConstants.TOXICITY_ENZYME_FUNCTION }; charTypeChars.put("toxicity", toxChars); String[] cytoToxChars = new String[] { CananoConstants.CYTOTOXICITY_CELL_VIABILITY, CananoConstants.CYTOTOXICITY_CASPASE3_ACTIVIATION }; charTypeChars.put("cytoTox", cytoToxChars); String[] bloodContactChars = new String[] { CananoConstants.BLOODCONTACTTOX_PLATE_AGGREGATION, CananoConstants.BLOODCONTACTTOX_HEMOLYSIS, CananoConstants.BLOODCONTACTTOX_PLASMA_PROTEIN_BINDING, CananoConstants.BLOODCONTACTTOX_COAGULATION }; charTypeChars.put("bloodContactTox", bloodContactChars); String[] immuneCellFuncChars = new String[] { CananoConstants.IMMUNOCELLFUNCTOX_OXIDATIVE_BURST, CananoConstants.IMMUNOCELLFUNCTOX_CHEMOTAXIS, CananoConstants.IMMUNOCELLFUNCTOX_LEUKOCYTE_PROLIFERATION, CananoConstants.IMMUNOCELLFUNCTOX_PHAGOCYTOSIS, CananoConstants.IMMUNOCELLFUNCTOX_CYTOKINE_INDUCTION, CananoConstants.IMMUNOCELLFUNCTOX_CFU_GM, CananoConstants.IMMUNOCELLFUNCTOX_COMPLEMENT_ACTIVATION, CananoConstants.IMMUNOCELLFUNCTOX_NKCELL_CYTOTOXIC_ACTIVITY }; charTypeChars.put("immuneCellFuncTox", immuneCellFuncChars); String[] metabolicChars = new String[] { CananoConstants.METABOLIC_STABILITY_CYP450, CananoConstants.METABOLIC_STABILITY_GLUCURONIDATION_SULPHATION, CananoConstants.METABOLIC_STABILITY_ROS }; charTypeChars.put("metabolicStabilityTox", metabolicChars); return charTypeChars; } public String[] getAllInstrumentTypes() throws Exception { // TODO query from database or properties file // String[] instrumentTypes=new String[] {"Dynamic Light Scattering // (DLS)", "Spectroscopy", "Other"}; SortedSet<String> instrumentTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct instrumentType.name from InstrumentType instrumentType"; List results = ida.search(hqlString); for (Object obj : results) { if (obj != null) instrumentTypes.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all instrumentTypes. " + e); throw new RuntimeException( "Problem to retrieve all intrument types. "); } finally { ida.close(); } return (String[]) instrumentTypes.toArray(new String[0]); } public String[] getManufacturers(String instrumentType) throws Exception { SortedSet<String> manufacturers = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); /* * String hqlString = "select distinct instrument.manufacturer from * Instrument instrument"; if * (!instrumentType.equals(CananoConstants.OTHER)) hqlString += " * where instrument.type = '" + instrumentType + "'"; */ String hqlString = "select distinct manufacturer.name from InstrumentType instrumentType join instrumentType.manufacturerCollection manufacturer "; if ((instrumentType != null) && (!instrumentType.equals(CananoConstants.OTHER))) hqlString += " where instrumentType.name = '" + instrumentType + "'"; List results = ida.search(hqlString); for (Object obj : results) { if (obj != null) manufacturers.add((String) obj); } } catch (Exception e) { logger .error("Problem to retrieve manufacturers for intrument type " + instrumentType + ". " + e); throw new RuntimeException( "Problem to retrieve manufacturers for intrument type " + instrumentType + "."); } finally { ida.close(); } // manufacturers.add(CananoConstants.OTHER); return (String[]) manufacturers.toArray(new String[0]); } public String[] getSizeDistributionGraphTypes() { // TODO query from database or properties file String[] graphTypes = new String[] { "Volume", "Intensity", "Number" }; return graphTypes; } public String[] getMolecularWeightDistributionGraphTypes() { // TODO query from database or properties file String[] graphTypes = new String[] { "Volume", "Mass", "Number" }; return graphTypes; } public String[] getMorphologyDistributionGraphTypes() { // TODO query from database or properties file String[] graphTypes = new String[] { "Image", "Graph" }; return graphTypes; } public String[] getShapeDistributionGraphTypes() { // TODO query from database or properties file String[] graphTypes = new String[] { "Image", "Graph" }; return graphTypes; } public String[] getStabilityDistributionGraphTypes() { // TODO query from database or properties file String[] graphTypes = new String[] { "Image", "Graph" }; return graphTypes; } public String[] getPurityDistributionGraphTypes() { // TODO query from database or properties file String[] graphTypes = new String[] { "Image", "Graph" }; return graphTypes; } public String[] getSolubilityDistributionGraphTypes() { // TODO query from database or properties file String[] graphTypes = new String[] { "Image", "Graph" }; return graphTypes; } public String[] getAllMorphologyTypes() { String[] morphologyTypes = new String[] { "Power", "Liquid", "Solid", "Crystalline", "Copolymer", "Fibril", "Colloid", "Oil" }; return morphologyTypes; } public String[] getAllShapeTypes() { String[] shapeTypes = new String[] { "Hexagonal", "Irregular", "Needle", "Oblate", "Rod", "Spherical", "Tetrahedral", "Tetrapod", "Triangular", "Elliptical", "Composite", "Cylindrical", "Vesicular", "Elliposid" }; return shapeTypes; } public String[] getAllStressorTypes() { String[] stressorTypes = new String[] { "Thermal", "PH", "Freeze thaw", "Photo", "Centrifugation", "Lyophilization", "Chemical" }; return stressorTypes; } public String[] getAllSurfaceTypes() { String[] surfaceTypes = new String[] { "surface type 1", "surface type 2" }; return surfaceTypes; } public String[] getAllAreaMeasureUnits() { String[] areaUnit = new String[] { "square nm" }; return areaUnit; } public String[] getAllChargeMeasureUnits() { String[] chargeUnit = new String[] { "a.u", "aC", "Ah", "C", "esu", "Fr", "statC" }; return chargeUnit; } public String[] getAllDensityMeasureUnits() { String[] densityUnits = new String[] { "kg/L" }; return densityUnits; } public String[] getAllControlTypes() { String[] chargeUnit = new String[] {" ", "Positive", "Negative"}; String[] chargeUnit = new String[] { "Positive", "Negative" }; return chargeUnit; } public String[] getAllConditionTypes() { String[] chargeUnit = new String[] {" ", "Particle Concentration", "Time", "Temperature"}; return chargeUnit; } public Map<String, String[]> getAllAgentTypes() { Map<String, String[]> agentTypes = new HashMap<String, String[]>(); String[] therapeuticsAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA"}; agentTypes.put("Therapeutics", therapeuticsAgentTypes); String[] targetingAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody" }; agentTypes.put("Targeting", targetingAgentTypes); String[] imagingAgentTypes = new String[] { "Small Molecule", "Image Contrast Agent" }; agentTypes.put("Imaging", imagingAgentTypes); String[] reportingAgentTypes = new String[] { "Peptide", "Small Molecule", "Probe", "DNA"}; agentTypes.put("Reporting", reportingAgentTypes); return agentTypes; } public Map<String,String[]> getAllAgentTargetTypes() { Map<String,String[]> agentTargetTypes=new HashMap<String, String[]>(); String[] targetTypes = new String[] { "Receptor", "Antigen" }; String[] targetTypes2 = new String[] { "Receptor"}; agentTargetTypes.put("Small Molecule", targetTypes2); agentTargetTypes.put("Peptide", targetTypes2); agentTargetTypes.put("Antibody", targetTypes); agentTargetTypes.put("DNA", targetTypes2); agentTargetTypes.put("Probe", targetTypes2); return agentTargetTypes; } public String[] getAllTimeUnits() { String[] timeUnits = new String[] { "seconds", "hours", "days", "months" }; return timeUnits; } public String[] getAllConcentrationUnits() { String[] concentrationUnits = new String[] { "g/ml", "mg/ml", "ug/ml", "ug/ul", "pg/ml" }; return concentrationUnits; } public String[] getAllConditionUnits() { String[] concentrationUnits = new String[] {"g/ml", "mg/ml", "ug/ml", "ug/ul", "pg/ml", "seconds", "hours", "days", "months", "degrees celcius", "degrees fahrenhiet"}; return concentrationUnits; } }
package gov.nih.nci.calab.service.common; import gov.nih.nci.calab.db.DataAccessProxy; import gov.nih.nci.calab.db.IDataAccess; import gov.nih.nci.calab.domain.MeasureUnit; import gov.nih.nci.calab.domain.StorageElement; import gov.nih.nci.calab.dto.administration.AliquotBean; import gov.nih.nci.calab.dto.administration.ContainerInfoBean; import gov.nih.nci.calab.dto.administration.SampleBean; import gov.nih.nci.calab.dto.workflow.AssayBean; import gov.nih.nci.calab.service.util.CalabConstants; import gov.nih.nci.calab.service.util.StringUtils; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; /** * The service to return prepopulated data that are shared across different * views. * * @author zengje * */ /* CVS $Id: LookupService.java,v 1.22 2006-04-25 19:02:07 pansu Exp $ */ public class LookupService { private static Logger logger = Logger.getLogger(LookupService.class); /** * Retriving all aliquot in the system, for views view aliquot, create run, * search sample. * * @return a list of AliquotBeans containing aliquot ID and aliquot name */ public List<AliquotBean> getAliquots() throws Exception { List<AliquotBean> aliquots = new ArrayList<AliquotBean>(); IDataAccess ida = (new DataAccessProxy()).getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select aliquot.id, aliquot.name, status.status from Aliquot aliquot left join aliquot.dataStatus status order by aliquot.name"; List results = ida.search(hqlString); for (Object obj : results) { Object[] aliquotInfo = (Object[]) obj; aliquots.add(new AliquotBean(StringUtils.convertToString(aliquotInfo[0]), StringUtils.convertToString(aliquotInfo[1]), StringUtils.convertToString(aliquotInfo[2]))); } } catch (Exception e) { logger.error("Error in retrieving all aliquot Ids and names", e); throw new RuntimeException( "Error in retrieving all aliquot Ids and names"); } finally { ida.close(); } return aliquots; } /** * Retrieving all unmasked aliquots for views use aliquot and create * aliquot. * * @return a list of AliquotBeans containing unmasked aliquot IDs and names. * */ public List<AliquotBean> getUnmaskedAliquots() throws Exception { List<AliquotBean> aliquots = new ArrayList<AliquotBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select aliquot.id, aliquot.name from Aliquot aliquot where aliquot.dataStatus is null order by aliquot.name"; List results = ida.search(hqlString); for (Object obj : results) { Object[] aliquotInfo = (Object[]) obj; aliquots.add(new AliquotBean(StringUtils .convertToString(aliquotInfo[0]), StringUtils .convertToString(aliquotInfo[1]), CalabConstants.ACTIVE_STATUS)); } } catch (Exception e) { logger.error("Error in retrieving all aliquot Ids and names", e); throw new RuntimeException( "Error in retrieving all aliquot Ids and names"); } finally { ida.close(); } return aliquots; } /** * Retrieving all sample types. * * @return a list of all sample types */ public List<String> getAllSampleTypes() throws Exception { // Detail here // Retrieve data from Sample_Type table List<String> sampleTypes = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sampleType.name from SampleType sampleType order by sampleType.name"; List results = ida.search(hqlString); for (Object obj : results) { sampleTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all sample types", e); throw new RuntimeException("Error in retrieving all sample types"); } finally { ida.close(); } return sampleTypes; } /** * * @return the default sample container information in a form of * ContainerInfoBean */ public ContainerInfoBean getSampleContainerInfo() throws Exception { // tmp code to be replaced List<String> containerTypes = getAllContainerTypes(); List<MeasureUnit> units = getAllMeasureUnits(); List<StorageElement> storageElements = getAllRoomAndFreezers(); List<String> quantityUnits = new ArrayList<String>(); List<String> concentrationUnits = new ArrayList<String>(); List<String> volumeUnits = new ArrayList<String>(); List<String> rooms = new ArrayList<String>(); List<String> freezers = new ArrayList<String>(); for (MeasureUnit unit : units) { if (unit.getType().equalsIgnoreCase("Quantity")) { quantityUnits.add(unit.getName()); } else if (unit.getType().equalsIgnoreCase("Volume")) { volumeUnits.add(unit.getName()); } else if (unit.getType().equalsIgnoreCase("Concentration")) { concentrationUnits.add(unit.getName()); } } for (StorageElement storageElement : storageElements) { if (storageElement.getType().equalsIgnoreCase("Room")) { rooms.add((storageElement.getLocation())); } else if (storageElement.getType().equalsIgnoreCase("Freezer")) { freezers.add((storageElement.getLocation())); } } // set labs and racks to null for now ContainerInfoBean containerInfo = new ContainerInfoBean(containerTypes, quantityUnits, concentrationUnits, volumeUnits, null, rooms, freezers); return containerInfo; } private List<String> getAllContainerTypes() throws Exception { List<String> containerTypes = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct container.containerType from SampleContainer container order by container.containerType"; List results = ida.search(hqlString); for (Object obj : results) { containerTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all container types", e); throw new RuntimeException( "Error in retrieving all container types."); } finally { ida.close(); } return containerTypes; } private List<MeasureUnit> getAllMeasureUnits() throws Exception { List<MeasureUnit> units = new ArrayList<MeasureUnit>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from MeasureUnit"; List results = ida.search(hqlString); for (Object obj : results) { units.add((MeasureUnit) obj); } } catch (Exception e) { logger.error("Error in retrieving all measure units", e); throw new RuntimeException("Error in retrieving all measure units."); } finally { ida.close(); } return units; } private List<StorageElement> getAllRoomAndFreezers() throws Exception { List<StorageElement> storageElements = new ArrayList<StorageElement>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from StorageElement where type in ('Room', 'Freezer')"; List results = ida.search(hqlString); for (Object obj : results) { storageElements.add((StorageElement) obj); } } catch (Exception e) { logger.error("Error in retrieving all rooms and freezers", e); throw new RuntimeException( "Error in retrieving all rooms and freezers."); } finally { ida.close(); } return storageElements; } /** * * @return the default sample container information in a form of * ContainerInfoBean */ public ContainerInfoBean getAliquotContainerInfo() throws Exception { return getSampleContainerInfo(); } /** * Get all samples in the database * * @return a list of SampleBean containing sample Ids and names */ public List<SampleBean> getAllSamples() throws Exception { List<SampleBean> samples = new ArrayList<SampleBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sample.id, sample.name from Sample sample order by sample.name"; List results = ida.search(hqlString); for (Object obj : results) { Object[] sampleInfo = (Object[]) obj; samples.add(new SampleBean(StringUtils .convertToString(sampleInfo[0]), StringUtils .convertToString(sampleInfo[1]))); } } catch (Exception e) { logger.error("Error in retrieving all sample IDs and names", e); throw new RuntimeException( "Error in retrieving all sample IDs and names"); } finally { ida.close(); } return samples; } /** * Retrieve all Assay Types from the system * * @return A list of all assay type */ public List getAllAssayTypes() throws Exception { List<String> assayTypes = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select assayType.name from AssayType assayType order by assayType.executeOrder"; List results = ida.search(hqlString); for (Object obj : results) { assayTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all assay types", e); throw new RuntimeException("Error in retrieving all assay types"); } finally { ida.close(); } return assayTypes; } /** * Retrieve all assays * * @return a list of all assays in certain type */ public List<String> getAllAssignedAliquots() { // Detail here List<String> aliquots = new ArrayList<String>(); return aliquots; } /** * Retrieve all assays * * @return a list of all assays in certain type */ public List<String> getAllInFiles() { // Detail here List<String> allInFiles = new ArrayList<String>(); return allInFiles; } /** * Retrieve all assays * * @return a list of all assays in certain type */ public List<String> getAllOutFiles() { // Detail here List<String> allOutFiles = new ArrayList<String>(); return allOutFiles; } /** * Retrieve assays by assayType * * @return a list of all assays in certain type */ public List<AssayBean> getAllAssayBeans() throws Exception { List<AssayBean> assayBeans = new ArrayList<AssayBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select assay.id, assay.name, assay.assayType from Assay assay"; List results = ida.search(hqlString); for (Object obj : results) { Object[] objArray = (Object[]) obj; AssayBean assay = new AssayBean( ((Long) objArray[0]).toString(), (String) objArray[1], (String) objArray[2]); assayBeans.add(assay); } } catch (Exception e) { logger.error("Error in retrieving all assay beans. ", e); throw new RuntimeException("Error in retrieving all assays beans. "); } finally { ida.close(); } return assayBeans; } public List<String> getAllUsernames() throws Exception { List<String> usernames = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select user.loginName from User user order by user.loginName"; List results = ida.search(hqlString); for (Object obj : results) { usernames.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all aliquot Ids and names", e); throw new RuntimeException( "Error in retrieving all aliquot Ids and names"); } finally { ida.close(); } return usernames; } }
package gov.nih.nci.calab.ui.workflow; /** * This class saves the association between a run and the user selected aliquot IDs and comments . * * @author pansu */ /* CVS $Id: UseAliquotAction.java,v 1.10 2006-04-27 15:56:15 pansu Exp $*/ import gov.nih.nci.calab.service.util.StringUtils; import gov.nih.nci.calab.service.workflow.ExecuteWorkflowService; import gov.nih.nci.calab.ui.core.AbstractBaseAction; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.validator.DynaValidatorForm; public class UseAliquotAction extends AbstractBaseAction { private static Logger logger = Logger.getLogger(UseAliquotAction.class); public ActionForward executeTask(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = null; String runId=null; String runName=null; String[] aliquotIds=null; HttpSession session = request.getSession(); try { DynaValidatorForm theForm = (DynaValidatorForm) form; runId = (String) theForm.get("runId"); runName = (String) theForm.get("runName"); aliquotIds = (String[]) theForm.get("aliquotIds"); String comments = (String) theForm.get("comments"); ExecuteWorkflowService executeWorkflowService = new ExecuteWorkflowService(); executeWorkflowService.saveRunAliquots(runId, aliquotIds, comments, (String)session.getAttribute("creator"),(String)session.getAttribute("creationDate") ); ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage("message.useAliquot", runName); msgs.add("message", msg); saveMessages(request, msgs); session.setAttribute("newWorkflowCreated", "true"); forward = mapping.findForward("success"); } catch (Exception e) { logger.error("Caught exception when saving selected aliquot IDs.", e); ActionMessages errors = new ActionMessages(); ActionMessage error = new ActionMessage("error.useAliquot", runName); errors.add("error", error); saveMessages(request, errors); forward = mapping.getInputForward(); } return forward; } public boolean loginRequired() { return true; } }
package info.curtbinder.reefangel.phone; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.database.CursorIndexOutOfBoundsException; import android.database.SQLException; import android.os.Bundle; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class StatusActivity extends BaseActivity implements OnClickListener, OnLongClickListener { private static final String TAG = StatusActivity.class.getSimpleName(); // Display views private Button refreshButton; private TextView updateTime; // private TextView messageText; private ViewPager pager; private CustomPagerAdapter pagerAdapter; private String[] profiles; // minimum number of pages: status, main relay private static final int MIN_PAGES = 2; private static final int POS_CONTROLLER = 0; private static final int POS_MAIN_RELAY = 1; private static final int POS_EXP1_RELAY = 2; private static final int POS_EXP2_RELAY = 3; private static final int POS_EXP3_RELAY = 4; private static final int POS_EXP4_RELAY = 5; private static final int POS_EXP5_RELAY = 6; private static final int POS_EXP6_RELAY = 7; private static final int POS_EXP7_RELAY = 8; private static final int POS_EXP8_RELAY = 9; private ControllerWidget controller; private RelayBoxWidget main; private RelayBoxWidget[] exprelays = new RelayBoxWidget[Controller.MAX_EXPANSION_RELAYS]; // Message Receivers StatusReceiver receiver; IntentFilter filter; // View visibility // private boolean showMessageText; /** Called when the activity is first created. */ @Override public void onCreate ( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); setContentView( R.layout.status ); // Message Receiver stuff receiver = new StatusReceiver(); filter = new IntentFilter( MessageCommands.UPDATE_DISPLAY_DATA_INTENT ); filter.addAction( MessageCommands.UPDATE_STATUS_INTENT ); filter.addAction( MessageCommands.ERROR_MESSAGE_INTENT ); profiles = getResources().getStringArray( R.array.profileLabels ); createViews(); findViews(); setPagerPrefs(); // TODO possibly move to onresume setOnClickListeners(); // Check if this is the first run, if so we need to prompt the user // to configure before we start the service and proceed // this should be the last thing done in OnCreate() if ( rapp.isFirstRun() ) { Log.w( TAG, "First Run of app" ); Intent i = new Intent( this, FirstRunActivity.class ); i.addFlags( Intent.FLAG_ACTIVITY_SINGLE_TOP ); startActivity( i ); finish(); } } @Override protected void onPause ( ) { super.onPause(); unregisterReceiver( receiver ); } @Override protected void onResume ( ) { super.onResume(); registerReceiver( receiver, filter, Permissions.QUERY_STATUS, null ); updateViewsVisibility(); updateDisplay(); // TODO either put the displaying of the changelog here or in OnStart } private void createViews ( ) { Context ctx = rapp.getBaseContext(); controller = new ControllerWidget( ctx ); main = new RelayBoxWidget( ctx ); for ( int i = 0; i < Controller.MAX_EXPANSION_RELAYS; i++ ) { exprelays[i] = new RelayBoxWidget( ctx ); exprelays[i].setRelayBoxNumber( i + 1 ); } } private void findViews ( ) { refreshButton = (Button) findViewById( R.id.refresh_button ); updateTime = (TextView) findViewById( R.id.updated ); pager = (ViewPager) findViewById( R.id.pager ); } private void setOnClickListeners ( ) { refreshButton.setOnClickListener( this ); refreshButton.setOnLongClickListener( this ); // TODO consider clearing click listeners and updating clickable always int i; if ( rapp.isCommunicateController() ) { main.setOnClickListeners(); for ( i = 0; i < Controller.MAX_EXPANSION_RELAYS; i++ ) exprelays[i].setOnClickListeners(); } else { main.setClickable( false ); for ( i = 0; i < Controller.MAX_EXPANSION_RELAYS; i++ ) exprelays[i].setClickable( false ); } } private void updateViewsVisibility ( ) { // updates all the views visibility based on user settings // get values from Preferences // showMessageText = false; // Labels updateRefreshButtonLabel(); String separator = getString( R.string.labelSeparator ); controller.setT1Label( rapp.getPrefT1Label() + separator ); controller.setT2Label( rapp.getPrefT2Label() + separator ); controller.setT3Label( rapp.getPrefT3Label() + separator ); controller.setPHLabel( rapp.getPrefPHLabel() + separator ); controller.setDPLabel( rapp.getPrefDPLabel() + separator ); controller.setAPLabel( rapp.getPrefAPLabel() + separator ); controller.setSalinityLabel( rapp.getPrefSalinityLabel() + separator ); controller.setORPLabel( rapp.getPrefORPLabel() + separator ); int qty = rapp.getPrefExpansionRelayQuantity(); Log.d( TAG, "Expansion Relays: " + qty ); main.setRelayTitle( getString( R.string.prefMainRelayTitle ) ); // set the labels switch ( qty ) { case 8: exprelays[7] .setRelayTitle( getString( R.string.prefExp8RelayTitle ) ); case 7: exprelays[6] .setRelayTitle( getString( R.string.prefExp7RelayTitle ) ); case 6: exprelays[5] .setRelayTitle( getString( R.string.prefExp6RelayTitle ) ); case 5: exprelays[4] .setRelayTitle( getString( R.string.prefExp5RelayTitle ) ); case 4: exprelays[3] .setRelayTitle( getString( R.string.prefExp4RelayTitle ) ); case 3: exprelays[2] .setRelayTitle( getString( R.string.prefExp3RelayTitle ) ); case 2: exprelays[1] .setRelayTitle( getString( R.string.prefExp2RelayTitle ) ); case 1: exprelays[0] .setRelayTitle( getString( R.string.prefExp1RelayTitle ) ); default: break; } int i, j; for ( i = 0; i < Controller.MAX_RELAY_PORTS; i++ ) { main.setPortLabel( i, rapp.getPrefMainRelayLabel( i ) + separator ); for ( j = 0; j < Controller.MAX_EXPANSION_RELAYS; j++ ) { // skip over the relays that are not installed if ( (j + 1) > qty ) break; exprelays[j].setPortLabel( i, rapp.getPrefRelayLabel( j + 1, i ) + separator ); } } // Visibility controller.setT2Visibility( rapp.getPrefT2Visibility() ); controller.setT3Visibility( rapp.getPrefT3Visibility() ); controller.setDPVisibility( rapp.getPrefDPVisibility() ); controller.setAPVisibility( rapp.getPrefAPVisibility() ); controller.setSalinityVisibility( rapp.getPrefSalinityVisibility() ); controller.setORPVisibility( rapp.getPrefORPVisibility() ); // if ( ! showMessageText ) // messageText.setVisibility(View.GONE); } @Override public void onClick ( View v ) { switch ( v.getId() ) { case R.id.refresh_button: // launch the update Log.d( TAG, "onClick Refresh button" ); launchStatusTask(); break; } } @Override public boolean onLongClick ( View v ) { // if it's not a controller, don't even bother processing // the long clicks if ( ! rapp.isCommunicateController() ) return true; switch ( v.getId() ) { case R.id.refresh_button: // launch the profile selector Log.d( TAG, "onLongClick Refresh button" ); if ( !rapp.isAwayProfileEnabled() ) { Log.d( TAG, "Away profile not enabled, cancelling" ); return true; } DialogInterface.OnClickListener ocl = new DialogInterface.OnClickListener() { @Override public void onClick ( DialogInterface dialog, int item ) { switchProfiles( item ); dialog.dismiss(); } }; AlertDialog.Builder builder = new AlertDialog.Builder( this ); builder.setTitle( R.string.titleSelectProfile ); builder.setSingleChoiceItems( profiles, rapp.getSelectedProfile(), ocl ); AlertDialog dlg = builder.create(); dlg.show(); return true; } return false; } private void switchProfiles ( int id ) { String s = "Switched to profile: " + profiles[id]; Log.d( TAG, s ); Toast.makeText( getApplicationContext(), s, Toast.LENGTH_SHORT ).show(); s = String.format( "%d", id ); rapp.setPref( R.string.prefProfileSelectedKey, s ); updateRefreshButtonLabel(); } private void updateRefreshButtonLabel ( ) { // button label will be: Refresh - PROFILE // only allow for the changing of the label IF it's a controller // AND if the away profile is enabled String s; if ( rapp.isAwayProfileEnabled() && rapp.isCommunicateController() ) s = String.format( "%s - %s", getString( R.string.buttonRefresh ), profiles[rapp.getSelectedProfile()] ); else s = getString( R.string.buttonRefresh ); refreshButton.setText( s ); } @Override public boolean onKeyDown ( int keyCode, KeyEvent event ) { switch ( keyCode ) { case KeyEvent.KEYCODE_R: // launch the update Log.d( TAG, "onKeyDown R" ); launchStatusTask(); break; default: return super.onKeyDown( keyCode, event ); } return true; } private void launchStatusTask ( ) { Log.d( TAG, "launchStatusTask" ); Intent i = new Intent( MessageCommands.QUERY_STATUS_INTENT ); sendBroadcast( i, Permissions.QUERY_STATUS ); } public void updateDisplay ( ) { Log.d( TAG, "updateDisplay" ); try { Cursor c = rapp.data.getLatestData(); String updateStatus; String[] values; short r, ron, roff; short[] expr = new short[Controller.MAX_EXPANSION_RELAYS]; short[] expron = new short[Controller.MAX_EXPANSION_RELAYS]; short[] exproff = new short[Controller.MAX_EXPANSION_RELAYS]; if ( c.moveToFirst() ) { updateStatus = c.getString( c.getColumnIndex( RAData.PCOL_LOGDATE ) ); values = new String[] { c.getString( c .getColumnIndex( RAData.PCOL_T1 ) ), c.getString( c .getColumnIndex( RAData.PCOL_T2 ) ), c.getString( c .getColumnIndex( RAData.PCOL_T3 ) ), c.getString( c .getColumnIndex( RAData.PCOL_PH ) ), c.getString( c .getColumnIndex( RAData.PCOL_DP ) ), c.getString( c .getColumnIndex( RAData.PCOL_AP ) ), c.getString( c .getColumnIndex( RAData.PCOL_SAL ) ), c.getString( c .getColumnIndex( RAData.PCOL_ORP ) ) }; r = c.getShort( c.getColumnIndex( RAData.PCOL_RDATA ) ); ron = c.getShort( c.getColumnIndex( RAData.PCOL_RONMASK ) ); roff = c.getShort( c.getColumnIndex( RAData.PCOL_ROFFMASK ) ); expr[0] = c.getShort( c.getColumnIndex( RAData.PCOL_R1DATA ) ); expron[0] = c.getShort( c.getColumnIndex( RAData.PCOL_R1ONMASK ) ); exproff[0] = c.getShort( c.getColumnIndex( RAData.PCOL_R1OFFMASK ) ); expr[1] = c.getShort( c.getColumnIndex( RAData.PCOL_R2DATA ) ); expron[1] = c.getShort( c.getColumnIndex( RAData.PCOL_R2ONMASK ) ); exproff[1] = c.getShort( c.getColumnIndex( RAData.PCOL_R2OFFMASK ) ); expr[2] = c.getShort( c.getColumnIndex( RAData.PCOL_R3DATA ) ); expron[2] = c.getShort( c.getColumnIndex( RAData.PCOL_R3ONMASK ) ); exproff[2] = c.getShort( c.getColumnIndex( RAData.PCOL_R3OFFMASK ) ); expr[3] = c.getShort( c.getColumnIndex( RAData.PCOL_R4DATA ) ); expron[3] = c.getShort( c.getColumnIndex( RAData.PCOL_R4ONMASK ) ); exproff[3] = c.getShort( c.getColumnIndex( RAData.PCOL_R4OFFMASK ) ); expr[4] = c.getShort( c.getColumnIndex( RAData.PCOL_R1DATA ) ); expron[4] = c.getShort( c.getColumnIndex( RAData.PCOL_R1ONMASK ) ); exproff[4] = c.getShort( c.getColumnIndex( RAData.PCOL_R1OFFMASK ) ); expr[5] = c.getShort( c.getColumnIndex( RAData.PCOL_R2DATA ) ); expron[5] = c.getShort( c.getColumnIndex( RAData.PCOL_R2ONMASK ) ); exproff[5] = c.getShort( c.getColumnIndex( RAData.PCOL_R2OFFMASK ) ); expr[6] = c.getShort( c.getColumnIndex( RAData.PCOL_R3DATA ) ); expron[6] = c.getShort( c.getColumnIndex( RAData.PCOL_R3ONMASK ) ); exproff[6] = c.getShort( c.getColumnIndex( RAData.PCOL_R3OFFMASK ) ); expr[7] = c.getShort( c.getColumnIndex( RAData.PCOL_R4DATA ) ); expron[7] = c.getShort( c.getColumnIndex( RAData.PCOL_R4ONMASK ) ); exproff[7] = c.getShort( c.getColumnIndex( RAData.PCOL_R4OFFMASK ) ); } else { updateStatus = getString( R.string.messageNever ); values = getNeverValues(); r = ron = roff = 0; for ( int i = 0; i < Controller.MAX_EXPANSION_RELAYS; i++ ) { expr[i] = expron[i] = exproff[i] = 0; } } c.close(); updateTime.setText( updateStatus ); controller.updateDisplay( values ); boolean fUseMask = rapp.isCommunicateController(); main.updateRelayValues( new Relay( r, ron, roff ), fUseMask ); for ( int i = 0; i < rapp.getPrefExpansionRelayQuantity(); i++ ) { exprelays[i].updateRelayValues( new Relay( expr[i], expron[i], exproff[i] ), fUseMask ); } } catch ( SQLException e ) { Log.d( TAG, "SQLException: " + e.getMessage() ); } catch ( CursorIndexOutOfBoundsException e ) { Log.d( TAG, "CursorIndex out of bounds: " + e.getMessage() ); } } class StatusReceiver extends BroadcastReceiver { private final String TAG = StatusReceiver.class.getSimpleName(); @Override public void onReceive ( Context context, Intent intent ) { // Log.d(TAG, "onReceive"); String action = intent.getAction(); if ( action.equals( MessageCommands.UPDATE_STATUS_INTENT ) ) { int id = intent.getIntExtra( MessageCommands.UPDATE_STATUS_ID, R.string.defaultStatusText ); Log.d( TAG, getResources().getString( id ) ); updateTime.setText( getResources().getString( id ) ); } else if ( action .equals( MessageCommands.UPDATE_DISPLAY_DATA_INTENT ) ) { Log.d( TAG, "update data intent" ); // TODO have insert be done by the task and only updateDisplay // here rapp.insertData( intent ); updateDisplay(); } else if ( action.equals( MessageCommands.ERROR_MESSAGE_INTENT ) ) { Log.d( TAG, intent .getStringExtra( MessageCommands.ERROR_MESSAGE_STRING ) ); updateTime .setText( intent .getStringExtra( MessageCommands.ERROR_MESSAGE_STRING ) ); } } } private String[] getNeverValues ( ) { return new String[] { getString( R.string.defaultStatusText ), getString( R.string.defaultStatusText ), getString( R.string.defaultStatusText ), getString( R.string.defaultStatusText ), getString( R.string.defaultStatusText ), getString( R.string.defaultStatusText ), getString( R.string.defaultStatusText ), getString( R.string.defaultStatusText ) }; } @Override public boolean onCreateOptionsMenu ( Menu menu ) { MenuInflater inflater = getMenuInflater(); inflater.inflate( R.menu.status_menu, menu ); return true; } @Override public boolean onOptionsItemSelected ( MenuItem item ) { // Handle item selection switch ( item.getItemId() ) { case R.id.settings: // launch settings Log.d( TAG, "Settings clicked" ); // scroll to first page on entering settings pager.setCurrentItem( POS_CONTROLLER ); startActivity( new Intent( this, PrefsActivity.class ) ); break; case R.id.about: // launch about box Log.d( TAG, "About clicked" ); startActivity( new Intent( this, AboutActivity.class ) ); break; case R.id.params: Log.d( TAG, "Parameters clicked" ); startActivity( new Intent( this, ParamsListActivity.class ) ); break; case R.id.memory: // launch memory Log.d( TAG, "Memory clicked" ); startActivity( new Intent( this, MemoryTabsActivity.class ) ); break; case R.id.commands: // launch commands Log.d( TAG, "Commands clicked" ); startActivity( new Intent( this, CommandTabsActivity.class ) ); break; default: return super.onOptionsItemSelected( item ); } return true; } private void setPagerPrefs ( ) { Log.d( TAG, "Create pager adapter" ); pagerAdapter = new CustomPagerAdapter(); pager.setAdapter( pagerAdapter ); // Set the minimum pages to keep loaded // will set to minimum pages since the pages are not complex pager.setOffscreenPageLimit( MIN_PAGES ); } private class CustomPagerAdapter extends PagerAdapter { private final String TAG = CustomPagerAdapter.class.getSimpleName(); @Override public int getCount ( ) { int qty = MIN_PAGES + rapp.getPrefExpansionRelayQuantity(); return qty; } @Override public void destroyItem ( ViewGroup container, int position, Object object ) { Log.d( TAG, "destroyItem " + position ); ((ViewPager) container).removeView( (View) object ); } @Override public Object instantiateItem ( ViewGroup container, int position ) { View v; switch ( position ) { default: case POS_CONTROLLER: // Controller Status Log.d( TAG, "Create controller" ); v = controller; break; case POS_MAIN_RELAY: // Main Relay Log.d( TAG, "Create main relay" ); v = main; break; case POS_EXP1_RELAY: // Expansion Relay 1 case POS_EXP2_RELAY: // Expansion Relay 2 case POS_EXP3_RELAY: // Expansion Relay 3 case POS_EXP4_RELAY: // Expansion Relay 4 case POS_EXP5_RELAY: // Expansion Relay 5 case POS_EXP6_RELAY: // Expansion Relay 6 case POS_EXP7_RELAY: // Expansion Relay 7 case POS_EXP8_RELAY: // Expansion Relay 8 int relay = position - MIN_PAGES; Log.d( TAG, "Create exp relay " + relay + " (" + position + ")" ); v = exprelays[relay]; break; } ((ViewPager) container).addView( v ); return v; } @Override public boolean isViewFromObject ( View view, Object object ) { return view == object; } } }
package io.flutter.preview; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.LayeredIcon; import com.intellij.ui.SimpleTextAttributes; import com.jetbrains.lang.dart.DartComponentType; import com.jetbrains.lang.dart.util.DartPresentableUtil; import org.dartlang.analysis.server.protocol.Element; import org.dartlang.analysis.server.protocol.ElementKind; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import static com.intellij.icons.AllIcons.Nodes.Class; import static com.intellij.icons.AllIcons.Nodes.Enum; import static com.intellij.icons.AllIcons.Nodes.*; import static com.intellij.icons.AllIcons.RunConfigurations.Junit; public class DartElementPresentationUtil { private static final LayeredIcon STATIC_FINAL_FIELD_ICON = new LayeredIcon(Field, StaticMark, FinalMark); private static final LayeredIcon FINAL_FIELD_ICON = new LayeredIcon(Field, FinalMark); private static final LayeredIcon STATIC_FIELD_ICON = new LayeredIcon(Field, StaticMark); private static final LayeredIcon STATIC_METHOD_ICON = new LayeredIcon(Method, StaticMark); private static final LayeredIcon TOP_LEVEL_FUNCTION_ICON = new LayeredIcon(Function, StaticMark); private static final LayeredIcon TOP_LEVEL_VAR_ICON = new LayeredIcon(Variable, StaticMark); private static final LayeredIcon CONSTRUCTOR_INVOCATION_ICON = new LayeredIcon(Class, TabPin); private static final LayeredIcon FUNCTION_INVOCATION_ICON = new LayeredIcon(Method, TabPin); private static final LayeredIcon TOP_LEVEL_CONST_ICON = new LayeredIcon(Variable, StaticMark, FinalMark); @Nullable public static Icon getIcon(@NotNull Element element) { final boolean finalOrConst = element.isConst() || element.isFinal(); switch (element.getKind()) { case ElementKind.CLASS: return element.isAbstract() ? AbstractClass : Class; case ElementKind.MIXIN: return AbstractClass; case ElementKind.CONSTRUCTOR: return Method; case ElementKind.CONSTRUCTOR_INVOCATION: return CONSTRUCTOR_INVOCATION_ICON; case ElementKind.ENUM: return Enum; case ElementKind.ENUM_CONSTANT: return STATIC_FINAL_FIELD_ICON; case ElementKind.FIELD: if (finalOrConst && element.isTopLevelOrStatic()) return STATIC_FINAL_FIELD_ICON; if (finalOrConst) return FINAL_FIELD_ICON; if (element.isTopLevelOrStatic()) return STATIC_FIELD_ICON; return Field; case ElementKind.FUNCTION: return element.isTopLevelOrStatic() ? TOP_LEVEL_FUNCTION_ICON : Function; case ElementKind.FUNCTION_INVOCATION: return FUNCTION_INVOCATION_ICON; case ElementKind.FUNCTION_TYPE_ALIAS: return DartComponentType.TYPEDEF.getIcon(); case ElementKind.GETTER: return element.isTopLevelOrStatic() ? PropertyReadStatic : PropertyRead; case ElementKind.METHOD: if (element.isAbstract()) return AbstractMethod; return element.isTopLevelOrStatic() ? STATIC_METHOD_ICON : Method; case ElementKind.SETTER: return element.isTopLevelOrStatic() ? PropertyWriteStatic : PropertyWrite; case ElementKind.TOP_LEVEL_VARIABLE: return finalOrConst ? TOP_LEVEL_CONST_ICON : TOP_LEVEL_VAR_ICON; case ElementKind.UNIT_TEST_GROUP: return TestSourceFolder; case ElementKind.UNIT_TEST_TEST: return Junit; case ElementKind.CLASS_TYPE_ALIAS: case ElementKind.COMPILATION_UNIT: case ElementKind.FILE: case ElementKind.LABEL: case ElementKind.LIBRARY: case ElementKind.LOCAL_VARIABLE: case ElementKind.PARAMETER: case ElementKind.PREFIX: case ElementKind.TYPE_PARAMETER: case ElementKind.UNKNOWN: default: return null; // unexpected } } public static void renderElement(@NotNull Element element, @NotNull OutlineTreeCellRenderer renderer, boolean nameInBold) { final SimpleTextAttributes attributes = nameInBold ? SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES; renderer.appendSearch(element.getName(), attributes); if (!StringUtil.isEmpty(element.getTypeParameters())) { renderer.appendSearch(element.getTypeParameters(), attributes); } if (!StringUtil.isEmpty(element.getParameters())) { renderer.appendSearch(element.getParameters(), attributes); } if (!StringUtil.isEmpty(element.getReturnType())) { renderer.append(" "); renderer.append(DartPresentableUtil.RIGHT_ARROW); renderer.append(" "); renderer.appendSearch(element.getReturnType(), SimpleTextAttributes.REGULAR_ATTRIBUTES); } } }
package jade.content.schema.facets; import jade.content.onto.*; import jade.content.schema.*; import jade.content.abs.*; import jade.util.leap.Iterator; /** * This facet forces the elements in an AbsAggregate * to be instances of a given schema. * @author Giovanni Caire - TILAB */ public class TypedAggregateFacet implements Facet { private ObjectSchema type; /** Construct a <code>TypedAggregateFacet</code> that forces the elements in an AbsAggregate to be instances of a given schema */ public TypedAggregateFacet(ObjectSchema s) { type = s; } public ObjectSchema getType() { return type; } /** Check whether a given value for the slot this Facet applies to is valid. @param value The value to be checked @throws OntologyException If the value is not valid */ public void validate(AbsObject value, Ontology onto) throws OntologyException { if (!(value instanceof AbsAggregate)) { throw new OntologyException(value+" is not an AbsAggregate"); } AbsAggregate agg = (AbsAggregate) value; Iterator it = agg.iterator(); while (it.hasNext()) { AbsTerm el = (AbsTerm) it.next(); ObjectSchema s = onto.getSchema(el.getTypeName()); if (!s.isCompatibleWith(type)) { throw new OntologyException("Schema "+s+" for element "+el+" is not compatible with type "+type); } } } }
package org.xins.server; import org.apache.log4j.Logger; import org.xins.util.MandatoryArgumentChecker; import org.xins.util.text.FastStringBuffer; /** * Base class for function implementation classes. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) */ public abstract class Function extends Object implements DefaultResultCodes { // Class fields // Class functions /** * Checks if the specified value is <code>null</code> or an empty string. * Only if it is then <code>true</code> is returned. * * @param value * the value to check. * * @return * <code>true</code> if and only if <code>value != null &amp;&amp; * value.length() != 0</code>. */ protected static final boolean isMissing(String value) { return value == null || value.length() == 0; } // Constructors protected Function(API api, String name, String version) throws IllegalArgumentException { // Check argument MandatoryArgumentChecker.check("api", api, "name", name, "version", version); _log = Logger.getLogger(getClass().getName()); _api = api; _name = name; _version = version; _api.functionAdded(this); } // Fields /** * The logger used by this function. This field is initialized by the * constructor and set to a non-<code>null</code> value. */ protected final Logger _log; /** * The API implementation this function is part of. */ private final API _api; /** * The name of this function. */ private final String _name; /** * The version of the specification this function implements. */ private final String _version; /** * Statistics object linked to this function. */ private final Statistics _statistics = new Statistics(); /** * Lock object for a successful call. */ private final Object _successfulCallLock = new Object(); /** * Lock object for an unsuccessful call. */ private final Object _unsuccessfulCallLock = new Object(); /** * Buffer for log messages for successful calls. This field is * initialized at construction time and cannot be <code>null</code>. */ private final FastStringBuffer _successfulCallStringBuffer = new FastStringBuffer(256); /** * Buffer for log messages for unsuccessful calls. This field is * initialized at construction time and cannot be <code>null</code>. */ private final FastStringBuffer _unsuccessfulCallStringBuffer = new FastStringBuffer(256); /** * The number of successful calls executed up until now. */ private int _successfulCalls; /** * The number of unsuccessful calls executed up until now. */ private int _unsuccessfulCalls; /** * The start time of the most recent successful call. */ private long _lastSuccessfulStart; /** * The start time of the most recent unsuccessful call. */ private long _lastUnsuccessfulStart; /** * The duration of the most recent successful call. */ private long _lastSuccessfulDuration; /** * The duration of the most recent unsuccessful call. */ private long _lastUnsuccessfulDuration; /** * The total duration of all successful calls up until now. */ private long _successfulDuration; /** * The total duration of all unsuccessful calls up until now. */ private long _unsuccessfulDuration; /** * The minimum time a successful call took. */ private long _successfulMin = Long.MAX_VALUE; /** * The minimum time an unsuccessful call took. */ private long _unsuccessfulMin = Long.MAX_VALUE; /** * The maximum time a successful call took. */ private long _successfulMax; /** * The maximum time an unsuccessful call took. */ private long _unsuccessfulMax; // Methods /** * Returns the name of this function. * * @return * the name, not <code>null</code>. */ final String getName() { return _name; } /** * Returns the specification version for this function. * * @return * the version, not <code>null</code>. */ final String getVersion() { return _version; } /** * Returns the call statistics for this function. * * @return * the statistics, never <code>null</code>. */ final Statistics getStatistics() { return _statistics; } /** * Callback method that may be called after a call to this function. This * method will store statistics-related information. * * <p />This method does not <em>have</em> to be called. If statistics * gathering is disabled, then this method should not be called. * * @param start * the timestamp indicating when the call was started, as a number of * milliseconds since midnight January 1, 1970 UTC. * * @param duration * the duration of the function call, as a number of milliseconds. * * @param success * indication if the call was successful. * * @param code * the function result code, or <code>null</code>. */ final void performedCall(long start, long duration, boolean success, String code) { boolean debugEnabled = _log.isDebugEnabled(); String message = null; if (success) { if (debugEnabled) { synchronized (_successfulCallStringBuffer) { _successfulCallStringBuffer.clear(); _successfulCallStringBuffer.append("Function "); _successfulCallStringBuffer.append(_name); _successfulCallStringBuffer.append(" call succeeded. Duration: "); _successfulCallStringBuffer.append(String.valueOf(duration)); _successfulCallStringBuffer.append(" ms."); if (code != null) { _successfulCallStringBuffer.append(" Code: \""); _successfulCallStringBuffer.append(code); _successfulCallStringBuffer.append("\"."); } message = _unsuccessfulCallStringBuffer.toString(); } } synchronized (_successfulCallLock) { _lastSuccessfulStart = start; _lastSuccessfulDuration = duration; _successfulCalls++; _successfulDuration += duration; _successfulMin = _successfulMin > duration ? duration : _successfulMin; _successfulMax = _successfulMax < duration ? duration : _successfulMax; } } else { if (debugEnabled) { synchronized (_unsuccessfulCallStringBuffer) { _unsuccessfulCallStringBuffer.clear(); _unsuccessfulCallStringBuffer.append("Function "); _unsuccessfulCallStringBuffer.append(_name); _unsuccessfulCallStringBuffer.append(" call failed. Duration: "); _unsuccessfulCallStringBuffer.append(String.valueOf(duration)); _unsuccessfulCallStringBuffer.append(" ms."); if (code != null) { _unsuccessfulCallStringBuffer.append(" Code: \""); _unsuccessfulCallStringBuffer.append(code); _unsuccessfulCallStringBuffer.append("\"."); } message = _unsuccessfulCallStringBuffer.toString(); } } synchronized (_unsuccessfulCallLock) { _lastUnsuccessfulStart = start; _lastUnsuccessfulDuration = duration; _unsuccessfulCalls++; _unsuccessfulDuration += duration; _unsuccessfulMin = _unsuccessfulMin > duration ? duration : _unsuccessfulMin; _unsuccessfulMax = _unsuccessfulMax < duration ? duration : _unsuccessfulMax; } if (debugEnabled) { _log.debug(message); } } } // Inner classes /** * Call statistics pertaining to a certain function. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) */ final class Statistics extends Object { // Constructors /** * Constructs a new <code>Statistics</code> object. */ private Statistics() { // empty } // Fields // Methods /** * Returns the number of successful calls executed up until now. * * @return * the number of successful calls executed up until now. */ public int getSuccessfulCalls() { return _successfulCalls; } /** * Returns the number of unsuccessful calls executed up until now. * * @return * the number of unsuccessful calls executed up until now. */ public int getUnsuccessfulCalls() { return _unsuccessfulCalls; } /** * Returns the start time of the most recent successful call. * * @return * the start time of the most recent successful call. */ public long getLastSuccessfulStart() { return _lastSuccessfulStart; } /** * Returns the start time of the most recent unsuccessful call. * * @return * the start time of the most recent unsuccessful call. */ public long getLastUnsuccessfulStart() { return _lastUnsuccessfulStart; } /** * Returns the duration of the most recent successful call. * * @return * the duration of the most recent successful call. */ public long getLastSuccessfulDuration() { return _lastSuccessfulDuration; } /** * Returns the duration of the most recent unsuccessful call. * * @return * the duration of the most recent unsuccessful call. */ public long getLastUnsuccessfulDuration() { return _unsuccessfulDuration; } /** * Returns the total duration of all successful calls up until now. * * @return * the total duration of all successful calls up until now. */ public long getSuccessfulDuration() { return _successfulDuration; } /** * Returns the total duration of all unsuccessful calls up until now. * * @return * the total duration of all unsuccessful calls up until now. */ public long getUnsuccessfulDuration() { return _unsuccessfulDuration; } /** * Returns the minimum time a successful call took. * * @return * the minimum time a successful call took. */ public long getSuccessfulMin() { return _successfulMin; } /** * Returns the minimum time an unsuccessful call took. * * @return * the minimum time an unsuccessful call took. */ public long getUnsuccessfulMin() { return _unsuccessfulMin; } /** * Returns the maximum time a successful call took. * * @return * the maximum time a successful call took. */ public long getSuccessfulMax() { return _successfulMax; } /** * Returns the maximum time an unsuccessful call took. * * @return * the maximum time an unsuccessful call took. */ public long getUnsuccessfulMax() { return _unsuccessfulMax; } } }
// samskivert library - useful routines for java programs // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.jdbc.depot; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import com.samskivert.util.ArrayUtil; import com.samskivert.jdbc.ConnectionProvider; import com.samskivert.jdbc.DatabaseLiaison; import com.samskivert.jdbc.JDBCUtil; import com.samskivert.jdbc.depot.Modifier.*; import com.samskivert.jdbc.depot.clause.DeleteClause; import com.samskivert.jdbc.depot.clause.FieldOverride; import com.samskivert.jdbc.depot.clause.InsertClause; import com.samskivert.jdbc.depot.clause.QueryClause; import com.samskivert.jdbc.depot.clause.SelectClause; import com.samskivert.jdbc.depot.clause.UpdateClause; import com.samskivert.jdbc.depot.expression.SQLExpression; import com.samskivert.jdbc.depot.expression.ValueExp; /** * Provides a base for classes that provide access to persistent objects. Also defines the * mechanism by which all persistent queries and updates are routed through the distributed cache. */ public abstract class DepotRepository { /** * Creates a repository with the supplied connection provider and its own private persistence * context. */ protected DepotRepository (ConnectionProvider conprov) { _ctx = new PersistenceContext(getClass().getName(), conprov); _ctx.repositoryCreated(this); } /** * Creates a repository with the supplied persistence context. */ protected DepotRepository (PersistenceContext context) { _ctx = context; _ctx.repositoryCreated(this); } /** * Adds the persistent classes used by this repository to the supplied set. */ protected abstract void getManagedRecords (Set<Class<? extends PersistentRecord>> classes); /** * Loads the persistent object that matches the specified primary key. */ protected <T extends PersistentRecord> T load (Class<T> type, Comparable<?> primaryKey, QueryClause... clauses) throws DatabaseException { clauses = ArrayUtil.append(clauses, _ctx.getMarshaller(type).makePrimaryKey(primaryKey)); return load(type, clauses); } /** * Loads the persistent object that matches the specified primary key. */ protected <T extends PersistentRecord> T load (Class<T> type, String ix, Comparable<?> val, QueryClause... clauses) throws DatabaseException { clauses = ArrayUtil.append(clauses, new Key<T>(type, ix, val)); return load(type, clauses); } /** * Loads the persistent object that matches the specified two-column primary key. */ protected <T extends PersistentRecord> T load (Class<T> type, String ix1, Comparable<?> val1, String ix2, Comparable<?> val2, QueryClause... clauses) throws DatabaseException { clauses = ArrayUtil.append(clauses, new Key<T>(type, ix1, val1, ix2, val2)); return load(type, clauses); } /** * Loads the persistent object that matches the specified three-column primary key. */ protected <T extends PersistentRecord> T load (Class<T> type, String ix1, Comparable<?> val1, String ix2, Comparable<?> val2, String ix3, Comparable<?> val3, QueryClause... clauses) throws DatabaseException { clauses = ArrayUtil.append(clauses, new Key<T>(type, ix1, val1, ix2, val2, ix3, val3)); return load(type, clauses); } /** * Loads the first persistent object that matches the supplied query clauses. */ protected <T extends PersistentRecord> T load ( Class<T> type, Collection<? extends QueryClause> clauses) throws DatabaseException { return load(type, clauses.toArray(new QueryClause[clauses.size()])); } /** * Loads the first persistent object that matches the supplied query clauses. */ protected <T extends PersistentRecord> T load (Class<T> type, QueryClause... clauses) throws DatabaseException { return _ctx.invoke(new FindOneQuery<T>(_ctx, type, clauses)); } /** * Loads all persistent objects that match the specified clauses. * * We have two strategies for doing this: one performs the query as-is, the second executes * two passes: first fetching only key columns and consulting the cache for each such key; * then, in the second pass, fetching the full entity only for keys that were not found in * the cache. * * The more complex strategy could save a lot of data shuffling. On the other hand, its * complexity is an inherent drawback, and it does execute two separate database queries * for what the simple method does in one. */ protected <T extends PersistentRecord> List<T> findAll ( Class<T> type, Collection<? extends QueryClause> clauses) throws DatabaseException { DepotMarshaller<T> marsh = _ctx.getMarshaller(type); boolean useExplicit = (marsh.getTableName() == null) || !marsh.hasPrimaryKey() || !_ctx.isUsingCache(); // queries on @Computed records or the presence of FieldOverrides use the simple algorithm for (QueryClause clause : clauses) { useExplicit |= (clause instanceof FieldOverride); } return _ctx.invoke(useExplicit ? new FindAllQuery.Explicitly<T>(_ctx, type, clauses) : new FindAllQuery.WithCache<T>(_ctx, type, clauses)); } /** * A varargs version of {@link #findAll(Class<T>,Collection<QueryClause>)}. */ protected <T extends PersistentRecord> List<T> findAll (Class<T> type, QueryClause... clauses) throws DatabaseException { return findAll(type, Arrays.asList(clauses)); } /** * Looks up and returns {@link Key} records for all rows that match the supplied query clauses. * * @param forUpdate if true, the query will be run using a read-write connection to ensure that * it talks to the master database, if false, the query will be run on a read-only connection * and may load keys from a slave. For performance reasons, you should always pass false unless * you know you will be modifying the database as a result of this query and absolutely need * the latest data. */ protected <T extends PersistentRecord> List<Key<T>> findAllKeys ( Class<T> type, boolean forUpdate, QueryClause... clause) { return findAllKeys(type, forUpdate, Arrays.asList(clause)); } /** * Looks up and returns {@link Key} records for all rows that match the supplied query clauses. * * @param forUpdate if true, the query will be run using a read-write connection to ensure that * it talks to the master database, if false, the query will be run on a read-only connection * and may load keys from a slave. For performance reasons, you should always pass false unless * you know you will be modifying the database as a result of this query and absolutely need * the latest data. */ protected <T extends PersistentRecord> List<Key<T>> findAllKeys ( Class<T> type, boolean forUpdate, Collection<? extends QueryClause> clauses) { final List<Key<T>> keys = new ArrayList<Key<T>>(); final DepotMarshaller<T> marsh = _ctx.getMarshaller(type); SelectClause<T> select = new SelectClause<T>(type, marsh.getPrimaryKeyFields(), clauses); final SQLBuilder builder = _ctx.getSQLBuilder(DepotTypes.getDepotTypes(_ctx, select)); builder.newQuery(select); if (forUpdate) { _ctx.invoke(new Modifier(null) { @Override public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { PreparedStatement stmt = builder.prepare(conn); try { ResultSet rs = stmt.executeQuery(); while (rs.next()) { keys.add(marsh.makePrimaryKey(rs)); } return 0; } finally { JDBCUtil.close(stmt); } } }); } else { _ctx.invoke(new Query.Trivial<Void>() { @Override public Void invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { PreparedStatement stmt = builder.prepare(conn); try { ResultSet rs = stmt.executeQuery(); while (rs.next()) { keys.add(marsh.makePrimaryKey(rs)); } return null; } finally { JDBCUtil.close(stmt); } } }); } return keys; } protected <T extends PersistentRecord> int insert (T record) throws DatabaseException { @SuppressWarnings("unchecked") final Class<T> pClass = (Class<T>) record.getClass(); final DepotMarshaller<T> marsh = _ctx.getMarshaller(pClass); Key<T> key = marsh.getPrimaryKey(record, false); DepotTypes types = DepotTypes.getDepotTypes(_ctx); types.addClass(_ctx, pClass); final SQLBuilder builder = _ctx.getSQLBuilder(types); // key will be null if record was supplied without a primary key return _ctx.invoke(new CachingModifier<T>(record, key, key) { @Override public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { // set any auto-generated column values Set<String> identityFields = marsh.generateFieldValues(conn, liaison, _result, false); // if needed, update our modifier's key so that it can cache our results if (_key == null) { updateKey(marsh.getPrimaryKey(_result, false)); } builder.newQuery(new InsertClause<T>(pClass, _result, identityFields)); PreparedStatement stmt = builder.prepare(conn); try { int mods = stmt.executeUpdate(); // run any post-factum value generators marsh.generateFieldValues(conn, liaison, _result, true); // and check once more if a key now exists if (_key == null) { updateKey(marsh.getPrimaryKey(_result, false)); } return mods; } finally { JDBCUtil.close(stmt); } } }); } protected <T extends PersistentRecord> int update (T record) throws DatabaseException { @SuppressWarnings("unchecked") Class<T> pClass = (Class<T>) record.getClass(); requireNotComputed(pClass, "update"); DepotMarshaller<T> marsh = _ctx.getMarshaller(pClass); Key<T> key = marsh.getPrimaryKey(record); if (key == null) { throw new IllegalArgumentException("Can't update record with null primary key."); } UpdateClause<T> update = new UpdateClause<T>(pClass, key, marsh._columnFields, record); final SQLBuilder builder = _ctx.getSQLBuilder(DepotTypes.getDepotTypes(_ctx, update)); builder.newQuery(update); return _ctx.invoke(new CachingModifier<T>(record, key, key) { @Override public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { PreparedStatement stmt = builder.prepare(conn); try { return stmt.executeUpdate(); } finally { JDBCUtil.close(stmt); } } }); } protected <T extends PersistentRecord> int update (T record, final String... modifiedFields) throws DatabaseException { @SuppressWarnings("unchecked") Class<T> pClass = (Class<T>) record.getClass(); requireNotComputed(pClass, "updatePartial"); DepotMarshaller<T> marsh = _ctx.getMarshaller(pClass); Key<T> key = marsh.getPrimaryKey(record); if (key == null) { throw new IllegalArgumentException("Can't update record with null primary key."); } UpdateClause<T> update = new UpdateClause<T>(pClass, key, modifiedFields, record); final SQLBuilder builder = _ctx.getSQLBuilder(DepotTypes.getDepotTypes(_ctx, update)); builder.newQuery(update); return _ctx.invoke(new CachingModifier<T>(record, key, key) { @Override public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { PreparedStatement stmt = builder.prepare(conn); // clear out _result so that we don't rewrite this partial record to the cache _result = null; try { return stmt.executeUpdate(); } finally { JDBCUtil.close(stmt); } } }); } protected <T extends PersistentRecord> int updatePartial ( Class<T> type, Comparable<?> primaryKey, Map<String,Object> updates) throws DatabaseException { Object[] fieldsValues = new Object[updates.size()*2]; int idx = 0; for (Map.Entry<String,Object> entry : updates.entrySet()) { fieldsValues[idx++] = entry.getKey(); fieldsValues[idx++] = entry.getValue(); } return updatePartial(type, primaryKey, fieldsValues); } protected <T extends PersistentRecord> int updatePartial ( Class<T> type, Comparable<?> primaryKey, Object... fieldsValues) throws DatabaseException { return updatePartial(_ctx.getMarshaller(type).makePrimaryKey(primaryKey), fieldsValues); } protected <T extends PersistentRecord> int updatePartial ( Class<T> type, String ix1, Comparable<?> val1, String ix2, Comparable<?> val2, Object... fieldsValues) throws DatabaseException { return updatePartial(new Key<T>(type, ix1, val1, ix2, val2), fieldsValues); } protected <T extends PersistentRecord> int updatePartial ( Class<T> type, String ix1, Comparable<?> val1, String ix2, Comparable<?> val2, String ix3, Comparable<?> val3, Object... fieldsValues) throws DatabaseException { return updatePartial(new Key<T>(type, ix1, val1, ix2, val2, ix3, val3), fieldsValues); } protected <T extends PersistentRecord> int updatePartial (Key<T> key, Object... fieldsValues) throws DatabaseException { return updatePartial(key.getPersistentClass(), key, key, fieldsValues); } protected <T extends PersistentRecord> int updatePartial ( Class<T> type, final WhereClause key, CacheInvalidator invalidator, Object... fieldsValues) throws DatabaseException { if (invalidator instanceof ValidatingCacheInvalidator) { ((ValidatingCacheInvalidator)invalidator).validateFlushType(type); // sanity check } key.validateQueryType(type); // and another // separate the arguments into keys and values final String[] fields = new String[fieldsValues.length/2]; final SQLExpression[] values = new SQLExpression[fields.length]; for (int ii = 0, idx = 0; ii < fields.length; ii++) { fields[ii] = (String)fieldsValues[idx++]; values[ii] = new ValueExp(fieldsValues[idx++]); } UpdateClause<T> update = new UpdateClause<T>(type, key, fields, values); final SQLBuilder builder = _ctx.getSQLBuilder(DepotTypes.getDepotTypes(_ctx, update)); builder.newQuery(update); return _ctx.invoke(new Modifier(invalidator) { @Override public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { PreparedStatement stmt = builder.prepare(conn); try { return stmt.executeUpdate(); } finally { JDBCUtil.close(stmt); } } }); } protected <T extends PersistentRecord> int updateLiteral ( Class<T> type, Comparable<?> primaryKey, Map<String, SQLExpression> fieldsToValues) throws DatabaseException { Key<T> key = _ctx.getMarshaller(type).makePrimaryKey(primaryKey); return updateLiteral(type, key, key, fieldsToValues); } protected <T extends PersistentRecord> int updateLiteral ( Class<T> type, String ix1, Comparable<?> val1, String ix2, Comparable<?> val2, Map<String, SQLExpression> fieldsToValues) throws DatabaseException { Key<T> key = new Key<T>(type, ix1, val1, ix2, val2); return updateLiteral(type, key, key, fieldsToValues); } protected <T extends PersistentRecord> int updateLiteral ( Class<T> type, String ix1, Comparable<?> val1, String ix2, Comparable<?> val2, String ix3, Comparable<?> val3, Map<String, SQLExpression> fieldsToValues) throws DatabaseException { Key<T> key = new Key<T>(type, ix1, val1, ix2, val2, ix3, val3); return updateLiteral(type, key, key, fieldsToValues); } protected <T extends PersistentRecord> int updateLiteral ( Class<T> type, final WhereClause key, CacheInvalidator invalidator, Map<String, SQLExpression> fieldsToValues) throws DatabaseException { requireNotComputed(type, "updateLiteral"); if (invalidator instanceof ValidatingCacheInvalidator) { ((ValidatingCacheInvalidator)invalidator).validateFlushType(type); // sanity check } key.validateQueryType(type); // and another // separate the arguments into keys and values final String[] fields = new String[fieldsToValues.size()]; final SQLExpression[] values = new SQLExpression[fields.length]; int ii = 0; for (Map.Entry<String, SQLExpression> entry : fieldsToValues.entrySet()) { fields[ii] = entry.getKey(); values[ii] = entry.getValue(); ii ++; } UpdateClause<T> update = new UpdateClause<T>(type, key, fields, values); final SQLBuilder builder = _ctx.getSQLBuilder(DepotTypes.getDepotTypes(_ctx, update)); builder.newQuery(update); return _ctx.invoke(new Modifier(invalidator) { @Override public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { PreparedStatement stmt = builder.prepare(conn); try { return stmt.executeUpdate(); } finally { JDBCUtil.close(stmt); } } }); } /** * Stores the supplied persisent object in the database. If it has no primary key assigned (it * is null or zero), it will be inserted directly. Otherwise an update will first be attempted * and if that matches zero rows, the object will be inserted. * * @return true if the record was created, false if it was updated. */ protected <T extends PersistentRecord> boolean store (T record) throws DatabaseException { @SuppressWarnings("unchecked") final Class<T> pClass = (Class<T>) record.getClass(); requireNotComputed(pClass, "store"); final DepotMarshaller<T> marsh = _ctx.getMarshaller(pClass); Key<T> key = marsh.hasPrimaryKey() ? marsh.getPrimaryKey(record) : null; final UpdateClause<T> update = new UpdateClause<T>(pClass, key, marsh._columnFields, record); final SQLBuilder builder = _ctx.getSQLBuilder(DepotTypes.getDepotTypes(_ctx, update)); // if our primary key isn't null, we start by trying to update rather than insert if (key != null) { builder.newQuery(update); } final boolean[] created = new boolean[1]; _ctx.invoke(new CachingModifier<T>(record, key, key) { @Override public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { PreparedStatement stmt = null; try { if (_key != null) { // run the update stmt = builder.prepare(conn); int mods = stmt.executeUpdate(); if (mods > 0) { // if it succeeded, we're done return mods; } JDBCUtil.close(stmt); } // if the update modified zero rows or the primary key was obviously unset, do // an insertion: first, set any auto-generated column values Set<String> identityFields = marsh.generateFieldValues(conn, liaison, _result, false); // update our modifier's key so that it can cache our results if (_key == null) { updateKey(marsh.getPrimaryKey(_result, false)); } builder.newQuery(new InsertClause<T>(pClass, _result, identityFields)); stmt = builder.prepare(conn); int mods = stmt.executeUpdate(); // run any post-factum value generators marsh.generateFieldValues(conn, liaison, _result, true); // and check once more if a key now exists if (_key == null) { updateKey(marsh.getPrimaryKey(_result, false)); } created[0] = true; return mods; } finally { JDBCUtil.close(stmt); } } }); return created[0]; } /** * Deletes all persistent objects from the database with a primary key matching the primary key * of the supplied object. * * @return the number of rows deleted by this action. */ protected <T extends PersistentRecord> int delete (T record) throws DatabaseException { @SuppressWarnings("unchecked") Class<T> type = (Class<T>)record.getClass(); Key<T> primaryKey = _ctx.getMarshaller(type).getPrimaryKey(record); if (primaryKey == null) { throw new IllegalArgumentException("Can't delete record with null primary key."); } return delete(type, primaryKey); } /** * Deletes all persistent objects from the database with a primary key matching the supplied * primary key. * * @return the number of rows deleted by this action. */ protected <T extends PersistentRecord> int delete (Class<T> type, Comparable<?> primaryKeyValue) throws DatabaseException { return delete(type, _ctx.getMarshaller(type).makePrimaryKey(primaryKeyValue)); } /** * Deletes all persistent objects from the database with a primary key matching the supplied * primary key. * * @return the number of rows deleted by this action. */ protected <T extends PersistentRecord> int delete (Class<T> type, Key<T> primaryKey) throws DatabaseException { return deleteAll(type, primaryKey, primaryKey); } /** * Deletes all persistent objects from the database that match the supplied where clause. * * @return the number of rows deleted by this action. */ protected <T extends PersistentRecord> int deleteAll (Class<T> type, final WhereClause where) throws DatabaseException { // look up the primary keys for all rows matching our where clause and delete using those KeySet<T> pwhere = new KeySet<T>(type, findAllKeys(type, true, where)); return deleteAll(type, pwhere, pwhere); } /** * Deletes all persistent objects from the database that match the supplied key. * * @return the number of rows deleted by this action. */ protected <T extends PersistentRecord> int deleteAll ( Class<T> type, final WhereClause where, CacheInvalidator invalidator) throws DatabaseException { if (invalidator instanceof ValidatingCacheInvalidator) { ((ValidatingCacheInvalidator)invalidator).validateFlushType(type); // sanity check } where.validateQueryType(type); // and another DeleteClause<T> delete = new DeleteClause<T>(type, where); final SQLBuilder builder = _ctx.getSQLBuilder(DepotTypes.getDepotTypes(_ctx, delete)); builder.newQuery(delete); return _ctx.invoke(new Modifier(invalidator) { @Override public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { PreparedStatement stmt = builder.prepare(conn); try { return stmt.executeUpdate(); } finally { JDBCUtil.close(stmt); } } }); } // make sure the given type corresponds to a concrete class protected void requireNotComputed (Class<? extends PersistentRecord> type, String action) throws DatabaseException { DepotMarshaller<?> marsh = _ctx.getMarshaller(type); if (marsh == null) { throw new DatabaseException("Unknown persistent type [class=" + type + "]"); } if (marsh.getTableName() == null) { throw new DatabaseException( "Can't " + action + " computed entities [class=" + type + "]"); } } protected PersistenceContext _ctx; }
package ui.issuecolumn; import java.util.Comparator; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.collections.transformation.SortedList; import javafx.collections.transformation.TransformationList; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.input.Dragboard; import javafx.scene.input.TransferMode; import javafx.scene.layout.HBox; import javafx.stage.Stage; import model.Model; import model.TurboIssue; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import service.ServiceManager; import ui.DragData; import ui.UI; import ui.components.FilterTextField; import ui.components.HTStatusBar; import util.events.ColumnClickedEvent; import command.CommandType; import command.TurboCommandExecutor; import filter.ParseException; import filter.Parser; import filter.QualifierApplicationException; import filter.expression.Disjunction; import filter.expression.FilterExpression; import filter.expression.Qualifier; /** * An IssueColumn is a Column meant for containing issues. The main additions to * Column are filtering functionality and a list of issues to be maintained. * The IssueColumn does not specify how the list is to be displayed -- subclasses * override methods which determine that. */ public abstract class IssueColumn extends Column { private static final Logger logger = LogManager.getLogger(IssueColumn.class.getName()); // Collection-related private ObservableList<TurboIssue> issues = FXCollections.observableArrayList(); // Filter-related private TransformationList<TurboIssue, TurboIssue> transformedIssueList = null; public static final FilterExpression EMPTY = filter.expression.Qualifier.EMPTY; private Predicate<TurboIssue> predicate = p -> true; private FilterExpression currentFilterExpression = EMPTY; protected FilterTextField filterTextField; private UI ui; public IssueColumn(UI ui, Stage mainStage, Model model, ColumnControl parentColumnControl, int columnIndex, TurboCommandExecutor dragAndDropExecutor) { super(mainStage, model, parentColumnControl, columnIndex, dragAndDropExecutor); this.ui = ui; getChildren().add(createFilterBox()); setupIssueColumnDragEvents(model, columnIndex); this.setOnMouseClicked(e-> { ui.triggerEvent(new ColumnClickedEvent(columnIndex)); try { requestFocus(); } catch (Exception e1) { logger.warn("Nothing to focus on as panel was closed"); } }); focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> unused, Boolean wasFocused, Boolean isFocused) { if (isFocused) { getStyleClass().add("issue-panel-focused"); } else { getStyleClass().remove("issue-panel-focused"); } } }); } private void setupIssueColumnDragEvents(Model model, int columnIndex) { setOnDragOver(e -> { if (e.getGestureSource() != this && e.getDragboard().hasString()) { DragData dd = DragData.deserialise(e.getDragboard().getString()); if (dd.getSource() == DragData.Source.ISSUE_CARD) { e.acceptTransferModes(TransferMode.MOVE); } } }); setOnDragDropped(e -> { Dragboard db = e.getDragboard(); boolean success = false; if (db.hasString()) { success = true; DragData dd = DragData.deserialise(db.getString()); if (dd.getColumnIndex() != columnIndex) { TurboIssue rightIssue = model.getIssueWithId(dd.getIssueIndex()); applyCurrentFilterExpressionToIssue(rightIssue, true); } } e.setDropCompleted(success); e.consume(); }); } private Node createFilterBox() { filterTextField = new FilterTextField("", 0).setOnConfirm((text) -> { applyStringFilter(text); return text; }); List<String> collaboratorNames = ServiceManager.getInstance().getModel().getCollaborators() .stream().map(c -> c.getGithubName()).collect(Collectors.toList()); filterTextField.addKeywords(collaboratorNames); filterTextField.setOnMouseClicked(e-> {ui.triggerEvent(new ColumnClickedEvent(columnIndex));}); setupIssueDragEvents(filterTextField); HBox buttonsBox = new HBox(); buttonsBox.setSpacing(5); buttonsBox.setAlignment(Pos.TOP_RIGHT); buttonsBox.setMinWidth(50); buttonsBox.getChildren().addAll(createButtons()); HBox layout = new HBox(); layout.getChildren().addAll(filterTextField, buttonsBox); layout.setPadding(new Insets(0, 0, 3, 0)); return layout; } private Label[] createButtons() { // Label addIssue = new Label(ADD_ISSUE); // addIssue.getStyleClass().add("label-button"); // addIssue.setOnMouseClicked((e) -> { // ui.triggerEvent(new IssueCreatedEvent()); Label closeList = new Label(CLOSE_COLUMN); closeList.getStyleClass().add("label-button"); closeList.setOnMouseClicked((e) -> { parentColumnControl.closeColumn(columnIndex); }); // Label toggleHierarchyMode = new Label(TOGGLE_HIERARCHY); // toggleHierarchyMode.getStyleClass().add("label-button"); // toggleHierarchyMode.setOnMouseClicked((e) -> { // parentColumnControl.toggleColumn(columnIndex); return new Label[] { closeList }; } private void setupIssueDragEvents(Node filterBox) { filterBox.setOnDragOver(e -> { if (e.getGestureSource() != this && e.getDragboard().hasString()) { DragData dd = DragData.deserialise(e.getDragboard().getString()); if (dd.getSource() == DragData.Source.ISSUE_CARD) { e.acceptTransferModes(TransferMode.MOVE); } else if (dd.getSource() == DragData.Source.LABEL_TAB || dd.getSource() == DragData.Source.ASSIGNEE_TAB || dd.getSource() == DragData.Source.MILESTONE_TAB) { e.acceptTransferModes(TransferMode.COPY); } } }); filterBox.setOnDragEntered(e -> { if (e.getDragboard().hasString()) { DragData dd = DragData.deserialise(e.getDragboard().getString()); if (dd.getSource() == DragData.Source.ISSUE_CARD) { filterBox.getStyleClass().add("dragged-over"); } else if (dd.getSource() == DragData.Source.COLUMN) { if (parentColumnControl.getCurrentlyDraggedColumnIndex() != columnIndex) { // Apparently the dragboard can't be updated while // the drag is in progress. This is why we use an // external source for updates. assert parentColumnControl.getCurrentlyDraggedColumnIndex() != -1; int previous = parentColumnControl.getCurrentlyDraggedColumnIndex(); parentColumnControl.setCurrentlyDraggedColumnIndex(columnIndex); parentColumnControl.swapColumns(previous, columnIndex); } } } e.consume(); }); filterBox.setOnDragExited(e -> { filterBox.getStyleClass().remove("dragged-over"); e.consume(); }); filterBox.setOnDragDropped(e -> { Dragboard db = e.getDragboard(); boolean success = false; if (db.hasString()) { success = true; DragData dd = DragData.deserialise(db.getString()); if (dd.getSource() == DragData.Source.ISSUE_CARD) { TurboIssue rightIssue = model.getIssueWithId(dd.getIssueIndex()); if (rightIssue.getLabels().size() == 0) { // If the issue has no labels, show it by its title to inform // the user that there are no similar issues filter(new Qualifier("keyword", rightIssue.getTitle())); } else { // Otherwise, take the disjunction of its labels to show similar // issues. FilterExpression result = new Qualifier("label", rightIssue.getLabels().get(0).getName()); List<FilterExpression> rest = rightIssue.getLabels().stream() .skip(1) .map(label -> new Qualifier("label", label.getName())) .collect(Collectors.toList()); for (FilterExpression label : rest) { result = new Disjunction(label, result); } filter(result); } } else if (dd.getSource() == DragData.Source.COLUMN) { // This event is never triggered when the drag is ended. // It's not a huge deal, as this is only used to // reinitialise the currently-dragged slot in ColumnControl. // The other main consequence of this is that we can't // assert to check if the slot has been cleared when starting a drag-swap. } else if (dd.getSource() == DragData.Source.LABEL_TAB) { filter(new Qualifier("label", dd.getEntityName())); } else if (dd.getSource() == DragData.Source.ASSIGNEE_TAB) { filter(new Qualifier("assignee", dd.getEntityName())); } else if (dd.getSource() == DragData.Source.MILESTONE_TAB) { filter(new Qualifier("milestone", dd.getEntityName())); } } e.setDropCompleted(success); e.consume(); }); } // These two methods are triggered by the contents of the input area // changing. As such they should not be invoked manually, or the input // area won't update. private void applyStringFilter(String filterString) { try { FilterExpression filter = Parser.parse(filterString); if (filter != null) { this.applyFilterExpression(filter); } else { this.applyFilterExpression(EMPTY); } // Clear displayed message on successful filter HTStatusBar.displayMessage(""); } catch (ParseException ex) { this.applyFilterExpression(EMPTY); // Overrides message in status bar HTStatusBar.displayMessage("Panel " + (columnIndex + 1) + ": Parse error in filter: " + ex.getMessage()); } } private void applyFilterExpression(FilterExpression filter) { currentFilterExpression = filter; predicate = issue -> Qualifier.process(filter, issue); refreshItems(); } // An odd workaround for the above problem: serialising, then // immediately parsing a filter expression, just so the update can be // triggered // through the text contents of the input area changing. public void filter(FilterExpression filterExpr) { filterByString(filterExpr.toString()); } public void filterByString(String filterString) { filterTextField.setFilterText(filterString); } public FilterExpression getCurrentFilterExpression() { return currentFilterExpression; } public String getCurrentFilterString() { return filterTextField.getText(); } private void applyCurrentFilterExpressionToIssue(TurboIssue issue, boolean updateModel) { if (currentFilterExpression != EMPTY) { try { if (currentFilterExpression.canBeAppliedToIssue()) { TurboIssue clone = new TurboIssue(issue); currentFilterExpression.applyTo(issue, model); if (updateModel) { dragAndDropExecutor.executeCommand(CommandType.EDIT_ISSUE, model, clone, issue); } parentColumnControl.refresh(); } else { throw new QualifierApplicationException("Could not apply predicate " + currentFilterExpression + "."); } } catch (QualifierApplicationException ex) { parentColumnControl.displayMessage(ex.getMessage()); } } } public TransformationList<TurboIssue, TurboIssue> getIssueList() { return transformedIssueList; } public void setItems(List<TurboIssue> items) { this.issues = FXCollections.observableArrayList(items); refreshItems(); } /** * To be overridden by subclasses. * * See docs in Column for refreshItems. * */ // deselect is not overriden @Override public void refreshItems() { transformedIssueList = new FilteredList<TurboIssue>(issues, predicate); // If parent issue, sort child issues by depth if (currentFilterExpression instanceof filter.expression.Qualifier) { List<String> names = ((filter.expression.Qualifier) currentFilterExpression).getQualifierNames(); if (names.size() == 1 && names.get(0).equals("parent")) { transformedIssueList = new SortedList<>(transformedIssueList, new Comparator<TurboIssue>() { @Override public int compare(TurboIssue a, TurboIssue b) { return a.getDepth() - b.getDepth(); } }); } } } }
package FrontEnd; import java.awt.Container; import javax.swing.JFrame; import javax.swing.JPanel; import BackEnd.Empleado; import BackEnd.Producto; import BackEndDAO.ProductoDAO; import java.awt.BorderLayout; import javax.swing.JMenuBar; import javax.swing.BoxLayout; import javax.swing.JTabbedPane; import javax.swing.JButton; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JTable; import javax.swing.JScrollPane; import javax.swing.table.DefaultTableModel; import java.awt.event.ActionListener; import java.sql.SQLException; import java.awt.event.ActionEvent; public class PanelControl extends JPanel { private JTable tableProductos; private JTable tableDescuentos; private JTable tableEmpleados; private JTable table; PanelControl(JFrame marco,Empleado empleado) { setLayout(new BorderLayout(0, 0)); JButton btnAceptar = new JButton("Aceptar"); btnAceptar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { marco.setContentPane(new Inicio(marco)); marco.validate(); } }); add(btnAceptar, BorderLayout.SOUTH); JPanel panel = new JPanel(); add(panel, BorderLayout.NORTH); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); JMenuBar menuBar = new JMenuBar(); panel.add(menuBar); JMenu mnAadir = new JMenu("Añadir"); menuBar.add(mnAadir); JMenuItem mntmProducto = new JMenuItem("Producto"); mnAadir.add(mntmProducto); JMenuItem menuItemDescuento = new JMenuItem("Descuento"); mnAadir.add(menuItemDescuento); JMenuItem menuItemEmpleado = new JMenuItem("Empleado"); mnAadir.add(menuItemEmpleado); JMenu mnFiltrar = new JMenu("Filtrar"); menuBar.add(mnFiltrar); JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP); add(tabbedPane, BorderLayout.CENTER); JScrollPane scrollPaneVenta = new JScrollPane(); tabbedPane.addTab("Ventas", null, scrollPaneVenta, null); table = new JTable(); scrollPaneVenta.setViewportView(table); JScrollPane scrollPaneDescuento = new JScrollPane(); tabbedPane.addTab("Descuentos", null, scrollPaneDescuento, null); tableDescuentos = new JTable(); tableDescuentos.setModel(new DefaultTableModel( new Object[][] { }, new String[] { } )); scrollPaneDescuento.setViewportView(tableDescuentos); JScrollPane scrollPaneEmpleado = new JScrollPane(); tabbedPane.addTab("Empleados", null, scrollPaneEmpleado, null); tableEmpleados = new JTable(); scrollPaneEmpleado.setViewportView(tableEmpleados); JScrollPane scrollPaneProducto = new JScrollPane(); tabbedPane.addTab("Productos", null, scrollPaneProducto, null); DefaultTableModel modeloProducto = new DefaultTableModel( new Object[][] { }, new String[] { "Codigo", "Nombre", "Precio" } ); ProductoDAO productoDao = new ProductoDAO(); try { for (Producto p : productoDao.obtenerTodosLosProductos()) { modeloProducto.addRow(new Object[] { p.getCodProducto(), p.getNombre(), p.getPrecio() }); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } tableProductos = new JTable(); tableProductos.setModel(modeloProducto); scrollPaneProducto.setViewportView(tableProductos); } }
package com.gildedrose; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import org.junit.Test; public class GildedRoseTest { private static final String BACKSTAGE_PASSES_TO_A_TAFKAL80ETC_CONCERT = "Backstage passes to a TAFKAL80ETC concert"; private static final String JUNK = "junk"; private static final String AGED_BRIE = "Aged Brie"; private GildedRose app; private void initialize(Item... items) { app = new GildedRose(items); } @Test public void itemsWhosQualityIsNegativeAreReportedAsQualityZero() { initialize(new Item(JUNK, 0, -1)); assertThat(itemOne().quality, is(0)); } @Test public void ctItemsWhosQualityBecomesNegativeAreReportedAsQualityZero() { initialize(new Item(JUNK, 0, 0)); updateQuality(); assertThat(itemOne().quality, is(0)); } @Test public void ctSpecialItemsWhosQualityIs50CannotGetHigherQuality() { initialize(new Item(AGED_BRIE, -10, 50)); updateQuality(); assertThat(itemOne().quality, is(50)); } @Test public void ctSpecialItemsIncreaseInQualityWithAge() { initialize(new Item(AGED_BRIE, 11, 40)); updateQuality(); assertThat(itemOne().quality, is(41)); } @Test public void ctAgedBrieIncreasesInQualityByTwoOnItsExpirationDay() { initialize(new Item(AGED_BRIE, 0, 40)); updateQuality(); assertThat(itemOne().quality, is(42)); } @Test public void ctAgedBrieIncreasesInQualityByTwoAfterItsExpirationDay() { initialize(new Item(AGED_BRIE, -1, 40)); updateQuality(); assertThat(itemOne().quality, is(42)); } @Test public void ctAgedBrieIncreasesInQualityByOneBeforeItsExpirationDay() { initialize(new Item(AGED_BRIE, 1, 40)); updateQuality(); assertThat(itemOne().quality, is(41)); } @Test public void ctConcertPassIncreasesInQualityByOneWhenMoreThan10DaysBeforeItsExpirationDay() { initialize(new Item(BACKSTAGE_PASSES_TO_A_TAFKAL80ETC_CONCERT, 11, 20)); updateQuality(); assertThat(itemOne().quality, is(21)); } @Test public void ctConcertPassIncreasesInQualityByTwoWhen10DaysBeforeItsExpirationDay() { initialize(new Item(BACKSTAGE_PASSES_TO_A_TAFKAL80ETC_CONCERT, 10, 20)); updateQuality(); assertThat(itemOne().quality, is(22)); } @Test public void ctConcertPassIncreasesInQualityByThreeWhen5DaysBeforeItsExpirationDay() { initialize(new Item(BACKSTAGE_PASSES_TO_A_TAFKAL80ETC_CONCERT, 5, 20)); updateQuality(); assertThat(itemOne().quality, is(23)); } @Test public void ctConcertPassIsWorthlessWhenAfterItsExpirationDay() { initialize(new Item(BACKSTAGE_PASSES_TO_A_TAFKAL80ETC_CONCERT, -1, 20)); updateQuality(); assertThat(itemOne().quality, is(0)); } @Test public void ctConcertPassCannotExceedQuality50Before10DaysToSellIn() { initialize(new Item(BACKSTAGE_PASSES_TO_A_TAFKAL80ETC_CONCERT,11,50)); updateQuality(); assertThat(itemOne().quality,is(50)); } @Test public void ctConcertPassCannotExceedQuality50Before5DaysToSellIn() { initialize(new Item(BACKSTAGE_PASSES_TO_A_TAFKAL80ETC_CONCERT,5,50)); updateQuality(); assertThat(itemOne().quality,is(50)); } @Test public void ctConcertPassCannotExceedQuality50Before0DaysToSellIn() { initialize(new Item(BACKSTAGE_PASSES_TO_A_TAFKAL80ETC_CONCERT,1,50)); updateQuality(); assertThat(itemOne().quality,is(50)); } @Test public void ctConcertPassCannotExceedQualtiy50() { initialize(new Item(BACKSTAGE_PASSES_TO_A_TAFKAL80ETC_CONCERT, 2, 48)); updateQuality(); assertThat(itemOne().quality, is(50)); } @Test public void ctHandOfRangnarosQualityNeverDecreases() { initialize(new Item("Sulfuras, Hand of Ragnaros", 10, 10)); updateQuality(); assertThat(itemOne().quality,is(10)); } @Test public void ctHandOfRangnarosNeverExpires() { initialize(new Item("Sulfuras, Hand of Ragnaros", 10, 10)); updateQuality(); assertThat(itemOne().sellIn,is(10)); } private void updateQuality() { app.updateQuality(); } private Item itemOne() { return app.items[0]; } }
package com.jcabi.github; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Assume; import org.junit.Test; public final class RtRepoITCase { /** * RtRepo can identify itself. * @throws Exception If some problem inside */ @Test public void identifiesItself() throws Exception { final Repo repo = RtRepoITCase.repo(); MatcherAssert.assertThat( repo.coordinates(), Matchers.notNullValue() ); } /** * RtRepo can fetch events. * @throws Exception If some problem inside */ @Test public void iteratesEvents() throws Exception { final Repo repo = RtRepoITCase.repo(); MatcherAssert.assertThat( repo.events(), Matchers.not(Matchers.emptyIterable()) ); } /** * RtRepo can fetch its commits. * @throws Exception If some problem inside */ @Test public void fetchCommits() throws Exception { final Repo repo = RtRepoITCase.repo(); MatcherAssert.assertThat(repo.commits(), Matchers.notNullValue()); } /** * RtRepo can fetch assignees. * @throws Exception If some problem inside */ @Test public void iteratesAssignees() throws Exception { final Repo repo = RtRepoITCase.repo(); MatcherAssert.assertThat( repo.assignees().iterate(), Matchers.not(Matchers.emptyIterable()) ); } /** * Create and return repo to test. * @return Repo * @throws Exception If some problem inside */ private static Repo repo() throws Exception { final String key = System.getProperty("failsafe.github.key"); Assume.assumeThat(key, Matchers.notNullValue()); final Github github = new RtGithub(key); return github.repos().get( new Coordinates.Simple(System.getProperty("failsafe.github.repo")) ); } }
package com.test.generics; import java.math.*; import org.junit.jupiter.api.*; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.core.Is.is; @DisplayName("Test cases for various \"Number\" classes") public class NumbersTest { @DisplayName("Tests for our domain-specific Integer class") @Test public void testInteger() { assertThat(new Integer(BigInteger.ZERO).toString(), is("ComplexNumber{realPart=0, imaginaryPart=0}")); assertThat(new Integer(new BigInteger("42")).toString(), is("ComplexNumber{realPart=42, imaginaryPart=0}")); assertThat(new Integer(new BigInteger("1234567890987654321")).toString(), is("ComplexNumber{realPart=1234567890987654321, imaginaryPart=0}")); assertThat(new Integer(new BigInteger("-1234567890987654321")).toString(), is("ComplexNumber{realPart=-1234567890987654321, imaginaryPart=0}")); } @DisplayName("Tests for our domain-specific RationalNumber class") @Test public void testRationalNumber() { assertThat(new RationalNumber(BigInteger.ZERO, BigInteger.ONE).toString(), is("ComplexNumber{realPart=0, imaginaryPart=0}")); assertThat(new RationalNumber(BigInteger.ONE, new BigInteger("42"), 20).toString(), is("ComplexNumber{realPart=0.02380952380952380952, imaginaryPart=0}")); assertThat(new RationalNumber(BigInteger.ONE, new BigInteger("-42"), 20).toString(), is("ComplexNumber{realPart=-0.02380952380952380952, imaginaryPart=0}")); } @DisplayName("Tests for our domain-specific RealNumber class") @Test public void testRealNumber() { final String pi_1000 = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989"; assertThat(new RealNumber(new BigDecimal(pi_1000)).toString(), is("ComplexNumber{realPart=" + pi_1000 + ", imaginaryPart=0}")); } @DisplayName("Tests for our domain-specific ComplexNumber class") @Test public void testComplexNumber() { assertThat(new ComplexNumber(BigDecimal.TEN, BigDecimal.ONE).toString(), is("ComplexNumber{realPart=10, imaginaryPart=1}")); } }
package guitests; import static org.junit.Assert.assertEquals; import static org.loadui.testfx.Assertions.assertNodeExists; import static org.loadui.testfx.controls.Commons.hasText; import java.util.List; import java.util.Map; import java.util.Optional; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.input.KeyCombination; import org.junit.Before; import org.junit.Test; import prefs.PanelInfo; import prefs.Preferences; import ui.BoardAutoCreator; import ui.TestController; import ui.UI; import ui.components.KeyboardShortcuts; import ui.issuepanel.PanelControl; import util.PlatformEx; import static ui.BoardAutoCreator.SAMPLE_BOARD; import static ui.BoardAutoCreator.SAMPLE_BOARD_DIALOG; import static ui.BoardAutoCreator.SAVE_MESSAGE; public class BoardAutoCreatorTest extends UITest { private PanelControl panelControl; @Before public void cleanUpBoards() { UI ui = TestController.getUI(); panelControl = ui.getPanelControl(); Preferences testPref = UI.prefs; List<String> boardNames = testPref.getAllBoardNames(); boardNames.stream().forEach(testPref::removeBoard); } @Test public void boardAutoCreator_clickYesInSavePrompt_currentBoardSaved() { int panelCount = panelControl.getPanelCount(); assertEquals(0, panelControl.getNumberOfSavedBoards()); // create 3 new panels pushKeys(KeyboardShortcuts.CREATE_RIGHT_PANEL); pushKeys(KeyboardShortcuts.CREATE_RIGHT_PANEL); pushKeys(KeyboardShortcuts.CREATE_RIGHT_PANEL); assertEquals(panelCount + 3, panelControl.getPanelCount()); // create milestones board traverseMenu("Boards", "Auto-create", "Milestones"); PlatformEx.waitOnFxThread(); waitUntilNodeAppears(String.format(SAVE_MESSAGE, "Milestones")); // opt to save current board click("Yes"); // save as "New Board" click("OK"); assertEquals(2, panelControl.getNumberOfSavedBoards()); assertEquals(5, panelControl.getPanelCount()); // check that "New Board" is saved correctly traverseMenu("Boards", "Open", "New Board"); PlatformEx.waitOnFxThread(); assertEquals(panelCount + 3, panelControl.getPanelCount()); } @Test public void milestoneBoardAutoCreationTest() { assertEquals(0, panelControl.getNumberOfSavedBoards()); traverseMenu("Boards", "Auto-create", "Milestones"); PlatformEx.waitOnFxThread(); waitUntilNodeAppears(String.format(SAVE_MESSAGE, "Milestones")); click("No"); assertNodeExists(hasText("Milestones board has been created and loaded.\n\n" + "It is saved under the name \"Milestones\".")); click("OK"); assertEquals(5, panelControl.getPanelCount()); assertEquals(Optional.of(1), panelControl.getCurrentlySelectedPanel()); assertEquals(1, panelControl.getNumberOfSavedBoards()); List<PanelInfo> panelInfos = panelControl.getCurrentPanelInfos(); assertEquals("milestone:curr-1 sort:status", panelInfos.get(0).getPanelFilter()); assertEquals("milestone:curr sort:status", panelInfos.get(1).getPanelFilter()); assertEquals("milestone:curr+1 sort:status", panelInfos.get(2).getPanelFilter()); assertEquals("milestone:curr+2 sort:status", panelInfos.get(3).getPanelFilter()); assertEquals("milestone:curr+3 sort:status", panelInfos.get(4).getPanelFilter()); assertEquals("Previous Milestone", panelInfos.get(0).getPanelName()); assertEquals("Current Milestone", panelInfos.get(1).getPanelName()); assertEquals("Next Milestone", panelInfos.get(2).getPanelName()); assertEquals("Next Next Milestone", panelInfos.get(3).getPanelName()); assertEquals("Next Next Next Milestone", panelInfos.get(4).getPanelName()); } @Test public void workAllocationBoardAutoCreationTest() { assertEquals(0, panelControl.getNumberOfSavedBoards()); traverseMenu("Boards", "Auto-create", "Work Allocation"); PlatformEx.waitOnFxThread(); waitUntilNodeAppears(String.format(SAVE_MESSAGE, "Work Allocation")); click("No"); assertNodeExists(hasText("Work Allocation board has been created and loaded.\n\n" + "It is saved under the name \"Work Allocation\".")); click("OK"); assertEquals(5, panelControl.getPanelCount()); assertEquals(Optional.of(0), panelControl.getCurrentlySelectedPanel()); assertEquals(1, panelControl.getNumberOfSavedBoards()); List<PanelInfo> panelInfos = panelControl.getCurrentPanelInfos(); assertEquals("assignee:User 1 sort:milestone,status", panelInfos.get(0).getPanelFilter()); assertEquals("assignee:User 10 sort:milestone,status", panelInfos.get(1).getPanelFilter()); assertEquals("assignee:User 11 sort:milestone,status", panelInfos.get(2).getPanelFilter()); assertEquals("assignee:User 12 sort:milestone,status", panelInfos.get(3).getPanelFilter()); assertEquals("assignee:User 2 sort:milestone,status", panelInfos.get(4).getPanelFilter()); assertEquals("Work allocated to User 1", panelInfos.get(0).getPanelName()); assertEquals("Work allocated to User 10", panelInfos.get(1).getPanelName()); assertEquals("Work allocated to User 11", panelInfos.get(2).getPanelName()); assertEquals("Work allocated to User 12", panelInfos.get(3).getPanelName()); assertEquals("Work allocated to User 2", panelInfos.get(4).getPanelName()); } @Test public void sampleBoardAutoCreationTest() { assertEquals(0, panelControl.getNumberOfSavedBoards()); traverseMenu("Boards", "Auto-create", SAMPLE_BOARD); waitUntilNodeAppears(String.format(SAVE_MESSAGE, SAMPLE_BOARD)); click("No"); waitUntilNodeAppears(SAMPLE_BOARD_DIALOG); click("OK"); verifyBoard(panelControl, BoardAutoCreator.getSamplePanelDetails()); } /** * Confirms the currently displayed board consists the set of panels specified in panelDetails */ public static void verifyBoard(PanelControl pc, Map<String, String> panelDetails) { List<PanelInfo> panelInfos = pc.getCurrentPanelInfos(); assertEquals(panelDetails.size(), pc.getPanelCount()); assertEquals(Optional.of(0), pc.getCurrentlySelectedPanel()); assertEquals(1, pc.getNumberOfSavedBoards()); int i = 0; for (String panelName : panelDetails.keySet()) { assertEquals(panelName, panelInfos.get(i).getPanelName()); assertEquals(BoardAutoCreator.getSamplePanelDetails().get(panelName), panelInfos.get(i).getPanelFilter()); i++; } } }
package gwt.react.client.proptypes.html; import elemental2.dom.HTMLLabelElement; import gwt.react.client.api.ReactRef; import gwt.react.client.events.*; import gwt.react.client.proptypes.ReactRefCallback; import gwt.react.client.proptypes.html.attributeTypes.YesNo; import jsinterop.annotations.JsOverlay; import jsinterop.annotations.JsPackage; import jsinterop.annotations.JsType; @JsType(isNative=true, namespace=JsPackage.GLOBAL, name="Object") public class LabelProps extends HtmlGlobalFields { @JsOverlay public final LabelProps htmlFor(String s) { htmlFor = s; return this; } @JsOverlay public final LabelProps form(String s) { form = s; return this; } //React Specific @Deprecated @JsOverlay public final LabelProps ref(String s) { ref = s; return this; } @JsOverlay public final LabelProps ref(ReactRefCallback callback) { ref = callback; return this; } @JsOverlay public final LabelProps ref(ReactRef<HTMLLabelElement> reactRef) { ref = reactRef; return this; } @JsOverlay public final LabelProps key(String s) { key = s; return this; } //Global HTML props @JsOverlay public final LabelProps accessKey(String s) { accessKey = s; return this;} @JsOverlay public final LabelProps className(String s) { className = s; return this; } @JsOverlay public final LabelProps contentEditable(boolean b) { contentEditable = b; return this; } @JsOverlay public final LabelProps contextMenu(String s) { contextMenu = s; return this; } @JsOverlay public final LabelProps dir(String s) { dir = s; return this; } @JsOverlay public final LabelProps draggable(boolean b) { draggable = b; return this; } @JsOverlay public final LabelProps hidden(boolean b) { hidden = b; return this; } @JsOverlay public final LabelProps id(String s) { id = s; return this; } @JsOverlay public final LabelProps lang(String s) { lang = s; return this; } @JsOverlay public final LabelProps spellcheck(boolean b) { spellCheck = b; return this; } @JsOverlay public final LabelProps style(CssProps s) { style = s; return this; } @JsOverlay public final LabelProps tabIndex(int i) { tabIndex = i; return this; } @JsOverlay public final LabelProps title(String s) { title = s; return this; } @JsOverlay public final LabelProps translate(YesNo s) { translate = s.name(); return this; } //Applicable Event Handlers //TODO Refine // Focus Events @JsOverlay public final LabelProps onBlur(FocusEventHandler handler) { onBlur = handler; return this; } @JsOverlay public final LabelProps onFocus(FocusEventHandler handler) { onFocus = handler; return this; } // Keyboard Events @JsOverlay public final LabelProps onKeyDown(KeyboardEventHandler handler) { onKeyDown = handler; return this; } @JsOverlay public final LabelProps onKeyPress(KeyboardEventHandler handler) { onKeyPress = handler; return this; } @JsOverlay public final LabelProps onKeyUp(KeyboardEventHandler handler) { onKeyUp = handler; return this; } @JsOverlay public final LabelProps onClick(MouseEventHandler handler) { onClick = handler; return this; } @JsOverlay public final LabelProps onContextMenu(MouseEventHandler handler) { onContextMenu = handler; return this; } @JsOverlay public final LabelProps onDoubleClick(MouseEventHandler handler) { onDoubleClick = handler; return this; } @JsOverlay public final LabelProps onDrag(DragEventHandler handler) { onDrag = handler; return this; } @JsOverlay public final LabelProps onDragEnd(DragEventHandler handler) { onDragEnd = handler; return this; } @JsOverlay public final LabelProps onDragEnter(DragEventHandler handler) { onDragEnter = handler; return this; } @JsOverlay public final LabelProps onDragExit(DragEventHandler handler) { onDragExit = handler; return this; } @JsOverlay public final LabelProps onDragLeave(DragEventHandler handler) { onDragLeave = handler; return this; } @JsOverlay public final LabelProps onDragOver(DragEventHandler handler) { onDragOver = handler; return this; } @JsOverlay public final LabelProps onDragStart(DragEventHandler handler) { onDragStart = handler; return this; } @JsOverlay public final LabelProps onDrop(DragEventHandler handler) { onDrop = handler; return this; } @JsOverlay public final LabelProps onMouseDown(MouseEventHandler handler) { onMouseDown = handler; return this; } @JsOverlay public final LabelProps onMouseEnter(MouseEventHandler handler) { onMouseEnter = handler; return this; } @JsOverlay public final LabelProps onMouseLeave(MouseEventHandler handler) { onMouseLeave = handler; return this; } @JsOverlay public final LabelProps onMouseMove(MouseEventHandler handler) { onMouseMove = handler; return this; } @JsOverlay public final LabelProps onMouseOut(MouseEventHandler handler) { onMouseOut = handler; return this; } @JsOverlay public final LabelProps onMouseOver(MouseEventHandler handler) { onMouseOver = handler; return this; } @JsOverlay public final LabelProps onMouseUp(MouseEventHandler handler) { onMouseUp = handler; return this; } // Touch Events @JsOverlay public final LabelProps onTouchCancel(TouchEventHandler handler) { onTouchCancel = handler; return this; } @JsOverlay public final LabelProps onTouchEnd(TouchEventHandler handler) { onTouchEnd = handler; return this; } @JsOverlay public final LabelProps onTouchMove(TouchEventHandler handler) { onTouchMove = handler; return this; } @JsOverlay public final LabelProps onTouchStart(TouchEventHandler handler) { onTouchStart = handler; return this; } }
package org.apache.commons.lang; import java.io.IOException; import java.io.Writer; import java.io.PrintWriter; import org.apache.commons.lang.exception.NestableRuntimeException; public class StringEscapeUtils { /** * The entity set to use when escaping and unescaping HTML. */ protected static Entities DEFAULT_ENTITIES = Entities.HTML40; /** * <p><code>StringEscapeUtils</code> instances should NOT be constructed in * standard programming.</p> * <p>Instead, the class should be used as:</p> * <pre>StringEscapeUtils.escapeJava("foo");</pre> * * <p>This constructor is public to permit tools that require a JavaBean * instance to operate.</p> */ public StringEscapeUtils() { } // Java and JavaScript /** * <p>Escapes the characters in a <code>String</code> using Java String rules.</p> * <p>Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.) </p> * * <p>So a tab becomes the characters <code>'\\'</code> and * <code>'t'</code>.</p> * * <p>The only difference between Java strings and JavaScript strings * is that in JavaScript, a single quote must be escaped.</p> * * <p>Example: * <pre> * input string: He didn't say, "Stop!" * output string: He didn't say, \"Stop!\" * </pre> * </p> * * @param str String to escape values in * @return String with escaped values * @throws NullPointerException if str is <code>null</code> */ public static String escapeJava(String str) { return escapeJavaStyleString(str, false); } /** * <p>Escapes the characters in a <code>String</code> using Java String rules to a <code>Writer</code>.</p> * * @see #escapeJava(java.lang.String) * @param out Writer to write escaped string into * @param str String to escape values in * @throws NullPointerException if str is <code>null</code> * @throws IOException if error occurs on undelying Writer */ public static void escapeJava(Writer out, String str) throws IOException { escapeJavaStyleString(out, str, false); } /** * <p>Escapes the characters in a <code>String</code> using JavaScript String rules.</p> * <p>Escapes any values it finds into their JavaScript String form. * Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.) </p> * * <p>So a tab becomes the characters <code>'\\'</code> and * <code>'t'</code>.</p> * * <p>The only difference between Java strings and JavaScript strings * is that in JavaScript, a single quote must be escaped.</p> * * <p>Example: * <pre> * input string: He didn't say, "Stop!" * output string: He didn\'t say, \"Stop!\" * </pre> * </p> * * @param str String to escape values in * @return String with escaped values * @throws NullPointerException if str is <code>null</code> */ public static String escapeJavaScript(String str) { return escapeJavaStyleString(str, true); } /** * <p>Escapes the characters in a <code>String</code> using JavaScript String rules to a <code>Writer</code>.</p> * * @see #escapeJavaScript(java.lang.String) * @param out Writer to write escaped string into * @param str String to escape values in * @throws NullPointerException if str is <code>null</code> * @throws IOException if error occurs on undelying Writer **/ public static void escapeJavaScript(Writer out, String str) throws IOException { escapeJavaStyleString(out, str, true); } private static String escapeJavaStyleString(String str, boolean escapeSingleQuotes) { try { StringPrintWriter writer = new StringPrintWriter(str.length() * 2); escapeJavaStyleString(writer, str, escapeSingleQuotes); return writer.getString(); } catch (IOException ioe) { // this should never ever happen while writing to a StringWriter ioe.printStackTrace(); return null; } } private static void escapeJavaStyleString(Writer out, String str, boolean escapeSingleQuote) throws IOException { int sz; sz = str.length(); for (int i = 0; i < sz; i++) { char ch = str.charAt(i); // handle unicode if (ch > 0xfff) { out.write("\\u" + hex(ch)); } else if (ch > 0xff) { out.write("\\u0" + hex(ch)); } else if (ch > 0x7f) { out.write("\\u00" + hex(ch)); } else if (ch < 32) { switch (ch) { case '\b': out.write('\\'); out.write('b'); break; case '\n': out.write('\\'); out.write('n'); break; case '\t': out.write('\\'); out.write('t'); break; case '\f': out.write('\\'); out.write('f'); break; case '\r': out.write('\\'); out.write('r'); break; default : if (ch > 0xf) { out.write("\\u00" + hex(ch)); } else { out.write("\\u000" + hex(ch)); } break; } } else { switch (ch) { case '\'': if (escapeSingleQuote) out.write('\\'); out.write('\''); break; case '"': out.write('\\'); out.write('"'); break; case '\\': out.write('\\'); out.write('\\'); break; default : out.write(ch); break; } } } } /** * Returns an upper case hexadecimal <code>String</code> for the given character. * * @param ch The character to convert. * @return An upper case hexadecimal <code>String</code> */ private static String hex(char ch) { return Integer.toHexString(ch).toUpperCase(); } /** * Unescapes any Java literals found in the <code>String</code>. * For example, it will turn a sequence of '\' and 'n' into a newline character, * unless the '\' is preceded by another '\'. * * @param str The <code>String</code> to unescape. * @return A new unescaped <code>String</code>. */ public static String unescapeJava(String str) { try { StringPrintWriter writer = new StringPrintWriter(str.length()); unescapeJava(writer, str); return writer.getString(); } catch (IOException ioe) { // this should never ever happen while writing to a StringWriter ioe.printStackTrace(); return null; } } /** * Unescapes any Java literals found in the <code>String</code> to a <code>Writer</code>. * For example, it will turn a sequence of '\' and 'n' into a newline character, * unless the '\' is preceded by another '\'. * * @param out The <code>Writer</code> used to output unescaped characters. * @param str The <code>String</code> to unescape. */ public static void unescapeJava(Writer out, String str) throws IOException { int sz = str.length(); StringBuffer unicode = new StringBuffer(4); boolean hadSlash = false; boolean inUnicode = false; for (int i = 0; i < sz; i++) { char ch = str.charAt(i); if (inUnicode) { // if in unicode, then we're reading unicode // values in somehow unicode.append(ch); if (unicode.length() == 4) { // unicode now contains the four hex digits // which represents our unicode chacater try { int value = Integer.parseInt(unicode.toString(), 16); out.write((char) value); unicode.setLength(0); inUnicode = false; hadSlash = false; } catch (NumberFormatException nfe) { throw new NestableRuntimeException("Unable to parse unicode value: " + unicode, nfe); } } continue; } if (hadSlash) { // handle an escaped value hadSlash = false; switch (ch) { case '\\': out.write('\\'); break; case '\'': out.write('\''); break; case '\"': out.write('"'); break; case 'r': out.write('\r'); break; case 'f': out.write('\f'); break; case 't': out.write('\t'); break; case 'n': out.write('\n'); break; case 'b': out.write('\b'); break; case 'u': { // uh-oh, we're in unicode country.... inUnicode = true; break; } default : out.write(ch); break; } continue; } else if (ch == '\\') { hadSlash = true; continue; } out.write(ch); } if (hadSlash) { // then we're in the weird case of a \ at the end of the // string, let's output it anyway. out.write('\\'); } } /** * Unescapes any JavaScript literals found in the <code>String</code>. * For example, it will turn a sequence of '\' and 'n' into a newline character, * unless the '\' is preceded by another '\'. * * @param str The <code>String</code> to unescape. * @return A new unescaped <code>String</code>. * @see #unescapeJava(String) */ public static String unescapeJavaScript(String str) { return unescapeJava(str); } /** * Unescapes any JavaScript literals found in the <code>String</code> to a <code>Writer</code>. * For example, it will turn a sequence of '\' and 'n' into a newline character, * unless the '\' is preceded by another '\'. * * @param out The <code>Writer</code> used to output unescaped characters. * @param str The <code>String</code> to unescape. * @see #unescapeJava(Writer,String) */ public static void unescapeJavaScript(Writer out, String str) throws IOException { unescapeJava(out, str); } // HTML and XML public static String escapeHtml(String str) { //todo: add a version that takes a Writer //todo: rewrite underlying method to use a Writer instead of a StringBuffer return Entities.HTML40.escape(str); } /** * <p>Unescapes a string containing entity escapes to a string * containing the actual Unicode characters corresponding to the * escapes. Supports HTML 4.0 entities.</p> * <p>For example, the string "&amp;lt;Fran&ccedilla;ais&amp;gt;" * will become "<Fran\u00E7ais>"</p> * <p>If an entity is unrecognized, it is left alone, and inserted * verbatim into the result string. e.g. "&amp;gt;&amp;zzzz;x" will * become "&gt;&amp;zzzz;x".</p> * * @param str The <code>String</code> to unescape * @return A new unescaped <code>String</code>. * @see #escapeHtml(String) **/ public static String unescapeHtml(String str) { return Entities.HTML40.unescape(str); } /** * <p>Escapes the characters in a <code>String</code> using XML entities.</p> * <p> * For example: <tt>"bread" & "butter"</tt> => * <tt>&amp;quot;bread&amp;quot; &amp;amp; &amp;quot;butter&amp;quot;</tt>. * </p> * <p> * Supports only the four basic XML entities (gt, lt, quot, amp). * Does not support DTDs or external entities. * </p> * @param str The <code>String</code> to escape * @return A new escaped <code>String</code>. * @see #unescapeXml(java.lang.String) **/ public static String escapeXml(String str) { return Entities.XML.escape(str); } /** * <p>Unescapes a string containing XML entity escapes to a string * containing the actual Unicode characters corresponding to the * escapes. * </p> * <p> * Supports only the four basic XML entities (gt, lt, quot, amp). * Does not support DTDs or external entities. * </p> * * @param str The <code>String</code> to unescape * @return A new unescaped <code>String</code>. * @see #escapeXml(String) **/ public static String unescapeXml(String str) { return Entities.XML.unescape(str); } public static String escapeSql(String s) { return StringUtils.replace(s, "'", "''"); } }
package net.loxal.example; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.RandomStringUtils; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; public class ExampleTest { private static final Logger LOG = LoggerFactory.getLogger(ExampleTest.class); static List<Character> unsortedCharacters; static List<Character> sortedCharacters; private final Example example = new Example(); private static List<Character> createCharacters() { char[] randomChars = RandomStringUtils.random(1234, "abcdefghijklmnopqrstuvwxyz").toCharArray(); List<Character> randomCharacters = Arrays.asList(ArrayUtils.toObject(randomChars)); List<Character> characters = new LinkedList<>(); characters.add('z'); characters.add('z'); characters.add('z'); characters.add('b'); characters.add('a'); characters.add('c'); characters.add('y'); characters.add('c'); characters.addAll(randomCharacters); characters.add('d'); characters.add('x'); characters.add('f'); characters.add('e'); characters.add('e'); characters.add('e'); characters.add('u'); characters.add('v'); characters.add('u'); characters.add('a'); characters.add('a'); return characters; } @BeforeClass public static void beforeClass() { LOG.info("@BeforeClass"); unsortedCharacters = createCharacters(); sortedCharacters = new LinkedList<>(unsortedCharacters); Collections.sort(sortedCharacters); } @Before public void setUp() throws Exception { LOG.info("@Before"); } @After public void tearDown() throws Exception { } @Test public void sortUsingBubleSort() throws Exception { Method sort = Example.class.getDeclaredMethod("sortUsingBubbleSort", List.class); Character[] characters = (Character[]) sort.invoke(example, unsortedCharacters); verifySortOrder(characters); } private void verifySortOrder(Character[] characters) { assertEquals(sortedCharacters, Arrays.asList(characters)); assertArrayEquals(sortedCharacters.toArray(), Arrays.asList(characters).toArray()); } @Test public void sortUsingImprovedBubleSort() throws Exception { Example example = new Example(); Method sort = Example.class.getDeclaredMethod("sortUsingImprovedBubbleSort", List.class); Character[] characters = (Character[]) sort.invoke(example, unsortedCharacters); verifySortOrder(characters); } }
package htsquirrel.gui.pages.settings; import static htsquirrel.HTSquirrel.applyTheme; import static htsquirrel.HTSquirrel.getTheme; import static htsquirrel.HTSquirrel.setTheme; import static htsquirrel.utilities.ConfigProperties.saveConfigProperties; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; public class SettingsBase extends javax.swing.JPanel { /** * Creates new form SettingsBase */ public SettingsBase() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { labelTitle = new javax.swing.JLabel(); labelLanguage = new javax.swing.JLabel(); comboBoxLanguage = new javax.swing.JComboBox(); labelTheme = new javax.swing.JLabel(); comboBoxTheme = new javax.swing.JComboBox(); buttonOk = new javax.swing.JButton(); labelTitle.setFont(new java.awt.Font("DejaVu Sans", 0, 18)); // NOI18N labelTitle.setForeground(new java.awt.Color(255, 102, 0)); labelTitle.setText("Settings"); labelLanguage.setText("Language:"); comboBoxLanguage.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "English", "Srpski" })); labelTheme.setText("Theme:"); comboBoxTheme.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Dark", "Light" })); buttonOk.setText("Ok"); buttonOk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonOkActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(labelTitle) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(labelLanguage) .addComponent(labelTheme)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(buttonOk, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(comboBoxLanguage, 0, 100, Short.MAX_VALUE) .addComponent(comboBoxTheme, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))) .addContainerGap(210, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(labelTitle) .addGap(45, 45, 45) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(labelLanguage) .addComponent(comboBoxLanguage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(labelTheme) .addComponent(comboBoxTheme, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(50, 50, 50) .addComponent(buttonOk) .addContainerGap(82, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void buttonOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOkActionPerformed if (!(comboBoxTheme.getSelectedItem().toString().equals(getTheme()))) { setTheme(comboBoxTheme.getSelectedItem().toString()); try { saveConfigProperties(); } catch (IOException ex) { Logger.getLogger(SettingsBase.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_buttonOkActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton buttonOk; private javax.swing.JComboBox comboBoxLanguage; private javax.swing.JComboBox comboBoxTheme; private javax.swing.JLabel labelLanguage; private javax.swing.JLabel labelTheme; private javax.swing.JLabel labelTitle; // End of variables declaration//GEN-END:variables }
package info.tregmine.database.db; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.Map; import org.apache.commons.dbcp.BasicDataSource; import org.bukkit.configuration.file.FileConfiguration; import com.mysql.jdbc.exceptions.jdbc4.CommunicationsException; import info.tregmine.Tregmine; import info.tregmine.database.DAOException; import info.tregmine.database.IContext; import info.tregmine.database.IContextFactory; public class DBContextFactory implements IContextFactory { private BasicDataSource ds; private Map<String, LoggingConnection.LogEntry> queryLog; private Tregmine plugin; private String driver; private String url; private String user; private String password; public DBContextFactory(FileConfiguration config, Tregmine instance) { queryLog = new HashMap<>(); String driver = config.getString("db.driver"); if (driver == null) { driver = "com.mysql.jdbc.Driver"; } try { Class.forName(driver).newInstance(); } catch (ClassNotFoundException ex) { throw new RuntimeException(ex); } catch (IllegalAccessException ex) { throw new RuntimeException(ex); } catch (InstantiationException ex) { throw new RuntimeException(ex); } String user = config.getString("db.user"); String password = config.getString("db.password"); String url = config.getString("db.url"); ds = new BasicDataSource(); ds.setDriverClassName(driver); ds.setUrl(url); ds.setUsername(user); ds.setPassword(password); ds.setMaxActive(5); ds.setMaxIdle(5); ds.setDefaultAutoCommit(true); this.driver = driver; this.url = url; this.user = user; this.password = password; this.plugin = instance; } public void regenerate() throws DAOException{ try{ ds.close(); ds = null; ds = new BasicDataSource(); ds.setDriverClassName(driver); ds.setUrl(url); ds.setUsername(user); ds.setPassword(password); ds.setMaxActive(5); ds.setMaxIdle(5); ds.setDefaultAutoCommit(true); createTime = System.currentTimeMillis(); }catch(SQLException e){ throw new DAOException(e); } } @Override public IContext createContext() throws DAOException { try { // It's the responsibility of the context to make sure that the // connection is correctly closed Connection conn = ds.getConnection(); try (Statement stmt = conn.createStatement()) { stmt.execute("SET NAMES latin1"); } return new DBContext(new LoggingConnection(conn, queryLog), plugin); } catch (SQLException e) { if(e.getMessage().toLowerCase().contains("communications link failure")){ this.plugin.setReconnecting(true); System.out.println(this.plugin.kickAll(ChatColor.RED + "Connection to the database was lost!\nPlease reconnect in a few moments.") + " players were ejected from the server."); regenerate(); Connection conn; try { conn = ds.getConnection(); try (Statement stmt = conn.createStatement()) { stmt.execute("SET NAMES latin1"); } this.plugin.setReconnecting(false); return new DBContext(new LoggingConnection(conn, queryLog), plugin); } catch (SQLException e1) { // Giving up re-attempts. e1.printStackTrace(); System.out.println("Two failed attempts to connect to the server. Whatever."); return null; } } throw new DAOException(e); } } public Map<String, LoggingConnection.LogEntry> getLog() { return queryLog; } }
package org.jsoup.select; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.junit.Test; import static org.junit.Assert.*; /** * Tests that the selector selects correctly. * * @author Jonathan Hedley, jonathan@hedley.net */ public class SelectorTest { @Test public void testByTag() { Elements els = Jsoup.parse("<div id=1><div id=2><p>Hello</p></div></div><div id=3>").select("div"); assertEquals(3, els.size()); assertEquals("1", els.get(0).id()); assertEquals("2", els.get(1).id()); assertEquals("3", els.get(2).id()); Elements none = Jsoup.parse("<div id=1><div id=2><p>Hello</p></div></div><div id=3>").select("span"); assertEquals(0, none.size()); } @Test public void testById() { Elements els = Jsoup.parse("<div><p id=foo>Hello</p><p id=foo>Foo two!</p></div>").select("#foo"); assertEquals(2, els.size()); assertEquals("Hello", els.get(0).text()); assertEquals("Foo two!", els.get(1).text()); Elements none = Jsoup.parse("<div id=1></div>").select("#foo"); assertEquals(0, none.size()); } @Test public void testByClass() { Elements els = Jsoup.parse("<p id=0 class='one two'><p id=1 class='one'><p id=2 class='two'>").select("p.one"); assertEquals(2, els.size()); assertEquals("0", els.get(0).id()); assertEquals("1", els.get(1).id()); Elements none = Jsoup.parse("<div class='one'></div>").select(".foo"); assertEquals(0, none.size()); Elements els2 = Jsoup.parse("<div class='One-Two'></div>").select(".one-two"); assertEquals(1, els2.size()); } @Test public void testByAttribute() { String h = "<div Title=Foo /><div Title=Bar /><div Style=Qux /><div title=Bam /><div title=SLAM /><div />"; Document doc = Jsoup.parse(h); Elements withTitle = doc.select("[title]"); assertEquals(4, withTitle.size()); Elements foo = doc.select("[title=foo]"); assertEquals(1, foo.size()); Elements not = doc.select("div[title!=bar]"); assertEquals(5, not.size()); assertEquals("Foo", not.first().attr("title")); Elements starts = doc.select("[title^=ba]"); assertEquals(2, starts.size()); assertEquals("Bar", starts.first().attr("title")); assertEquals("Bam", starts.last().attr("title")); Elements ends = doc.select("[title$=am]"); assertEquals(2, ends.size()); assertEquals("Bam", ends.first().attr("title")); assertEquals("SLAM", ends.last().attr("title")); Elements contains = doc.select("[title*=a]"); assertEquals(3, contains.size()); assertEquals("Bar", contains.first().attr("title")); assertEquals("SLAM", contains.last().attr("title")); } @Test public void testNamespacedTag() { Document doc = Jsoup.parse("<div><abc:def id=1>Hello</abc:def></div> <abc:def class=bold id=2>There</abc:def>"); Elements byTag = doc.select("abc|def"); assertEquals(2, byTag.size()); assertEquals("1", byTag.first().id()); assertEquals("2", byTag.last().id()); Elements byAttr = doc.select(".bold"); assertEquals(1, byAttr.size()); assertEquals("2", byAttr.last().id()); Elements byTagAttr = doc.select("abc|def.bold"); assertEquals(1, byTagAttr.size()); assertEquals("2", byTagAttr.last().id()); Elements byContains = doc.select("abc|def:contains(e)"); assertEquals(2, byContains.size()); assertEquals("1", byContains.first().id()); assertEquals("2", byContains.last().id()); } @Test public void testByAttributeStarting() { Document doc = Jsoup.parse("<div id=1 data-name=jsoup>Hello</div><p data-val=5 id=2>There</p><p id=3>No</p>"); Elements withData = doc.select("[^data-]"); assertEquals(2, withData.size()); assertEquals("1", withData.first().id()); assertEquals("2", withData.last().id()); withData = doc.select("p[^data-]"); assertEquals(1, withData.size()); assertEquals("2", withData.first().id()); } @Test public void testByAttributeRegex() { Document doc = Jsoup.parse("<p><img src=foo.png id=1><img src=bar.jpg id=2><img src=qux.JPEG id=3><img src=old.gif><img></p>"); Elements imgs = doc.select("img[src~=(?i)\\.(png|jpe?g)]"); assertEquals(3, imgs.size()); assertEquals("1", imgs.get(0).id()); assertEquals("2", imgs.get(1).id()); assertEquals("3", imgs.get(2).id()); } @Test public void testByAttributeRegexCharacterClass() { Document doc = Jsoup.parse("<p><img src=foo.png id=1><img src=bar.jpg id=2><img src=qux.JPEG id=3><img src=old.gif id=4></p>"); Elements imgs = doc.select("img[src~=[o]]"); assertEquals(2, imgs.size()); assertEquals("1", imgs.get(0).id()); assertEquals("4", imgs.get(1).id()); } @Test public void testByAttributeRegexCombined() { Document doc = Jsoup.parse("<div><table class=x><td>Hello</td></table></div>"); Elements els = doc.select("div table[class~=x|y]"); assertEquals(1, els.size()); assertEquals("Hello", els.text()); } @Test public void testCombinedWithContains() { Document doc = Jsoup.parse("<p id=1>One</p><p>Two +</p><p>Three +</p>"); Elements els = doc.select("p#1 + :contains(+)"); assertEquals(1, els.size()); assertEquals("Two +", els.text()); assertEquals("p", els.first().tagName()); } @Test public void testAllElements() { String h = "<div><p>Hello</p><p><b>there</b></p></div>"; Document doc = Jsoup.parse(h); Elements allDoc = doc.select("*"); Elements allUnderDiv = doc.select("div *"); assertEquals(8, allDoc.size()); assertEquals(3, allUnderDiv.size()); assertEquals("p", allUnderDiv.first().tagName()); } @Test public void testAllWithClass() { String h = "<p class=first>One<p class=first>Two<p>Three"; Document doc = Jsoup.parse(h); Elements ps = doc.select("*.first"); assertEquals(2, ps.size()); } @Test public void testGroupOr() { String h = "<div title=foo /><div title=bar /><div /><p></p><img /><span title=qux>"; Document doc = Jsoup.parse(h); Elements els = doc.select("p,div,[title]"); assertEquals(5, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("foo", els.get(0).attr("title")); assertEquals("div", els.get(1).tagName()); assertEquals("bar", els.get(1).attr("title")); assertEquals("div", els.get(2).tagName()); assertTrue(els.get(2).attr("title").length() == 0); // missing attributes come back as empty string assertFalse(els.get(2).hasAttr("title")); assertEquals("p", els.get(3).tagName()); assertEquals("span", els.get(4).tagName()); } @Test public void testGroupOrAttribute() { String h = "<div id=1 /><div id=2 /><div title=foo /><div title=bar />"; Elements els = Jsoup.parse(h).select("[id],[title=foo]"); assertEquals(3, els.size()); assertEquals("1", els.get(0).id()); assertEquals("2", els.get(1).id()); assertEquals("foo", els.get(2).attr("title")); } @Test public void descendant() { String h = "<div class=head><p class=first>Hello</p><p>There</p></div><p>None</p>"; Document doc = Jsoup.parse(h); Elements els = doc.select(".head p"); assertEquals(2, els.size()); assertEquals("Hello", els.get(0).text()); assertEquals("There", els.get(1).text()); Elements p = doc.select("p.first"); assertEquals(1, p.size()); assertEquals("Hello", p.get(0).text()); Elements empty = doc.select("p .first"); // self, not descend, should not match assertEquals(0, empty.size()); } @Test public void and() { String h = "<div id=1 class='foo bar' title=bar name=qux><p class=foo title=bar>Hello</p></div"; Document doc = Jsoup.parse(h); Elements div = doc.select("div.foo"); assertEquals(1, div.size()); assertEquals("div", div.first().tagName()); Elements p = doc.select("div .foo"); // space indicates like "div *.foo" assertEquals(1, p.size()); assertEquals("p", p.first().tagName()); Elements div2 = doc.select("div#1.foo.bar[title=bar][name=qux]"); // very specific! assertEquals(1, div2.size()); assertEquals("div", div2.first().tagName()); Elements p2 = doc.select("div *.foo"); // space indicates like "div *.foo" assertEquals(1, p2.size()); assertEquals("p", p2.first().tagName()); } @Test public void deeperDescendant() { String h = "<div class=head><p><span class=first>Hello</div><div class=head><p class=first><span>Another</span><p>Again</div>"; Elements els = Jsoup.parse(h).select("div p .first"); assertEquals(1, els.size()); assertEquals("Hello", els.first().text()); assertEquals("span", els.first().tagName()); } @Test public void parentChildElement() { String h = "<div id=1><div id=2><div id = 3></div></div></div><div id=4></div>"; Document doc = Jsoup.parse(h); Elements divs = doc.select("div > div"); assertEquals(2, divs.size()); assertEquals("2", divs.get(0).id()); // 2 is child of 1 assertEquals("3", divs.get(1).id()); // 3 is child of 2 Elements div2 = doc.select("div#1 > div"); assertEquals(1, div2.size()); assertEquals("2", div2.get(0).id()); } @Test public void parentWithClassChild() { String h = "<h1 class=foo><a href=1 /></h1><h1 class=foo><a href=2 class=bar /></h1><h1><a href=3 /></h1>"; Document doc = Jsoup.parse(h); Elements allAs = doc.select("h1 > a"); assertEquals(3, allAs.size()); assertEquals("a", allAs.first().tagName()); Elements fooAs = doc.select("h1.foo > a"); assertEquals(2, fooAs.size()); assertEquals("a", fooAs.first().tagName()); Elements barAs = doc.select("h1.foo > a.bar"); assertEquals(1, barAs.size()); } @Test public void parentChildStar() { String h = "<div id=1><p>Hello<p><b>there</b></p></div><div id=2><span>Hi</span></div>"; Document doc = Jsoup.parse(h); Elements divChilds = doc.select("div > *"); assertEquals(3, divChilds.size()); assertEquals("p", divChilds.get(0).tagName()); assertEquals("p", divChilds.get(1).tagName()); assertEquals("span", divChilds.get(2).tagName()); } @Test public void multiChildDescent() { String h = "<div id=foo><h1 class=bar><a href=http://example.com/>One</a></h1></div>"; Document doc = Jsoup.parse(h); Elements els = doc.select("div#foo > h1.bar > a[href*=example]"); assertEquals(1, els.size()); assertEquals("a", els.first().tagName()); } @Test public void caseInsensitive() { String h = "<dIv tItle=bAr><div>"; // mixed case so a simple toLowerCase() on value doesn't catch Document doc = Jsoup.parse(h); assertEquals(2, doc.select("DIV").size()); assertEquals(1, doc.select("DIV[TITLE]").size()); assertEquals(1, doc.select("DIV[TITLE=BAR]").size()); assertEquals(0, doc.select("DIV[TITLE=BARBARELLA").size()); } @Test public void adjacentSiblings() { String h = "<ol><li>One<li>Two<li>Three</ol>"; Document doc = Jsoup.parse(h); Elements sibs = doc.select("li + li"); assertEquals(2, sibs.size()); assertEquals("Two", sibs.get(0).text()); assertEquals("Three", sibs.get(1).text()); } @Test public void adjacentSiblingsWithId() { String h = "<ol><li id=1>One<li id=2>Two<li id=3>Three</ol>"; Document doc = Jsoup.parse(h); Elements sibs = doc.select("li#1 + li#2"); assertEquals(1, sibs.size()); assertEquals("Two", sibs.get(0).text()); } @Test public void notAdjacent() { String h = "<ol><li id=1>One<li id=2>Two<li id=3>Three</ol>"; Document doc = Jsoup.parse(h); Elements sibs = doc.select("li#1 + li#3"); assertEquals(0, sibs.size()); } @Test public void mixCombinator() { String h = "<div class=foo><ol><li>One<li>Two<li>Three</ol></div>"; Document doc = Jsoup.parse(h); Elements sibs = doc.select("body > div.foo li + li"); assertEquals(2, sibs.size()); assertEquals("Two", sibs.get(0).text()); assertEquals("Three", sibs.get(1).text()); } @Test public void mixCombinatorGroup() { String h = "<div class=foo><ol><li>One<li>Two<li>Three</ol></div>"; Document doc = Jsoup.parse(h); Elements els = doc.select(".foo > ol, ol > li + li"); assertEquals(3, els.size()); assertEquals("ol", els.get(0).tagName()); assertEquals("Two", els.get(1).text()); assertEquals("Three", els.get(2).text()); } @Test public void generalSiblings() { String h = "<ol><li id=1>One<li id=2>Two<li id=3>Three</ol>"; Document doc = Jsoup.parse(h); Elements els = doc.select("#1 ~ #3"); assertEquals(1, els.size()); assertEquals("Three", els.first().text()); } // for http://github.com/jhy/jsoup/issues#issue/10 @Test public void testCharactersInIdAndClass() { // using CSS spec for identifiers (id and class): a-z0-9, -, _. NOT . (which is OK in html spec, but not css) String h = "<div><p id='a1-foo_bar'>One</p><p class='b2-qux_bif'>Two</p></div>"; Document doc = Jsoup.parse(h); Element el1 = doc.getElementById("a1-foo_bar"); assertEquals("One", el1.text()); Element el2 = doc.getElementsByClass("b2-qux_bif").first(); assertEquals("Two", el2.text()); Element el3 = doc.select("#a1-foo_bar").first(); assertEquals("One", el3.text()); Element el4 = doc.select(".b2-qux_bif").first(); assertEquals("Two", el4.text()); } // for http://github.com/jhy/jsoup/issues#issue/13 @Test public void testSupportsLeadingCombinator() { String h = "<div><p><span>One</span><span>Two</span></p></div>"; Document doc = Jsoup.parse(h); Element p = doc.select("div > p").first(); Elements spans = p.select("> span"); assertEquals(2, spans.size()); assertEquals("One", spans.first().text()); // make sure doesn't get nested h = "<div id=1><div id=2><div id=3></div></div></div>"; doc = Jsoup.parse(h); Element div = doc.select("div").select(" > div").first(); assertEquals("2", div.id()); } @Test public void testPseudoLessThan() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p><p>Three</>p></div><div><p>Four</p>"); Elements ps = doc.select("div p:lt(2)"); assertEquals(3, ps.size()); assertEquals("One", ps.get(0).text()); assertEquals("Two", ps.get(1).text()); assertEquals("Four", ps.get(2).text()); } @Test public void testPseudoGreaterThan() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p><p>Three</p></div><div><p>Four</p>"); Elements ps = doc.select("div p:gt(0)"); assertEquals(2, ps.size()); assertEquals("Two", ps.get(0).text()); assertEquals("Three", ps.get(1).text()); } @Test public void testPseudoEquals() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p><p>Three</>p></div><div><p>Four</p>"); Elements ps = doc.select("div p:eq(0)"); assertEquals(2, ps.size()); assertEquals("One", ps.get(0).text()); assertEquals("Four", ps.get(1).text()); Elements ps2 = doc.select("div:eq(0) p:eq(0)"); assertEquals(1, ps2.size()); assertEquals("One", ps2.get(0).text()); assertEquals("p", ps2.get(0).tagName()); } @Test public void testPseudoBetween() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p><p>Three</>p></div><div><p>Four</p>"); Elements ps = doc.select("div p:gt(0):lt(2)"); assertEquals(1, ps.size()); assertEquals("Two", ps.get(0).text()); } @Test public void testPseudoCombined() { Document doc = Jsoup.parse("<div class='foo'><p>One</p><p>Two</p></div><div><p>Three</p><p>Four</p></div>"); Elements ps = doc.select("div.foo p:gt(0)"); assertEquals(1, ps.size()); assertEquals("Two", ps.get(0).text()); } @Test public void testPseudoHas() { Document doc = Jsoup.parse("<div id=0><p><span>Hello</span></p></div> <div id=1><span class=foo>There</span></div> <div id=2><p>Not</p></div>"); Elements divs1 = doc.select("div:has(span)"); assertEquals(2, divs1.size()); assertEquals("0", divs1.get(0).id()); assertEquals("1", divs1.get(1).id()); Elements divs2 = doc.select("div:has([class]"); assertEquals(1, divs2.size()); assertEquals("1", divs2.get(0).id()); Elements divs3 = doc.select("div:has(span, p)"); assertEquals(3, divs3.size()); assertEquals("0", divs3.get(0).id()); assertEquals("1", divs3.get(1).id()); assertEquals("2", divs3.get(2).id()); Elements els1 = doc.body().select(":has(p)"); assertEquals(3, els1.size()); // body, div, dib assertEquals("body", els1.first().tagName()); assertEquals("0", els1.get(1).id()); assertEquals("2", els1.get(2).id()); } @Test public void testNestedHas() { Document doc = Jsoup.parse("<div><p><span>One</span></p></div> <div><p>Two</p></div>"); Elements divs = doc.select("div:has(p:has(span))"); assertEquals(1, divs.size()); assertEquals("One", divs.first().text()); // test matches in has divs = doc.select("div:has(p:matches((?i)two))"); assertEquals(1, divs.size()); assertEquals("div", divs.first().tagName()); assertEquals("Two", divs.first().text()); // test contains in has divs = doc.select("div:has(p:contains(two))"); assertEquals(1, divs.size()); assertEquals("div", divs.first().tagName()); assertEquals("Two", divs.first().text()); } @Test public void testPseudoContains() { Document doc = Jsoup.parse("<div><p>The Rain.</p> <p class=light>The <i>rain</i>.</p> <p>Rain, the.</p></div>"); Elements ps1 = doc.select("p:contains(Rain)"); assertEquals(3, ps1.size()); Elements ps2 = doc.select("p:contains(the rain)"); assertEquals(2, ps2.size()); assertEquals("The Rain.", ps2.first().html()); assertEquals("The <i>rain</i>.", ps2.last().html()); Elements ps3 = doc.select("p:contains(the Rain):has(i)"); assertEquals(1, ps3.size()); assertEquals("light", ps3.first().className()); Elements ps4 = doc.select(".light:contains(rain)"); assertEquals(1, ps4.size()); assertEquals("light", ps3.first().className()); Elements ps5 = doc.select(":contains(rain)"); assertEquals(8, ps5.size()); // html, body, div,... } @Test public void testPsuedoContainsWithParentheses() { Document doc = Jsoup.parse("<div><p id=1>This (is good)</p><p id=2>This is bad)</p>"); Elements ps1 = doc.select("p:contains(this (is good))"); assertEquals(1, ps1.size()); assertEquals("1", ps1.first().id()); Elements ps2 = doc.select("p:contains(this is bad\\))"); assertEquals(1, ps2.size()); assertEquals("2", ps2.first().id()); } @Test public void containsOwn() { Document doc = Jsoup.parse("<p id=1>Hello <b>there</b> now</p>"); Elements ps = doc.select("p:containsOwn(Hello now)"); assertEquals(1, ps.size()); assertEquals("1", ps.first().id()); assertEquals(0, doc.select("p:containsOwn(there)").size()); } @Test public void testMatches() { Document doc = Jsoup.parse("<p id=1>The <i>Rain</i></p> <p id=2>There are 99 bottles.</p> <p id=3>Harder (this)</p> <p id=4>Rain</p>"); Elements p1 = doc.select("p:matches(The rain)"); // no match, case sensitive assertEquals(0, p1.size()); Elements p2 = doc.select("p:matches((?i)the rain)"); // case insense. should include root, html, body assertEquals(1, p2.size()); assertEquals("1", p2.first().id()); Elements p4 = doc.select("p:matches((?i)^rain$)"); // bounding assertEquals(1, p4.size()); assertEquals("4", p4.first().id()); Elements p5 = doc.select("p:matches(\\d+)"); assertEquals(1, p5.size()); assertEquals("2", p5.first().id()); Elements p6 = doc.select("p:matches(\\w+\\s+\\(\\w+\\))"); // test bracket matching assertEquals(1, p6.size()); assertEquals("3", p6.first().id()); Elements p7 = doc.select("p:matches((?i)the):has(i)"); // multi assertEquals(1, p7.size()); assertEquals("1", p7.first().id()); } @Test public void matchesOwn() { Document doc = Jsoup.parse("<p id=1>Hello <b>there</b> now</p>"); Elements p1 = doc.select("p:matchesOwn((?i)hello now)"); assertEquals(1, p1.size()); assertEquals("1", p1.first().id()); assertEquals(0, doc.select("p:matchesOwn(there)").size()); } @Test public void testRelaxedTags() { Document doc = Jsoup.parse("<abc_def id=1>Hello</abc_def> <abc-def id=2>There</abc-def>"); Elements el1 = doc.select("abc_def"); assertEquals(1, el1.size()); assertEquals("1", el1.first().id()); Elements el2 = doc.select("abc-def"); assertEquals(1, el2.size()); assertEquals("2", el2.first().id()); } @Test public void notParas() { Document doc = Jsoup.parse("<p id=1>One</p> <p>Two</p> <p><span>Three</span></p>"); Elements el1 = doc.select("p:not([id=1])"); assertEquals(2, el1.size()); assertEquals("Two", el1.first().text()); assertEquals("Three", el1.last().text()); Elements el2 = doc.select("p:not(:has(span))"); assertEquals(2, el2.size()); assertEquals("One", el2.first().text()); assertEquals("Two", el2.last().text()); } @Test public void notAll() { Document doc = Jsoup.parse("<p>Two</p> <p><span>Three</span></p>"); Elements el1 = doc.body().select(":not(p)"); // should just be the span assertEquals(2, el1.size()); assertEquals("body", el1.first().tagName()); assertEquals("span", el1.last().tagName()); } @Test public void notClass() { Document doc = Jsoup.parse("<div class=left>One</div><div class=right id=1><p>Two</p></div>"); Elements el1 = doc.select("div:not(.left)"); assertEquals(1, el1.size()); assertEquals("1", el1.first().id()); } @Test public void handlesCommasInSelector() { Document doc = Jsoup.parse("<p name='1,2'>One</p><div>Two</div><ol><li>123</li><li>Text</li></ol>"); Elements ps = doc.select("[name=1,2]"); assertEquals(1, ps.size()); Elements containers = doc.select("div, li:matches([0-9,]+)"); assertEquals(2, containers.size()); assertEquals("div", containers.get(0).tagName()); assertEquals("li", containers.get(1).tagName()); assertEquals("123", containers.get(1).text()); } @Test public void selectSupplementaryCharacter() { String s = new String(Character.toChars(135361)); Document doc = Jsoup.parse("<div k" + s + "='" + s + "'>^" + s +"$/div>"); assertEquals("div", doc.select("div[k" + s + "]").first().tagName()); assertEquals("div", doc.select("div:containsOwn(" + s + ")").first().tagName()); } }
package jAudioFeatureExtractor.ACE.DataTypes; import java.io.File; import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Set; import javax.swing.JOptionPane; import jAudioFeatureExtractor.Aggregators.ZernikeMoments; import jAudioFeatureExtractor.DataModel; import jAudioFeatureExtractor.Aggregators.Aggregator; import jAudioFeatureExtractor.DataTypes.RecordingInfo; import jAudioFeatureExtractor.ModelListener; import jAudioFeatureExtractor.jAudioTools.AudioSamples; /** * Batch * * Batch is the class used to represent an execution unit including both files and settings in jAudio. All settings * have defaults except the input data. This requires setRecordings(File[]) or setRecordings(RecordingInfo[]) to be * executed first. By default, Batch.execute() is a blocking calculation. For non-blocking, see CommandLineThread * for the simplist way to get non-blocking capabailities. * * @author Daniel McEnnis */ public class Batch implements Serializable { static final long serialVersionUID = 1; String name = "Batch"; RecordingInfo[] recording = new RecordingInfo[0]; int windowSize=1024; double windowOverlap=0.0; double samplingRate=44100.0; boolean normalise=true; boolean perWindow=false; boolean overall=true; String destinationFK = null; String destinationFV = null; int outputType; transient DataModel dm_ ; HashMap<String, Boolean> activated = new HashMap<String, Boolean>(); HashMap<String, String[]> attributes = new HashMap<String, String[]>(); String[] aggregatorNames; String[][] aggregatorFeatures; String[][] aggregatorParameters; public Batch(){ init("features.xml",null); } public Batch(String features, ModelListener l){ init(features,l); } protected void init(String features, ModelListener l){ dm_ = new DataModel(features,l); activated.put("ConstantQ",true); aggregatorNames = new String[]{"Zernike Moments"}; aggregatorFeatures = new String[][]{new String[]{"ConstantQ"}}; aggregatorParameters = new String[][]{new String[]{"8"}}; } /** * Set the data model against which this batch is executed. * * @param dm * Context of this batch. */ public void setDataModel(DataModel dm) { dm_ = dm; } /** * Execute this batch by first setting the context ass specified in the * batch, then executing using the data model. * * @throws Exception */ public void execute() throws Exception { applyAttributes(); dm_.extract(windowSize, windowOverlap, samplingRate, normalise, perWindow, overall, recording, outputType); } /** * Sets the recordings that this batch will load and execute. * * @param files * recordings which are to be scheduled for porcessing. * @throws Exception */ public void setRecordings(File[] files) throws Exception { recording = new RecordingInfo[files.length]; // Go through the files one by one for (int i = 0; i < files.length; i++) { // Verify that the file exists if (files[i].exists()) { try { // Generate a RecordingInfo object for the loaded file recording[i] = new RecordingInfo(files[i].getName(), files[i].getPath(), null, false); } catch (Exception e) { recording = null; throw e; } } else { recording = null; throw new Exception("The selected file " + files[i].getName() + " does not exist."); } } } /** * Sets the attributes for how the features are to be extracted when * executed. * * @param windowSize * Size of the analysis window in samples. * @param windowOverlap * Percent overlap of the windows. Must be greater than or equal * to 0 and less than 1. * @param samplingRate * number of samples per second of audio. * @param normalise * should the files be normalised before execution. * @param perWindow * should features be extracted for each window in each file. * @param overall * should overall features be extracted for each files. * @param outputType * what format should the extracted features be saved in. */ public void setSettings(int windowSize, double windowOverlap, double samplingRate, boolean normalise, boolean perWindow, boolean overall, int outputType) { this.windowSize = windowSize; this.windowOverlap = windowOverlap; this.samplingRate = samplingRate; this.normalise = normalise; this.perWindow = perWindow; this.overall = overall; this.outputType = outputType; } /** * Sets where the extracted features should be stored. * * @param FK * Location where feature descriptions should be stored. * @param FV * Location where extracted features should be stored. */ public void setDestination(String FK, String FV) { destinationFK = FK; destinationFV = FV; } /** * Sets which features are active and the parameters of these features. * * @param activated * Which features are to be extracted. * @param attributes * settings of parameters of these features. */ public void setFeatures(HashMap<String, Boolean> activated, HashMap<String, String[]> attributes) { this.activated = activated; this.attributes = attributes; } /** * Returns the name of this batch. * * @return name assigned to this batch. */ public String getName() { return name; } /** * Sets the name of this batch. This name must be unique. * * @param name * Name of this batch. */ public void setName(String name) { this.name = name; } /** * Apply the stored attributes against the current feature list. * * @throws Exception */ private void applyAttributes() throws Exception { for (int i = 0; i < dm_.features.length; ++i) { String name = dm_.features[i].getFeatureDefinition().name; if (attributes.containsKey(name)) { dm_.defaults[i] = activated.get(name); String[] tmp = attributes.get(name); for (int j = 0; j < tmp.length; ++j) { dm_.features[i].setElement(j, tmp[j]); } }else{ dm_.defaults[i] = false; } } LinkedList<Aggregator> aggregatorList = new LinkedList<Aggregator>(); if(aggregatorNames != null) { for (int i = 0; i < aggregatorNames.length; ++i) { Aggregator tmp; if (dm_.aggregatorMap.containsKey(aggregatorNames[i])) { tmp = (Aggregator) dm_.aggregatorMap.get(aggregatorNames[i]).clone(); // if(!tmp.getAggregatorDefinition().generic){ tmp.setParameters(aggregatorFeatures[i], aggregatorParameters[i]); aggregatorList.add(tmp); } else { throw new Exception("Aggregator " + aggregatorNames[i] + " is not known. Check the spelling?"); } } } if(overall && (aggregatorList.size()==0)){ throw new Exception("Attempting to get overall stats without specifying any aggregators to create it"); } dm_.aggregators = aggregatorList.toArray(new Aggregator[]{}); } /** * Returns the expanded list of aggregators that would be executed if execute() were called. This returns * an empty array if either aggregators or features to be extracted have not been seet yet. * * @return array of aggregators scheduled to execute */ public Aggregator[] getAggregator() throws Exception{ LinkedList<Aggregator> aggregatorList = new LinkedList<Aggregator>(); if(aggregatorNames != null){ for(int i=0;i<aggregatorNames.length;++i){ Aggregator tmp = (Aggregator)dm_.aggregatorMap.get(aggregatorNames[i]).clone(); // if(!tmp.getAggregatorDefinition().generic){ tmp.setParameters(aggregatorFeatures[i],aggregatorParameters[i]); aggregatorList.add(tmp); } } if(overall && (aggregatorList.size()==0)){ throw new Exception("Attempting to get overall stats without specifying any aggregators to create it"); } return aggregatorList.toArray(new Aggregator[]{}); } /** * Output this batch in XML format. * * @return String contains a complete batch XML file. */ public String outputXML() { StringBuffer ret = new StringBuffer(); String sep = System.getProperty("line.separator"); ret.append("\t<batch ID=\"").append(name).append("\">").append(sep); ret.append("\t\t<fileSet>").append(sep); for (int i = 0; i < recording.length; ++i) { ret.append("\t\t\t<file>").append(recording[i].file_path).append( "</file>").append(sep); } ret.append("\t\t</fileSet>").append(sep); ret.append("\t\t<settings>").append(sep); ret.append("\t\t\t<windowSize>").append(windowSize).append( "</windowSize>").append(sep); ret.append("\t\t\t<windowOverlap>").append(windowOverlap).append( "</windowOverlap>").append(sep); ret.append("\t\t\t<samplingRate>").append(samplingRate).append( "</samplingRate>").append(sep); ret.append("\t\t\t<normalise>").append(normalise) .append("</normalise>").append(sep); ret.append("\t\t\t<perWindowStats>").append(perWindow).append( "</perWindowStats>").append(sep); ret.append("\t\t\t<overallStats>").append(overall).append( "</overallStats>").append(sep); if (outputType == 0) { ret.append("\t\t\t<outputType>ACE</outputType>").append(sep); } else { ret.append("\t\t\t<outputType>ARFF</outputType>").append(sep); } Set s = attributes.entrySet(); for (Iterator<Map.Entry<String, String[]>> iterator = s.iterator(); iterator .hasNext();) { Map.Entry<String, String[]> i = iterator.next(); String name = i.getKey(); String[] att = i.getValue(); ret.append("\t\t\t<feature>").append(sep); ret.append("\t\t\t\t<name>").append(name).append("</name>").append( sep); ret.append("\t\t\t\t<active>").append(activated.get(name)).append( "</active>").append(sep); for (int j = 0; j < att.length; ++j) { ret.append("\t\t\t\t<attribute>").append(att[j]).append( "</attribute>").append(sep); } ret.append("\t\t\t</feature>").append(sep); } for(int i=0;i<aggregatorNames.length;++i){ ret.append("\t\t\t<aggregator>").append(sep); ret.append("\t\t\t\t<aggregatorName>").append(aggregatorNames[i]).append("</aggregatorName>").append(sep); if(aggregatorFeatures[i] != null){ for(int j=0;j<aggregatorFeatures[i].length;++j){ ret.append("\t\t\t\t<aggregatorFeature>").append(aggregatorFeatures[i][j]).append("</aggregatorFeature>").append(sep); } } if(aggregatorParameters[i]!= null){ for(int j=0;j<aggregatorParameters[i].length;++j){ ret.append("\t\t\t\t<aggregatorAttribute>").append(aggregatorParameters[i][j]).append("</aggregatorAttribute>").append(sep); } } ret.append("\t\t\t</aggregator>").append(sep); } ret.append("\t\t</settings>").append(sep); ret.append("\t\t<destination>").append(destinationFK).append( "</destination>").append(sep); ret.append("\t\t<destination>").append(destinationFV).append( "</destination>").append(sep); ret.append("\t</batch>").append(sep); return ret.toString(); } /** * apply this batch against info needed for a datamodel so that it can be * executed. * * @param recording * list of files to be analyzed * @param windowSize * size of the analysis window in samples * @param windowOverlap * percent overlap as a value between 0 and 1. * @param samplingRate * number of samples per second * @param normalise * should the file be normalized before execution * @param perWindow * should features be extracted on a window bby window basis * @param overall * should global features be extracted * @param destinationFK * location of the feature declaration file * @param destinationFV * location where extracted features should be stored * @param outputType * what output format should extracted features be stored in. */ public void applySettings(RecordingInfo[][] recording, int[] windowSize, double[] windowOverlap, double[] samplingRate, boolean[] normalise, boolean[] perWindow, boolean[] overall, String[] destinationFK, String[] destinationFV, int[] outputType) { try { applyAttributes(); dm_.featureDefinitions = new FeatureDefinition[dm_.features.length]; for (int i = 0; i < dm_.featureDefinitions.length; ++i) { dm_.featureDefinitions[i] = dm_.features[i] .getFeatureDefinition(); } dm_.recordingInfo = this.recording; } catch (Exception e) { System.err.println("INTERNAL ERROR: " + e.getMessage()); e.printStackTrace(); } recording[0] = this.recording; windowSize[0] = this.windowSize; windowOverlap[0] = this.windowOverlap; samplingRate[0] = this.samplingRate; normalise[0] = this.normalise; perWindow[0] = this.perWindow; overall[0] = this.overall; destinationFK[0] = this.destinationFK; destinationFV[0] = this.destinationFV; outputType[0] = this.outputType; } /** * Returns a map of all parameters for all features in the feature set. * * @return map of all feature parameters */ public HashMap<String, String[]> getAttributes() { return attributes; } /** * Returns a map defining which features will appear in the output. * * @return map of features and whether they are scheduled for output or not. */ public HashMap<String, Boolean> getActivated() { return activated; } /** * sets parameter values for all features simultaneously. Exceptions for bad parameters * are thrown on application (i.e. Batch.execute()) not here. * * @retun map of paramter settings. */ public void setAttributes(HashMap<String, String[]> attributes) { this.attributes = attributes; } /** * Returns the location for the XML key file. Null means either a stream set * on the backing DataModel or no key to be outputed (weka format). * * @return location to store the ACE key XML file */ public String getDestinationFK() { return destinationFK; } /** * sets the file location for the ACE key XML file. This location is not * validated until Batch.execute() is run. * * @return location to store the ACE key XML file */ public void setDestinationFK(String destinationFK) { this.destinationFK = destinationFK; } /** * Returns the location of either the location to put the ACE XML data file * or the Weka output file. Null implies stream output. */ public String getDestinationFV() { return destinationFV; } /** * sets the file location for the result file. This location is not * validated until Batch.execute() is run. * * @return location to store the output data file in */ public void setDestinationFV(String destinationFV) { this.destinationFV = destinationFV; } /** * Scheduled to normalise input files before analysis. * * @return are files to be normalised or not on loading */ public boolean isNormalise() { return normalise; } /** * Set or cancel normalisation of input audio files before analysis. * * @return normalise or not */ public void setNormalise(boolean normalise) { this.normalise = normalise; } /** * Get the type of output to be produced * * @return integer representing the output type (by Java constant) */ public int getOutputType() { return outputType; } /** * Set the style of output (Weka, ACE, etc.) * * @return style of output by constant */ public void setOutputType(int outputType) { this.outputType = outputType; } /** * Should aggregated per-file results be generated? * * @return are aggregated per-file results generated */ public boolean isOverall() { return overall; } /** * Should aggregated per-file results be generated? * * @param overall sets whether to output aggregated results or not. */ public void setOverall(boolean overall) { this.overall = overall; } /** * Should per-window results be generated? * * @return are per-window results generated */ public boolean isPerWindow() { return perWindow; } /** * Should per-window results be generated? * * @return overall sets whether to output per-window results or not. */ public void setPerWindow(boolean perWindow) { this.perWindow = perWindow; } /** * Get the sampling rate to which all files will be transformed to whether * or not they are at that rate to begiun with. * * @return analysis sampling rate */ public double getSamplingRate() { return samplingRate; } /** * Set the sampling rate to which all files will be transformed to whether * or not they are at that rate to begiun with. * * @param samplingRate new analysis sample rate */ public void setSamplingRate(double samplingRate) { this.samplingRate = samplingRate; } /** * Gets the number of samples per window that are also present in the previous window * * @return degree of overlap between successive windows */ public double getWindowOverlap() { return windowOverlap; } /** * Sets the number of samples per window that are also present in the previous window * * @param windowOverlap degree of overlap between successive windows */ public void setWindowOverlap(double windowOverlap) { this.windowOverlap = windowOverlap; } /** * Gets the number of samples inside of each analysis window * * @return number of samples per window */ public int getWindowSize() { return windowSize; } /** * Sets the number of samples inside of each analysis window * * @param windowSize number of samples per window */ public void setWindowSize(int windowSize) { this.windowSize = windowSize; } /** * Sets the audio content to be analyzed when execute() is called * whether or not the sources are from a file or not. * * @param recording array of RecordingInfo objects representing independent units of audio data. */ public void setRecording(RecordingInfo[] recording) { this.recording = recording; } /** * Gets the audio content to be analyzed when execute() is called * whether or not the sources are from a file or not. * * @return array of RecordingInfo objects representing independent units of audio data. */ public RecordingInfo[] getRecording() { return recording; } /** * Gets the underlying DataModel this Batch is encapsulating * * @return underlying DataModel */ public DataModel getDataModel() { return dm_; } /** * Sets the aggregators, their parameters, and which features are used by them. Internally * Batch creates the aggregators from the name, sets the features and parameters using * Aggregator.setParameters() from the given content. See Aggregator * for the specific syntax of feature and parameter string arrays. */ public void setAggregators(String[] aggNames, String[][] aggFeatures, String[][] aggParam) { if ((aggNames.length == aggFeatures.length) && (aggFeatures.length == aggParam.length)) { aggregatorNames = aggNames; aggregatorFeatures = aggFeatures; aggregatorParameters = aggParam; } else { System.out .println("INTERNAL ERROR: Parameters are not of the same length - implying differing numbers of aggregators to define:" + aggNames.length + " " + aggFeatures.length + " " + aggParam.length); } } /** * Get an array containing an ordered array of all aggregators. Unlike getAggregator(), this returns the list of * aggregators <b>before</b> the generic aggregators have been expanded with the list of chosen features. * */ public String[] getAggregatorNames(){ return aggregatorNames; } /** * Returns an array of String arrays where the first index is the index of the source aggregator, the second the index of the feature * in the aggregator, and the String value the value of the feature to be included. Only specific aggregators have non-null entries. * * @return array defining all features assigned to each (specific) aggregator. General Aggregators have none set. */ public String[][] getAggregatorFeatures(){ return aggregatorFeatures; } /** * Gets an array of String arrays where the first index is the index of the source aggregator, the second the paramater * in the aggregator, and the String value the value of the parameter to be set. * * @return array defining all features assigned to each (specific) aggregator. General Aggregators have none set. */ public String[][] getAggregatorParameters(){ return aggregatorParameters; } }
package org.orbeon.oxf.test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.dom4j.Document; import org.dom4j.Element; import org.orbeon.exception.OrbeonFormatter; import org.orbeon.oxf.resources.ResourceManager; import org.orbeon.oxf.resources.ResourceManagerWrapper; import org.orbeon.oxf.util.NumberUtils; import org.orbeon.oxf.xml.ForwardingXMLReceiver; import org.orbeon.oxf.xml.TransformerUtils; import org.orbeon.oxf.xml.XPathUtils; import org.orbeon.oxf.xml.dom4j.LocationData; import org.orbeon.oxf.xml.dom4j.LocationDocumentResult; import org.orbeon.oxf.xml.dom4j.LocationDocumentSource; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; import javax.xml.transform.*; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.stream.StreamSource; import java.io.InputStream; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Properties; public class UtilsTest extends TestCase { public UtilsTest(String s) { super(s); } public static TestSuite suite() { TestSuite suite = new TestSuite(); suite.addTest(new UtilsTest("testNumberUtils")); suite.addTest(new UtilsTest("testLocationDocumentSourceResult")); suite.addTest(new UtilsTest("testTransformerWrapper")); return suite; } public void testNumberUtils() { byte[] bytes1 = {(byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc, (byte) 0xde, (byte) 0xf0}; String results1 = "123456789abcdef0"; assertEquals(NumberUtils.toHexString(bytes1), results1); byte[] bytes2 = {(byte) 0x01, (byte) 0x23, (byte) 0x45, (byte) 0x67, (byte) 0x89, (byte) 0xab, (byte) 0xcd, (byte) 0xef}; String results2 = "0123456789abcdef"; assertEquals(NumberUtils.toHexString(bytes2), results2); byte[] bytes3 = {(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00}; String results3 = "0000000000000000"; assertEquals(NumberUtils.toHexString(bytes3), results3); } private ResourceManager setupResourceManager() { // Setup resource manager final Map<String, Object> props = new HashMap<String, Object>(); final Properties properties = System.getProperties(); for (Enumeration e = properties.propertyNames(); e.hasMoreElements();) { String name = (String) e.nextElement(); if (name.startsWith("oxf.resources.")) props.put(name, properties.getProperty(name)); } ResourceManagerWrapper.init(props); return ResourceManagerWrapper.instance(); } public void testLocationDocumentSourceResult() { try { Transformer transformer = TransformerUtils.getIdentityTransformer(); ResourceManager resourceManager = setupResourceManager(); InputStream is = resourceManager.getContentAsStream("/ops/unit-tests/company.xml"); String path = resourceManager.getRealPath("/ops/unit-tests/company.xml"); Source source = new StreamSource(is, path); LocationDocumentResult result = new LocationDocumentResult(); transformer.transform(source, result); Document doc = result.getDocument(); Element firstName = (Element) XPathUtils.selectSingleNode(doc, "//firstname"); assertEquals("Ada", firstName.getTextTrim()); assertEquals(4, ((LocationData) firstName.getData()).line()); source = new LocationDocumentSource(doc); SAXResult saxResult = new SAXResult(new ForwardingXMLReceiver() { Locator locator; StringBuffer buff = new StringBuffer(); boolean foundFirstName = false; public void setDocumentLocator(Locator locator) { this.locator = locator; } public void startElement(String uri, String localname, String qName, Attributes attributes) throws SAXException { if ("firstname".equals(localname)) { assertEquals(4, locator.getLineNumber()); foundFirstName = true; } } public void characters(char[] chars, int start, int length) throws SAXException { if (foundFirstName) buff.append(chars, start, length); } public void endElement(String uri, String localname, String qName) throws SAXException { if ("firstname".equals(localname)) { assertEquals("Ada", buff.toString()); } } }); transformer.transform(source, saxResult); } catch (Exception e) { System.err.println(OrbeonFormatter.format(e)); fail(e.toString()); } } public void testTransformerWrapper() { final String publicProperty = "[public]"; final String privateProperty = "[private]"; final Properties[] privateOutputProperties = new Properties[] { new Properties() }; Transformer transformer = TransformerUtils.testCreateTransformerWrapper(new Transformer() { public void clearParameters() { } public ErrorListener getErrorListener() { return null; } public Properties getOutputProperties() { return privateOutputProperties[0]; } public String getOutputProperty(String name) throws IllegalArgumentException { return (String) privateOutputProperties[0].get(name); } public Object getParameter(String name) { return null; } public URIResolver getURIResolver() { return null; } public void setErrorListener(ErrorListener listener) throws IllegalArgumentException { } public void setOutputProperties(Properties oformat) throws IllegalArgumentException { privateOutputProperties[0] = oformat; } public void setOutputProperty(String name, String value) throws IllegalArgumentException { privateOutputProperties[0].put(name, value); } public void setParameter(String name, Object value) { } public void setURIResolver(URIResolver resolver) { } public void transform(Source xmlSource, Result outputTarget) { } }, publicProperty, privateProperty); // Set individual property transformer.setOutputProperty(publicProperty, "3"); assertEquals(transformer.getOutputProperty(publicProperty), "3"); assertEquals(transformer.getOutputProperties().get(publicProperty), "3"); assertEquals(transformer.getOutputProperty(publicProperty), privateOutputProperties[0].get(privateProperty)); // Set all properties Properties p2 = new Properties(); p2.put(publicProperty, "2"); transformer.setOutputProperties(p2); assertEquals(transformer.getOutputProperty(publicProperty), "2"); assertEquals(transformer.getOutputProperties().get(publicProperty), "2"); assertEquals(transformer.getOutputProperty(publicProperty), privateOutputProperties[0].get(privateProperty)); } }
package org.osiam.client; import com.github.springtestdbunit.DbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseSetup; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.osiam.client.connector.OsiamConnector; import org.osiam.client.exception.ConflictException; import org.osiam.client.oauth.GrantType; import org.osiam.client.oauth.Scope; import org.osiam.client.update.UpdateUser; import org.osiam.resources.scim.Address; import org.osiam.resources.scim.BasicMultiValuedAttribute; import org.osiam.resources.scim.Email; import org.osiam.resources.scim.Entitlement; import org.osiam.resources.scim.Ims; import org.osiam.resources.scim.Name; import org.osiam.resources.scim.PhoneNumber; import org.osiam.resources.scim.Photo; import org.osiam.resources.scim.Role; import org.osiam.resources.scim.User; import org.osiam.resources.scim.GroupRef; import org.osiam.resources.scim.X509Certificate; import org.osiam.resources.type.EmailType; import org.osiam.resources.type.GroupRefType; import org.osiam.resources.type.ImsType; import org.osiam.resources.type.PhoneNumberType; import org.osiam.resources.type.PhotoType; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import java.util.ArrayList; import java.util.List; import java.util.UUID; import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/context.xml") @TestExecutionListeners({DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class}) @DatabaseSetup("/database_seed.xml") public class UpdateUserIT extends AbstractIntegrationTestBase { private String idExistingUser = "7d33bcbe-a54c-43d8-867e-f6146164941e"; private UpdateUser updateUser; private User originalUser; private User returnUser; private User databaseUser; private static String IRRELEVANT = "Irrelevant"; @Test @Ignore ("Ignored because of several bugs in the OSIAM server.") public void delete_multivalue_attributes(){ try{ getOriginalUser("dma"); createUpdateUserWithMultiDeleteFields(); updateUser(); assertTrue(isValuePartOfMultivalueList(Email.class, originalUser.getEmails(), "hsimpson@atom-example.com")); assertFalse(isValuePartOfMultivalueList(Email.class, returnUser.getEmails(), "hsimpson@atom-example.com")); assertTrue(isValuePartOfMultivalueList(PhoneNumber.class, originalUser.getPhoneNumbers(), "0245817964")); assertFalse(isValuePartOfMultivalueList(PhoneNumber.class, returnUser.getPhoneNumbers(), "0245817964")); assertTrue(isValuePartOfMultivalueList(Ims.class, originalUser.getIms(), "ims01")); assertFalse(isValuePartOfMultivalueList(Ims.class, returnUser.getIms(), "ims01")); assertTrue(isValuePartOfMultivalueList(Photo.class, originalUser.getPhotos(), "photo01.jpg")); assertFalse(isValuePartOfMultivalueList(Photo.class,returnUser.getPhotos(), "photo01.jpg")); assertTrue(isValuePartOfMultivalueList(Role.class, originalUser.getRoles(), "role01")); assertFalse(isValuePartOfMultivalueList(Role.class, returnUser.getRoles(), "role01")); assertTrue(isValuePartOfAddressList(originalUser.getAddresses(), "formated address 01")); assertFalse(isValuePartOfAddressList(returnUser.getAddresses(), "formated address 01"));//TODO other address was deleted assertTrue(isValuePartOfMultivalueList(Entitlement.class, originalUser.getEntitlements(), "right2")); // TODO at the second run it will fail assertFalse(isValuePartOfMultivalueList(Entitlement.class, returnUser.getEntitlements(), "right2"));//TODO at the second run it will fail assertTrue(isValuePartOfMultivalueList(GroupRef.class, originalUser.getGroups(), "d30a77eb-d7cf-4cd1-9fb3-cc640ef09578"));//TODO Gruppen werden nicht gespeicher assertFalse(isValuePartOfMultivalueList(GroupRef.class, returnUser.getGroups(), "d30a77eb-d7cf-4cd1-9fb3-cc640ef09578")); //TODO Gruppen werden nicht gespeicher assertTrue(isValuePartOfMultivalueList(X509Certificate.class, originalUser.getX509Certificates(), "certificate01"));//TODO at the second run it will fail assertFalse(isValuePartOfMultivalueList(X509Certificate.class, returnUser.getX509Certificates(), "certificate01"));//TODO at the second run it will fail }finally{ oConnector.deleteUser(idExistingUser, accessToken); } } @Ignore("Return user and database user not consistent yet. Check this always in updateUser() once consistency is reached and delete this test. Also should implement equals on User.") public void compare_returned_user_with_database_user() { try { // create test user getOriginalUser("dma"); // create update user createUpdateUserWithMultiDeleteFields(); // update test user with update user updateUser(); // check consistency of update return value and user in database and expect equality assertTrue(returnUser.equals(databaseUser)); } finally { oConnector.deleteUser(idExistingUser, accessToken); } } @Test @Ignore("Ignored due to single deletion is currently not working!") public void REGT_015_delete_multivalue_attributes_twice() { try { getOriginalUser("dma"); createUpdateUserWithMultiDeleteFields(); try { // try to delete twice updateUser(); updateUser(); } catch (Exception ex) { // should run without exception fail("Expected no exception, but got: " + ex.getMessage()); } // entitlements and certificates available in the returned user should be deleted, even in the database assertTrue(isValuePartOfMultivalueList(Entitlement.class, originalUser.getEntitlements(), "right2")); assertFalse(isValuePartOfMultivalueList(Entitlement.class, returnUser.getEntitlements(), "right2")); assertFalse(isValuePartOfMultivalueList(Entitlement.class, databaseUser.getEntitlements(), "right2")); assertTrue(isValuePartOfMultivalueList(X509Certificate.class, originalUser.getX509Certificates(), "certificate01")); assertFalse(isValuePartOfMultivalueList(X509Certificate.class, returnUser.getX509Certificates(), "certificate01")); assertFalse(isValuePartOfMultivalueList(X509Certificate.class, databaseUser.getX509Certificates(), "certificate01")); } finally { oConnector.deleteUser(originalUser.getId(), accessToken); } } @Test @Ignore("Only ok because see TODO") public void delete_all_multivalue_attributes() { try { getOriginalUser("dama"); createUpdateUserWithMultiAllDeleteFields(); updateUser(); assertNotNull(originalUser.getEmails()); assertNull(returnUser.getEmails()); assertNull(returnUser.getAddresses()); assertNull(returnUser.getEntitlements()); assertNull(returnUser.getGroups());//TODO da Gruppen nicht gespeichert werden sind sie immer null assertNull(returnUser.getIms()); assertNull(returnUser.getPhoneNumbers()); assertNull(returnUser.getPhotos()); assertNull(returnUser.getRoles()); assertNull(returnUser.getX509Certificates()); } finally { oConnector.deleteUser(idExistingUser, accessToken); } } @Test @Ignore ("see TODO's") public void add_multivalue_attributes(){ try{ getOriginalUser("ama"); createUpdateUserWithMultiAddFields(); updateUser(); assertEquals(originalUser.getPhoneNumbers().size() + 1, returnUser.getPhoneNumbers().size()); assertTrue(isValuePartOfMultivalueList(PhoneNumber.class, returnUser.getPhoneNumbers(), "99999999991")); assertEquals(originalUser.getEmails().size() + 1, returnUser.getEmails().size()); assertTrue(isValuePartOfMultivalueList(Email.class, returnUser.getEmails(), "mac@muster.de")); assertEquals(originalUser.getAddresses().size() + 1, returnUser.getAddresses().size()); getAddress(returnUser.getAddresses(), "new Address"); assertEquals(originalUser.getEntitlements().size() + 1, returnUser.getEntitlements().size());//TODO at the second run it will fail assertTrue(isValuePartOfMultivalueList(Entitlement.class, returnUser.getEntitlements(), "right3"));//TODO at the second run it will fail assertEquals(originalUser.getGroups().size() + 1, returnUser.getGroups().size());//TODO gruppen werden aktuell nicht gespeichert assertTrue(isValuePartOfMultivalueList(GroupRef.class, returnUser.getGroups(), "d30a77eb-d7cf-4cd1-9fb3-cc640ef09578"));//TODO gruppen werden aktuell nicht gespeichert assertEquals(originalUser.getIms().size() + 1, returnUser.getIms().size()); assertTrue(isValuePartOfMultivalueList(Ims.class, returnUser.getIms(), "ims03")); assertEquals(originalUser.getPhotos().size() + 1, returnUser.getPhotos().size()); assertTrue(isValuePartOfMultivalueList(Photo.class, returnUser.getPhotos(), "photo03.jpg")); assertEquals(originalUser.getRoles().size() + 1, returnUser.getRoles().size()); assertTrue(isValuePartOfMultivalueList(Role.class, returnUser.getRoles(), "role03")); assertEquals(originalUser.getX509Certificates().size() + 1, returnUser.getX509Certificates().size());//TODO at the second run it will fail assertTrue(isValuePartOfMultivalueList(X509Certificate.class, returnUser.getX509Certificates(), "certificate03"));//TODO at the second run it will fail }finally{ oConnector.deleteUser(idExistingUser, accessToken); } } @Test @Ignore ("see TODO's") public void update_multivalue_attributes(){ try{ getOriginalUser("uma"); createUpdateUserWithMultiUpdateFields(); updateUser(); //phonenumber PhoneNumber phoneNumber = getSingleMultiValueAttribute(PhoneNumber.class, returnUser.getPhoneNumbers(), "+497845/1157"); assertFalse(phoneNumber.isPrimary());//TODO primary wird beim telefon nicht gesetzt phoneNumber = getSingleMultiValueAttribute(PhoneNumber.class, returnUser.getPhoneNumbers(), "0245817964"); assertTrue(phoneNumber.isPrimary());//TODO primary wird beim telefon nicht gesetzt assertEquals(PhoneNumberType.OTHER, phoneNumber.getType()); //email Email email = getSingleMultiValueAttribute(Email.class, returnUser.getEmails(), "hsimpson@atom-example.com"); assertFalse(email.isPrimary()); email = getSingleMultiValueAttribute(Email.class, returnUser.getEmails(), "hsimpson@home-example.com"); assertTrue(email.isPrimary()); assertEquals(EmailType.OTHER, email.getType()); Ims ims = getSingleMultiValueAttribute(Ims.class, returnUser.getIms(), "ims01"); assertEquals(ImsType.ICQ, ims.getType());//TODO der type wird nicht upgedatet Photo photo = getSingleMultiValueAttribute(Photo.class, returnUser.getPhotos(), "photo01.jpg"); assertEquals(PhotoType.PHOTO, photo.getType());//TODO der type wird nicht upgedatet GroupRef userGroup = getSingleMultiValueAttribute(GroupRef.class, returnUser.getGroups(), "69e1a5dc-89be-4343-976c-b5541af249f4"); //TODO gruppen werden nicht angelegt assertEquals(GroupRefType.INDIRECT, userGroup.getType()); }finally{ oConnector.deleteUser(idExistingUser, accessToken); } } @Test public void update_all_single_values(){ try{ getOriginalUser("uasv"); createUpdateUserWithUpdateFields(); updateUser(); assertEquals("UserName", returnUser.getUserName()); assertEquals("NickName", returnUser.getNickName()); assertNotEquals(originalUser.isActive(), returnUser.isActive()); assertEquals("DisplayName", returnUser.getDisplayName()); assertEquals("ExternalId", returnUser.getExternalId()); assertEquals("Locale", returnUser.getLocale()); assertEquals("PreferredLanguage", returnUser.getPreferredLanguage()); assertEquals("ProfileUrl", returnUser.getProfileUrl()); assertEquals("Timezone", returnUser.getTimezone()); assertEquals("Title", returnUser.getTitle()); assertEquals("UserType", returnUser.getUserType()); assertEquals("FamilyName", returnUser.getName().getFamilyName()); assertEquals("ExternalId", returnUser.getExternalId()); }finally{ oConnector.deleteUser(idExistingUser, accessToken); } } @Test public void delete_all_single_values(){ try{ getOriginalUser("desv"); createUpdateUserWithDeleteFields(); updateUser(); assertNull(returnUser.getNickName()); assertNull(returnUser.getDisplayName()); assertNull(returnUser.getLocale()); assertNull(returnUser.getPreferredLanguage()); assertNull(returnUser.getProfileUrl()); assertNull(returnUser.getTimezone()); assertNull(returnUser.getTitle()); assertNull(returnUser.getUserType()); assertNull(returnUser.getName()); assertNull(returnUser.getExternalId()); }finally{ oConnector.deleteUser(idExistingUser, accessToken); } } @Test public void update_password() { try{ getOriginalUser("uasv"); createUpdateUserWithUpdateFields(); updateUser(); makeNewConnectionWithNewPassword(); }finally{ oConnector.deleteUser(idExistingUser, accessToken); } } @Test public void change_one_field_and_other_attributes_are_the_same(){ try{ getOriginalUser("cnaoaats"); createUpdateUserWithJustOtherNickname(); updateUser(); assertNotEquals(originalUser.getNickName(), returnUser.getNickName()); assertEquals(originalUser.isActive(), returnUser.isActive()); assertEquals(originalUser.getDisplayName(), returnUser.getDisplayName()); assertEquals(originalUser.getExternalId(), returnUser.getExternalId()); assertEquals(originalUser.getLocale(), returnUser.getLocale()); assertEquals(originalUser.getPreferredLanguage(), returnUser.getPreferredLanguage()); assertEquals(originalUser.getProfileUrl(), returnUser.getProfileUrl()); assertEquals(originalUser.getTimezone(), returnUser.getTimezone()); assertEquals(originalUser.getTitle(), returnUser.getTitle()); assertEquals(originalUser.getUserType(), returnUser.getUserType()); assertEquals(originalUser.getName().getFamilyName(), returnUser.getName().getFamilyName()); }finally{ oConnector.deleteUser(idExistingUser, accessToken); } } @Test (expected = ConflictException.class) @Ignore ("No exception is thrown an the moment") public void username_is_set_no_empty_string_is_thrown_probably(){ try{ getOriginalUser("ietiuuitp"); createUpdateUserWithEmptyUserName(); updateUser(); fail("exception expected"); }finally{ oConnector.deleteUser(idExistingUser, accessToken); } } public <T extends BasicMultiValuedAttribute> boolean isValuePartOfMultivalueList(Class<T> clazz, List<T> list, String value){ if(list != null){ for (Object actAttribute : list) { BasicMultiValuedAttribute real = clazz.cast(actAttribute); if(real.getValue().equals(value)){ return true; } } } return false; } public boolean isValuePartOfAddressList(List<Address> list, String formated){ if(list != null){ for (Address actAttribute : list) { if(actAttribute.getFormatted().equals(formated)){ return true; } } } return false; } public <T extends BasicMultiValuedAttribute> T getSingleMultiValueAttribute(Class<T> clazz, List<T> multiValues, Object value){ if(multiValues != null){ for (Object actMultiValuedAttribute : multiValues) { BasicMultiValuedAttribute real = clazz.cast(actMultiValuedAttribute); if(real.getValue().equals(value)){ return (T) real; } } } fail("The value " + value + " could not be found"); return null; //Can't be reached } public void delete_multivalue_attributes_which_is_not_available() { try { getOriginalUser("dma"); createUpdateUserWithWrongEmail(); updateUser(); } finally { oConnector.deleteUser(idExistingUser, accessToken); } } @Test @Ignore("Ignored due to update user problem.") public void REGT_015_update_multivalue_attributes_twice() throws InterruptedException { try { getOriginalUser("uma"); Thread.sleep(1000); // wait to grant different modification datetime createUpdateUserWithMultiUpdateFields(); try { // try to update twice updateUser(); updateUser(); } catch (Exception ex) { // should run without exception fail("Expected no exception, but got: " + ex.getMessage()); } // entitlements and certificates available in the update user should be updated Entitlement entitlementBefore = getSingleMultiValueAttribute(Entitlement.class, originalUser.getEntitlements(), "right1"); Entitlement entitlementAfter = getSingleMultiValueAttribute(Entitlement.class, returnUser.getEntitlements(), "right1"); assertEquals(entitlementBefore.getValue(), entitlementAfter.getValue()); X509Certificate certificateBefore = getSingleMultiValueAttribute(X509Certificate.class, originalUser.getX509Certificates(), "certificate01"); X509Certificate certificateAfter = getSingleMultiValueAttribute(X509Certificate.class, returnUser.getX509Certificates(), "certificate01"); assertEquals(certificateBefore.getValue(), certificateAfter.getValue()); assertNotEquals(originalUser.getMeta().getLastModified(), returnUser.getMeta().getLastModified()); } finally { oConnector.deleteUser(idExistingUser, accessToken); } } @Test public void update_attributes_doesnt_change_the_password() { try { getOriginalUser("uadctp"); createUpdateUserWithUpdateFieldsWithoutPassword(); updateUser(); makeNewConnection(); } finally { oConnector.deleteUser(idExistingUser, accessToken); } } public void getOriginalUser(String userName) { User.Builder userBuilder = new User.Builder(userName); Email email01 = new Email.Builder().setValue("hsimpson@atom-example.com").setType(EmailType.WORK).setPrimary(true).build(); Email email02 = new Email.Builder().setValue("hsimpson@home-example.com").setType(EmailType.WORK).build(); List<Email> emails = new ArrayList<>(); emails.add(email01); emails.add(email02); PhoneNumber phoneNumber01 = new PhoneNumber.Builder().setValue("+497845/1157").setType(PhoneNumberType.WORK).setPrimary(true).build(); PhoneNumber phoneNumber02 = new PhoneNumber.Builder().setValue("0245817964").setType(PhoneNumberType.HOME).build(); List<PhoneNumber> phoneNumbers = new ArrayList<>(); phoneNumbers.add(phoneNumber01); phoneNumbers.add(phoneNumber02); Address simpleAddress01 = new Address.Builder().setCountry("de").setFormatted("formated address 01").setLocality("Berlin").setPostalCode("111111").build(); Address simpleAddress02 = new Address.Builder().setCountry("en").setFormatted("address formated 02").setLocality("New York").setPostalCode("123456").build(); List<Address> addresses = new ArrayList<>(); addresses.add(simpleAddress01); addresses.add(simpleAddress02); Entitlement entitlement01 = new Entitlement.Builder().setValue("right1").build(); Entitlement entitlement02 = new Entitlement.Builder().setValue("right2").build(); List<Entitlement> entitlements = new ArrayList<>(); entitlements.add(entitlement01); entitlements.add(entitlement02); GroupRef group01 = new GroupRef.Builder().setValue("69e1a5dc-89be-4343-976c-b5541af249f4").build(); GroupRef group02 = new GroupRef.Builder().setValue("d30a77eb-d7cf-4cd1-9fb3-cc640ef09578").build(); List<GroupRef> groups = new ArrayList<>(); groups.add(group01); groups.add(group02); Ims ims01 = new Ims.Builder().setValue("ims01").setType(ImsType.SKYPE).build(); Ims ims02 = new Ims.Builder().setValue("ims02").build(); List<Ims> ims = new ArrayList<>(); ims.add(ims01); ims.add(ims02); Photo photo01 = new Photo.Builder().setValue("photo01.jpg").setType(PhotoType.THUMBNAIL).build(); Photo photo02 = new Photo.Builder().setValue("photo02.jpg").build(); List<Photo> photos = new ArrayList<>(); photos.add(photo01); photos.add(photo02); Role role01 = new Role.Builder().setValue("role01").build(); Role role02 = new Role.Builder().setValue("role02").build(); List<Role> roles = new ArrayList<>(); roles.add(role01); roles.add(role02); X509Certificate certificate01 = new X509Certificate.Builder().setValue("certificate01").build(); X509Certificate certificate02 = new X509Certificate.Builder().setValue("certificate02").build(); List<X509Certificate> certificates = new ArrayList<>(); certificates.add(certificate01); certificates.add(certificate02); Name name = new Name.Builder().setFamilyName("familiyName").setFormatted("formatted Name").setGivenName("givenName").build(); userBuilder.setNickName("irgendwas") .setEmails(emails) .setPhoneNumbers(phoneNumbers) .setActive(false) .setDisplayName("irgendwas") .setLocale("de") .setPassword("geheim") .setPreferredLanguage("de") .setProfileUrl("irgendwas") .setTimezone("irgendwas") .setTitle("irgendwas") .setUserType("irgendwas") .setAddresses(addresses) .setGroups(groups) .setIms(ims) .setPhotos(photos) .setRoles(roles) .setName(name) .setX509Certificates(certificates) .setEntitlements(entitlements) .setExternalId("irgendwas") ; User newUser = userBuilder.build(); originalUser = oConnector.createUser(newUser, accessToken); idExistingUser = originalUser.getId(); } private void createUpdateUserWithUpdateFields() { Name newName = new Name.Builder().setFamilyName("FamilyName").build(); updateUser = new UpdateUser.Builder() .updateUserName("UserName") .updateNickName("NickName") .updateExternalId("ExternalId") .updateDisplayName("DisplayName") .updatePassword("Password") .updateLocale("Locale") .updatePreferredLanguage("PreferredLanguage") .updateProfileUrl("ProfileUrl") .updateTimezone("Timezone") .updateTitle("Title") .updateUserType("UserType") .updateExternalId("ExternalId") .updateName(newName) .updateActive(true).build(); } private void createUpdateUserWithUpdateFieldsWithoutPassword() { Name newName = new Name.Builder().setFamilyName("newFamilyName").build(); updateUser = new UpdateUser.Builder() .updateUserName(UUID.randomUUID().toString()) .updateNickName(IRRELEVANT) .updateExternalId(IRRELEVANT) .updateDisplayName(IRRELEVANT) .updateLocale(IRRELEVANT) .updatePreferredLanguage(IRRELEVANT) .updateProfileUrl(IRRELEVANT) .updateTimezone(IRRELEVANT) .updateTitle(IRRELEVANT) .updateUserType(IRRELEVANT) .updateName(newName) .updateActive(true).build(); } private void createUpdateUserWithMultiUpdateFields(){ Email email = new Email.Builder() .setValue("hsimpson@home-example.com").setType(EmailType.OTHER).setPrimary(true).build(); PhoneNumber phoneNumber = new PhoneNumber.Builder().setValue("0245817964").setType(PhoneNumberType.OTHER) .setPrimary(true).build(); //Now the other should not be primary anymore Ims ims = new Ims.Builder().setValue("ims01").setType(ImsType.ICQ).build(); Photo photo = new Photo.Builder().setValue("photo01.jpg").setType(PhotoType.PHOTO).build(); Role role = new Role.Builder().setValue("role01").build(); GroupRef group = new GroupRef.Builder().setValue("69e1a5dc-89be-4343-976c-b5541af249f4").build(); updateUser = new UpdateUser.Builder() .addEmail(email) .addPhoneNumber(phoneNumber) .addPhoto(photo) .addIms(ims) .addRole(role) .addGroupMembership(group) .build(); } private void createUpdateUserWithDeleteFields(){ updateUser = new UpdateUser.Builder() .deleteDisplayName() .deleteNickName() .deleteLocal() .deletePreferredLanguage() .deleteProfileUrl() .deleteTimezone() .deleteTitle() .deleteUserType() .deleteName() .deleteExternalId() .build(); } private void createUpdateUserWithMultiDeleteFields(){ Address deleteAddress = null; for (Address actAddress : originalUser.getAddresses()) { if(actAddress.getFormatted().equals("formated address 01")){ deleteAddress = actAddress; break; } } Email email = new Email.Builder().setValue("hsimpson@atom-example.com").build(); Entitlement entitlement = new Entitlement.Builder().setValue("right2").build(); Ims ims = new Ims.Builder().setValue("ims01").build(); PhoneNumber phoneNumber = new PhoneNumber.Builder().setValue("0245817964").build(); Photo photo = new Photo.Builder().setValue("photo01.jpg").build(); X509Certificate x509Certificate = new X509Certificate.Builder().setValue("certificate01").build(); updateUser = new UpdateUser.Builder() .deleteEmail(email) .deleteEntitlement(entitlement) .deleteGroup("d30a77eb-d7cf-4cd1-9fb3-cc640ef09578") .deleteIms(ims) .deletePhoneNumber(phoneNumber) .deletePhoto(photo) .deleteRole("role01") .deleteX509Certificate(x509Certificate) .deleteAddress(deleteAddress) .build(); } private void createUpdateUserWithWrongEmail(){ Email email = new Email.Builder().setValue("test@test.com").build(); updateUser = new UpdateUser.Builder() .deleteEmail(email) .build(); } private void createUpdateUserWithMultiAddFields(){ Email email = new Email.Builder() .setValue("mac@muster.de").setType(EmailType.HOME).build(); PhoneNumber phonenumber = new PhoneNumber.Builder() .setValue("99999999991").setType(PhoneNumberType.HOME).build(); Address newSimpleAddress = new Address.Builder().setCountry("fr").setFormatted("new Address").setLocality("New City").setPostalCode("66666").build(); Entitlement entitlement = new Entitlement.Builder().setValue("right3").build(); Ims ims = new Ims.Builder().setValue("ims03").build(); Photo photo = new Photo.Builder().setValue("photo03.jpg").build(); Role role = new Role.Builder().setValue("role03").build(); X509Certificate certificate = new X509Certificate.Builder().setValue("certificate03").build(); GroupRef groupMembership = new GroupRef.Builder().setValue("d30a77eb-d7cf-4cd1-9fb3-cc640ef09578").build(); updateUser = new UpdateUser.Builder() .addEmail(email) .addPhoneNumber(phonenumber) .addAddress(newSimpleAddress) .addEntitlement(entitlement) .addGroupMembership(groupMembership) //TODO Gruppen werden nicht gespeichert .addIms(ims) .addPhoto(photo) .addRole(role) .addX509Certificate(certificate)//TODO at the second run it will fail .build(); } private void createUpdateUserWithMultiAllDeleteFields(){ updateUser = new UpdateUser.Builder() .deleteEmails() .deleteAddresses() .deleteEntitlements() .deleteGroups() .deleteIms() .deletePhoneNumbers() .deletePhotos() .deleteRoles() .deleteX509Certificates() .build(); } private void createUpdateUserWithJustOtherNickname() { updateUser = new UpdateUser.Builder() .updateNickName(IRRELEVANT) .build(); } private void createUpdateUserWithEmptyUserName() { updateUser = new UpdateUser.Builder().updateUserName("") .build(); } private void updateUser() { returnUser = oConnector.updateUser(idExistingUser, updateUser, accessToken); // also get user again from database to be able to compare with return object databaseUser = oConnector.getUser(returnUser.getId(), accessToken); /* TODO: Uncomment once returnUser and databaseUser are consistent! */ // assertTrue(returnUser.equals(databaseUser)); } private void makeNewConnectionWithNewPassword() { OsiamConnector.Builder oConBuilder = new OsiamConnector.Builder(ENDPOINT_ADDRESS). setClientId(CLIENT_ID). setClientSecret(CLIENT_SECRET). setGrantType(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS). setUserName("UserName"). setPassword("Password"). setScope(Scope.ALL); oConnector = oConBuilder.build(); oConnector.retrieveAccessToken(); } private void makeNewConnection() { OsiamConnector.Builder oConBuilder = new OsiamConnector.Builder(ENDPOINT_ADDRESS). setClientId(CLIENT_ID). setClientSecret(CLIENT_SECRET). setGrantType(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS). setUserName("marissa"). setPassword("koala"). setScope(Scope.ALL); oConnector = oConBuilder.build(); oConnector.retrieveAccessToken(); } public Address getAddress(List<Address> addresses, String formated) { Address returnAddress = null; if (addresses != null) { for (Address actAddress : addresses) { if (actAddress.getFormatted().equals(formated)) { returnAddress = actAddress; break; } } } if (returnAddress == null) { fail("The address with the formated part of " + formated + " could not be found"); } return returnAddress; } }
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import com.xerox.amazonws.sdb.Domain; import com.xerox.amazonws.sdb.Item; import com.xerox.amazonws.sdb.ItemAttribute; import com.xerox.amazonws.sdb.ItemListener; import com.xerox.amazonws.sdb.ListDomainsResult; import com.xerox.amazonws.sdb.QueryResult; import com.xerox.amazonws.sdb.SDBException; import com.xerox.amazonws.sdb.SimpleDB; /** * Sample application demonstrating various operations against SDS. * */ public class sdbShell { /** * Executes specified query against given domain while demonstrating pagination. * * @param domain query domain * @param queryString query string * @param maxResults maximum number of values to return per page of results */ private static void executeQuery(Domain domain, String queryString, int maxResults) { String nextToken = ""; do { try { QueryResult result = domain.listItems(queryString, nextToken, maxResults); List<Item> items = result.getItemList(); for (Item i : items) { System.out.println(i.getIdentifier()); } nextToken = result.getNextToken(); } catch (SDBException ex) { System.out.println("Query '" + queryString + "' Failure: "); ex.printStackTrace(); } } while (nextToken != null && nextToken.trim().length() > 0); System.out.println("Done."); } private static void getItems(Domain domain, String queryString, int maxResults, ItemIdListener listener) { String nextToken = ""; do { try { QueryResult result = domain.listItems(queryString, nextToken, maxResults); List<Item> items = result.getItemList(); for (Item i : items) { listener.itemAvailable(i.getIdentifier()); } nextToken = result.getNextToken(); } catch (SDBException ex) { System.out.println("Query '" + queryString + "' Failure: "); ex.printStackTrace(); } } while (nextToken != null && nextToken.trim().length() > 0); } /** * Executes specified query against given domain. * * @param domain query domain * @param queryString query string */ private static void executeQuery(Domain domain, String queryString) { executeQuery(domain, queryString, 0); } /** * Main execution body. * * @param args command line arguments (none required or processed) */ public static void main(String [] args) { if (args.length < 2) { System.err.println("usage: sdbShell <access key> <secret key> [command file]"); System.exit(1); } try { String awsAccessId = args[0]; String awsSecretKey = args[1]; if (awsAccessId == null || awsAccessId.trim().length() == 0) { System.out.println("Access key not set"); return; } if (awsSecretKey == null || awsSecretKey.trim().length() == 0) { System.out.println("Secret key not set"); return; } SimpleDB sds = new SimpleDB(awsAccessId, awsSecretKey, true); InputStream iStr = System.in; if (args.length > 2) { iStr = new FileInputStream(args[2]); } BufferedReader rdr = new BufferedReader(new InputStreamReader(iStr)); boolean done = false; Domain dom = null; while (!done) { System.out.print("sdbShell> "); String line = rdr.readLine(); if (line == null) { // exit, if end of input System.exit(0); } StringTokenizer st = new StringTokenizer(line); if (st.countTokens() == 0) { continue; } String cmd = st.nextToken().toLowerCase(); if (cmd.equals("q") || cmd.equals("quit")) { done = true; } else if (cmd.equals("h") || cmd.equals("?") || cmd.equals("help")) { showHelp(); } else if (cmd.equals("d") || cmd.equals("domains")) { ListDomainsResult result = sds.listDomains(); List<Domain> domains = result.getDomainList(); for (Domain d : domains) { System.out.println(d.getName()); } } else if (cmd.equals("ad") || cmd.equals("adddomain")) { if (st.countTokens() != 1) { System.out.println("Error: need domain name."); continue; } Domain d = sds.createDomain(st.nextToken()); } else if (cmd.equals("dd") || cmd.equals("deletedomain")) { if (st.countTokens() != 1) { System.out.println("Error: need domain name."); continue; } sds.deleteDomain(st.nextToken()); } else if (cmd.equals("sd") || cmd.equals("setdomain")) { if (st.countTokens() != 1) { System.out.println("Error: need domain name."); continue; } dom = sds.getDomain(st.nextToken()); } else if (cmd.equals("aa") || cmd.equals("addattr")) { if (checkDomain(dom)) { if (st.countTokens() != 3) { System.out.println("Error: need item id, attribute name and value."); continue; } Item item = dom.getItem(st.nextToken()); List<ItemAttribute> list = new ArrayList<ItemAttribute>(); list.add(new ItemAttribute(st.nextToken(), st.nextToken(), false)); item.putAttributes(list); } } else if (cmd.equals("ra") || cmd.equals("replaceattr")) { if (checkDomain(dom)) { if (st.countTokens() != 3) { System.out.println("Error: need item id, attribute name and value."); continue; } Item item = dom.getItem(st.nextToken()); List<ItemAttribute> list = new ArrayList<ItemAttribute>(); list.add(new ItemAttribute(st.nextToken(), st.nextToken(), true)); item.putAttributes(list); } } else if (cmd.equals("da") || cmd.equals("deleteattr")) { if (checkDomain(dom)) { if (st.countTokens() != 2) { System.out.println("Error: need item id and attribute name."); continue; } Item item = dom.getItem(st.nextToken()); List<ItemAttribute> list = new ArrayList<ItemAttribute>(); list.add(new ItemAttribute(st.nextToken(), null, true)); item.deleteAttributes(list); } } else if (cmd.equals("di") || cmd.equals("deleteitem")) { if (checkDomain(dom)) { if (st.countTokens() != 1) { System.out.println("Error: need item id."); continue; } dom.deleteItem(st.nextToken()); } } else if (cmd.equals("i") || cmd.equals("item")) { if (checkDomain(dom)) { if (st.countTokens() != 1) { System.out.println("Error: need item id."); continue; } Item item = dom.getItem(st.nextToken()); List<ItemAttribute> attrs = item.getAttributes(null); System.out.println("Item : "+item.getIdentifier()); for (ItemAttribute attr : attrs) { System.out.println(" "+attr.getName()+" = "+attr.getValue()); } } } else if (cmd.equals("gi") || cmd.equals("getitems")) { if (checkDomain(dom)) { dom.listItemsAttributes("", new ItemListener() { public synchronized void itemAvailable(String id, List<ItemAttribute> attrs) { System.out.println("Item : "+id); for (ItemAttribute attr : attrs) { System.out.println(" "+attr.getName()+" = "+attr.getValue()); } } }); } } else if (cmd.equals("l") || cmd.equals("list")) { if (checkDomain(dom)) executeQuery(dom, null); } else { if (checkDomain(dom)) executeQuery(dom, line); } } } catch (Exception ex) { ex.printStackTrace(); if (ex.getCause() != null) { System.err.println("caused by : "); ex.getCause().printStackTrace(); } } } private static boolean checkDomain(Domain dom) { if (dom == null) { System.out.println("domain must be set!"); return false; } return true; } private static void showHelp() { System.out.println("SimpleDB Shell Commands:"); System.out.println("adddomain(ad) <domain name> : add new domain"); System.out.println("deletedomain(dd) <domain name> : delete domain (not functional in SDS yet)"); System.out.println("domains(d) : list domains"); System.out.println("setdomain(sd) <domain name> : set current domain"); System.out.println("addattr(aa) <item id> <attr name> <attr value> : add attribute to item in current domain"); System.out.println("replaceattr(aa) <item id> <attr name> <attr value> : replace attribute to item in current domain"); System.out.println("deleteattr(da) <item id> <attr name> : delete attribute of item in current domain"); System.out.println("deleteitem(di) <item id> : delete item in current domain"); System.out.println("list(l) or <filter string> : lists items matching filter in current domain"); System.out.println("item(i) <item id> : shows item attributes"); System.out.println("getitems(gi) : shows attributes for multiple items"); System.out.println("help(h,?) : show help"); System.out.println("quit(q) : exit the shell"); } interface ItemIdListener { public void itemAvailable(String item); } }
package se.lth.cs.connect; import static org.junit.Assert.assertEquals; import org.junit.Rule; import org.junit.Test; import com.jayway.restassured.response.Response; import ro.pippo.test.PippoRule; import ro.pippo.test.PippoTest; public class TestUserAPI extends PippoTest { // This rule ensures that we have a server running before doing the tests public Connect app = new Connect(); @Rule public PippoRule pippoRule = new PippoRule(app); @Test public void testAccessDenied() { // These routes require an active session => requests should be denied // Status code 401 => all is ok (expected) // Any other code means that we have an error somewhere. when().get("/v1/account/login").then().statusCode(401); when().get("/v1/account/collections").then().statusCode(401); when().get("/v1/account/self").then().statusCode(401); when().post("/v1/account/logout").then().statusCode(401); when().post("/v1/account/delete").then().statusCode(401); when().post("/v1/account/change-password").then().statusCode(401); when().get("/v1/account/invites").then().statusCode(401); when().get("/v1/account/dat12asm@student.lu.se").then().statusCode(401); } /** * Verify that 1) an email is sent after signup, and 2) that the email * is sent to the correct email address. */ @Test public void testRegistration() { // Use mailbox to capture emails instead of sending them Mailbox mailbox = new Mailbox(); app.useMailClient(mailbox); // Register Response reg = given(). param("email", "test-reg@serptest.test"). param("passw", "hejsanhoppsan"). post("/v1/account/register"); reg.then(). statusCode(200); assertEquals("Must send registration email", mailbox.getInbox().size(), 1); assertEquals("Recipient must match registered email", mailbox.top().recipient, "test-reg@serptest.test"); // Cleanup given(). cookie("JSESSIONID", reg.getCookie("JSESSIONID")). when(). post("/v1/account/delete"). then(). statusCode(200); } @Test public void testLifecycle() { // This test case is not very important, but it showcases how to // (re)use a session for multiple queries and how to create post // requests with data. Response reg = given(). param("email", "test@serptest.test"). param("passw", "hejsanhoppsan"). post("/v1/account/register"); reg.then(). statusCode(200); given(). cookie("JSESSIONID", reg.getCookie("JSESSIONID")). when(). post("/v1/account/logout"). then(). statusCode(200); Response login = given(). param("email", "test@serptest.test"). param("passw", "hejsanhoppsan"). post("/v1/account/login"); reg.then(). statusCode(200); given(). cookie("JSESSIONID", login.getCookie("JSESSIONID")). when(). post("/v1/account/delete"). then(). statusCode(200); } }
package org.jdesktop.swingx.decorator; /** * Encapsulates state that depends on the UI and needs * to be updated on LookAndFeel change. * * @author Jeanette Winzenburg * @deprecated (pre-1.6.1) moved; use {@link org.jdesktop.swingx.plaf.UIDependent} instead */ @Deprecated public interface UIDependent { /** * method to call after the LookAndFeel changed. * */ void updateUI(); }
package org.jaxen.expr; import org.jaxen.Context; class DefaultNumberExpr extends DefaultExpr implements NumberExpr { private static final long serialVersionUID = -6021898973386269611L; private Double number; DefaultNumberExpr( Double number ) { this.number = number; } public Number getNumber() { return this.number; } public String toString() { return "[(DefaultNumberExpr): " + getNumber() + "]"; } public String getText() { return getNumber().toString(); } public Object evaluate( Context context ) { return getNumber(); } public void accept( Visitor visitor ) { visitor.visit( this ); } }
package net.sf.jabref.external; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.List; import java.util.ArrayList; import javax.swing.*; import net.sf.jabref.*; import net.sf.jabref.gui.FileListTableModel; import net.sf.jabref.gui.FileListEntry; import net.sf.jabref.util.XMPUtil; import com.jgoodies.forms.builder.ButtonBarBuilder; /** * * This action goes through all selected entries in the BasePanel, and attempts * to write the XMP data to the external pdf. * * @author $Author$ * @version $Revision$ ($Date$) * */ public class WriteXMPAction extends AbstractWorker { BasePanel panel; BibtexEntry[] entries; BibtexDatabase database; OptionsDialog optDiag; boolean goOn = true; int skipped, entriesChanged, errors; public WriteXMPAction(BasePanel panel) { this.panel = panel; } public void init() { database = panel.getDatabase(); // Get entries and check if it makes sense to perform this operation entries = panel.getSelectedEntries(); if (entries.length == 0) { entries = database.getEntries().toArray(new BibtexEntry[]{}); if (entries.length == 0) { JOptionPane.showMessageDialog(panel, Globals.lang("This operation requires at least one entry."), Globals.lang("Write XMP-metadata"), JOptionPane.ERROR_MESSAGE); goOn = false; return; } else { int response = JOptionPane.showConfirmDialog(panel, Globals.lang("Write XMP-metadata for all PDFs in current database?"), Globals.lang("Write XMP-metadata"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (response != JOptionPane.YES_OPTION) { goOn = false; return; } } } errors = entriesChanged = skipped = 0; if (optDiag == null) { optDiag = new OptionsDialog(panel.frame()); } optDiag.open(); panel.output(Globals.lang("Writing XMP metadata...")); } public void run() { if (!goOn) return; for (int i = 0; i < entries.length; i++) { BibtexEntry entry = entries[i]; // Make a list of all PDFs linked from this entry: List<File> files = new ArrayList<File>(); // First check the (legacy) "pdf" field: String pdf = entry.getField("pdf"); String[] dirs = panel.metaData().getFileDirectory("pdf"); File f = Util.expandFilename(pdf, dirs); if (f != null) files.add(f); // Then check the "file" field: dirs = panel.metaData().getFileDirectory(GUIGlobals.FILE_FIELD); String field = entry.getField(GUIGlobals.FILE_FIELD); if (field != null) { FileListTableModel tm = new FileListTableModel(); tm.setContent(field); for (int j=0; j<tm.getRowCount(); j++) { FileListEntry flEntry = tm.getEntry(j); if ((flEntry.getType()!=null) && (flEntry.getType().getName().toLowerCase().equals("pdf"))) { f = Util.expandFilename(flEntry.getLink(), dirs); if (f != null) files.add(f); } } } optDiag.progressArea.append(entry.getCiteKey() + "\n"); if (files.size() == 0) { skipped++; optDiag.progressArea.append(" " + Globals.lang("Skipped - No PDF linked") + ".\n"); } else for (File file : files) { if (!file.exists()) { skipped++; optDiag.progressArea.append(" " + Globals.lang("Skipped - PDF does not exist") + ":\n"); optDiag.progressArea.append(" " + file.getPath() + "\n"); } else { try { XMPUtil.writeXMP(file, entry, database); optDiag.progressArea.append(" " + Globals.lang("Ok") + ".\n"); entriesChanged++; } catch (Exception e) { optDiag.progressArea.append(" " + Globals.lang("Error while writing") + " '" + file.getPath() + "':\n"); optDiag.progressArea.append(" " + e.getLocalizedMessage() + "\n"); errors++; } } } if (optDiag.canceled){ optDiag.progressArea.append("\n" + Globals.lang("Operation canceled.\n")); break; } } optDiag.progressArea.append("\n" + Globals.lang("Finished writing XMP for %0 file (%1 skipped, %2 errors).", String .valueOf(entriesChanged), String.valueOf(skipped), String.valueOf(errors))); optDiag.done(); } public void update() { if (!goOn) return; panel.output(Globals.lang("Finished writing XMP for %0 file (%1 skipped, %2 errors).", String.valueOf(entriesChanged), String.valueOf(skipped), String.valueOf(errors))); } class OptionsDialog extends JDialog { private static final long serialVersionUID = 7459164400811785958L; JButton okButton = new JButton(Globals.lang("Ok")), cancelButton = new JButton( Globals.lang("Cancel")); boolean canceled; JTextArea progressArea; public OptionsDialog(JFrame parent) { super(parent, Globals.lang("Writing XMP metadata for selected entries..."), false); okButton.setEnabled(false); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); AbstractAction cancel = new AbstractAction() { private static final long serialVersionUID = -338601477652815366L; public void actionPerformed(ActionEvent e) { canceled = true; } }; cancelButton.addActionListener(cancel); InputMap im = cancelButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); ActionMap am = cancelButton.getActionMap(); im.put(Globals.prefs.getKey("Close dialog"), "close"); am.put("close", cancel); progressArea = new JTextArea(15, 60); JScrollPane scrollPane = new JScrollPane(progressArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); Dimension d = progressArea.getPreferredSize(); d.height += scrollPane.getHorizontalScrollBar().getHeight() + 15; d.width += scrollPane.getVerticalScrollBar().getWidth() + 15; panel.setSize(d); progressArea.setBackground(Color.WHITE); progressArea.setEditable(false); progressArea.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3)); progressArea.setText(""); JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createEmptyBorder(3, 2, 3, 2)); panel.add(scrollPane); // progressArea.setPreferredSize(new Dimension(300, 300)); ButtonBarBuilder bb = new ButtonBarBuilder(); bb.addGlue(); bb.addButton(okButton); bb.addRelatedGap(); bb.addButton(cancelButton); bb.addGlue(); JPanel bbPanel = bb.getPanel(); bbPanel.setBorder(BorderFactory.createEmptyBorder(0, 3, 3, 3)); getContentPane().add(panel, BorderLayout.CENTER); getContentPane().add(bbPanel, BorderLayout.SOUTH); pack(); this.setResizable(false); } public void done() { okButton.setEnabled(true); cancelButton.setEnabled(false); } public void open() { progressArea.setText(""); canceled = false; Util.placeDialog(optDiag, panel.frame()); okButton.setEnabled(false); cancelButton.setEnabled(true); new FocusRequester(okButton); optDiag.setVisible(true); } } }
package org.apache.xmlrpc.secure; import java.security.KeyStore; import java.security.Provider; import java.security.Security; public class SecurityTool implements SecurityConstants { /** * Class name of the security provider to be * used by the secure web server. */ protected static String securityProviderClass; /** * The security protocol to be used by the * secure web server. Currently the options are * SSL and TLS. */ private static String securityProtocol; /** * Password used to access the key store. */ private static String keyStorePassword; /** * Format to be used for the key store. With * the Sun JSSE the standard "JKS" format is * available along with the "PKCS12" format. */ private static String keyStoreType; /** * Path to the key store that will be used by * the secure web server. */ private static String keyStore; /** * Password used to access the key store. */ private static String trustStorePassword; /** * Format to be used for the key store. With * the Sun JSSE the standard "JKS" format is * available along with the "PKCS12" format. */ private static String trustStoreType; /** * Path to the key store that will be used by * the secure web server. */ private static String trustStore; /** * The type of key manager to be used by the * secure web server. With the Sun JSSE only * type available is the X509 type which * is implemented in the SunX509 classes. */ private static String keyManagerType; /** * The protocol handler package to use for * the secure web server. This allows the URL * class to handle https streams. */ private static String protocolHandlerPackages; public static void setup() throws Exception { /* * We want to dynamically register the SunJSSE provider * because we don't want people to have to modify their * JVM setups manually. */ Security.addProvider((Provider)Class.forName( SecurityTool.getSecurityProviderClass()).newInstance()); /* * Set the packages that will provide the URL stream * handlers that can cope with TLS/SSL. */ System.setProperty(PROTOCOL_HANDLER_PACKAGES, SecurityTool.getProtocolHandlerPackages()); // Setup KeyStore System.setProperty(KEY_STORE_TYPE, SecurityTool.getKeyStoreType()); System.setProperty(KEY_STORE, SecurityTool.getKeyStore()); System.setProperty(KEY_STORE_PASSWORD, SecurityTool.getKeyStorePassword()); // Setup TrustStore System.setProperty(TRUST_STORE_TYPE, SecurityTool.getTrustStoreType()); System.setProperty(TRUST_STORE, SecurityTool.getTrustStore()); System.setProperty(TRUST_STORE_PASSWORD, SecurityTool.getTrustStorePassword()); } /** * Set the protocol handler packages. * * @param String protocol handler package. */ public static void setProtocolHandlerPackages(String x) { protocolHandlerPackages = x; } /** * Get the protocol handler packages. * * @param String protocol handler package. */ public static String getProtocolHandlerPackages() { if (System.getProperty(PROTOCOL_HANDLER_PACKAGES) != null) { return System.getProperty(PROTOCOL_HANDLER_PACKAGES); } if (protocolHandlerPackages == null) { return DEFAULT_PROTOCOL_HANDLER_PACKAGES; } else { return protocolHandlerPackages; } } /** * Set the security provider class. * * @param String name of security provider class. */ public static void setSecurityProviderClass(String x) { securityProviderClass = x; } /** * Get the security provider class. * * @return String name of security provider class. */ public static String getSecurityProviderClass() { if (System.getProperty(SECURITY_PROVIDER_CLASS) != null) { return System.getProperty(SECURITY_PROVIDER_CLASS); } if (securityProviderClass == null) { return DEFAULT_SECURITY_PROVIDER_CLASS; } else { return securityProviderClass; } } /** * Set the key store password. * * @param String key store password. */ public static void setKeyStorePassword(String x) { keyStorePassword = x; } /** * Set the security protocol. * * @param String security protocol. */ public static void setSecurityProtocol(String x) { securityProtocol = x; } /** * Get the security protocol. * * @return String security protocol. */ public static String getSecurityProtocol() { if (System.getProperty(SECURITY_PROTOCOL) != null) { return System.getProperty(SECURITY_PROTOCOL); } if (securityProtocol== null) { return DEFAULT_SECURITY_PROTOCOL; } else { return securityProtocol; } } /** * Set the key store location. * * @param String key store location. */ public static void setKeyStore(String x) { keyStore = x; } /** * Get the key store location. * * @return String key store location. */ public static String getKeyStore() { if (System.getProperty(KEY_STORE) != null) { return System.getProperty(KEY_STORE); } if (keyStore == null) { return DEFAULT_KEY_STORE; } else { return keyStore; } } /** * Set the key store format. * * @param String key store format. */ public static void setKeyStoreType(String x) { keyStoreType = x; } /** * Get the key store format. * * @return String key store format. */ public static String getKeyStoreType() { if (System.getProperty(KEY_STORE_TYPE) != null) { return System.getProperty(KEY_STORE_TYPE); } if (keyStoreType == null) { /* * If the keystore type hasn't been specified * then let the system determine the default * type. */ return KeyStore.getDefaultType(); } else { return keyStoreType; } } /** * Get the key store password. * * @return String key store password. */ public static String getKeyStorePassword() { if (System.getProperty(KEY_STORE_PASSWORD) != null) { return System.getProperty(KEY_STORE_PASSWORD); } if (keyStorePassword == null) { return DEFAULT_KEY_STORE_PASSWORD; } else { return keyStorePassword; } } /** * Set the key store location. * * @param String key store location. */ public static void setTrustStore(String x) { trustStore = x; } /** * Get the key store location. * * @return String key store location. */ public static String getTrustStore() { if (System.getProperty(TRUST_STORE) != null) { return System.getProperty(TRUST_STORE); } if (trustStore == null) { return DEFAULT_TRUST_STORE; } else { return trustStore; } } /** * Set the key store format. * * @param String key store format. */ public static void setTrustStoreType(String x) { trustStoreType = x; } /** * Get the key store format. * * @return String key store format. */ public static String getTrustStoreType() { if (System.getProperty(TRUST_STORE_TYPE) != null) { return System.getProperty(TRUST_STORE_TYPE); } if (trustStoreType == null) { /* * If the keystore type hasn't been specified * then let the system determine the default * type. */ return KeyStore.getDefaultType(); } else { return trustStoreType; } } /** * Set the trust store password. * * @param String trust store password. */ public static void setTrustStorePassword(String x) { trustStorePassword = x; } /** * Get the trust store password. * * @return String trust store password. */ public static String getTrustStorePassword() { if (System.getProperty(TRUST_STORE_PASSWORD) != null) { return System.getProperty(TRUST_STORE_PASSWORD); } if (trustStorePassword == null) { return DEFAULT_TRUST_STORE_PASSWORD; } else { return trustStorePassword; } } /** * Set the key manager type. * * @param String key manager type. */ public static void setKeyManagerType(String x) { keyManagerType = x; } /** * Get the key manager type. * * @return String key manager type. */ public static String getKeyManagerType() { if (System.getProperty(KEY_MANAGER_TYPE) != null) { return System.getProperty(KEY_MANAGER_TYPE); } if (keyManagerType == null) { return DEFAULT_KEY_MANAGER_TYPE; } else { return keyManagerType; } } }
package org.jivesoftware; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.spark.ChatManager; import org.jivesoftware.spark.SparkManager; import org.jivesoftware.spark.UserManager; import org.jivesoftware.spark.ui.ChatRoom; import org.jivesoftware.spark.ui.conferences.ConferenceUtils; import org.jivesoftware.spark.util.log.Log; import org.jivesoftware.spark.util.StringUtils; import org.jivesoftware.spark.util.Utilities; /** * Uses the Windows registry to perform URI XMPP mappings. * * @author Derek DeMoro */ public class SparkStartupListener implements com.install4j.api.launcher.StartupNotification.Listener { public void startupPerformed(String string) { if (string.indexOf("xmpp") == -1) { return; } if (string.indexOf("?message") != -1) { try { handleJID(string); } catch (Exception e) { Log.error(e); } } else if (string.indexOf("?join") != -1) { try { handleConference(string); } catch (Exception e) { Log.error(e); } } else if (string.indexOf("?") == -1) { // Then use the direct jid int index = string.indexOf(":"); if (index != -1) { String jid = string.substring(index + 1); UserManager userManager = SparkManager.getUserManager(); String nickname = userManager.getUserNicknameFromJID(jid); if (nickname == null) { nickname = jid; } ChatManager chatManager = SparkManager.getChatManager(); ChatRoom chatRoom = chatManager.createChatRoom(jid, nickname, nickname); chatManager.getChatContainer().activateChatRoom(chatRoom); } } } /** * Factory method to handle different types of URI Mappings. * * @param uriMapping the uri mapping string. * @throws Exception thrown if an exception occurs. */ public void handleJID(String uriMapping) throws Exception { int index = uriMapping.indexOf("xmpp:"); int messageIndex = uriMapping.indexOf("?message"); int bodyIndex = uriMapping.indexOf("body="); String jid = uriMapping.substring(index + 5, messageIndex); String body = null; // Find body if (bodyIndex != -1) { body = uriMapping.substring(bodyIndex + 5); } body = StringUtils.unescapeFromXML(body); body = StringUtils.replace(body, "%20", " "); UserManager userManager = SparkManager.getUserManager(); String nickname = userManager.getUserNicknameFromJID(jid); if (nickname == null) { nickname = jid; } ChatManager chatManager = SparkManager.getChatManager(); ChatRoom chatRoom = chatManager.createChatRoom(jid, nickname, nickname); if (body != null) { Message message = new Message(); message.setBody(body); chatRoom.sendMessage(message); } chatManager.getChatContainer().activateChatRoom(chatRoom); } /** * Handles the URI Mapping to join a conference room. * * @param uriMapping the uri mapping. * @throws Exception thrown if the conference cannot be joined. */ public void handleConference(String uriMapping) throws Exception { int index = uriMapping.indexOf("xmpp:"); int join = uriMapping.indexOf("?join"); String conference = uriMapping.substring(index + 5, join); ConferenceUtils.autoJoinConferenceRoom(conference, conference, null); } public static void main(String args[]){ SparkStartupListener l = new SparkStartupListener(); l.startupPerformed("xmpp:jorge@jivesoftware.com?message;body=hello%20there"); } }
package org.tuckey.web.filters.urlrewrite; import org.tuckey.web.filters.urlrewrite.extend.RewriteMatch; import org.tuckey.web.filters.urlrewrite.utils.Log; import org.tuckey.web.filters.urlrewrite.utils.StringMatchingMatcher; import org.tuckey.web.filters.urlrewrite.utils.StringUtils; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Hashtable; public class Run { private static Log log = Log.getLog(Run.class); /** * Weather or not the user wants the classStr created for each run. */ private boolean newEachTime = false; private String classStr; private static final String DEAULT_METHOD_STR = "run"; private String methodStr = DEAULT_METHOD_STR; /** * Used to identify the condition. */ private int id = 0; private String error = null; private boolean valid = false; private boolean initialised = false; /** * The instance of the classStr to run. Note, will be null if newEachTime is true. */ private Object runClassInstance; /** * handles to the methods we are going to run. */ private Constructor runConstructor; private Method initMethod; private Method filterInitMethod; private Method runMethod; private Class[] runMethodParams; private String[] runMethodParamNames; private boolean runMethodUseDefaultParams = true; private Method destroyMethod; /** * The config that we pass to the objectwe are trying to run. */ private RunConfig runServletConfig; private Hashtable initParams = new Hashtable(); private static boolean loadClass = true; private static Class[][] runMethodPossibleSignatures = { {ServletRequest.class, ServletResponse.class}, {ServletRequest.class}, {ServletResponse.class}, {HttpServletRequest.class, HttpServletResponse.class}, {HttpServletRequest.class}, {HttpServletResponse.class} }; private boolean filter = false; /** * @see #initialise(ServletContext,Class) initialise */ public boolean initialise(ServletContext context) { return initialise(context, null); } /** * Initialise the Run, this will check specified classStr, constructor and methodStr exist. */ public boolean initialise(ServletContext context, Class extraParam) { log.debug("initialising run"); runServletConfig = new RunConfig(context, initParams); initialised = true; valid = false; if (StringUtils.isBlank(classStr)) { setError("cannot initialise run " + id + " value is empty"); return valid; } if (methodStr == null) { methodStr = DEAULT_METHOD_STR; } log.debug("methodStr: " + methodStr); String rawMethodStr = methodStr; int bkStart = rawMethodStr.indexOf('('); int bkEnd = rawMethodStr.indexOf(')'); if (bkStart != -1 && bkEnd != -1 && (bkEnd - bkStart) > 0) { runMethodUseDefaultParams = false; // set method str back to just method name methodStr = rawMethodStr.substring(0, bkStart); // get the list of params ie, "String name, int id" String paramsList = rawMethodStr.substring(bkStart + 1, bkEnd); paramsList = StringUtils.trimToNull(paramsList); if (paramsList != null) { String[] params = paramsList.split(","); // validate and clean the incoming params list Class[] paramClasses = new Class[params.length]; String[] paramNames = new String[params.length]; for (int i = 0; i < params.length; i++) { String param = StringUtils.trimToNull(params[i]); if (param == null) continue; if (param.contains(" ")) { String paramName = StringUtils.trimToNull(param.substring(param.indexOf(" "))); if (paramName != null) { log.debug("param name: " + paramName); paramNames[i] = paramName; } param = param.substring(0, param.indexOf(' ')); } Class clazz = parseClass(param); if (clazz == null) return valid; paramClasses[i] = clazz; } runMethodParams = paramClasses; runMethodParamNames = paramNames; } } if (loadClass) { prepareRunObject(extraParam); } else { valid = true; } return valid; } /** * Turns a class or language keyword name into the Class object, works with short names, ie, L - Long. * <p/> * boolean Z * byte B * char C * class or interface Lclassname; * double D * float F * int I * long J * short S * * @see Class */ private Class parseClass(String param) { // do shortcuts Class paramClass = null; if ("boolean".equals(param) || "bool".equals(param) || "z".equalsIgnoreCase(param)) paramClass = boolean.class; if ("byte".equals(param) || "b".equalsIgnoreCase(param)) paramClass = byte.class; if ("char".equals(param) || "c".equalsIgnoreCase(param)) paramClass = char.class; if ("short".equals(param) || "s".equalsIgnoreCase(param)) paramClass = short.class; if ("int".equals(param) || "i".equalsIgnoreCase(param)) paramClass = int.class; if ("long".equals(param) || "l".equalsIgnoreCase(param)) paramClass = long.class; if ("float".equals(param) || "f".equalsIgnoreCase(param)) paramClass = float.class; if ("double".equals(param) || "d".equalsIgnoreCase(param)) paramClass = double.class; if ("Boolean".equals(param) || "Bool".equals(param)) paramClass = Boolean.class; if ("Byte".equals(param)) paramClass = Byte.class; if ("Character".equalsIgnoreCase(param) || "C".equals(param)) paramClass = Character.class; if ("Short".equals(param)) paramClass = Short.class; if ("Integer".equals(param)) paramClass = Integer.class; if ("Long".equals(param)) paramClass = Long.class; if ("Float".equals(param)) paramClass = Float.class; if ("Double".equals(param)) paramClass = Double.class; if ("Class".equalsIgnoreCase(param)) paramClass = Class.class; if ("Number".equalsIgnoreCase(param)) paramClass = Number.class; if ("Object".equalsIgnoreCase(param)) paramClass = Object.class; if ("String".equalsIgnoreCase(param) || "str".equalsIgnoreCase(param)) paramClass = String.class; if ("HttpServletRequest".equalsIgnoreCase(param) || "req".equalsIgnoreCase(param) || "request".equalsIgnoreCase(param)) paramClass = HttpServletRequest.class; if ("HttpServletResponse".equalsIgnoreCase(param) || "res".equalsIgnoreCase(param) || "response".equalsIgnoreCase(param)) paramClass = HttpServletResponse.class; if ("ServletRequest".equalsIgnoreCase(param)) paramClass = ServletRequest.class; if ("ServletResponse".equalsIgnoreCase(param)) paramClass = ServletResponse.class; if ("javax.servlet.FilterChain".equalsIgnoreCase(param) || "FilterChain".equalsIgnoreCase(param) || "chain".equalsIgnoreCase(param)) { filter = true; paramClass = FilterChain.class; } if (loadClass) { if (paramClass == null) { try { paramClass = Class.forName(param); if (paramClass == null) { setError("had trouble finding " + param + " after Class.forName got a null object"); return null; } } catch (ClassNotFoundException e) { setError("could not find " + param + " got a " + e.toString(), e); return null; } catch (NoClassDefFoundError e) { setError("could not find " + param + " got a " + e.toString(), e); return null; } } if (paramClass == null) { setError("could not find class of type " + param); return null; } } if (log.isDebugEnabled()) { log.debug("parseClass found class " + paramClass + " for " + param); } return paramClass; } /** * Prepare the object for running by constructing and setting up method handles. */ private void prepareRunObject(Class extraParam) { if (log.isDebugEnabled()) { log.debug("looking for class " + classStr); } Class runClass; try { runClass = Class.forName(classStr); if (runClass == null) { setError("had trouble finding " + classStr + " after Class.forName got a null object"); return; } } catch (ClassNotFoundException e) { setError("could not find " + classStr + " got a " + e.toString(), e); return; } catch (NoClassDefFoundError e) { setError("could not find " + classStr + " got a " + e.toString(), e); return; } try { runConstructor = runClass.getConstructor((Class[]) null); } catch (NoSuchMethodException e) { setError("could not get constructor for " + classStr, e); return; } if (!runMethodUseDefaultParams) { if (log.isDebugEnabled()) { log.debug("looking for " + methodStr + " with specific params"); } try { runMethod = runClass.getMethod(methodStr, runMethodParams); } catch (NoSuchMethodException e) { // do nothing } } else { if (log.isDebugEnabled()) { log.debug("looking for " + methodStr + "(ServletRequest, ServletResponse)"); } for (int i = 0; i < runMethodPossibleSignatures.length; i++) { Class[] runMethodPossibleSignature = runMethodPossibleSignatures[i]; if (extraParam != null) { if (runMethodPossibleSignature.length == 2) { runMethodPossibleSignature = new Class[]{runMethodPossibleSignature[0], runMethodPossibleSignature[1], extraParam}; } if (runMethodPossibleSignature.length == 1) { runMethodPossibleSignature = new Class[]{runMethodPossibleSignature[0], extraParam}; } } if (log.isDebugEnabled()) { String possible = ""; for (int j = 0; j < runMethodPossibleSignature.length; j++) { possible += (j > 0 ? "," : "") + runMethodPossibleSignature[j].getName(); } log.debug("looking for " + methodStr + "(" + possible + ")"); } try { runMethod = runClass.getMethod(methodStr, runMethodPossibleSignature); runMethodParams = runMethodPossibleSignature; break; } catch (NoSuchMethodException e) { // do nothing except be paranoid about resetting runMethodParams runMethodParams = null; } } if (runMethod == null) { setError("could not find method with the name " + methodStr + " on " + classStr); return; } } Method[] methods = runClass.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if ("destroy".equals(method.getName()) && method.getParameterTypes().length == 0) { log.debug("found destroy methodStr"); destroyMethod = method; } if ("init".equals(method.getName()) && method.getParameterTypes().length == 1 && ServletConfig.class.getName().equals(method.getParameterTypes()[0].getName())) { log.debug("found init methodStr"); initMethod = method; } if ("init".equals(method.getName()) && method.getParameterTypes().length == 1 && FilterConfig.class.getName().equals(method.getParameterTypes()[0].getName())) { log.debug("found filter init methodStr"); filterInitMethod = method; } if (initMethod != null && destroyMethod != null) break; } if (!newEachTime) { runClassInstance = fetchNewInstance(); } valid = true; } private void invokeDestroy(Object runClassInstanceToDestroy) { if (runClassInstanceToDestroy != null && destroyMethod != null) { if (log.isDebugEnabled()) { log.debug("running " + classStr + ".destroy()"); } try { destroyMethod.invoke(runClassInstanceToDestroy, (Object[]) null); } catch (IllegalAccessException e) { logInvokeException("destroy()", e); } catch (InvocationTargetException e) { logInvokeException("destroy()", e); } } } /** * Invokes the run method. * <p/> * Exceptions at invocation time are either rethrown as a ServletException or as thr original exception if we can * manage to do it. * <p/> * We don't log exceptions here, the container can do that. */ private RewriteMatch invokeRunMethod(Object classInstanceToRun, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain chain, Object[] matchObjs) throws ServletException, InvocationTargetException { if (log.isDebugEnabled()) { log.debug("running " + classStr + "." + getMethodSignature() + " "); } if (classInstanceToRun == null || runMethod == null) return null; RewriteMatch returned = null; Object[] params = null; if (runMethodParams != null && runMethodParams.length > 0) { params = new Object[runMethodParams.length]; int paramMatchCounter = 0; for (int i = 0; i < runMethodParams.length; i++) { Class runMethodParam = runMethodParams[i]; String runMethodParamName = null; if (runMethodParamNames != null && runMethodParamNames.length > i) { runMethodParamName = runMethodParamNames[i]; } Object param; if (runMethodParamName != null) { log.debug("need parameter from request called " + runMethodParamName); Object matchObj = httpServletRequest.getParameter(runMethodParamName); param = getConvertedParam(runMethodParam, matchObj); } else if (runMethodParam.isAssignableFrom(HttpServletRequest.class)) { param = httpServletRequest; } else if (runMethodParam.isAssignableFrom(HttpServletResponse.class)) { param = httpServletResponse; } else if (runMethodParam.isAssignableFrom(FilterChain.class)) { param = chain; } else { Object matchObj = null; if (matchObjs != null && matchObjs.length > paramMatchCounter) { matchObj = matchObjs[paramMatchCounter]; } param = getConvertedParam(runMethodParam, matchObj); paramMatchCounter++; } params[i] = param; if (log.isDebugEnabled()) { log.debug("argument " + i + " (" + runMethodParam.getName() + "): " + param); } } } try { Object objReturned = runMethod.invoke(classInstanceToRun, (Object[]) params); if (objReturned != null && objReturned instanceof RewriteMatch) { // if we get a rewriteMatch object then return it for execution later returned = (RewriteMatch) objReturned; } } catch (IllegalAccessException e) { if (log.isDebugEnabled()) log.debug(e); throw new ServletException(e); } return returned; } private Object getConvertedParam(Class runMethodParam, Object matchObj) { // for how to handle methods better Object param = null; if (matchObj == null) { if (runMethodParam.isPrimitive()) { if (runMethodParam.equals(boolean.class)) param = Boolean.FALSE; else if (runMethodParam.equals(char.class)) param = new Character('\u0000'); else if (runMethodParam.equals(byte.class)) param = new Byte((byte) 0); else if (runMethodParam.equals(short.class)) param = new Short((short) 0); else if (runMethodParam.equals(int.class)) param = new Integer(0); else if (runMethodParam.equals(long.class)) param = new Long(0L); else if (runMethodParam.equals(float.class)) param = new Float(0f); else if (runMethodParam.equals(double.class)) param = new Double(0d); } } else { if (runMethodParam.equals(Boolean.class) || runMethodParam.equals(boolean.class)) param = Boolean.valueOf((String) matchObj); else if (runMethodParam.equals(Character.class) || runMethodParam.equals(char.class)) param = new Character(((String) matchObj).charAt(0)); else if (runMethodParam.equals(Byte.class) || runMethodParam.equals(byte.class)) param = Byte.valueOf((String) matchObj); else if (runMethodParam.equals(Short.class) || runMethodParam.equals(short.class)) param = Short.valueOf((String) matchObj); else if (runMethodParam.equals(Integer.class) || runMethodParam.equals(int.class)) param = Integer.valueOf((String) matchObj); else if (runMethodParam.equals(Long.class) || runMethodParam.equals(long.class)) param = Long.valueOf((String) matchObj); else if (runMethodParam.equals(Float.class) || runMethodParam.equals(float.class)) param = Float.valueOf((String) matchObj); else if (runMethodParam.equals(Double.class) || runMethodParam.equals(double.class)) param = Double.valueOf((String) matchObj); else if (matchObj != null && matchObj instanceof Throwable && runMethodParam.isAssignableFrom(matchObj.getClass())) param = matchObj; else { try { // last attempt param = runMethodParam.cast(matchObj); } catch (ClassCastException e) { // do nothing } } } return param; } /** * Run the underlying destroy methodStr on the run classStr. */ public void destroy() { initialised = false; valid = false; invokeDestroy(runClassInstance); // be paranoid and clean up all hooks to users classStr destroyMethod = null; runMethod = null; initMethod = null; filterInitMethod = null; runServletConfig = null; runConstructor = null; runClassInstance = null; methodStr = null; classStr = null; error = null; } /** * @see #execute(HttpServletRequest,HttpServletResponse,Object[],FilterChain) */ public RewriteMatch execute(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException, InvocationTargetException { Object[] params = null; return execute(httpServletRequest, httpServletResponse, params, null); } public RewriteMatch execute(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, StringMatchingMatcher matcher, ConditionMatch conditionMatch, FilterChain chain) throws IOException, ServletException, InvocationTargetException { int matches = 0; int condMatches = 0; if (matcher != null && matcher.isFound()) { matches = matcher.groupCount(); } if (conditionMatch != null) { StringMatchingMatcher condMatcher = conditionMatch.getMatcher(); if (condMatcher != null && condMatcher.isFound()) { condMatches = condMatcher.groupCount(); } } String[] allMatches = null; if ((matches + condMatches) > 0) { allMatches = new String[matches + condMatches]; if (matcher != null && matches > 0) { for (int i = 0; i < matches; i++) { allMatches[i] = matcher.group(i + 1); // note, good groups start from 1 } } if (conditionMatch != null && condMatches > 0) { for (int i = 0; i < condMatches; i++) { allMatches[i] = conditionMatch.getMatcher().group(i); } } } return execute(httpServletRequest, httpServletResponse, allMatches, chain); } /** * Will invoke the instance created in initialise. * * @param httpServletRequest * @param httpServletResponse */ public RewriteMatch execute(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Throwable throwable) throws IOException, ServletException, InvocationTargetException { Object[] params = new Object[]{throwable}; return execute(httpServletRequest, httpServletResponse, params, null); } public RewriteMatch execute(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object[] params) throws IOException, ServletException, InvocationTargetException { return execute(httpServletRequest, httpServletResponse, params, null); } public RewriteMatch execute(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object[] params, FilterChain chain) throws IOException, ServletException, InvocationTargetException { if (!initialised) { log.debug("not initialised skipping"); return null; } if (!valid) { log.debug("not valid skipping"); return null; } RewriteMatch returned; try { if (newEachTime) { Object newRunClassInstance = fetchNewInstance(); returned = invokeRunMethod(newRunClassInstance, httpServletRequest, httpServletResponse, chain, params); invokeDestroy(newRunClassInstance); } else { returned = invokeRunMethod(runClassInstance, httpServletRequest, httpServletResponse, chain, params); } } catch (ServletException e) { httpServletRequest.setAttribute("javax.servlet.error.exception", e); throw e; } return returned; } private void logInvokeException(String methodStr, Exception e) { Throwable cause = e.getCause(); if (cause == null) { setError("when invoking " + methodStr + " on " + classStr + " got an " + e.toString(), e); } else { setError("when invoking " + methodStr + " on " + classStr + " got an " + e.toString() + " caused by " + cause.toString(), cause); } } /** * Get a new instance of the classStr we want to run and init if required. * * @return the new instance */ private Object fetchNewInstance() { Object obj; log.debug("getting new instance of " + classStr); try { obj = runConstructor.newInstance((Object[]) null); } catch (InstantiationException e) { logInvokeException("constructor", e); return null; } catch (IllegalAccessException e) { logInvokeException("constructor", e); return null; } catch (InvocationTargetException e) { logInvokeException("constructor", e); return null; } if (initMethod != null) { log.debug("about to run init(ServletConfig) on " + classStr); Object[] args = new Object[1]; args[0] = runServletConfig; try { initMethod.invoke(obj, args); } catch (IllegalAccessException e) { logInvokeException("init(ServletConfig)", e); return null; } catch (InvocationTargetException e) { logInvokeException("init(ServletConfig)", e); return null; } } if (filterInitMethod != null) { log.debug("about to run init(FilterConfig) on " + classStr); Object[] args = new Object[1]; args[0] = runServletConfig; try { filterInitMethod.invoke(obj, args); } catch (IllegalAccessException e) { logInvokeException("init(FilterConfig)", e); return null; } catch (InvocationTargetException e) { logInvokeException("init(FilterConfig)", e); return null; } } return obj; } public String getError() { return error; } public void setId(int id) { this.id = id; } public int getId() { return id; } public boolean isValid() { return valid; } public boolean isInitialised() { return initialised; } /** * The name of the classStr that will be run for each rule match. * * @return String eg, org.tuckey.YellowObject */ public String getClassStr() { return classStr; } /** * The name of the methodStr that will be run for each rule match. * * @return String eg, setDate */ public String getMethodStr() { return methodStr; } /** * The name of the method signature ie, setDate(java.util.Date, int). Includes fully qualified object names * for paramters. */ public String getMethodSignature() { if (methodStr == null) return null; StringBuffer sb = new StringBuffer(methodStr); if (runMethodParams != null) { for (int i = 0; i < runMethodParams.length; i++) { Class runMethodParam = runMethodParams[i]; if (runMethodParam == null) continue; if (i == 0) sb.append("("); if (i > 0) sb.append(", "); sb.append(runMethodParam.getName()); if (i + 1 == runMethodParams.length) sb.append(")"); } } return sb.toString(); } public boolean isNewEachTime() { return newEachTime; } public void setNewEachTime(boolean newEachTime) { this.newEachTime = newEachTime; } /** * Gets a handle on the instance of the class run is running. * <p/> * If newEachTime is set to true this will always return null. */ public Object getRunClassInstance() { return runClassInstance; } public void addInitParam(String name, String value) { if (name != null) { initParams.put(name, value); } } public String getInitParam(String paramName) { return (String) initParams.get(paramName); } public void setClassStr(String classStr) { this.classStr = classStr; } public void setMethodStr(String methodStr) { this.methodStr = methodStr; } public static void setLoadClass(boolean loadClass) { Run.loadClass = loadClass; } public void setError(String error, Throwable t) { this.error = error; log.error(error, t); } public void setError(String error) { this.error = error; log.error(error); } public String getDisplayName() { return "Run " + id; } public boolean isFilter() { return filter; } }
package org.helioviewer.jhv.io; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; import javax.swing.SwingWorker; import org.helioviewer.base.AlphanumComparator; import org.helioviewer.base.DownloadStream; import org.helioviewer.base.logging.Log; import org.helioviewer.jhv.JHVGlobals; import org.helioviewer.jhv.Settings; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; public class DataSources { public static final HashSet<String> SupportedObservatories = new HashSet<String>(); /** * Item to select. Has a nice toString() so that a list can be put into a * JComboBox * <p> * Also has some advanced sorting and overloaded equal. * * @author Helge Dietert */ public class Item implements Comparable<Item> { /** * Flag if this should take as default item */ private final boolean defaultItem; /** * Tooltip description */ private final String description; /** * Key as needed to send to the API for this item */ private final String key; /** * Display name for a dropdown list */ private final String name; /** * Creates a new item * * @param key * Key to reference the API * @param defaultItem * Flag to indicate usage as default * @param name * Nice name to show, will be shown as toString() * @param description * Longer description */ public Item(String key, boolean defaultItem, String name, String description) { this.key = key; this.defaultItem = defaultItem; this.name = name; this.description = description; } /** * Compare it to some other item with the advanced key * * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(Item other) { return keyComparator.compare(key, other.key); } /** * Sorting and equal from sortKey,key * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { try { Item other = (Item) obj; return key == other.key; } catch (ClassCastException e) { return false; } catch (NullPointerException e) { return false; } } /** * @return the description */ public String getDescription() { return description; } /** * @return the key */ public String getKey() { return key; } /** * @return the name */ public String getName() { return name; } /** * True if it was created as default item * * @return the defaultItem */ public boolean isDefaultItem() { return defaultItem; } /** * Shows a nice string (name) */ @Override public String toString() { return name; } } private static DataSources instance; private DataSources() {} public static DataSources getSingletonInstance() { if (instance == null) { instance = new DataSources(); String prop = Settings.getSingletonInstance().getProperty("supported.data.sources"); if (prop != null && SupportedObservatories.isEmpty()) { String supportedObservatories[] = prop.split(" "); for (String s : supportedObservatories) { if (!s.isEmpty()) { SupportedObservatories.add(s); } } } } return instance; } /** * Result with the available data sources */ private JSONObject jsonResult; /** * Used comparator to sort the items after the key */ private final Comparator<String> keyComparator = new AlphanumComparator(); private void reload() { jsonResult = null; while (true) { try { String queryString = Settings.getSingletonInstance().getProperty("API.dataSources.path"); URL query = new URL(queryString); DownloadStream ds = new DownloadStream(query, JHVGlobals.getStdConnectTimeout(), JHVGlobals.getStdReadTimeout()); Reader reader = new BufferedReader(new InputStreamReader(ds.getInput(), "UTF-8")); jsonResult = new JSONObject(new JSONTokener(reader)); break; } catch (MalformedURLException e) { // Should not occur Log.error("Invalid url to retrieve data source", e); break; } catch (JSONException e) { // Should not occur Log.error("While retrieving the available data sources got invalid response", e); break; } catch (IOException e) { // Log.error("Error while reading the available data sources", // Message.err("Cannot Download Source Information", // "When trying to read the available data sources from the internet got:\n" // + e.getMessage(), false); try { Thread.sleep(5000); } catch (InterruptedException e1) { // Should not occur Log.error(e1); } } } } /** * For the given root this will create a sorted list or items * * @param root * Element for which the children will be created * @return List of items to select or null if some error occurs */ private Item[] getChildrenList(JSONObject root) { try { SortedSet<Item> children = new TreeSet<Item>(); Iterator<?> iter = root.keys(); while (iter.hasNext()) { String key = (String) iter.next(); JSONObject child = root.getJSONObject(key); Item newItem = new Item(key, child.optBoolean("default", false), child.getString("name").replace((char) 8287, ' '), // e.g. 304\u205f\u212b child.getString("description")); children.add(newItem); } return children.toArray(new Item[children.size()]); } catch (JSONException e) { Log.error("Error finding children of " + root, e); } return null; } /** * Gives the JSON Object for an detector * * @param observatory * Key of the observatory * @param instrument * Key of the instrument * @param detector * Key of the detector * @return JSON object for the given observatory * @throws JSONException */ private JSONObject getDetector(String observatory, String instrument, String detector) throws JSONException { return getInstrument(observatory, instrument).getJSONObject("children").getJSONObject(detector); } /** * Resolves the detectors for a observatory and instrument * * @param observatory * Name of observatory to query * @param instrument * Name of instrument to query * @return List of available measurements, null if not valid */ public Item[] getDetectors(String observatory, String instrument) { try { return getChildrenList(getInstrument(observatory, instrument).getJSONObject("children")); } catch (JSONException e) { Log.error("Cannot find instruments for " + observatory, e); return null; } } /** * Gives the JSON Object for an instrument * * @param observatory * Key of the observatory * @param instrument * Key of the instrument * @return JSON object for the given observatory * @throws JSONException */ private JSONObject getInstrument(String observatory, String instrument) throws JSONException { return getObservatory(observatory).getJSONObject("children").getJSONObject(instrument); } /** * Resolves the instruments for a observatory * * @param observatory * Name of observatory for which the instruments are returned * @return List of available instruments, null if this observatory is not * supported */ public Item[] getInstruments(String observatory) { try { return getChildrenList(getObservatory(observatory).getJSONObject("children")); } catch (JSONException e) { Log.error("Cannot find instruments for " + observatory, e); return null; } } /** * Resolves the detectors for a observatory and instrument * * @param observatory * Name of observatory to query * @param instrument * Name of instrument to query * @param detector * Name of detector to query * @return List of available measurements, null if not valid */ public Item[] getMeasurements(String observatory, String instrument, String detector) { try { return getChildrenList(getDetector(observatory, instrument, detector).getJSONObject("children")); } catch (JSONException e) { Log.error("Cannot find instruments for " + observatory, e); return null; } } /** * Resolve the available observatories * * @return List of available observatories */ public Item[] getObservatories() { ArrayList<Item> result = new ArrayList<Item>(); for (Item item : getChildrenList(jsonResult)) { if (SupportedObservatories.contains(item.getName())) { result.add(item); } } return result.toArray(new Item[result.size()]); } private JSONObject getObservatory(String observatory) throws JSONException { return jsonResult.getJSONObject(observatory); } private String selectedServer = ""; private final String[] serverList = new String[] { "ROB", "GSFC", "IAS" }; public void changeServer(String server, final boolean donotloadStartup) { selectedServer = server; if (server.contains("ROB")) { Settings.getSingletonInstance().setProperty("API.dataSources.path", "http://swhv.oma.be/hv/api/?action=getDataSources&verbose=true&enable=[STEREO_A,STEREO_B,PROBA2]"); Settings.getSingletonInstance().setProperty("API.jp2images.path", "http://swhv.oma.be/hv/api/index.php"); Settings.getSingletonInstance().setProperty("API.jp2series.path", "http://swhv.oma.be/hv/api/index.php"); Settings.getSingletonInstance().setProperty("default.remote.path", "jpip://swhv.oma.be:8090"); Settings.getSingletonInstance().setProperty("API.event.path", "http://swhv.oma.be/hv/api/"); Settings.getSingletonInstance().setProperty("default.httpRemote.path", "http://swhv.oma.be/hv/jp2/"); } else if (server.contains("GSFC")) { Settings.getSingletonInstance().setProperty("API.dataSources.path", "http://helioviewer.org/api/?action=getDataSources&verbose=true&enable=[STEREO_A,STEREO_B,PROBA2]"); Settings.getSingletonInstance().setProperty("API.jp2images.path", "http://helioviewer.org/api/index.php"); Settings.getSingletonInstance().setProperty("API.jp2series.path", "http://helioviewer.org/api/index.php"); Settings.getSingletonInstance().setProperty("default.remote.path", "jpip://helioviewer.org:8090"); Settings.getSingletonInstance().setProperty("API.event.path", "http://helioviewer.org/api/"); Settings.getSingletonInstance().setProperty("default.httpRemote.path", "http://helioviewer.org/jp2/"); } else if (server.contains("IAS")) { Settings.getSingletonInstance().setProperty("API.dataSources.path", "http://helioviewer.ias.u-psud.fr/helioviewer/api/?action=getDataSources&verbose=true&enable=[STEREO_A,STEREO_B,PROBA2]"); Settings.getSingletonInstance().setProperty("API.jp2images.path", "http://helioviewer.ias.u-psud.fr/helioviewer/api/index.php"); Settings.getSingletonInstance().setProperty("API.jp2series.path", "http://helioviewer.ias.u-psud.fr/helioviewer/api/index.php"); Settings.getSingletonInstance().setProperty("default.remote.path", "jpip://helioviewer.ias.u-psud.fr:8080"); Settings.getSingletonInstance().setProperty("API.event.path", "http://helioviewer.ias.u-psud.fr/helioviewer/api/"); Settings.getSingletonInstance().setProperty("default.httpRemote.path", "http://helioviewer.ias.u-psud.fr/helioviewer/jp2/"); } SwingWorker<Void, Void> reloadSources = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() { Thread.currentThread().setName("ReloadServer"); reload(); return null; } @Override protected void done() { for (DataSourcesListener l : listeners) { l.serverChanged(donotloadStartup); } } }; reloadSources.execute(); } public String[] getServerList() { return serverList; } public String getSelectedServer() { return selectedServer; } private static final HashSet<DataSourcesListener> listeners = new HashSet<DataSourcesListener>(); public void addListener(DataSourcesListener listener) { listeners.add(listener); } public void removeListener(DataSourcesListener listener) { listeners.remove(listener); } }
package zerocopy; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; public class TraditionalClient { public static void main(String[] args) { int port = 2000; String server = "localhost"; Socket socket = null; String lineToBeSent; DataOutputStream output = null; FileInputStream inputStream = null; int ERROR = 1; // connect to server try { socket = new Socket(server, port); System.out.println("Connected with server " + socket.getInetAddress() + ":" + socket.getPort()); } catch (UnknownHostException e) { System.out.println(e); System.exit(ERROR); } catch (IOException e) { System.out.println(e); System.exit(ERROR); } try { String fname = "src/zerocopy/data.txt"; inputStream = new FileInputStream(fname); output = new DataOutputStream(socket.getOutputStream()); long start = System.currentTimeMillis(); byte[] b = new byte[4096]; long read = 0, total = 0; while ((read = inputStream.read(b)) >= 0) { total = total + read; output.write(b); } System.out.println("bytes send--" + total + " and totaltime--" + (System.currentTimeMillis() - start)); } catch (IOException e) { System.out.println(e); } try { output.close(); socket.close(); inputStream.close(); } catch (IOException e) { System.out.println(e); } } }
package org.helioviewer.jhv.export; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import org.helioviewer.jhv.opengl.GLInfo; import com.jogamp.opengl.util.awt.ImageUtil; public class ExportUtils { public static BufferedImage pasteCanvases(BufferedImage im1, BufferedImage im2, int movieLinePosition, int height) { ImageUtil.flipImageVertically(im1); if (im2 == null) return im1; BufferedImage ret = new BufferedImage(im1.getWidth(), height, im1.getType()); Graphics2D g2 = ret.createGraphics(); g2.drawImage(im1, null, 0, 0); AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(1, 1), AffineTransformOp.TYPE_BILINEAR); im2 = op.filter(im2, null); g2.drawImage(im2, 0, im1.getHeight(), im1.getWidth(), ret.getHeight() - im1.getHeight(), null); if (ExportMovie.EVEMovieLinePosition != -1) { g2.setColor(Color.BLACK); double scaleY = (ret.getHeight() - im1.getHeight()) / (double) im2.getHeight(); double scaleX = ret.getWidth() / (double) im2.getWidth(); AffineTransform at = AffineTransform.getTranslateInstance(0, im1.getHeight()); at.concatenate(AffineTransform.getScaleInstance(scaleX, scaleY)); g2.setTransform(at); g2.drawLine(movieLinePosition * GLInfo.pixelScale[0], 0, movieLinePosition * GLInfo.pixelScale[0], im2.getHeight()); } g2.dispose(); return ret; } }
package tk.teamfield3.jTTD.util.math; public class Quaternion { private float x; private float y; private float z; private float w; public Quaternion(float x, float y, float z, float w) { this.x = x; this.y = y; this.z = z; this.w = w; } public float length() { return (float) Math.sqrt(x * x + y * y + z * z + w * w); } public Quaternion getNormalized() { float length = length(); return new Quaternion(x / length, y / length, z / length, w / length); } public Quaternion conjugate() { return new Quaternion(-x, -y, -z, w); } public Quaternion multiply(Quaternion r) { float wNew = w * r.getW() - x * r.getX() - y * r.getY() - z * r.getZ(); float xNew = x * r.getW() + w * r.getX() + y * r.getZ() - z * r.getY(); float yNew = y * r.getW() + w * r.getY() + z * r.getX() - x * r.getZ(); float zNew = z * r.getW() + w * r.getZ() + x * r.getY() - y * r.getX(); return new Quaternion(xNew, yNew, zNew, wNew); } public Quaternion multiply(Vector3f r) { float wNew = -x * r.getX() - y * r.getY() - z * r.getZ(); float xNew = w * r.getX() + y * r.getZ() - z * r.getY(); float yNew = w * r.getY() + z * r.getX() - x * r.getZ(); float zNew = w * r.getZ() + x * r.getY() - y * r.getX(); return new Quaternion(xNew, yNew, zNew, wNew); } public float getX() { return x; } public void setX(float x) { this.x = x; } public float getY() { return y; } public void setY(float y) { this.y = y; } public float getZ() { return z; } public void setZ(float z) { this.z = z; } public float getW() { return w; } public void setW(float w) { this.w = w; } }
package krasa.grepconsole.tail; import com.intellij.execution.DefaultExecutionResult; import com.intellij.execution.ExecutionException; import com.intellij.execution.ExecutionManager; import com.intellij.execution.Executor; import com.intellij.execution.configurations.RunProfile; import com.intellij.execution.configurations.RunProfileState; import com.intellij.execution.filters.Filter; import com.intellij.execution.filters.TextConsoleBuilder; import com.intellij.execution.filters.TextConsoleBuilderFactory; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.ui.ConsoleView; import com.intellij.execution.ui.ExecutionConsole; import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.execution.ui.RunnerLayoutUi; import com.intellij.execution.ui.actions.CloseAction; import com.intellij.execution.ui.layout.PlaceInGrid; import com.intellij.icons.AllIcons; import com.intellij.notification.Notification; import com.intellij.notification.Notifications; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.ComponentWithActions; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.ui.content.Content; import krasa.grepconsole.plugin.GrepConsoleApplicationComponent; import krasa.grepconsole.plugin.GrepProjectComponent; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Copy of com.intellij.execution.RunContentExecutor Runs a process and prints the output in a content tab within the * Run toolwindow. * * @author yole */ public class TailContentExecutor implements Disposable { private final Project myProject; private final ProcessHandler myProcess; private final List<Filter> myFilterList = new ArrayList<>(); private Runnable myRerunAction; private Runnable myStopAction; private Runnable myAfterCompletion; private Computable<Boolean> myStopEnabled; private String myTitle = "Output"; private String myHelpId = null; private boolean myActivateToolWindow = true; private File file; public TailContentExecutor(@NotNull Project project, @NotNull ProcessHandler process) { myProject = project; myProcess = process; } public TailContentExecutor withFilter(Filter filter) { myFilterList.add(filter); return this; } public TailContentExecutor withTitle(String title) { myTitle = title; return this; } public TailContentExecutor withRerun(Runnable rerun) { myRerunAction = rerun; return this; } public TailContentExecutor withStop(@NotNull Runnable stop, @NotNull Computable<Boolean> stopEnabled) { myStopAction = stop; myStopEnabled = stopEnabled; return this; } public TailContentExecutor withAfterCompletion(Runnable afterCompletion) { myAfterCompletion = afterCompletion; return this; } public TailContentExecutor withHelpId(String helpId) { myHelpId = helpId; return this; } public TailContentExecutor withActivateToolWindow(boolean activateToolWindow) { myActivateToolWindow = activateToolWindow; return this; } private ConsoleView createConsole(@NotNull Project project, @NotNull ProcessHandler processHandler) { TextConsoleBuilder consoleBuilder = TextConsoleBuilderFactory.getInstance().createBuilder(project); consoleBuilder.filters(myFilterList); ConsoleView console = consoleBuilder.getConsole(); console.attachToProcess(processHandler); return console; } public void run() { FileDocumentManager.getInstance().saveAllDocuments(); ConsoleView consoleView = createConsole(myProject, myProcess); if (myHelpId != null) { consoleView.setHelpId(myHelpId); } Executor executor = TailRunExecutor.getRunExecutorInstance(); DefaultActionGroup actions = new DefaultActionGroup(); // Create runner UI layout final RunnerLayoutUi.Factory factory = RunnerLayoutUi.Factory.getInstance(myProject); final RunnerLayoutUi layoutUi = factory.create("Tail", "Tail", "Tail", this); final JComponent consolePanel = createConsolePanel(consoleView, actions); RunContentDescriptor descriptor = new RunContentDescriptor(new RunProfile() { @Nullable @Override public RunProfileState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment executionEnvironment) throws ExecutionException { return null; } @Override public String getName() { return myTitle; } @Nullable @Override public Icon getIcon() { return AllIcons.Process.DisabledRun; } }, new DefaultExecutionResult(consoleView, myProcess), layoutUi); descriptor.setExecutionId(System.nanoTime()); descriptor.setFocusComputable(() -> consoleView.getPreferredFocusableComponent()); descriptor.setAutoFocusContent(true); ComponentWithActions componentWithActions = new MyImpl(null, null, (JComponent) consoleView, null, consolePanel); final Content content = layoutUi.createContent(ExecutionConsole.CONSOLE_CONTENT_ID, componentWithActions, myTitle, AllIcons.Debugger.Console, consolePanel); layoutUi.addContent(content, 0, PlaceInGrid.right, false); layoutUi.getOptions().setLeftToolbar(createActionToolbar(consolePanel, consoleView, layoutUi, descriptor, executor), "RunnerToolbar"); Disposer.register(myProject, descriptor); Disposer.register(descriptor, this); Disposer.register(descriptor, content); Disposer.register(content, consoleView); if (myStopAction != null) { Disposer.register(consoleView, new Disposable() { @Override public void dispose() { myStopAction.run(); } }); } for (AnAction action : consoleView.createConsoleActions()) { actions.add(action); } ExecutionManager.getInstance(myProject).getContentManager().showRunContent(executor, descriptor); if (myActivateToolWindow) { activateToolWindow(); } if (myAfterCompletion != null) { myProcess.addProcessListener(new ProcessAdapter() { @Override public void processTerminated(ProcessEvent event) { SwingUtilities.invokeLater(myAfterCompletion); } }); } myProcess.startNotify(); } @NotNull private ActionGroup createActionToolbar(JComponent consolePanel, ConsoleView consoleView, @NotNull final RunnerLayoutUi myUi, RunContentDescriptor contentDescriptor, Executor runExecutorInstance) { final DefaultActionGroup actionGroup = new DefaultActionGroup(); actionGroup.add(new RerunAction(consolePanel)); actionGroup.add(new StopAction()); actionGroup.add(new PinAction()); actionGroup.add(myUi.getOptions().getLayoutActions()); CloseAction closeAction = new CloseAction(runExecutorInstance, contentDescriptor, myProject) { @Override public void actionPerformed(AnActionEvent e) { super.actionPerformed(e); GrepProjectComponent.getInstance(myProject).unpin(file); } }; GrepProjectComponent.getInstance(myProject).register(closeAction); actionGroup.add(closeAction); actionGroup.add(new CloseAll()); return actionGroup; } public void activateToolWindow() { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { ToolWindowManager.getInstance(myProject).getToolWindow(TailRunExecutor.TOOLWINDOWS_ID).activate(null); } }); } private static JComponent createConsolePanel(ConsoleView view, ActionGroup actions) { JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.add(view.getComponent(), BorderLayout.CENTER); panel.add(createToolbar(actions), BorderLayout.WEST); return panel; } private static JComponent createToolbar(ActionGroup actions) { ActionToolbar actionToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, actions, false); return actionToolbar.getComponent(); } @Override public void dispose() { } public void forFile(File file) { this.file = file; } private class RerunAction extends AnAction implements DumbAware { public RerunAction(JComponent consolePanel) { super("Rerun", "Rerun", AllIcons.Actions.Restart); registerCustomShortcutSet(CommonShortcuts.getRerun(), consolePanel); } @Override public void actionPerformed(AnActionEvent e) { try { myRerunAction.run(); } catch (Exception e1) { Notification notification = GrepConsoleApplicationComponent.NOTIFICATION.createNotification(e1.getMessage(), MessageType.WARNING); Notifications.Bus.notify(notification, e.getProject()); } } @Override public void update(AnActionEvent e) { e.getPresentation().setVisible(myRerunAction != null); } } private class StopAction extends AnAction implements DumbAware { public StopAction() { super("Stop", "Stop", AllIcons.Actions.Suspend); } @Override public void actionPerformed(AnActionEvent e) { myStopAction.run(); } @Override public void update(AnActionEvent e) { e.getPresentation().setVisible(myStopAction != null); e.getPresentation().setEnabled(myStopEnabled != null && myStopEnabled.compute()); } } private class CloseAll extends AnAction implements DumbAware { public CloseAll() { super("Close All", "Close All", AllIcons.Actions.Exit); } @Override public void actionPerformed(AnActionEvent e) { GrepProjectComponent.getInstance(myProject).closeAllTails(e); } } public class PinAction extends ToggleAction implements DumbAware { private boolean pinned; public PinAction() { super("Pin", "Reopen with project", AllIcons.General.Pin_tab); GrepProjectComponent projectComponent = GrepProjectComponent.getInstance(myProject); projectComponent.register(this); pinned = projectComponent.isPinned(file.getAbsoluteFile()); } @Override public boolean isSelected(AnActionEvent anActionEvent) { return pinned; } public void refreshPinStatus(GrepProjectComponent projectComponent) { pinned = projectComponent.isPinned(file.getAbsoluteFile()); } @Override public void setSelected(AnActionEvent anActionEvent, boolean b) { pinned = b; GrepProjectComponent projectComponent = GrepProjectComponent.getInstance(myProject); if (pinned) { projectComponent.pin(file); } else { projectComponent.unpin(file); } } } static class MyImpl implements ComponentWithActions { private final ActionGroup myToolbar; private final String myToolbarPlace; private final JComponent myToolbarContext; private final JComponent mySearchComponent; private final JComponent myComponent; public MyImpl(final ActionGroup toolbar, final String toolbarPlace, final JComponent toolbarContext, final JComponent searchComponent, final JComponent component) { myToolbar = toolbar; myToolbarPlace = toolbarPlace; myToolbarContext = toolbarContext; mySearchComponent = searchComponent; myComponent = component; } @Override public boolean isContentBuiltIn() { return false; } public MyImpl(final JComponent component) { this(null, null, null, null, component); } @Override public ActionGroup getToolbarActions() { return myToolbar; } @Override public JComponent getSearchComponent() { return mySearchComponent; } @Override public String getToolbarPlace() { return myToolbarPlace; } @Override public JComponent getToolbarContextComponent() { return myToolbarContext; } @Override @NotNull public JComponent getComponent() { return myComponent; } } }
package org.videolan; import java.net.MalformedURLException; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Enumeration; import javax.tv.xlet.Xlet; import org.videolan.bdjo.AppCache; public class BDJClassLoader extends URLClassLoader { public static BDJClassLoader newInstance(AppCache[] appCaches, String basePath, String classPathExt, String xletClass) { ArrayList classPath = new ArrayList(); URL url = translateClassPath(appCaches, basePath, null); if (url != null) classPath.add(url); String[] classPaths = StrUtil.split(classPathExt, ';'); for (int i = 0; i < classPaths.length; i++) { url = translateClassPath(appCaches, basePath, classPaths[i]); if ((url != null) && (classPath.indexOf(url) < 0)) classPath.add(url); } return new BDJClassLoader((URL[])classPath.toArray(new URL[classPath.size()]) , xletClass); } private static URL translateClassPath(AppCache[] appCaches, String basePath, String classPath) { String path; if ((classPath == null) || (classPath.length() <= 0)) path = basePath; else if (classPath.charAt(0) == '/') path = classPath.substring(1); else path = basePath + "/" + classPath; if (path.length() < 5) return null; String name = path.substring(0, 5); /* entry name in BDMV/JAR/ */ String dir = path.substring(5); /* optional sub directory */ /* find bdjo AppCache entry */ int i; for (i = 0; i < appCaches.length; i++) { if (appCaches[i].getRefToName().equals(name)) { break; } } if (i >= appCaches.length) return null; /* check AppCache type */ String protocol; if (appCaches[i].getType() == AppCache.JAR_FILE) { protocol = "file:"; name = name + ".jar"; } else if (appCaches[i].getType() == AppCache.DIRECTORY) { protocol = "file:/"; } else { return null; } /* map to disc root */ String fullPath = System.getProperty("bluray.vfs.root") + File.separator + "BDMV" + File.separator + "JAR" + File.separator + name; /* find from cache */ String cachePath = BDJLoader.getCachedFile(fullPath); /* build final url */ String url = protocol + cachePath + dir; try { return new URL(url); } catch (MalformedURLException e) { System.err.println("" + e + "\n" + Logger.dumpStack(e)); return null; } } private BDJClassLoader(URL[] urls, String xletClass) { super(urls); this.xletClass = xletClass; } protected Xlet loadXlet() throws ClassNotFoundException, IllegalAccessException, InstantiationException { return (Xlet)loadClass(xletClass).newInstance(); } protected void update(AppCache[] appCaches, String basePath, String classPathExt, String xletClass) { ArrayList classPath = new ArrayList(); URL[] urls = getURLs(); for (int i = 0; i < urls.length; i++) classPath.add(urls[i]); URL url = translateClassPath(appCaches, basePath, null); if (url != null) classPath.add(url); String[] classPaths = StrUtil.split(classPathExt, ';'); for (int i = 0; i < classPaths.length; i++) { url = translateClassPath(appCaches, basePath, classPaths[i]); if ((url != null) && (classPath.indexOf(url) < 0)) classPath.add(url); } for (int i = 0; i < classPath.size(); i++) addURL((URL)classPath.get(i)); this.xletClass = xletClass; } public Class loadClass(String name) throws java.lang.ClassNotFoundException { /* hook FileSystem in java.io.File */ if (name.equals("java.io.File")) { Class c = super.loadClass(name); if (c != null) { java.io.BDFileSystem.init(c); } return c; } try { return super.loadClass(name); } catch (ClassNotFoundException e0) { logger.error("ClassNotFoundException: " + name); throw e0; } catch (Error err) { logger.error("FATAL: " + err); throw err; } } private byte[] loadClassCode(String name) throws ClassNotFoundException { String path = name.replace('.', '/').concat(".class"); URL res = super.findResource(path); if (res == null) { logger.error("loadClassCode(): resource for class " + name + " not found"); throw new ClassNotFoundException(name); } InputStream is = null; ByteArrayOutputStream os = null; try { is = res.openStream(); os = new ByteArrayOutputStream(); byte[] buffer = new byte[0xffff]; while (true) { int r = is.read(buffer); if (r == -1) { break; } os.write(buffer, 0, r); } return os.toByteArray(); } catch (Exception e) { logger.error("loadClassCode(" + name + ") failed: " + e); throw new ClassNotFoundException(name); } finally { try { if (is != null) is.close(); } catch (IOException ioe) { } try { if (os != null) os.close(); } catch (IOException ioe) { } } } protected Class findClass(String name) throws ClassNotFoundException { try { return super.findClass(name); } catch (ClassFormatError ce) { /* try to "fix" broken class file */ /* if we got ClassFormatError, package was already created. */ byte[] b = loadClassCode(name); if (b == null) { logger.error("loadClassCode(" + name + ") failed"); /* this usually kills Xlet ... */ throw ce; } try { b = new BDJClassFileTransformer().strip(b, 0, b.length); return defineClass(b, 0, b.length); } catch (ThreadDeath td) { throw td; } catch (Throwable t) { logger.error("Class rewriting failed: " + t); throw new ClassNotFoundException(name); } } catch (Error er) { logger.error("Unexpected error: " + er + " " + Logger.dumpStack(er)); throw er; } } public URL getResource(String name) { name = name.replace('\\', '/'); return super.getResource(name); } /* final in J2ME public Enumeration getResources(String name) throws IOException { name = name.replace('\\', '/'); return super.getResources(name); } */ public URL findResource(String name) { name = name.replace('\\', '/'); return super.findResource(name); } public Enumeration findResources(String name) throws IOException { name = name.replace('\\', '/'); return super.findResources(name); } public InputStream getResourceAsStream(String name) { name = name.replace('\\', '/'); return super.getResourceAsStream(name); } private String xletClass; private static final Logger logger = Logger.getLogger(BDJClassLoader.class.getName()); }
package view.experiment.Analyzer.drawing; import static java.awt.event.KeyEvent.VK_F; import static java.awt.event.KeyEvent.VK_I; import static java.awt.event.KeyEvent.VK_O; import static java.awt.event.KeyEvent.VK_S; import static javax.swing.JFrame.EXIT_ON_CLOSE; import java.awt.Component; import java.awt.Frame; import java.awt.GridLayout; import java.io.File; import java.io.IOException; import java.nio.file.Path; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.SwingUtilities; import controller.experiment.Analyzer.ExperimentFileReader; import controller.experiment.Analyzer.TWMComputer; import model.experiment.Analyzer.SignalParameters; import view.MemorableDirectoryChooser; public class Drawer { public static Path choosePath(String[] args, Component parent) { Path selectedFile = null; if (args.length == 0) { MemorableDirectoryChooser chooser = new MemorableDirectoryChooser(Drawer.class); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); if (chooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) { selectedFile = chooser.getSelectedFile().toPath(); } else { return null; } } else { selectedFile = new File(args[0]).toPath(); } return selectedFile; } public static ExperimentFileReader getEreader(Path selectedFile) { ExperimentFileReader ereader; try { ereader = new ExperimentFileReader(selectedFile); } catch (IOException e) { e.printStackTrace(); return null; } return ereader; } public static void openNewTabs(final ExperimentFileReader reader, final JDrawingTabsPlane plane) { if (reader == null) { return; } for (double[] data : reader.getCroppedData()) { final int FREQ_INDEX = reader.getCroppedDataPeriodsCount(); SignalParameters params = TWMComputer.getSignalParameters(data, FREQ_INDEX); double angle = params.phase; double amplitude = params.amplitude; double zeroAmplitudeShift = params.nullOffset; double[] accordingWave = new double[data.length]; for (int i = 0; i < data.length; i++) { accordingWave[i] = Math.sin( 2.0 * Math.PI * reader.getCroppedDataPeriodsCount() * ((double) i / (double) data.length) + angle) * amplitude + zeroAmplitudeShift; } double[] zeroCrossageLine = new double[data.length]; for (int i = 0; i < zeroCrossageLine.length; i++) { zeroCrossageLine[i] = zeroAmplitudeShift; } plane.addSignalTab(new double[][] { data, accordingWave, zeroCrossageLine }, null); } } public static void main(String[] args) { JFrame frame = new JFrame("Рисователь"); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); JDrawingTabsPlane main = new JDrawingTabsPlane(); if (args.length > 0) { Path selectedFile = choosePath(args, frame); if (selectedFile == null) { System.exit(0); } ExperimentFileReader ereader = getEreader(selectedFile); if (ereader == null) { System.exit(0); } openNewTabs(ereader, main); } frame.getContentPane().setLayout(new GridLayout(1, 1)); frame.getContentPane().add(main); JMenuBar bar = new JMenuBar(); // File menu, F - Mnemonics JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic(VK_F); bar.add(fileMenu); // File -> open, O - mnemonics JMenuItem fileOpenMenuItem = new JMenuItem("Open...", VK_O); fileMenu.add(fileOpenMenuItem); fileOpenMenuItem.addActionListener(e -> { Path selectedFile = choosePath(args, frame); if (selectedFile != null) { ExperimentFileReader ereader = getEreader(selectedFile); openNewTabs(ereader, main); } }); // Settings Menu, S - Mnemonics JMenu settingsMenu = new JMenu("Настройки"); settingsMenu.setMnemonic(VK_S); bar.add(settingsMenu); // Settings -> showIndicies, I - Mnemonic JCheckBoxMenuItem showIndiciesMenuItem = new JCheckBoxMenuItem("Show Indicies", JGraphImagePlane.shouldShowIndicies); showIndiciesMenuItem.setMnemonic(VK_I); settingsMenu.add(showIndiciesMenuItem); frame.setJMenuBar(bar); frame.pack(); frame.setVisible(true); frame.setExtendedState(Frame.MAXIMIZED_BOTH); showIndiciesMenuItem.addChangeListener(e -> { Object o = e.getSource(); if (o instanceof JCheckBoxMenuItem) { JCheckBoxMenuItem i = (JCheckBoxMenuItem) o; JGraphImagePlane.shouldShowIndicies = i.isSelected(); SwingUtilities.invokeLater(main::repaint); } }); } }
package com.trendrr.strest.server; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.handler.codec.http.DefaultHttpRequest; import org.jboss.netty.handler.codec.http.DefaultHttpResponse; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.jboss.netty.handler.codec.http.HttpMethod; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpResponse; import org.jboss.netty.handler.codec.http.HttpResponseStatus; import org.jboss.netty.handler.codec.http.HttpVersion; import com.trendrr.oss.DynMap; import com.trendrr.strest.ContentTypes; import com.trendrr.strest.StrestUtil; import com.trendrr.strest.server.v2.models.StrestHeader; import com.trendrr.strest.server.v2.models.StrestHeader.TxnStatus; import com.trendrr.strest.server.v2.models.StrestRequest; import com.trendrr.strest.server.v2.models.StrestResponse; import com.trendrr.strest.server.v2.models.http.StrestHttpRequest; import com.trendrr.strest.server.v2.models.http.StrestHttpResponse; import com.trendrr.strest.server.v2.models.json.StrestJsonRequest; import com.trendrr.strest.server.v2.models.json.StrestJsonResponse; /** * @author Dustin Norlander * @created Jan 26, 2011 * */ public class ResponseBuilder { protected static Log log = LogFactory.getLog(ResponseBuilder.class); StrestResponse response; public static void main(String...strings) { // ResponseBuilder b = new ResponseBuilder(); } public static ResponseBuilder instance(StrestRequest request) { return new ResponseBuilder(request); } public static ResponseBuilder instance(StrestResponse response) { return new ResponseBuilder(response); } public ResponseBuilder(StrestResponse response) { this.response = response; } /** * creates a new response builder based on the txn id of the request. * @param request */ public ResponseBuilder(StrestRequest request) { if (request instanceof StrestJsonRequest) { this.response = new StrestJsonResponse(); } else if (request instanceof StrestHttpRequest) { this.response = new StrestHttpResponse(); } response.setProtocol(request.getProtocolName(), request.getProtocolVersion()); response.setTxnId(request.getTxnId()); } public ResponseBuilder txnStatus(TxnStatus status) { response.setTxnStatus(status); return this; } // /** // * Sets the status to 302, and the Location to the url. This is a standard (sort of) redirect. // * // * This could be problematic for STREST clients, it is up to them to implement // * redirects (or not). // * // * @param url // * @return // */ // public ResponseBuilder redirect(String url) { // this.response.setStatus(HttpResponseStatus.FOUND); // this.response.setHeader("Location", url); // return this; // /** // * Sets the status of the header. // * // * @param status // * @return // */ // public ResponseBuilder status(HttpResponseStatus status) { // this.response.setStatus(status); // return this; /** * Sets the status of the header. * * @param status * @return */ public ResponseBuilder status(int code, String message) { this.response.setStatus(code, message); return this; } /** * Set the Strest-Txn-Id header. * @param id * @return */ public ResponseBuilder txnId(String id) { if (id != null) response.setTxnId(id); return this; } public ResponseBuilder header(String header, String value) { response.addHeader(header, value); return this; } public ResponseBuilder content(String mimeType, byte[] bytes) { response.setContent(mimeType, bytes); return this; } /** * encodes the text as utf8 and swallows and logs a warning for any character encoding exceptions * @param mimeType * @param content * @return */ public ResponseBuilder contentUTF8(String mimeType, String content) { if (content == null) return this; try { this.content(mimeType, content.getBytes("utf8")); } catch (UnsupportedEncodingException e) { log.warn("Swallowed", e); } return this; } /** * same as above but sets mimetype to text/plain * @param content * @return */ public ResponseBuilder contentUTF8(String content) { this.contentUTF8(ContentTypes.TEXT, content); return this; } public ResponseBuilder contentJSON(DynMap mp) { return this.contentUTF8(ContentTypes.JSON, mp.toJSONString()); } public StrestResponse getResponse() { return this.response; } public void setResponse(StrestResponse response) { this.response = response; } }
package algorithms.util; /** * A class to estimate the amount of memory an object takes. * The user should know if it is to be on the heap or * stack (method local variables) when comparing the results to * available memory. * * Options for other data-types will be added as needed. * * @author nichole */ public class ObjectSpaceEstimator { private int nBoolean = 0; private int nByte = 0; private int nChar = 0; private int nShort = 0; private int nInt = 0; private int nFloat = 0; private int nObjRefs = 0; private int nArrayRefs = 0; private int nLong = 0; private int nDouble = 0; private int nReturnAddress = 0; //TODO: handle string, which is a character array but is ALWAYS on the heap // and for some jvm, strings are pooled objects, re-used. // sizes in bytes as [heap 32 bit, stack 32 bit, heap 54 bit, stack 64 bit] private final static int objOverheadSz = 16; private final static int[] word3264 = new int[]{4, 4, 4, 8}; private static String arch = System.getProperty("sun.arch.data.model"); private static boolean is32Bit = ((arch != null) && arch.equals("64")) ? false : true; private final static int[] booleanSz = word3264; private final static int[] byteSz = word3264; private final static int[] charSz = word3264; private final static int[] shortSz = word3264; private final static int[] intSz = word3264; private final static int[] floatSz = word3264; private final static int[] refSz = new int[]{4, 4, 8, 8}; private final static int[] arrayRefSz = new int[]{4, 4, 4, 4}; private final static int[] returnAddressSz = new int[]{4, 4, 8, 8}; private final static int[] longSz = new int[]{8, 8, 8, 16}; private final static int[] doubleSz = new int[]{8, 8, 8, 16}; /** * @param nBoolean the number of boolean primitives */ public void setNBooleanFields(int nBoolean) { this.nBoolean = nBoolean; } /** * @param nByte the number of byte primitives */ public void setNByteFields(int nByte) { this.nByte = nByte; } /** * @param nChar the number of char primitives to set */ public void setNCharFields(int nChar) { this.nChar = nChar; } /** * @param nShort the number of short primitives */ public void setNShortFields(int nShort) { this.nShort = nShort; } /** * @param nInt the number of int primitives */ public void setNIntFields(int nInt) { this.nInt = nInt; } /** * @param nFloat the number of float primitives */ public void setNFloatFields(int nFloat) { this.nFloat = nFloat; } /** * @param nObjRefs the number of object references */ public void setNObjRefsFields(int nObjRefs) { this.nObjRefs = nObjRefs; } /** * @param nArrayRefs the number of array references to set */ public void setNArrayRefsFields(int nArrayRefs) { this.nArrayRefs = nArrayRefs; } /** * @param nLong the number of long primitives */ public void setNLongFields(int nLong) { this.nLong = nLong; } /** * @param nDouble the number of double primitives */ public void setNDoubleFields(int nDouble) { this.nDouble = nDouble; } /** * @param nReturnAddress the nReturnAddress to set */ public void setNReturnAddress(int nReturnAddress) { this.nReturnAddress = nReturnAddress; } /** * estimate the size of an object in bytes for the given settings and for * placement on the heap. * @return total size in bytes for the object placed on the heap. */ public long estimateSizeOnHeap() { return estimateSize(true); } /** * estimate the size of an object in bytes for the given settings and for * placement on the stack (variables specific to a method frame, that is, * local variables). * * @return total size in bytes for the object places on the stack. */ public long estimateSizeOnStack() { return estimateSize(false); } private long estimateSize(boolean calcForHeap) { int idx; if (is32Bit) { if (calcForHeap) { idx = 0; } else { idx = 1; } } else { if (calcForHeap) { idx = 2; } else { idx = 3; } } long total = 0; // add fields total += nBoolean * booleanSz[idx]; total += nByte * byteSz[idx]; total += nChar * charSz[idx]; total += nShort * shortSz[idx]; total += nInt * intSz[idx]; total += nFloat * floatSz[idx]; total += nObjRefs * refSz[idx]; total += nArrayRefs * arrayRefSz[idx]; total += nLong * longSz[idx]; total += nDouble * doubleSz[idx]; total += nReturnAddress * returnAddressSz[idx]; // add object overhead total += 8; // pad up to 8 byte boundary long pad = total % 8; total += pad; return total; } }
package blang.engines.internals.factories; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.eclipse.xtext.xbase.lib.Pair; import bayonet.distributions.Random; import bayonet.smc.ParticlePopulation; import blang.engines.ParallelTempering; import blang.engines.internals.EngineStaticUtils; import blang.engines.internals.PosteriorInferenceEngine; import blang.engines.internals.Spline.MonotoneCubicSpline; import blang.engines.internals.SplineDerivatives; import blang.engines.internals.ptanalysis.Paths; import blang.engines.internals.schedules.AdaptiveTemperatureSchedule; import blang.inits.Arg; import blang.inits.DefaultValue; import blang.inits.GlobalArg; import blang.inits.experiments.ExperimentResults; import blang.System; import blang.inits.experiments.tabwriters.TabularWriter; import blang.inits.experiments.tabwriters.TidySerializer; import blang.io.BlangTidySerializer; import blang.runtime.Runner; import blang.runtime.SampledModel; import blang.runtime.internals.objectgraph.GraphAnalysis; import blang.types.StaticUtils; import briefj.BriefIO; import static blang.engines.internals.factories.PT.MonitoringOutput.*; import static blang.runtime.Runner.sampleColumn; public class PT extends ParallelTempering implements PosteriorInferenceEngine { @GlobalArg public ExperimentResults results = new ExperimentResults(); @Arg @DefaultValue("1_000") public int nScans = 1_000; @Arg(description = "Set to zero for disabling schedule adaptation") @DefaultValue("0.5") public double adaptFraction = 0.5; @Arg @DefaultValue("3") public double nPassesPerScan = 3; @Arg(description = "Collect statistics every thinning iteration (=1 to always collect, >1 to save hard drive space)") public int thinning = 1; @Arg @DefaultValue("1") public Random random = new Random(1); @Arg public Optional<Double> targetAccept = Optional.empty(); // TODO: refactor InitType into interface so that this option below can be passed in this way @Arg @DefaultValue({"--nParticles", "100", "--temperatureSchedule.threshold", "0.9"}) // should edit scmDefaults if defaults changed public SCM scmInit = scmDefault(); @Arg @DefaultValue("SCM") public InitType initialization = InitType.SCM; @Override public void performInference() { List<Round> rounds = rounds(); int scanIndex = 0; for (Round round : rounds) { System.out.indentWithTiming("Round(" + (round.roundIndex+1) + "/" + rounds.size() + ")"); reportRoundStatistics(round); for (int scanInRound = 0; scanInRound < round.nScans; scanInRound++) { moveKernel(nPassesPerScan); recordEnergyStatistics(densitySerializer, scanIndex); if (scanIndex % thinning == 0) recordSamples(scanIndex); if (nChains() > 1) swapAndRecordStatistics(scanIndex); scanIndex++; } if (nChains() > 1) { // Note: in last round, this is done only for instrumentation purpose reportAcceptanceRatios(round); reportParallelTemperingDiagnostics(round); MonotoneCubicSpline cumulativeLambdaEstimate = adapt(round.roundIndex == rounds.size() - 2); reportLambdaFunctions(round, cumulativeLambdaEstimate); } long roundTime = System.out.popIndent().watch.elapsed(TimeUnit.MILLISECONDS); reportRoundTiming(round, roundTime); results.flushAll(); } } @SuppressWarnings("unchecked") private void recordEnergyStatistics(BlangTidySerializer densitySerializer, int iter) { for (int i = 0; i < temperingParameters.size(); i++) { densitySerializer.serialize(states[i].logDensity(), SampleOutput.allLogDensities.toString(), Pair.of(sampleColumn, iter), Pair.of(Column.chain, i)); final double energy = -states[i].preAnnealedLogLikelihood(); densitySerializer.serialize(energy, SampleOutput.energy.toString(), Pair.of(sampleColumn, iter), Pair.of(Column.chain, i)); final int nOutOfSupport = states[i].nOutOfSupport(); densitySerializer.serialize(nOutOfSupport, SampleOutput.nOutOfSupport.toString(), Pair.of(sampleColumn, iter), Pair.of(Column.chain, i)); final double otherAnnealed = states[i].sumOtherAnnealed(); if (otherAnnealed != 0.0) { densitySerializer.serialize(otherAnnealed, SampleOutput.otherAnnealed.toString(), Pair.of(sampleColumn, iter), Pair.of(Column.chain, i)); } } densitySerializer.serialize(getTargetState().logDensity(), SampleOutput.logDensity.toString(), Pair.of(sampleColumn, iter)); } /** * @return The estimated cumulative lambda function. */ private MonotoneCubicSpline adapt(boolean finalAdapt) { List<Double> annealingParameters = new ArrayList<>(temperingParameters); Collections.reverse(annealingParameters); List<Double> acceptanceProbabilities = Arrays.stream(swapAcceptPrs).map(stat -> stat.getMean()).collect(Collectors.toList()); Collections.reverse(acceptanceProbabilities); MonotoneCubicSpline cumulativeLambdaEstimate = EngineStaticUtils.estimateCumulativeLambda(annealingParameters, acceptanceProbabilities); if (targetAccept.isPresent() && finalAdapt) { List<Double> newPartition = EngineStaticUtils.targetAcceptancePartition(cumulativeLambdaEstimate, targetAccept.get()); // here we need to take care of fact grid size may change nChains = Optional.of(newPartition.size()); initialize(states[0], random); setAnnealingParameters(newPartition); } else setAnnealingParameters(fixedSizeOptimalPartition(cumulativeLambdaEstimate, annealingParameters.size())); return cumulativeLambdaEstimate; } protected List<Double> fixedSizeOptimalPartition(MonotoneCubicSpline cumulativeLambdaEstimate, int size) { return EngineStaticUtils.fixedSizeOptimalPartition(cumulativeLambdaEstimate, size); } private void reportAcceptanceRatios(Round round) { TabularWriter swapTabularWriter = writer(MonitoringOutput.swapStatistics), annealingParamTabularWriter = writer(MonitoringOutput.annealingParameters); Pair<?,?> isAdapt = Pair.of(Column.isAdapt, round.isAdapt), r = Pair.of(Column.round, round.roundIndex); for (int i = 0; i < nChains() - 1; i++) { Pair<?,?> c = Pair.of(Column.chain, i); swapTabularWriter.write(isAdapt, r, c, Pair.of(TidySerializer.VALUE, swapAcceptPrs[i].getMean())); annealingParamTabularWriter.write(isAdapt, r, c, Pair.of(TidySerializer.VALUE, temperingParameters.get(i))); } } public static int _lamdbaDiscretization = 100; private void reportLambdaFunctions(Round round, MonotoneCubicSpline cumulativeLambdaEstimate) { Pair<?,?> r = Pair.of(Column.round, round.roundIndex), isAdapt = Pair.of(Column.isAdapt, round.isAdapt); for (int i = 1; i < _lamdbaDiscretization; i++) { double beta = ((double) i) / ((double) _lamdbaDiscretization); Pair<?,?> betaReport = Pair.of(Column.beta, beta); writer(MonitoringOutput.cumulativeLambda).write( r, isAdapt, betaReport, Pair.of(TidySerializer.VALUE, cumulativeLambdaEstimate.value(beta)) ); writer(MonitoringOutput.lambdaInstantaneous).write( r, isAdapt, betaReport, Pair.of(TidySerializer.VALUE, SplineDerivatives.derivative(cumulativeLambdaEstimate, beta)) ); } } private void reportRoundTiming(Round round, long time) { writer(MonitoringOutput.roundTimings).write( Pair.of(Column.round, round.roundIndex), Pair.of(Column.isAdapt, round.isAdapt), Pair.of(TidySerializer.VALUE, time) ); if (!round.isAdapt) { try { results.child(Runner.MONITORING_FOLDER).getAutoClosedBufferedWriter(Runner.RUNNING_TIME_SUMMARY) .append("postAdaptTime_ms\t" + time + "\n"); } catch (Exception e) {} } } @Override public void check(GraphAnalysis analysis) { // TODO: may want to check forward simulators ok return; } private List<Round> rounds() { double adaptFraction = nChains() == 1 ? 0.0 : this.adaptFraction; return rounds(nScans, adaptFraction); } public static List<Round> rounds(int nScans, double adaptFraction) { if (adaptFraction < 0.0 || adaptFraction >= 1.0) throw new RuntimeException(); List<Round> result = new ArrayList<>(); // first split int remainingAdaptIters = (int) (adaptFraction * nScans); int nonAdapt = nScans - remainingAdaptIters; result.add(new Round(nonAdapt, false)); while (remainingAdaptIters > 0) { int nextRemain = (int) (adaptFraction * remainingAdaptIters) - 1; result.add(new Round(remainingAdaptIters - nextRemain, true)); remainingAdaptIters = nextRemain; } Collections.reverse(result); int scan = 0; for (int r = 0; r < result.size(); r++) { Round cur = result.get(r); cur.roundIndex = r; cur.firstScanInclusive = scan; cur.lastScanExclusive = scan + cur.nScans; scan += cur.nScans; } return result; } public static enum InitType { COPIES, FORWARD, SCM } @Override public void setSampledModel(SampledModel model) { // low level-init always needed System.out.indentWithTiming("Initialization"); { initialize(model, random); informedInitialization(model); initSerializers(); } System.out.popIndent(); } private void informedInitialization(SampledModel model) { switch (initialization) { case COPIES : // nothing to do break; case FORWARD : for (SampledModel m : states) { double cParam = m.getExponent(); m.setExponent(0.0); m.forwardSample(random, false); m.setExponent(cParam); } break; case SCM : scmInit.results = results.child("init"); Random [] randoms = Random.parallelRandomStreams(random, scmInit.nParticles); ParticlePopulation<SampledModel> population = scmInit.initialize(model, randoms); List<Double> reorderedParameters = new ArrayList<>(temperingParameters); Collections.sort(reorderedParameters); for (int i = 0; i < reorderedParameters.size(); i++) { double nextParameter = reorderedParameters.get(i); int chainIndex = states.length - 1 - i; if (nextParameter == 0.0) { SampledModel current = states[chainIndex]; current.forwardSample(random, false); } else { population = scmInit.getApproximation(population, nextParameter, model, randoms, false); SampledModel init = population.sample(random).duplicate(); states[chainIndex] = init; } } break; default : throw new RuntimeException(); } } private BlangTidySerializer tidySerializer; private BlangTidySerializer densitySerializer; private BlangTidySerializer swapIndicatorSerializer; protected void initSerializers() { tidySerializer = new BlangTidySerializer(results.child(Runner.SAMPLES_FOLDER)); densitySerializer = new BlangTidySerializer(results.child(Runner.SAMPLES_FOLDER)); swapIndicatorSerializer = new BlangTidySerializer(results.child(Runner.MONITORING_FOLDER)); } private void reportRoundStatistics(Round round) { int movesPerScan = (int) (nChains()/2 /* communication */ + nPassesPerScan * states[0].nPosteriorSamplers() /* exploration */); System.out.formatln("Performing", round.nScans * states.length * movesPerScan, "moves...", "[", Pair.of("nScans", round.nScans), Pair.of("nChains", states.length), Pair.of("movesPerScan", movesPerScan), "]"); } @SuppressWarnings("unchecked") private void recordSamples(int scanIndex) { getTargetState().getSampleWriter(tidySerializer).write( Pair.of(sampleColumn, scanIndex)); } @SuppressWarnings("unchecked") private void swapAndRecordStatistics(int scanIndex) { // perform the swaps boolean[] swapIndicators = swapKernel(); // record info on the swap for (int c = 0; c < nChains(); c++) swapIndicatorSerializer.serialize(swapIndicators[c] ? 1 : 0, MonitoringOutput.swapIndicators.toString(), Pair.of(sampleColumn, scanIndex), Pair.of(Column.chain, c)); } private void reportParallelTemperingDiagnostics(Round round) { Pair<?,?> roundReport = Pair.of(Column.round, round.roundIndex); // swap statistics SummaryStatistics swapStats = StaticUtils.summaryStatistics( Arrays.stream(swapAcceptPrs).map(stat -> stat.getMean()).collect(Collectors.toList())); writer(MonitoringOutput.swapSummaries).printAndWrite( roundReport, Pair.of(Column.lowest, swapStats.getMin()), Pair.of(Column.average, swapStats.getMean()) ); // round trip information results.flushAll(); // make sure first the indicators are written File swapIndicsFile = new File(results.getFileInResultFolder(Runner.MONITORING_FOLDER), MonitoringOutput.swapIndicators + ".csv"); Paths paths = swapIndicsFile.exists() ? new Paths(swapIndicsFile.getAbsolutePath(), round.firstScanInclusive, round.lastScanExclusive) : null; double Lambda = Arrays.stream(swapAcceptPrs).map(stat -> 1.0 - stat.getMean()).mapToDouble(Double::doubleValue).sum(); writer(MonitoringOutput.globalLambda).printAndWrite( roundReport, Pair.of(TidySerializer.VALUE, Lambda) ); if (paths != null) { int n = paths.nRejuvenations(); double tau = ((double) n / round.nScans); writer(MonitoringOutput.actualTemperedRestarts).printAndWrite( roundReport, Pair.of(Column.count, n), Pair.of(Column.rate, tau) ); } if (reversible) System.err.println("Using provably suboptimal reversible PT. Do this only for PT benchmarking. Asymptotic rate is zero in this regime."); else { double tauBar = 1.0 / (2.0 + 2.0 * Lambda); double nBar = tauBar * round.nScans; writer(asymptoticRoundTripBound).printAndWrite( roundReport, Pair.of(Column.count, nBar), Pair.of(Column.rate, tauBar) ); } Optional<Double> optionalLogNorm = thermodynamicEstimator(); if (optionalLogNorm.isPresent()) writer(MonitoringOutput.logNormalizationContantProgress).printAndWrite( roundReport, Pair.of(TidySerializer.VALUE, optionalLogNorm.get()) ); else System.out.println("Thermodynamic integration disabled as support is being annealed\n" + " Use \"--engine SCM\" for log normalization computation instead"); // log normalization, again (this gets overwritten, so this will be the final estimate in the same format as SCM) if (optionalLogNorm.isPresent()) BriefIO.write(results.getFileInResultFolder(Runner.LOG_NORM_ESTIMATE), "" + optionalLogNorm.get()); } private SCM scmDefault() { SCM scmDefault = new SCM(); scmDefault.nParticles = 100; AdaptiveTemperatureSchedule schedule = new AdaptiveTemperatureSchedule(); schedule.threshold = 0.9; scmDefault.temperatureSchedule = schedule; return scmDefault; } private TabularWriter writer(MonitoringOutput output) { return results.child(Runner.MONITORING_FOLDER).getTabularWriter(output.toString()); } public static enum MonitoringOutput { swapIndicators, swapStatistics, annealingParameters, swapSummaries, logNormalizationContantProgress, globalLambda, actualTemperedRestarts, asymptoticRoundTripBound, roundTimings, lambdaInstantaneous, cumulativeLambda } public static enum SampleOutput { energy, logDensity, allLogDensities, nOutOfSupport, otherAnnealed; } public static enum Column { chain, round, isAdapt, count, rate, lowest, average, beta } public static class Round { int nScans; int roundIndex = -1; int firstScanInclusive; int lastScanExclusive; boolean isAdapt; public Round(int nScans, boolean isAdapt) { this.nScans = nScans; this.isAdapt = isAdapt; } @Override public String toString() { return "Round [nScans=" + nScans + ", roundIndex=" + roundIndex + ", isAdapt=" + isAdapt + "]"; } } }
package blog.sample.resource; import blog.sample.core.Article; import blog.sample.core.User; import blog.sample.dao.ArticleDAO; import blog.sample.dao.UserDAO; import blog.sample.view.ArticleListView; import blog.sample.view.ArticleView; import blog.sample.view.Template; import com.codahale.metrics.annotation.Timed; import io.dropwizard.hibernate.UnitOfWork; import javax.validation.Valid; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.sql.Timestamp; import java.util.Date; import java.util.List; @Path("/article") public class ArticleResource { private ArticleDAO articleDAO; private UserDAO userDAO; public ArticleResource(ArticleDAO articleDAO, UserDAO userDAO) { this.articleDAO = articleDAO; this.userDAO = userDAO; } @GET @Timed @UnitOfWork @Path("/view/all") @Produces(MediaType.TEXT_HTML) public ArticleListView viewAllArticles() { return new ArticleListView(articleDAO.findAll()); } @GET @UnitOfWork @Path("/view/{id}") @Produces(MediaType.TEXT_HTML) public ArticleView viewArticle(@PathParam("id") String id) { return new ArticleView(Template.VIEW_ARTICLE, articleDAO.findById(id)); } @GET @Path("/new") @Produces(MediaType.TEXT_HTML) public ArticleView newArticle() { return new ArticleView(Template.NEW_ARTICLE, new Article()); } @POST @UnitOfWork @Path("/save") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.TEXT_PLAIN) public String saveArticle(@Valid Article article) { User author = userDAO.findById("id1"); article.setPostDate(new Timestamp(new Date().getTime())); article.setAuthor(author); return articleDAO.saveArticle(article).getId(); } @GET @Timed @UnitOfWork @Path("/api/{id}") @Produces(MediaType.APPLICATION_JSON) public Article getArticle(@PathParam("id") String id) { return articleDAO.findById(id); } @GET @Timed @UnitOfWork @Path("/api/all") @Produces(MediaType.APPLICATION_JSON) public List<Article> getAllArticles() { return articleDAO.findAll(); } }
package br.org.piblimeira.app.view; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.context.annotation.RequestScope; import br.org.piblimeira.app.security.Identity; import br.org.piblimeira.domain.Usuario; import br.org.piblimeira.repository.UsuarioRepository; /** * CDI backing bean holding login credentials and delegating to session scoped spring bean. */ @Named @RequestScope public class LoginBean { @Inject private Identity identity; @Autowired UsuarioRepository usuarioRepository; private String userName = "admin"; private String password = "admin"; public String login() { List<Usuario> users = (List<Usuario>) usuarioRepository.findAll(); return identity.login(userName, password); } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
package br.ufmg.dcc.latin.util; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.time.Instant; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.bucket.terms.StringTerms; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder; import org.elasticsearch.search.aggregations.metrics.sum.Sum; public class Elasticsearch { private static TransportClient transportClient; public static void main(String args[]) { try { //getPageviewsByItemId(args[0], args[1]); getTextOfAllItems(args[0], args[1]); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void getPageviewsByItemId(String index, String fileName) throws IOException{ File fout = new File(fileName); FileOutputStream fos = new FileOutputStream(fout); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); bw.write("item_id,count\n"); Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "felipemoraes").build(); TransportClient transportClient = new TransportClient(settings); Client client = transportClient.addTransportAddress(new InetSocketTransportAddress("localhost", 9300)); TermsBuilder aggregation = AggregationBuilders .terms("total-events-by-items") .field("item_id") .size(0) .subAggregation( AggregationBuilders.sum("total-count") .field("count") ); SearchResponse sr = client .prepareSearch(index) .setTypes("item_metric") .setQuery( QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.boolFilter() .must( FilterBuilders.termFilter("type", "VIEW") ) ) ) .addAggregation(aggregation) .execute() .actionGet(); StringTerms aggregatorByItemId = sr.getAggregations().get("total-events-by-items"); for (Terms.Bucket bucketItemId: aggregatorByItemId.getBuckets()) { String itemId = bucketItemId.getKey(); Sum aggregatorTotalCount = bucketItemId.getAggregations().get("total-count"); double count = aggregatorTotalCount.getValue(); bw.write(itemId + "," + count + "\n"); } bw.close(); transportClient.close(); } public static void getTextOfAllItems(String directory, String index) throws IOException{ Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "felipemoraes").build(); FileWriter fids = new FileWriter(directory + "ids"); transportClient = new TransportClient(settings); Client client = transportClient.addTransportAddress(new InetSocketTransportAddress("localhost", 9300)); Instant from = Instant.ofEpochSecond(1417392000); Instant to = Instant.ofEpochSecond(1425081600); SearchResponse sr = client .prepareSearch(index) .setTypes("content") .setScroll(new TimeValue(60000)) .setSize(100) .addField("body") .addField("item_id") .setQuery( QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.rangeFilter("publication_date") .gte(from.toEpochMilli()).lte(to.toEpochMilli()) ) ) .execute() .actionGet(); while (true) { for (SearchHit hit : sr.getHits()) { fids.write(hit.fields().get("item_id").getValue().toString() + "\n"); FileWriter fw = new FileWriter(directory + hit.fields().get("item_id").getValue().toString() + ".txt"); fw.write(hit.getFields().get("body").getValue().toString()); fw.close(); } sr = client.prepareSearchScroll(sr.getScrollId()) .setScroll(new TimeValue(60000)) .execute().actionGet(); if (sr.getHits().getHits().length == 0) { break; } } fids.close(); } }
package cn.cerc.mis.client; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cn.cerc.db.core.Curl; import cn.cerc.db.core.DataSet; import cn.cerc.db.core.IHandle; import cn.cerc.db.core.ISession; import cn.cerc.mis.core.LocalService; import cn.cerc.mis.core.ServiceState; public interface ServiceServerImpl { static final Logger log = LoggerFactory.getLogger(ServiceServerImpl.class); String getRequestUrl(IHandle handle, String service); String getToken(IHandle handle); default boolean isLocal(IHandle handle, ServiceSign service) { String url = this.getRequestUrl(handle, service.id()); return url == null; } default DataSet call(ServiceSign service, IHandle handle, DataSet dataIn) { if (isLocal(handle, service)) return LocalService.call(service.id(), handle, dataIn); String url = this.getRequestUrl(handle, service.id()); try { Curl curl = new Curl(); String token = this.getToken(handle); if (token != null) curl.put(ISession.TOKEN, token); curl.put("dataIn", dataIn.json()); log.debug("request url: {}", url); log.debug("request params: {}", curl.getParameters()); String response = curl.doPost(url); log.debug("response: {}", response); return new DataSet().setJson(response); } catch (IOException e) { return new DataSet().setState(ServiceState.CALL_TIMEOUT).setMessage(url + " remote service error"); } } }
package com.akiban.qp.rowtype; import com.akiban.ais.model.*; import com.akiban.qp.expression.Expression; import java.util.*; import static java.lang.Math.max; // UserTable RowTypes are indexed by the UserTable's RowDef's ordinal. Derived RowTypes get higher values. public class SchemaAISBased implements Schema { // Schema interface @Override public synchronized UserTableRowType userTableRowType(UserTable table) { return (UserTableRowType) rowTypes.get(table.getTableId()); } @Override public synchronized IndexRowType indexRowType(Index index) { // TODO: Group index schema is always ""; need another way to // check for group _table_ index. if (false) assert ais.getTable(index.getIndexName().getSchemaName(), index.getIndexName().getTableName()).isUserTable() : index; return index.isTableIndex() ? userTableRowType((UserTable) index.leafMostTable()).indexRowType(index) : groupIndexRowType((GroupIndex) index); } @Override public synchronized FlattenedRowType newFlattenType(RowType parent, RowType child) { return new FlattenedRowType(this, nextTypeId(), parent, child); } @Override public synchronized ProjectedRowType newProjectType(List<Expression> columns) { return new ProjectedRowType(this, nextTypeId(), columns); } @Override public ProductRowType newProductType(RowType left, RowType right) { return new ProductRowType(this, nextTypeId(), left, right); } @Override public synchronized Iterator<RowType> rowTypes() { return rowTypes.values().iterator(); } // SchemaAISBased interface public SchemaAISBased(AkibanInformationSchema ais) { this.ais = ais; this.typeIdCounter = -1; // Create RowTypes for AIS UserTables for (UserTable userTable : ais.getUserTables().values()) { UserTableRowType userTableRowType = new UserTableRowType(this, userTable); int tableTypeId = userTableRowType.typeId(); rowTypes.put(tableTypeId, userTableRowType); typeIdCounter = max(typeIdCounter, userTableRowType.typeId()); } // Create RowTypes for AIS TableIndexes for (UserTable userTable : ais.getUserTables().values()) { UserTableRowType userTableRowType = userTableRowType(userTable); for (TableIndex index : userTable.getIndexesIncludingInternal()) { IndexRowType indexRowType = new IndexRowType(this, userTableRowType, index); userTableRowType.addIndexRowType(indexRowType); rowTypes.put(indexRowType.typeId(), indexRowType); } } // Create RowTypes for AIS GroupIndexes for (Group group : ais.getGroups().values()) { for (GroupIndex groupIndex : group.getIndexes()) { IndexRowType indexRowType = new IndexRowType(this, userTableRowType(groupIndex.leafMostTable()), groupIndex); rowTypes.put(indexRowType.typeId(), indexRowType); groupIndexRowTypes.add(indexRowType); } } } public AkibanInformationSchema ais() { return ais; } // For use by this package synchronized int nextTypeId() { return ++typeIdCounter; } // For use by this class private IndexRowType groupIndexRowType(GroupIndex groupIndex) { for (IndexRowType groupIndexRowType : groupIndexRowTypes) { if (groupIndexRowType.index() == groupIndex) { return groupIndexRowType; } } return null; } // Object state private final AkibanInformationSchema ais; private final Map<Integer, RowType> rowTypes = new HashMap<Integer, RowType>(); private final List<IndexRowType> groupIndexRowTypes = new ArrayList<IndexRowType>(); private volatile int typeIdCounter = 0; }
package com.amadeus.pcb.join; import cc.mallet.optimize.LimitedMemoryBFGS; import cc.mallet.optimize.OptimizationException; import net.didion.jwnl.data.Exc; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.ArrayRealVector; import org.apache.commons.math3.linear.RealVector; import org.apache.flink.api.common.functions.*; import org.apache.flink.api.common.operators.Order; import org.apache.flink.api.common.operators.base.JoinOperatorBase; import org.apache.flink.api.java.DataSet; import org.apache.flink.api.java.ExecutionEnvironment; import org.apache.flink.api.java.operators.IterativeDataSet; import org.apache.flink.api.java.tuple.*; import org.apache.flink.configuration.Configuration; import org.apache.flink.core.fs.FileSystem; import org.apache.flink.util.Collector; import org.apache.hadoop.util.hash.Hash; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.*; public class TrafficAnalysis { private static final double SLF = 1.0;//0.795; private static final double WAITING_FACTOR = 1.0; private static final int MAX_ITERATIONS = 8; private static final double OPTIMIZER_TOLERANCE = 0.000001; private static final int MAX_OPTIMIZER_ITERATIONS = 1000; private static long firstPossibleTimestamp = 1399248000000L; private static long lastPossibleTimestamp = 1399939199000L; private static String outputPath = "hdfs:///user/rwaury/output2/flights/"; private static String AP_COUNTRY_MAPPING = "AirportCountryMappingBroadcastSet"; private static String INVERTED_COVARIANCE_MATRIX = "InvertedCovarianceMatrixBroadcastSet"; private static final int OD_FEATURE_COUNT = 5; public static void main(String[] args) throws Exception { ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); DataSet<Tuple4<String, String, String, String>> airportCountryNR = env.readTextFile("hdfs:///user/rwaury/input2/ori_por_public.csv").setParallelism(1) .flatMap(new AirportCountryExtractor()).setParallelism(1); DataSet<Tuple2<String, String>> regionInfo = env.readTextFile("hdfs:///user/rwaury/input2/ori_country_region_info.csv").map(new FlightConnectionJoiner.RegionExtractor()); regionInfo.writeAsCsv(outputPath + "regionInfo", "\n", ",", FileSystem.WriteMode.OVERWRITE).setParallelism(1); DataSet<Tuple4<String, String, String, String>> airportCountry = airportCountryNR.join(regionInfo).where(2).equalTo(0).with(new RegionJoiner()); airportCountry.writeAsCsv(outputPath + "airportCountry", "\n", ",", FileSystem.WriteMode.OVERWRITE).setParallelism(1); DataSet<String> midtStrings = env.readTextFile("hdfs:///user/rwaury/input2/MIDTTotalHits.csv"); DataSet<MIDT> midt = midtStrings.flatMap(new MIDTParser()).groupBy(0,1,2,3,4,5,6,7).reduceGroup(new MIDTGrouper()); DataSet<Tuple5<String, String, String, Integer, Integer>> ODBounds = midt.map(new LowerBoundExtractor()).groupBy(0,1,2).sum(3).andSum(4); ODBounds.writeAsCsv(outputPath + "ODBounds", "\n", ",", FileSystem.WriteMode.OVERWRITE); DataSet<Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer>> APBoundsAgg = midtStrings.flatMap(new MIDTCapacityEmitter()).withBroadcastSet(airportCountry, AP_COUNTRY_MAPPING); DataSet<Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer>> APBounds = APBoundsAgg.groupBy(0,1,2,3,4).sum(5).andSum(6); /*DataSet<Tuple4<String, String, Integer, Integer>> APBounds = ODBounds.flatMap(new FlatMapFunction<Tuple5<String, String, String, Integer, Integer>, Tuple4<String, String, Integer, Integer>>() { @Override public void flatMap(Tuple5<String, String, String, Integer, Integer> odbound, Collector<Tuple4<String, String, Integer, Integer>> out) throws Exception { Tuple4<String, String, Integer, Integer> outgoing = new Tuple4<String, String, Integer, Integer>(odbound.f0, odbound.f2, odbound.f3, 0); Tuple4<String, String, Integer, Integer> incoming = new Tuple4<String, String, Integer, Integer>(odbound.f1, odbound.f2, 0, odbound.f3); out.collect(outgoing); out.collect(incoming); } }).groupBy(0,1).sum(2).andSum(3);*/ APBounds.writeAsCsv(outputPath + "APBounds", "\n", ",", FileSystem.WriteMode.OVERWRITE); DataSet<Flight> nonStopConnections = env.readFile(new FlightOutput.NonStopFullInputFormat(), outputPath + "oneFull"); DataSet<Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer>> inOutCapa = nonStopConnections.flatMap(new FlatMapFunction<Flight, Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer>>() { SimpleDateFormat format = new SimpleDateFormat("ddMMyyyy"); @Override public void flatMap(Flight flight, Collector<Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer>> out) throws Exception { if(flight.getLegCount() > 1) { return; } if(flight.getDepartureTimestamp() > lastPossibleTimestamp || flight.getDepartureTimestamp() < firstPossibleTimestamp) { return; } Date date = new Date(flight.getDepartureTimestamp()); String dayString = format.format(date); boolean isInterRegional = false; boolean isInternational = !flight.getOriginCountry().equals(flight.getDestinationCountry()); boolean isInterState = false; int capacity = flight.getMaxCapacity(); Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer> outgoing = new Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer> (flight.getOriginAirport(), dayString, isInterRegional, isInternational, isInterState, capacity, 0); Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer> incoming = new Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer> (flight.getDestinationAirport(), dayString, isInterRegional, isInternational, isInterState, 0, capacity); out.collect(incoming); out.collect(outgoing); } }); // in and out loads of airports per day and as domestic and international (boolean flag) DataSet<Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>> outgoingMarginalsAgg = inOutCapa.groupBy(0,1,2,3,4).reduceGroup(new GroupReduceFunction<Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer>, Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>>() { @Override public void reduce(Iterable<Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer>> tuple7s, Collector<Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>> out) throws Exception { boolean first = true; Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean> result = new Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>(); for(Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer> t : tuple7s) { if(first) { result.f0 = t.f0; result.f1 = t.f1; result.f2 = t.f2; result.f3 = t.f3; result.f4 = t.f4; result.f5 = 0; result.f6 = 1.0; // Ki(0) result.f7 = true; first = false; } result.f5 += t.f5; } result.f5 = (int)Math.round(SLF*result.f5); out.collect(result); } }); DataSet<Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>> incomingMarginalsAgg = inOutCapa.groupBy(0,1,2,3,4).reduceGroup(new GroupReduceFunction<Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer>, Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>>() { @Override public void reduce(Iterable<Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer>> tuple7s, Collector<Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>> out) throws Exception { boolean first = true; Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean> result = new Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>(); for(Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer> t : tuple7s) { if(first) { result.f0 = t.f0; result.f1 = t.f1; result.f2 = t.f2; result.f3 = t.f3; result.f4 = t.f4; result.f5 = 0; result.f6 = 1.0; // Kj(0) result.f7 = false; first = false; } result.f5 += t.f6; } result.f5 = (int)Math.round(SLF*result.f5); out.collect(result); } }); DataSet<Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>> outgoingMarginals = outgoingMarginalsAgg.join(APBounds, JoinOperatorBase.JoinHint.REPARTITION_SORT_MERGE).where(0,1,2,3,4).equalTo(0,1,2,3,4).with( new JoinFunction<Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>, Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer>, Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>>() { @Override public Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean> join(Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean> marginal, Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer> midtBound) throws Exception { int estimateResidual = Math.max(marginal.f5 - midtBound.f5, 0); return new Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>(marginal.f0, marginal.f1, marginal.f2, marginal.f3, marginal.f4, estimateResidual, marginal.f6, marginal.f7); } }); DataSet<Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>> incomingMarginals = incomingMarginalsAgg.join(APBounds, JoinOperatorBase.JoinHint.REPARTITION_SORT_MERGE).where(0,1,2,3,4).equalTo(0,1,2,3,4).with( new JoinFunction<Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>, Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer>, Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>>() { @Override public Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean> join(Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean> marginal, Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer> midtBound) throws Exception { int estimateResidual = Math.max(marginal.f5 - midtBound.f6, 0); return new Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>(marginal.f0, marginal.f1, marginal.f2, marginal.f3, marginal.f4, estimateResidual, marginal.f6, marginal.f7); } }); DataSet<Tuple2<Flight, Flight>> twoLegConnections = env.readFile(new FlightOutput.TwoLegFullInputFormat(), outputPath + "twoFull"); DataSet<Tuple3<Flight, Flight, Flight>> threeLegConnections = env.readFile(new FlightOutput.ThreeLegFullInputFormat(), outputPath + "threeFull"); DataSet<Tuple8<String, String, Boolean, Boolean, Boolean, String, Double, Integer>> nonStop = nonStopConnections.flatMap(new FlatMapFunction<Flight, Tuple8<String, String, Boolean, Boolean, Boolean, String, Double, Integer>>() { SimpleDateFormat format = new SimpleDateFormat("ddMMyyyy"); @Override public void flatMap(Flight value, Collector<Tuple8<String, String, Boolean, Boolean, Boolean, String, Double, Integer>> out) throws Exception { if(value.getDepartureTimestamp() > lastPossibleTimestamp || value.getDepartureTimestamp() < firstPossibleTimestamp) { return; } Date date = new Date(value.getDepartureTimestamp()); String dayString = format.format(date); long duration = value.getArrivalTimestamp() - value.getDepartureTimestamp(); if (duration <= 0L) throw new Exception("Value error: " + value.toString()); Integer minutes = (int) (duration / (60L * 1000L)); boolean isInterRegional = false; boolean isInternational = !value.getOriginCountry().equals(value.getDestinationCountry()); boolean isInterState = false; out.collect(new Tuple8<String, String, Boolean, Boolean, Boolean, String, Double, Integer> (value.getOriginAirport(), value.getDestinationAirport(), isInterRegional, isInternational, isInterState, dayString, dist(value.getOriginLatitude(), value.getOriginLongitude(), value.getDestinationLatitude(), value.getDestinationLongitude()), minutes)); } }); DataSet<Tuple8<String, String, Boolean, Boolean, Boolean, String, Double, Integer>> twoLeg = twoLegConnections.flatMap(new FlatMapFunction<Tuple2<Flight, Flight>, Tuple8<String, String, Boolean, Boolean, Boolean, String, Double, Integer>>() { SimpleDateFormat format = new SimpleDateFormat("ddMMyyyy"); @Override public void flatMap(Tuple2<Flight, Flight> value, Collector<Tuple8<String, String, Boolean, Boolean, Boolean, String, Double, Integer>> out) throws Exception { if(value.f0.getDepartureTimestamp() > lastPossibleTimestamp || value.f0.getDepartureTimestamp() < firstPossibleTimestamp) { return; } Date date = new Date(value.f0.getDepartureTimestamp()); String dayString = format.format(date); long flight1 = value.f0.getArrivalTimestamp() - value.f0.getDepartureTimestamp(); long wait1 = (long) (WAITING_FACTOR * (value.f1.getDepartureTimestamp() - value.f0.getArrivalTimestamp())); long flight2 = value.f1.getArrivalTimestamp() - value.f1.getDepartureTimestamp(); long duration = flight1 + wait1 + flight2; if(duration <= 0L) throw new Exception("Value error: " + value.toString()); Integer minutes = (int) (duration / (60L * 1000L)); boolean isInterRegional = false; boolean isInternational = !value.f0.getOriginCountry().equals(value.f1.getDestinationCountry()); boolean isInterState = false; out.collect(new Tuple8<String, String, Boolean, Boolean, Boolean, String, Double, Integer> (value.f0.getOriginAirport(), value.f1.getDestinationAirport(), isInterRegional, isInternational, isInterState, dayString, dist(value.f0.getOriginLatitude(), value.f0.getOriginLongitude(), value.f1.getDestinationLatitude(), value.f1.getDestinationLongitude()), minutes)); } }); DataSet<Tuple8<String, String, Boolean, Boolean, Boolean, String, Double, Integer>> threeLeg = threeLegConnections.flatMap(new FlatMapFunction<Tuple3<Flight, Flight, Flight>, Tuple8<String, String, Boolean, Boolean, Boolean, String, Double, Integer>>() { SimpleDateFormat format = new SimpleDateFormat("ddMMyyyy"); @Override public void flatMap(Tuple3<Flight, Flight, Flight> value, Collector<Tuple8<String, String, Boolean, Boolean, Boolean, String, Double, Integer>> out) throws Exception { if(value.f0.getDepartureTimestamp() > lastPossibleTimestamp || value.f0.getDepartureTimestamp() < firstPossibleTimestamp) { return; } Date date = new Date(value.f0.getDepartureTimestamp()); String dayString = format.format(date); long flight1 = value.f0.getArrivalTimestamp() - value.f0.getDepartureTimestamp(); long wait1 = (long) (WAITING_FACTOR * (value.f1.getDepartureTimestamp() - value.f0.getArrivalTimestamp())); long flight2 = value.f1.getArrivalTimestamp() - value.f1.getDepartureTimestamp(); long wait2 = (long) (WAITING_FACTOR * (value.f2.getDepartureTimestamp() - value.f1.getArrivalTimestamp())); long flight3 = value.f2.getArrivalTimestamp() - value.f2.getDepartureTimestamp(); long duration = flight1 + wait1 + flight2 + wait2 + flight3; if (duration <= 0L) throw new Exception("Value error: " + value.toString()); Integer minutes = (int) (duration / (60L * 1000L)); boolean isInterRegional = false; boolean isInternational = !value.f0.getOriginCountry().equals(value.f2.getDestinationCountry()); boolean isInterState = false; out.collect(new Tuple8<String, String, Boolean, Boolean, Boolean, String, Double, Integer> (value.f0.getOriginAirport(), value.f2.getDestinationAirport(), isInterRegional, isInternational, isInterState, dayString, dist(value.f0.getOriginLatitude(), value.f0.getOriginLongitude(), value.f2.getDestinationLatitude(), value.f2.getDestinationLongitude()), minutes)); } }); DataSet<Tuple8<String, String, Boolean, Boolean, Boolean, String, Double, Integer>> flights = nonStop.union(twoLeg).union(threeLeg); DataSet<Tuple7<String, String, String, Boolean, Boolean, Boolean, SerializableVector>> distances = flights.groupBy(0,1,2,3,4,5) .reduceGroup(new GroupReduceFunction<Tuple8<String, String, Boolean, Boolean, Boolean, String, Double, Integer>, Tuple7<String, String, String, Boolean, Boolean, Boolean, SerializableVector>>() { @Override public void reduce(Iterable<Tuple8<String, String, Boolean, Boolean, Boolean, String, Double, Integer>> values, Collector<Tuple7<String, String, String, Boolean, Boolean, Boolean, SerializableVector>> out) throws Exception { Tuple7<String, String, String, Boolean, Boolean, Boolean, SerializableVector> result = new Tuple7<String, String, String, Boolean, Boolean, Boolean, SerializableVector>(); int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; int sum = 0; int count = 0; boolean first = true; SerializableVector vector = new SerializableVector(OD_FEATURE_COUNT); for (Tuple8<String, String, Boolean, Boolean, Boolean, String, Double, Integer> t : values) { if (first) { result.f0 = t.f0; result.f1 = t.f1; result.f2 = t.f5; result.f3 = t.f2; result.f4 = t.f3; result.f5 = t.f4; vector.getVector().setEntry(0, t.f6); first = false; } int minutes = t.f7; sum += minutes; count++; if (minutes < min) { min = minutes; } if (minutes > max) { max = minutes; } } Double avg = (double) sum / (double) count; vector.getVector().setEntry(1, (double)min); vector.getVector().setEntry(2, (double)max); vector.getVector().setEntry(3, avg); vector.getVector().setEntry(4, (double)count); result.f6 = vector; out.collect(result); } }); IterativeDataSet<Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>> initial = outgoingMarginals.union(incomingMarginals).iterate(MAX_ITERATIONS); DataSet<Tuple7<String, String, String, Boolean, Boolean, Boolean, Double>> KiFractions = distances .join(initial.filter(new IncomingFilter()), JoinOperatorBase.JoinHint.REPARTITION_SORT_MERGE).where(1,2,3,4,5).equalTo(0,1,2,3,4).with(new KJoiner()); outgoingMarginals = KiFractions.groupBy(0,2,3,4,5).sum(6) .join(initial.filter(new OutgoingFilter()), JoinOperatorBase.JoinHint.REPARTITION_SORT_MERGE).where(0,2,3,4,5).equalTo(0,1,2,3,4).with(new KUpdater()); DataSet<Tuple7<String, String, String, Boolean, Boolean, Boolean, Double>> KjFractions = distances .join(outgoingMarginals, JoinOperatorBase.JoinHint.REPARTITION_SORT_MERGE).where(0,2,3,4,5).equalTo(0,1,2,3,4).with(new KJoiner()); incomingMarginals = KjFractions.groupBy(1,2,3,4,5).sum(6) .join(initial.filter(new IncomingFilter()), JoinOperatorBase.JoinHint.REPARTITION_SORT_MERGE).where(1,2,3,4,5).equalTo(0,1,2,3,4).with(new KUpdater()); DataSet<Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>> iteration = outgoingMarginals.union(incomingMarginals); DataSet<Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>> result = initial.closeWith(iteration); DataSet<Tuple5<String, String, String, Double, SerializableVector>> trafficMatrix = distances .join(result.filter(new OutgoingFilter()), JoinOperatorBase.JoinHint.REPARTITION_SORT_MERGE).where(0,2,3,4,5).equalTo(0,1,2,3,4).with(new TMJoinerOut()) .join(result.filter(new IncomingFilter()), JoinOperatorBase.JoinHint.REPARTITION_SORT_MERGE).where(1,2,3,4,5).equalTo(0,1,2,3,4).with(new TMJoinerIn()) .project(0,1,2,6,7); DataSet<Tuple5<String, String, String, Double, SerializableVector>> TMWithMIDT = trafficMatrix.coGroup(ODBounds).where(0,1,2).equalTo(0,1,2).with( new CoGroupFunction<Tuple5<String, String, String, Double, SerializableVector>, Tuple5<String, String, String, Integer, Integer>, Tuple5<String, String, String, Double, SerializableVector>>() { @Override public void coGroup(Iterable<Tuple5<String, String, String, Double, SerializableVector>> tm, Iterable<Tuple5<String, String, String, Integer, Integer>> midtBound, Collector<Tuple5<String, String, String, Double, SerializableVector>> out) throws Exception { Iterator<Tuple5<String, String, String, Integer, Integer>> midtIter = midtBound.iterator(); Iterator<Tuple5<String, String, String, Double, SerializableVector>> tmIter = tm.iterator(); if(!midtIter.hasNext()) { out.collect(tmIter.next()); if(tmIter.hasNext()) { throw new Exception("More than one TM entry: " + tmIter.next().toString()); } } else { Tuple5<String, String, String, Integer, Integer> midt = midtIter.next(); if(tmIter.hasNext()) { Tuple5<String, String, String, Double, SerializableVector> tmEntry = tmIter.next(); out.collect(new Tuple5<String, String, String, Double, SerializableVector>(tmEntry.f0, tmEntry.f1, tmEntry.f2, tmEntry.f3 + (double)midt.f3, tmEntry.f4)); } if(tmIter.hasNext()) { throw new Exception("More than one TM entry: " + tmIter.next().toString()); } if(midtIter.hasNext()) { throw new Exception("More than one MIDT bound: " + midtIter.next().toString()); } } } }); TMWithMIDT.project(0,1,2,3).writeAsCsv(outputPath + "trafficMatrix", "\n", ",", FileSystem.WriteMode.OVERWRITE); DataSet<Itinerary> nonStopItineraries = nonStopConnections.flatMap(new FlightExtractor1()); DataSet<Itinerary> twoLegItineraries = twoLegConnections.flatMap(new FlightExtractor2()); DataSet<Itinerary> threeLegItineraries = threeLegConnections.flatMap(new FlightExtractor3()); DataSet<Itinerary> itineraries = nonStopItineraries.union(twoLegItineraries).union(threeLegItineraries); //midt.groupBy(0,1,2).sortGroup(0, Order.ASCENDING).first(10000).writeAsCsv(outputPath + "groupedMIDT", "\n", ",", FileSystem.WriteMode.OVERWRITE); DataSet<Tuple4<String, String, String, LogitOptimizable>> trainedLogit = midt.groupBy(0,1,2).reduceGroup(new LogitTrainer()); //trainedLogit.writeAsCsv(outputPath + "logitResult", "\n", ",", FileSystem.WriteMode.OVERWRITE); DataSet<Tuple6<String, String, String, Double, SerializableVector, LogitOptimizable>> TMWithWeights = TMWithMIDT .join(trainedLogit, JoinOperatorBase.JoinHint.REPARTITION_SORT_MERGE).where(0,1,2).equalTo(0,1,2).with(new WeightTMJoiner()); //TMWithWeights.groupBy(0,1,2).sortGroup(2, Order.ASCENDING).first(10000000).writeAsCsv(outputPath + "tmWeights", "\n", ",", FileSystem.WriteMode.OVERWRITE); //itineraries.groupBy(0,1,2,3,4,5,6,7).sortGroup(2, Order.ASCENDING).first(1000000000).writeAsCsv(outputPath + "itineraries", "\n", ",", FileSystem.WriteMode.OVERWRITE); DataSet<Tuple5<String, String, String, Double, LogitOptimizable>> allWeighted = TMWithWeights.coGroup(trafficMatrix).where(2).equalTo(2).with(new ODDistanceComparator()); DataSet<Tuple11<String, String, String, String, String, String, Long, Integer, Itinerary, Integer, Double>> estimate = itineraries.coGroup(allWeighted).where(0,1,2).equalTo(0,1,2).with(new TrafficEstimator()); estimate.groupBy(0,1).sortGroup(6, Order.DESCENDING).first(1000000000).writeAsCsv(outputPath + "ItineraryEstimate", "\n", ",", FileSystem.WriteMode.OVERWRITE); estimate.groupBy(0,1).reduceGroup(new ODSum()).writeAsCsv(outputPath + "ODSum", "\n", ",", FileSystem.WriteMode.OVERWRITE).setParallelism(1); env.execute("TrafficAnalysis"); } private static class KJoiner implements JoinFunction<Tuple7<String, String, String, Boolean, Boolean, Boolean, SerializableVector>, Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>, Tuple7<String, String, String, Boolean, Boolean, Boolean, Double>> { @Override public Tuple7<String, String, String, Boolean, Boolean, Boolean, Double> join(Tuple7<String, String, String, Boolean, Boolean, Boolean, SerializableVector> distance, Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean> marginal) throws Exception { double KFraction = marginal.f5*marginal.f6*decayingFunction(distance.f6.getVector().getEntry(0), distance.f6.getVector().getEntry(1), distance.f6.getVector().getEntry(2), distance.f6.getVector().getEntry(3), distance.f6.getVector().getEntry(4)); if(Double.isNaN(KFraction) || KFraction < 0.0) { KFraction = 0.0; } return new Tuple7<String, String, String, Boolean, Boolean, Boolean, Double>(distance.f0, distance.f1, distance.f2, distance.f3, distance.f4, distance.f5, KFraction); } } private static class KUpdater implements JoinFunction<Tuple7<String, String, String, Boolean, Boolean, Boolean, Double>, Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>, Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>> { @Override public Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean> join(Tuple7<String, String, String, Boolean, Boolean, Boolean, Double> Ksum, Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean> marginal) throws Exception { double sum = Ksum.f6; //if(Double.isNaN(sum) || sum < 0.0) { // sum = 1.0; marginal.f6 = 1.0/sum; return marginal; } } private static class OutgoingFilter implements FilterFunction<Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>> { @Override public boolean filter(Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean> tuple) throws Exception { return tuple.f7.booleanValue(); } } private static class IncomingFilter implements FilterFunction<Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>> { @Override public boolean filter(Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean> tuple) throws Exception { return !tuple.f7.booleanValue(); } } private static class TMJoinerOut implements JoinFunction<Tuple7<String, String, String, Boolean, Boolean, Boolean, SerializableVector>, Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>, Tuple8<String, String, String, Boolean, Boolean, Boolean, Double, SerializableVector>> { @Override public Tuple8<String, String, String, Boolean, Boolean, Boolean, Double, SerializableVector> join(Tuple7<String, String, String, Boolean, Boolean, Boolean, SerializableVector> distance, Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean> marginal) throws Exception { double partialDist = marginal.f5*marginal.f6*decayingFunction(distance.f6.getVector().getEntry(0), distance.f6.getVector().getEntry(1), distance.f6.getVector().getEntry(2), distance.f6.getVector().getEntry(3), distance.f6.getVector().getEntry(4)); if(Double.isNaN(partialDist) || partialDist < 0.0) { partialDist = 0.0; } return new Tuple8<String, String, String, Boolean, Boolean, Boolean, Double, SerializableVector>(distance.f0, distance.f1, distance.f2, distance.f3, distance.f4, distance.f5, partialDist, distance.f6); } } private static class TMJoinerIn implements JoinFunction<Tuple8<String, String, String, Boolean, Boolean, Boolean, Double, SerializableVector>, Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean>, Tuple8<String, String, String, Boolean, Boolean, Boolean, Double, SerializableVector>> { @Override public Tuple8<String, String, String, Boolean, Boolean, Boolean, Double, SerializableVector> join(Tuple8<String, String, String, Boolean, Boolean, Boolean, Double, SerializableVector> tmOut, Tuple8<String, String, Boolean, Boolean, Boolean, Integer, Double, Boolean> marginal) throws Exception { double fullDistance = tmOut.f6*marginal.f5*marginal.f6; if(Double.isNaN(fullDistance) || fullDistance < 0.0) { fullDistance = 0.0; } return new Tuple8<String, String, String, Boolean, Boolean, Boolean, Double, SerializableVector>(tmOut.f0, tmOut.f1, tmOut.f2, tmOut.f3, tmOut.f4, tmOut.f5, fullDistance, tmOut.f7); } } private static class FlightExtractor1 implements FlatMapFunction<Flight, Itinerary> { SimpleDateFormat format = new SimpleDateFormat("ddMMyyyy"); @Override public void flatMap(Flight flight, Collector<Itinerary> out) throws Exception { if(flight.getDepartureTimestamp() > lastPossibleTimestamp || flight.getDepartureTimestamp() < firstPossibleTimestamp) { return; } Date date = new Date(flight.getDepartureTimestamp()); String dayString = format.format(date); Double distance = dist(flight.getOriginLatitude(), flight.getOriginLongitude(), flight.getDestinationLatitude(), flight.getDestinationLongitude()); Integer travelTime = (int) ((flight.getArrivalTimestamp() - flight.getDepartureTimestamp())/(60L*1000L)); out.collect(new Itinerary(flight.getOriginAirport(), flight.getDestinationAirport(), dayString, flight.getAirline() + flight.getFlightNumber(), "", "", "", "", distance, distance, travelTime, 0, flight.getLegCount(), flight.getMaxCapacity(), 0, "")); } } private static class FlightExtractor2 implements FlatMapFunction<Tuple2<Flight, Flight>, Itinerary> { SimpleDateFormat format = new SimpleDateFormat("ddMMyyyy"); @Override public void flatMap(Tuple2<Flight, Flight> flight, Collector<Itinerary> out) throws Exception { if(flight.f0.getDepartureTimestamp() > lastPossibleTimestamp || flight.f0.getDepartureTimestamp() < firstPossibleTimestamp) { return; } Date date = new Date(flight.f0.getDepartureTimestamp()); String dayString = format.format(date); Double directDistance = dist(flight.f0.getOriginLatitude(), flight.f0.getOriginLongitude(), flight.f1.getDestinationLatitude(), flight.f1.getDestinationLongitude()); Double travelledDistance = dist(flight.f0.getOriginLatitude(), flight.f0.getOriginLongitude(), flight.f0.getDestinationLatitude(), flight.f0.getDestinationLongitude()) + dist(flight.f1.getOriginLatitude(), flight.f1.getOriginLongitude(), flight.f1.getDestinationLatitude(), flight.f1.getDestinationLongitude()); Integer travelTime = (int) ((flight.f1.getArrivalTimestamp() - flight.f0.getDepartureTimestamp())/(60L*1000L)); Integer waitingTime = (int) ((flight.f1.getDepartureTimestamp() - flight.f0.getArrivalTimestamp())/(60L*1000L)); Integer legCount = flight.f0.getLegCount() + flight.f1.getLegCount(); Integer maxCapacity = Math.min(flight.f0.getMaxCapacity(), flight.f1.getMaxCapacity()); out.collect(new Itinerary(flight.f0.getOriginAirport(), flight.f1.getDestinationAirport(), dayString, flight.f0.getAirline() + flight.f0.getFlightNumber(), flight.f1.getAirline() + flight.f1.getFlightNumber(), "", "", "", directDistance, travelledDistance, travelTime, waitingTime, legCount, maxCapacity, 0, "")); } } private static class FlightExtractor3 implements FlatMapFunction<Tuple3<Flight, Flight, Flight>, Itinerary> { SimpleDateFormat format = new SimpleDateFormat("ddMMyyyy"); @Override public void flatMap(Tuple3<Flight, Flight, Flight> flight, Collector<Itinerary> out) throws Exception { if(flight.f0.getDepartureTimestamp() > lastPossibleTimestamp || flight.f0.getDepartureTimestamp() < firstPossibleTimestamp) { return; } Date date = new Date(flight.f0.getDepartureTimestamp()); String dayString = format.format(date); Double directDistance = dist(flight.f0.getOriginLatitude(), flight.f0.getOriginLongitude(), flight.f2.getDestinationLatitude(), flight.f2.getDestinationLongitude()); Double travelledDistance = dist(flight.f0.getOriginLatitude(), flight.f0.getOriginLongitude(), flight.f0.getDestinationLatitude(), flight.f0.getDestinationLongitude()) + dist(flight.f1.getOriginLatitude(), flight.f1.getOriginLongitude(), flight.f1.getDestinationLatitude(), flight.f1.getDestinationLongitude()) + dist(flight.f2.getOriginLatitude(), flight.f2.getOriginLongitude(), flight.f2.getDestinationLatitude(), flight.f2.getDestinationLongitude()); Integer travelTime = (int) ((flight.f2.getArrivalTimestamp() - flight.f0.getDepartureTimestamp())/(60L*1000L)); Integer waitingTime = (int) ( ((flight.f1.getDepartureTimestamp() - flight.f0.getArrivalTimestamp()) + (flight.f2.getDepartureTimestamp() - flight.f1.getArrivalTimestamp())) / (60L*1000L)); Integer legCount = flight.f0.getLegCount() + flight.f1.getLegCount() + flight.f2.getLegCount(); Integer maxCapacity = Math.min(flight.f0.getMaxCapacity(), Math.min(flight.f1.getMaxCapacity(), flight.f2.getMaxCapacity())); out.collect(new Itinerary(flight.f0.getOriginAirport(), flight.f2.getDestinationAirport(), dayString, flight.f0.getAirline() + flight.f0.getFlightNumber(), flight.f1.getAirline() + flight.f1.getFlightNumber(), flight.f2.getAirline() + flight.f2.getFlightNumber(), "", "", directDistance, travelledDistance, travelTime, waitingTime, legCount, maxCapacity, 0, "")); } } private static class MIDTCapacityEmitter extends RichFlatMapFunction<String, Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer>> { private SimpleDateFormat format = new SimpleDateFormat("ddMMyyyy"); private HashMap<String, String> APToCountry; @Override public void open(Configuration parameters) { Collection<Tuple4<String, String, String, String>> broadcastSet = this.getRuntimeContext().getBroadcastVariable(AP_COUNTRY_MAPPING); this.APToCountry = new HashMap<String, String>(broadcastSet.size()); for(Tuple4<String, String, String, String> t : broadcastSet) { this.APToCountry.put(t.f0, t.f2); } } @Override public void flatMap(String s, Collector<Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer>> out) throws Exception { if(s.startsWith("$")) { return; } String[] tmp = s.split(";"); if(tmp.length < 15) { return; } if(APToCountry == null) { throw new Exception("HashMap not initialized"); } int pax = Integer.parseInt(tmp[2].trim()); int segmentCount = Integer.parseInt(tmp[3].trim()); long departureDay = Long.parseLong(tmp[11].trim())-1; long departureTimestamp = firstPossibleTimestamp + (departureDay*24L*60L*60L*1000L); Date date = new Date(departureTimestamp); String dayString = format.format(date); if(departureDay > 6) { throw new Exception("Value error: " + s); } boolean isInterRegional = false; boolean isInternational = false; boolean isInterState = false; int offset = 9; int counter = 0; int index = 6; while(counter < segmentCount) { String apOut = tmp[index].trim(); String apIn = tmp[index+1].trim(); index += offset; counter++; String outCountry = APToCountry.get(apOut); String inCountry = APToCountry.get(apIn); if(outCountry != null && inCountry != null) { isInternational = !outCountry.equals(inCountry); } else { continue; //isInternational = false; // usually it cannot find train stations } Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer> tOut = new Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer>(apOut, dayString, isInterRegional, isInternational, isInterState, pax, 0); Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer> tIn = new Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer>(apIn, dayString, isInterRegional, isInternational, isInterState, 0, pax); out.collect(tOut); out.collect(tIn); } } } private static class MIDTParser implements FlatMapFunction<String, MIDT> { SimpleDateFormat format = new SimpleDateFormat("ddMMyyyy"); @Override public void flatMap(String s, Collector<MIDT> out) throws Exception { if(s.startsWith("$")) { return; } String[] tmp = s.split(";"); if(tmp.length < 15) { return; } //int legsInEntry = (tmp.length-(6+1))/9; String origin = tmp[0].trim(); String destination = tmp[1].trim(); int pax = Integer.parseInt(tmp[2].trim()); int segmentCount = Integer.parseInt(tmp[3].trim()); String flight1 = tmp[9].trim() + tmp[10].replaceAll("[^0-9]", ""); String flight2 = ""; String flight3 = ""; String flight4 = ""; String flight5 = ""; long departureDay = Long.parseLong(tmp[11].trim())-1; if(departureDay > 6) { throw new Exception("Value error: " + s); } int departure = Integer.parseInt(tmp[12].trim()); int arrival = Integer.parseInt(tmp[14].trim()); int waitingTime = 0; int tmpDep = 0; if(segmentCount > 1) { flight2 = tmp[18].trim() + tmp[19].replaceAll("[^0-9]", ""); tmpDep = Integer.parseInt(tmp[21].trim()); waitingTime += tmpDep - arrival; arrival = Integer.parseInt(tmp[23].trim()); } if(segmentCount > 2) { flight3 = tmp[27].trim() + tmp[28].replaceAll("[^0-9]", ""); tmpDep = Integer.parseInt(tmp[30].trim()); waitingTime += tmpDep - arrival; arrival = Integer.parseInt(tmp[32].trim()); } if(segmentCount > 3) { flight4 = tmp[36].trim() + tmp[37].replaceAll("[^0-9]", ""); tmpDep = Integer.parseInt(tmp[39].trim()); waitingTime += tmpDep - arrival; arrival = Integer.parseInt(tmp[41].trim()); } if(segmentCount > 4) { flight5 = tmp[45].trim() + tmp[46].replaceAll("[^0-9]", ""); tmpDep = Integer.parseInt(tmp[48].trim()); waitingTime += tmpDep - arrival; arrival = Integer.parseInt(tmp[49].trim()); } int travelTime = arrival - departure; if(travelTime < 0) { return; } long departureTimestamp = firstPossibleTimestamp + (departureDay*24L*60L*60L*1000L); Date date = new Date(departureTimestamp); String dayString = format.format(date); MIDT result = new MIDT(origin, destination, dayString, flight1, flight2, flight3, flight4, flight5, travelTime, waitingTime, segmentCount, pax); out.collect(result); } } private static class MIDTGrouper implements GroupReduceFunction<MIDT, MIDT> { @Override public void reduce(Iterable<MIDT> midts, Collector<MIDT> out) throws Exception { int paxSum = 0; int count = 0; Iterator<MIDT> iterator = midts.iterator(); MIDT midt = null; while(iterator.hasNext()) { midt = iterator.next(); paxSum += midt.f11; count++; } MIDT result = new MIDT(midt.f0, midt.f1, midt.f2, midt.f3, midt.f4, midt.f5, midt.f6, midt.f7, midt.f8, midt.f9, midt.f10, paxSum); out.collect(result); } } private static class LowerBoundExtractor implements MapFunction<MIDT, Tuple5<String, String, String, Integer, Integer>> { @Override public Tuple5<String, String, String, Integer, Integer> map(MIDT midt) throws Exception { return new Tuple5<String, String, String, Integer, Integer>(midt.f0, midt.f1, midt.f2, midt.f11, 0); } } private static class LogitTrainer implements GroupReduceFunction<MIDT, Tuple4<String, String, String, LogitOptimizable>> { @Override public void reduce(Iterable<MIDT> midts, Collector<Tuple4<String, String, String, LogitOptimizable>> out) throws Exception { ArrayList<LogitOptimizable.TrainingData> trainingData = new ArrayList<LogitOptimizable.TrainingData>(); Iterator<MIDT> iterator = midts.iterator(); MIDT midt = null; int minTravelTime = Integer.MAX_VALUE; while(iterator.hasNext()) { midt = iterator.next(); if(midt.f8 < minTravelTime) { minTravelTime = midt.f8; } double percentageWaiting = (midt.f8 == 0 || midt.f9 == 0) ? 0 : midt.f9/midt.f8; trainingData.add(new LogitOptimizable.TrainingData(midt.f8, percentageWaiting, midt.f10, midt.f11)); } if(trainingData.size() < 2) { return; } LogitOptimizable optimizable = new LogitOptimizable(); if(minTravelTime < 1) { minTravelTime = 1; } optimizable.setTrainingData(trainingData, minTravelTime); LimitedMemoryBFGS optimizer = new LimitedMemoryBFGS(optimizable); optimizer.setTolerance(OPTIMIZER_TOLERANCE); boolean converged = false; try { converged = optimizer.optimize(MAX_OPTIMIZER_ITERATIONS); } catch (IllegalArgumentException e) { // This exception may be thrown if L-BFGS // cannot step in the current direction. // This condition does not necessarily mean that // the optimizer has failed, but it doesn't want // to claim to have succeeded... } catch (OptimizationException o) { // see above } catch (Throwable t) { throw new Exception("Something went wrong in the optimizer. " + t.getMessage()); } if(!converged) { return; } optimizable.clear(); // push the results in the tuple out.collect(new Tuple4<String, String, String, LogitOptimizable>(midt.f0, midt.f1, midt.f2, optimizable)); } } private static class WeightTMJoiner implements JoinFunction<Tuple5<String, String, String, Double, SerializableVector>, Tuple4<String, String, String, LogitOptimizable>, Tuple6<String, String, String, Double, SerializableVector, LogitOptimizable>> { @Override public Tuple6<String, String, String, Double, SerializableVector, LogitOptimizable> join(Tuple5<String, String, String, Double, SerializableVector> tmEntry, Tuple4<String, String, String, LogitOptimizable> logit) throws Exception { return new Tuple6<String, String, String, Double, SerializableVector, LogitOptimizable>(tmEntry.f0, tmEntry.f1, tmEntry.f2, tmEntry.f3, tmEntry.f4, logit.f3); } } private static class ODDistanceComparator implements CoGroupFunction<Tuple6<String, String, String, Double, SerializableVector, LogitOptimizable>, Tuple5<String, String, String, Double, SerializableVector>, Tuple5<String, String, String, Double, LogitOptimizable>> { //private List<Tuple2<String, SerializableMatrix>> matrices = null; /*@Override public void open(Configuration parameters) { //this.matrices = getRuntimeContext().getBroadcastVariable(INVERTED_COVARIANCE_MATRIX); }*/ @Override public void coGroup(Iterable<Tuple6<String, String, String, Double, SerializableVector, LogitOptimizable>> weightedODs, Iterable<Tuple5<String, String, String, Double, SerializableVector>> unweightedODs, Collector<Tuple5<String, String, String, Double, LogitOptimizable>> out) throws Exception { ArrayList<Tuple6<String, String, String, Double, SerializableVector, LogitOptimizable>> weighted = new ArrayList<Tuple6<String, String, String, Double, SerializableVector, LogitOptimizable>>(); for(Tuple6<String, String, String, Double, SerializableVector, LogitOptimizable> w : weightedODs) { weighted.add(w.copy()); } double distance = 0.0; for(Tuple5<String, String, String, Double, SerializableVector> uw : unweightedODs) { double minDistance = Double.MAX_VALUE; Tuple6<String, String, String, Double, SerializableVector, LogitOptimizable> tmp = null; for(Tuple6<String, String, String, Double, SerializableVector, LogitOptimizable> w : weighted) { distance = uw.f4.getVector().getDistance(w.f4.getVector()); if(distance < minDistance) { minDistance = distance; tmp = w; } } if(tmp == null) { continue; } out.collect(new Tuple5<String, String, String, Double, LogitOptimizable>(uw.f0, uw.f1, uw.f2, uw.f3, tmp.f5)); } } } private static class TrafficEstimator implements CoGroupFunction<Itinerary, Tuple5<String, String, String, Double, LogitOptimizable>, Tuple11<String, String, String, String, String, String, Long, Integer, Itinerary, Integer, Double>> { @Override public void coGroup(Iterable<Itinerary> connections, Iterable<Tuple5<String, String, String, Double, LogitOptimizable>> logitModel, Collector<Tuple11<String, String, String, String, String, String, Long, Integer, Itinerary, Integer, Double>> out) throws Exception { Iterator<Tuple5<String, String, String, Double, LogitOptimizable>> logitIter = logitModel.iterator(); if(!logitIter.hasNext()) { return; // no model } Tuple5<String, String, String, Double, LogitOptimizable> logit = logitIter.next(); if(logitIter.hasNext()) { throw new Exception("More than one logit model: " + logitIter.next().toString()); } double estimate = logit.f3; double[] weights = logit.f4.asArray(); Iterator<Itinerary> connIter = connections.iterator(); if(!connIter.hasNext()) { return; // no connections } int count = 0; ArrayList<Itinerary> itineraries = new ArrayList<Itinerary>(); int minTime = Integer.MAX_VALUE; while (connIter.hasNext()) { Itinerary e = connIter.next().deepCopy(); /*if(itineraries.contains(e)) { throw new Exception("Itinerary found twice:" + e.toString()); }*/ itineraries.add(e); if(e.f10 < minTime) { minTime = e.f10; } count++; } if(minTime < 1) { minTime = 1; } double softmaxSum = 0.0; for(Itinerary e : itineraries) { softmaxSum += Math.exp(LogitOptimizable.linearPredictorFunction(LogitOptimizable.toArray(e, minTime), weights)); } for(Itinerary e : itineraries) { double itineraryEstimate = LogitOptimizable.softmax(e, softmaxSum, weights, minTime)*estimate; long roundedEstimate = Math.round(itineraryEstimate); if(roundedEstimate > 0L) { out.collect(new Tuple11<String, String, String, String, String, String, Long, Integer, Itinerary, Integer, Double>(e.f0, e.f1, e.f2, e.f3, e.f4, e.f5, roundedEstimate, e.f10, e, count, logit.f3)); } } } } private static class ODSum implements GroupReduceFunction<Tuple11<String, String, String, String, String, String, Long, Integer, Itinerary, Integer, Double>, Tuple6<String, String, Integer, Integer, Long, Double>> { @Override public void reduce(Iterable<Tuple11<String, String, String, String, String, String, Long, Integer, Itinerary, Integer, Double>> iterable, Collector<Tuple6<String, String, Integer, Integer, Long, Double>> out) throws Exception { Tuple6<String, String, Integer, Integer, Long, Double> result = new Tuple6<String, String, Integer, Integer, Long, Double>(); HashSet<String> days = new HashSet<String>(7); int itinCount = 0; long paxSum = 0L; double estimateSum = 0.0; for(Tuple11<String, String, String, String, String, String, Long, Integer, Itinerary, Integer, Double> t : iterable) { if(!days.contains(t.f2)) { days.add(t.f2); estimateSum += t.f10; } result.f0 = t.f0; result.f1 = t.f1; paxSum += t.f6; itinCount++; result.f3 = t.f9; } result.f2 = itinCount; result.f4 = paxSum; result.f5 = estimateSum; out.collect(result); } } private static class CovarianceMatrix implements GroupReduceFunction<Tuple9<String, String, String, Boolean, Double, Integer, Integer, Double, Integer>, Tuple2<String, SerializableMatrix>> { @Override public void reduce(Iterable<Tuple9<String, String, String, Boolean, Double, Integer, Integer, Double, Integer>> iterable, Collector<Tuple2<String, SerializableMatrix>> collector) throws Exception { } } public static class AirportCountryExtractor implements FlatMapFunction<String, Tuple4<String, String, String, String>> { String[] tmp = null; String from = null; String until = null; @Override public void flatMap(String value, Collector<Tuple4<String, String, String, String>> out) throws Exception { tmp = value.split("\\^"); if (tmp[0].trim().startsWith(" // header return; } if (!tmp[41].trim().equals("A")) { // not an airport return; } from = tmp[13].trim(); until = tmp[14].trim(); if (!until.equals("")) { // expired return; } String iataCode = tmp[0].trim(); String regionCode = ""; String countryCode = tmp[16].trim(); String stateCode = tmp[40].trim(); out.collect(new Tuple4<String, String, String, String>(iataCode, regionCode, countryCode, stateCode)); } } public static class RegionJoiner implements JoinFunction<Tuple4<String, String, String, String>, Tuple2<String, String>, Tuple4<String, String, String, String>> { @Override public Tuple4<String, String, String, String> join(Tuple4<String, String, String, String> first, Tuple2<String, String> second) throws Exception { first.f1 = second.f1; return first; } } /* * distance between two coordinates in kilometers */ private static double dist(double lat1, double long1, double lat2, double long2) { final double d2r = Math.PI / 180.0; double dlong = (long2 - long1) * d2r; double dlat = (lat2 - lat1) * d2r; double a = Math.pow(Math.sin(dlat / 2.0), 2.0) + Math.cos(lat1 * d2r) * Math.cos(lat2 * d2r) * Math.pow(Math.sin(dlong / 2.0), 2.0); double c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1.0 - a)); double d = 6367.0 * c; return d; } private static double decayingFunction(double minTravelTime, double maxTravelTime, double avgTravelTime, double distance, double count) { /*double mu = 3.3; double sigma = 0.5; double sigma2 = Math.pow(sigma, 2.0); double x = distance; double numerator = Math.exp((-Math.pow(Math.log(x)-mu, 2.0))/2.0*sigma2); double denominator = x*sigma*Math.sqrt(2.0*Math.PI); return numerator/denominator;*/ return 1.0/Math.sqrt(minTravelTime*avgTravelTime*distance); //return Math.exp(-2*(Math.log(distance)-1.8)*(Math.log(distance)-1.8)); } private static double mahalanobisDistance(ArrayRealVector x, ArrayRealVector y, Array2DRowRealMatrix Sinv) { ArrayRealVector xmy = x.subtract(y); RealVector SinvXmy = Sinv.operate(xmy); double result = xmy.dotProduct(SinvXmy); return Math.sqrt(result); } }
package com.bacic5i5j.gemini.database; import com.bacic5i5j.gemini.internal.DefaultHibernateAccess; import com.google.inject.ImplementedBy; import java.io.Serializable; /** * * * @(#)Access.java 1.0 10/03/2014 */ public interface Access<T, PK extends Serializable> { /** * * @param persistClass */ public void setClass(Class<T> persistClass); /** * * @param id * @return */ public T get(PK id); /** * * @param entity * @return */ public PK save(T entity); /** * * @param entity */ public void delete(T entity); /** * * @param id */ public T delete(PK id); /** * * @param entity * @return */ public void update(T entity); }
package com.bio4j.model.go.programs; import com.bio4j.model.go.GoGraph; import com.bio4j.model.go.nodes.GoTerm; import com.bio4j.model.go.nodes.SubOntologies; import com.ohnosequences.xml.api.model.XMLElement; import org.jdom2.Element; import com.ohnosequences.typedGraphs.*; import java.io.*; import java.util.*; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; /** * @author <a href="mailto:ppareja@era7.com">Pablo Pareja Tobes</a> */ public abstract class ImportGO<I extends UntypedGraph<RV,RVT,RE,RET>,RV,RVT,RE,RET> { // XML constants public static final String TERM_TAG_NAME = "term"; public static final String ID_TAG_NAME = "id"; public static final String NAME_TAG_NAME = "name"; public static final String DEF_TAG_NAME = "def"; public static final String DEFSTR_TAG_NAME = "defstr"; public static final String IS_ROOT_TAG_NAME = "is_root"; public static final String IS_OBSOLETE_TAG_NAME = "is_obsolete"; public static final String COMMENT_TAG_NAME = "comment"; public static final String NAMESPACE_TAG_NAME = "namespace"; public static final String RELATIONSHIP_TAG_NAME = "relationship"; public static final String REGULATES_OBOXML_RELATIONSHIP_NAME = "regulates"; public static final String POSITIVELY_REGULATES_OBOXML_RELATIONSHIP_NAME = "positively_regulates"; public static final String NEGATIVELY_REGULATES_OBOXML_RELATIONSHIP_NAME = "negatively_regulates"; public static final String PART_OF_OBOXML_RELATIONSHIP_NAME = "part_of"; public static final String HAS_PART_OF_OBOXML_RELATIONSHIP_NAME = "has_part"; public static final String IS_A_OBOXML_RELATIONSHIP_NAME = "is_a"; private static final Logger logger = Logger.getLogger("ImportGO"); private static FileHandler fh; protected abstract GoGraph<I,RV,RVT,RE,RET> config(); protected void importGO(String[] args){ if (args.length != 2) { System.out.println("This program expects the following parameters: \n" + "1. Gene ontology xml filename \n" + "2. Bio4j DB folder \n"); } else { int termCounter = 0; int limitForPrintingOut = 10000; long initTime = System.nanoTime(); File inFile = new File(args[0]); BufferedWriter statsBuff = null; GoGraph<I,RV,RVT,RE,RET> goGraph = config(); try { //This block configures the logger with handler and formatter fh = new FileHandler("ImportGO.log", true); SimpleFormatter formatter = new SimpleFormatter(); fh.setFormatter(formatter); logger.addHandler(fh); logger.setLevel(Level.ALL); statsBuff = new BufferedWriter(new FileWriter(new File("ImportGOStats.txt"))); Map<String, ArrayList<String>> termParentsMap = new HashMap<>(); Map<String, ArrayList<String>> regulatesMap = new HashMap<>(); Map<String, ArrayList<String>> negativelyRegulatesMap = new HashMap<>(); Map<String, ArrayList<String>> positivelyRegulatesMap = new HashMap<>(); Map<String, ArrayList<String>> partOfMap = new HashMap<>(); Map<String, ArrayList<String>> hasPartMap = new HashMap<>(); BufferedReader reader = new BufferedReader(new FileReader(inFile)); String line; StringBuilder termStBuilder = new StringBuilder(); logger.log(Level.INFO, "inserting subontologies nodes...."); SubOntologies<I,RV,RVT,RE,RET> subOntologiesBP = goGraph.SubOntologies().from( goGraph.raw().addVertex(null) ); subOntologiesBP.set(goGraph.SubOntologies().name, "biological_process"); SubOntologies<I,RV,RVT,RE,RET> subOntologiesCC = goGraph.SubOntologies().from( goGraph.raw().addVertex(null) ); subOntologiesCC.set(goGraph.SubOntologies().name, "cellular_component"); SubOntologies<I,RV,RVT,RE,RET> subOntologiesMM = goGraph.SubOntologies().from( goGraph.raw().addVertex(goGraph.SubOntologies().raw()) ); subOntologiesMM.set(goGraph.SubOntologies().name, "molecular_function"); logger.log(Level.INFO, "inserting term nodes...."); while ((line = reader.readLine()) != null) { if (line.trim().startsWith("<" + TERM_TAG_NAME)) { while (!line.trim().startsWith("</" + TERM_TAG_NAME + ">")) { termStBuilder.append(line); line = reader.readLine(); } //organism final line termStBuilder.append(line); XMLElement termXMLElement = new XMLElement(termStBuilder.toString()); termStBuilder.delete(0, termStBuilder.length()); String goId = termXMLElement.asJDomElement().getChildText(ID_TAG_NAME); String goName = termXMLElement.asJDomElement().getChildText(NAME_TAG_NAME); if (goName == null) { goName = ""; } String goNamespace = termXMLElement.asJDomElement().getChildText(NAMESPACE_TAG_NAME); if (goNamespace == null) { goNamespace = ""; } String goDefinition = ""; Element defElem = termXMLElement.asJDomElement().getChild(DEF_TAG_NAME); if (defElem != null) { Element defstrElem = defElem.getChild(DEFSTR_TAG_NAME); if (defstrElem != null) { goDefinition = defstrElem.getText(); } } String goComment = termXMLElement.asJDomElement().getChildText(COMMENT_TAG_NAME); if (goComment == null) { goComment = ""; } String goIsObsolete = termXMLElement.asJDomElement().getChildText(IS_OBSOLETE_TAG_NAME); if (goIsObsolete == null) { goIsObsolete = ""; } else { if (goIsObsolete.equals("1")) { goIsObsolete = "true"; } else { goIsObsolete = "false"; } } List<Element> termParentTerms = termXMLElement.asJDomElement().getChildren(IS_A_OBOXML_RELATIONSHIP_NAME); ArrayList<String> array = new ArrayList<>(); for (Element elem : termParentTerms) { array.add(elem.getText().trim()); } termParentsMap.put(goId, array); List<Element> relationshipTags = termXMLElement.asJDomElement().getChildren(RELATIONSHIP_TAG_NAME); for (Element relationshipTag : relationshipTags) { String relType = relationshipTag.getChildText("type"); String toSt = relationshipTag.getChildText("to"); if (relType.equals(REGULATES_OBOXML_RELATIONSHIP_NAME)) { ArrayList<String> tempArray = regulatesMap.get(goId); if (tempArray == null) { tempArray = new ArrayList<>(); regulatesMap.put(goId, tempArray); } tempArray.add(toSt); } else if (relType.equals(POSITIVELY_REGULATES_OBOXML_RELATIONSHIP_NAME)) { ArrayList<String> tempArray = positivelyRegulatesMap.get(goId); if (tempArray == null) { tempArray = new ArrayList<>(); positivelyRegulatesMap.put(goId, tempArray); } tempArray.add(toSt); } else if (relType.equals(NEGATIVELY_REGULATES_OBOXML_RELATIONSHIP_NAME)) { ArrayList<String> tempArray = negativelyRegulatesMap.get(goId); if (tempArray == null) { tempArray = new ArrayList<>(); negativelyRegulatesMap.put(goId, tempArray); } tempArray.add(toSt); } else if (relType.equals(PART_OF_OBOXML_RELATIONSHIP_NAME)) { ArrayList<String> tempArray = partOfMap.get(goId); if (tempArray == null) { tempArray = new ArrayList<>(); partOfMap.put(goId, tempArray); } tempArray.add(toSt); } else if (relType.equals(HAS_PART_OF_OBOXML_RELATIONSHIP_NAME)) { ArrayList<String> tempArray = hasPartMap.get(goId); if (tempArray == null) { tempArray = new ArrayList<>(); hasPartMap.put(goId, tempArray); } tempArray.add(toSt); } } GoTerm<I,RV,RVT,RE,RET> term = goGraph.GoTerm().from( goGraph.raw().addVertex( goGraph.GoTerm().raw() ) ); term.set(goGraph.GoTerm().id, goId); term.set(goGraph.GoTerm().name, goName); term.set(goGraph.GoTerm().definition, goDefinition); //term.set(goGraph.GoTerm().obso, goIsObsolete); term.set(goGraph.GoTerm().comment, goComment); //g.commit(); GoTerm<I,RV,RVT,RE,RET> tempGoTerm = goGraph.goTermIdIndex().getVertex(goId); //SubOntologies subOntologies = goGraph. SubOntologies<I,RV,RVT,RE,RET> tmpSubontologies = goGraph.subontologiesNameIndex().getVertex(goNamespace); goGraph.addEdge(tempGoTerm,goGraph.SubOntology(), tmpSubontologies); } termCounter++; if ((termCounter % limitForPrintingOut) == 0) { logger.log(Level.INFO, (termCounter + " terms inserted!!")); } } reader.close(); //goGraph.raw(). logger.log(Level.INFO, "Inserting relationships...."); logger.log(Level.INFO, "'is_a' relationships...."); Set<String> keys = termParentsMap.keySet(); for (String key : keys) { GoTerm<I,RV,RVT,RE,RET> tempGoTerm = goGraph.goTermIdIndex().getVertex(key); //System.out.println("id: " + tempGoTerm.id() + " name: " + tempGoTerm.name()); ArrayList<String> tempArray = termParentsMap.get(key); for (String string : tempArray) { //System.out.println("string: " + string); GoTerm<I,RV,RVT,RE,RET> tempGoTerm2 = goGraph.goTermIdIndex().getVertex(string); //System.out.println("id2: " + tempGoTerm2.id() + " name2: " + tempGoTerm2.name()); goGraph.addEdge(tempGoTerm,goGraph.IsA(), tempGoTerm2); } } logger.log(Level.INFO, "'regulates' relationships...."); keys = regulatesMap.keySet(); for (String key : keys) { GoTerm<I,RV,RVT,RE,RET> tempGoTerm = goGraph.goTermIdIndex().getVertex(key); ArrayList<String> tempArray = regulatesMap.get(key); for (String string : tempArray) { GoTerm<I,RV,RVT,RE,RET> tempGoTerm2 = goGraph.goTermIdIndex().getVertex(string); goGraph.addEdge(tempGoTerm, goGraph.Regulates(), tempGoTerm2); } } logger.log(Level.INFO, "'negatively_regulates' relationships...."); keys = negativelyRegulatesMap.keySet(); for (String key : keys) { GoTerm<I,RV,RVT,RE,RET> tempGoTerm = goGraph.goTermIdIndex().getVertex(key); ArrayList<String> tempArray = negativelyRegulatesMap.get(key); for (String string : tempArray) { GoTerm<I,RV,RVT,RE,RET> tempGoTerm2 = goGraph.goTermIdIndex().getVertex(string); goGraph.addEdge(tempGoTerm, goGraph.NegativelyRegulates(), tempGoTerm2); } } logger.log(Level.INFO, "'positively_regulates' relationships...."); keys = positivelyRegulatesMap.keySet(); for (String key : keys) { GoTerm<I,RV,RVT,RE,RET> tempGoTerm = goGraph.goTermIdIndex().getVertex(key); ArrayList<String> tempArray = positivelyRegulatesMap.get(key); for (String string : tempArray) { GoTerm<I,RV,RVT,RE,RET> tempGoTerm2 = goGraph.goTermIdIndex().getVertex(string); goGraph.addEdge(tempGoTerm, goGraph.PositivelyRegulates(), tempGoTerm2); } } logger.log(Level.INFO, "'part_of' relationships...."); keys = partOfMap.keySet(); for (String key : keys) { GoTerm<I,RV,RVT,RE,RET> tempGoTerm = goGraph.goTermIdIndex().getVertex(key); ArrayList<String> tempArray = partOfMap.get(key); for (String string : tempArray) { GoTerm<I,RV,RVT,RE,RET> tempGoTerm2 = goGraph.goTermIdIndex().getVertex(string); goGraph.addEdge(tempGoTerm, goGraph.PartOf(), tempGoTerm2); } } logger.log(Level.INFO, "'has_part_of' relationships...."); keys = hasPartMap.keySet(); for (String key : keys) { GoTerm<I,RV,RVT,RE,RET> tempGoTerm = goGraph.goTermIdIndex().getVertex(key); ArrayList<String> tempArray = hasPartMap.get(key); for (String string : tempArray) { GoTerm<I,RV,RVT,RE,RET> tempGoTerm2 = goGraph.goTermIdIndex().getVertex(string); goGraph.addEdge(tempGoTerm, goGraph.HasPartOf(), tempGoTerm2); } } logger.log(Level.INFO, "Done! :)"); } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage()); StackTraceElement[] trace = e.getStackTrace(); for (StackTraceElement stackTraceElement : trace) { logger.log(Level.SEVERE, stackTraceElement.toString()); } } finally { try { //closing logger file handler fh.close(); logger.log(Level.INFO, "Closing up manager...."); //shutdown, makes sure all changes are written to disk //graph.rawGraph().shutdown(); long elapsedTime = System.nanoTime() - initTime; long elapsedSeconds = Math.round((elapsedTime / 1000000000.0)); long hours = elapsedSeconds / 3600; long minutes = (elapsedSeconds % 3600) / 60; long seconds = (elapsedSeconds % 3600) % 60; statsBuff.write("Statistics for program ImportGeneOntology:\nInput file: " + inFile.getName() + "\nThere were " + termCounter + " terms inserted.\n" + "The elapsed time was: " + hours + "h " + minutes + "m " + seconds + "s\n"); statsBuff.close(); } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage()); StackTraceElement[] trace = e.getStackTrace(); for (StackTraceElement stackTraceElement : trace) { logger.log(Level.SEVERE, stackTraceElement.toString()); } } } } } }
package com.bnade.wow.handle; import com.bnade.wow.dto.Result; import com.bnade.wow.enums.ResultEnum; import com.bnade.wow.exception.UnknownResourceException; import com.bnade.wow.utils.ResultUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.validation.BindException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import javax.servlet.http.HttpServletRequest; @ControllerAdvice public class ExceptionHandle { private static final Logger logger = LoggerFactory.getLogger(ExceptionHandle.class); @ExceptionHandler(UnknownResourceException.class) @ResponseStatus(value = HttpStatus.NOT_FOUND) @ResponseBody public Result handle404Error(HttpServletRequest req) { String url = req.getMethod() + " " + req.getRequestURL() + "?" + req.getQueryString(); logger.debug("url {}", url); ResultEnum notFound = ResultEnum.NOT_FOUND; return ResultUtils.error(notFound.getCode(), notFound.getMessage(), url); } @ExceptionHandler(value = {IllegalArgumentException.class, BindException.class, // controllerbean MissingServletRequestParameterException.class, MethodArgumentTypeMismatchException.class, HttpRequestMethodNotSupportedException.class}) @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ResponseBody public Result handle400Error(HttpServletRequest req, Exception e) { String url = req.getMethod() + " " + req.getRequestURL() + "?" + req.getQueryString(); logger.debug("url: {}", url); ResultEnum badRequest = ResultEnum.BAD_REQUEST; return ResultUtils.error(badRequest.getCode(), badRequest.getMessage(), url); } @ExceptionHandler(value = Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ResponseBody public Result handleError(HttpServletRequest req, Exception e) { String url = req.getMethod() + " " + req.getRequestURL() + "?" + req.getQueryString(); logger.error("url: {}", url, e); ResultEnum serverError = ResultEnum.INTERNAL_SERVER_ERROR; return ResultUtils.error(serverError.getCode(), serverError.getMessage(), url); } }
package com.conveyal.r5.analyst; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClient; import com.amazonaws.services.sqs.model.MessageAttributeValue; import com.amazonaws.services.sqs.model.SendMessageRequest; import com.conveyal.r5.analyst.cluster.GridRequest; import com.conveyal.r5.analyst.cluster.Origin; import com.conveyal.r5.analyst.cluster.TaskStatistics; import com.conveyal.r5.api.util.LegMode; import com.conveyal.r5.profile.FastRaptorWorker; import com.conveyal.r5.profile.PerTargetPropagater; import com.conveyal.r5.profile.Propagater; import com.conveyal.r5.profile.RaptorWorker; import com.conveyal.r5.profile.StreetMode; import com.conveyal.r5.streets.LinkedPointSet; import com.conveyal.r5.streets.StreetRouter; import com.conveyal.r5.transit.TransportNetwork; import com.google.common.io.LittleEndianDataOutputStream; import gnu.trove.iterator.TIntIntIterator; import gnu.trove.map.TIntIntMap; import org.apache.commons.math3.random.MersenneTwister; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Base64; import java.util.BitSet; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.DoubleStream; import java.util.stream.Stream; /** * Computes an accessibility indicator at a single cell in a Web Mercator grid, using destination densities from * a Web Mercator density grid. Both grids must be at the same zoom level. The accessibility indicator is calculated * separately for each iteration of the range RAPTOR algorithm (each departure minute and randomization of the schedules * for the frequency-based routes) and all of these different values of the indicator are retained to allow * probabilistic scenario comparison. This does freeze the travel time cutoff and destination grid in the interest of * keeping the results down to an acceptable size. The results are placed on an Amazon SQS queue for collation by * a GridResultConsumer and a GridResultAssembler. * * These requests are enqueued by the frontend one for each origin in a regional analysis. */ public class GridComputer { private static final Logger LOG = LoggerFactory.getLogger(GridComputer.class); /** The number of iterations used to bootstrap the sampling distribution of the percentiles */ public static final int BOOTSTRAP_ITERATIONS = 1000; /** SQS client. TODO: async? */ private static final AmazonSQS sqs = new AmazonSQSClient(); private static final Base64.Encoder base64 = Base64.getEncoder(); private final GridCache gridCache; public final GridRequest request; private static WebMercatorGridPointSetCache pointSetCache = new WebMercatorGridPointSetCache(); public final TransportNetwork network; public GridComputer(GridRequest request, GridCache gridCache, TransportNetwork network) { this.request = request; this.gridCache = gridCache; this.network = network; } public void run() throws IOException { final Grid grid = gridCache.get(request.grid); // ensure they both have the same zoom level if (request.zoom != grid.zoom) throw new IllegalArgumentException("grid zooms do not match!"); // use the middle of the grid cell request.request.fromLat = Grid.pixelToLat(request.north + request.y + 0.5, request.zoom); request.request.fromLon = Grid.pixelToLon(request.west + request.x + 0.5, request.zoom); // Run the raptor algorithm to get times at each destination for each iteration // first, find the access stops StreetMode mode; if (request.request.accessModes.contains(LegMode.CAR)) mode = StreetMode.CAR; else if (request.request.accessModes.contains(LegMode.BICYCLE)) mode = StreetMode.BICYCLE; else mode = StreetMode.WALK; LOG.info("Maximum number of rides: {}", request.request.maxRides); LOG.info("Maximum trip duration: {}", request.request.maxTripDurationMinutes); // Use the extent of the grid as the targets; this avoids having to convert between coordinate systems, // and avoids including thousands of extra points in the weeds where there happens to be a transit stop. WebMercatorGridPointSet targets = pointSetCache.get(grid); // TODO recast using egress mode final LinkedPointSet linkedTargets = targets.link(network.streetLayer, mode); StreetRouter sr = new StreetRouter(network.streetLayer); sr.distanceLimitMeters = 2000; sr.setOrigin(request.request.fromLat, request.request.fromLon); sr.dominanceVariable = StreetRouter.State.RoutingVariable.DISTANCE_MILLIMETERS; sr.route(); TIntIntMap reachedStops = sr.getReachedStops(); // convert millimeters to seconds int millimetersPerSecond = (int) (request.request.walkSpeed * 1000); for (TIntIntIterator it = reachedStops.iterator(); it.hasNext();) { it.advance(); it.setValue(it.value() / millimetersPerSecond); } FastRaptorWorker router = new FastRaptorWorker(network.transitLayer, request.request, reachedStops); // Run the raptor algorithm int[][] timesAtStopsEachIteration = router.route(); // Do propagation int[] nonTransferTravelTimesToStops = linkedTargets.eval(sr::getTravelTimeToVertex).travelTimes; PerTargetPropagater propagater = new PerTargetPropagater(timesAtStopsEachIteration, nonTransferTravelTimesToStops, linkedTargets, request.request, request.cutoffMinutes * 60); // the Mersenne Twister is a high-quality RNG well-suited to Monte Carlo situations MersenneTwister twister = new MersenneTwister(); // compute the percentiles double[] samples = new double[BOOTSTRAP_ITERATIONS + 1]; propagater.propagate((target, times) -> { for (int bootstrap = 0; bootstrap < BOOTSTRAP_ITERATIONS; bootstrap++) { int count = 0; for (int minute = 0; minute < router.nMinutes; minute++) { int monteCarloDrawToUse = twister.nextInt(router.monteCarloDrawsPerMinute); int iteration = minute * router.monteCarloDrawsPerMinute + monteCarloDrawToUse; if (times[iteration] < request.cutoffMinutes * 60) count++; } if (count > router.nMinutes / 2) { int gridx = target % grid.width; int gridy = target / grid.width; samples[bootstrap] += grid.grid[gridx][gridy]; } } }); int[] intSamples = DoubleStream.of(samples).mapToInt(d -> (int) Math.round(d)).toArray(); // now construct the output // these things are tiny, no problem storing in memory ByteArrayOutputStream baos = new ByteArrayOutputStream(); new Origin(request, intSamples).write(baos); // send this origin to an SQS queue as a binary payload; it will be consumed by GridResultConsumer // and GridResultAssembler SendMessageRequest smr = new SendMessageRequest(request.outputQueue, base64.encodeToString(baos.toByteArray())); smr = smr.addMessageAttributesEntry("jobId", new MessageAttributeValue().withDataType("String").withStringValue(request.jobId)); sqs.sendMessage(smr); } }
package com.e16din.alertmanager; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnKeyListener; import android.os.Handler; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager.BadTokenException; import android.widget.DatePicker; import android.widget.TextView; import android.widget.TimePicker; import com.afollestad.materialdialogs.AlertDialogWrapper; import com.afollestad.materialdialogs.MaterialDialog; import java.util.ArrayList; import java.util.Date; public class AlertManager { private AlertManager() { } private static final int INVALID_VALUE = -100500; public static final int MILLISECONDS_IN_THE_DAY = 86400; public static void setCustomPostfix(String customPostfix) { AlertManager.customPostfix = customPostfix; } private static class Holder { public static final AlertManager HOLDER_INSTANCE = new AlertManager(); } public static AlertManager manager(Context context) { Holder.HOLDER_INSTANCE.setContext(context); return Holder.HOLDER_INSTANCE; } private static int customAlertTitle = R.string.title_alert; private static int customErrorTitle = R.string.title_error; private static String customPostfix = ""; public static String getCustomPostfix() { return customPostfix; } public static int getCustomAlertTitle() { return customAlertTitle; } public static void setCustomAlertTitle(int customAlertTitle) { AlertManager.customAlertTitle = customAlertTitle; } public static int getCustomErrorTitle() { return customErrorTitle; } public static void setCustomErrorTitle(int customErrorTitle) { AlertManager.customErrorTitle = customErrorTitle; } private Context context = null; private ArrayList<String> displayedAlerts = new ArrayList<>(); public boolean isAlertDisplayed(String message) { return displayedAlerts.contains(message); } private void setContext(Context context) { this.context = context; } public void showErrorAlert(String message, boolean isCancelable) { showAlert(message, customErrorTitle, isCancelable, null); } public void showErrorAlert(int message, boolean isCancelable) { showAlert(message, customErrorTitle, isCancelable, null); } public void showErrorAlert(String message, boolean isCancelable, final DialogInterface.OnClickListener listener) { showAlert(message, customErrorTitle, isCancelable, listener); } public void showErrorAlert(int message, boolean isCancelable, final DialogInterface.OnClickListener listener) { showAlert(message, customErrorTitle, isCancelable, listener); } public void showErrorAlert(String message) { showAlert(message, customErrorTitle, false, null); } public void showErrorAlert(int message) { showAlert(message, customErrorTitle, false, null); } public void showErrorAlert(String message, final DialogInterface.OnClickListener listener) { showAlert(message, customErrorTitle, false, listener); } public void showErrorAlert(int message, final DialogInterface.OnClickListener listener) { showAlert(message, customErrorTitle, false, listener); } public void showAlert(String message, boolean isCancelable) { showAlert(message, customAlertTitle, isCancelable, null); } public void showAlert(int message, boolean isCancelable) { showAlert(message, customAlertTitle, isCancelable, null); } public void showAlert(String message) { showAlert(message, customAlertTitle, false, null); } public void showAlert(int message) { showAlert(message, customAlertTitle, false, null); } public void showAlert(String message, final DialogInterface.OnClickListener listener) { showAlert(message, customAlertTitle, false, listener); } public void showAlert(int message, final DialogInterface.OnClickListener listener) { showAlert(message, customAlertTitle, false, listener); } public void showAlert(final String message, final int title, final boolean isCancelable, final DialogInterface.OnClickListener listener) { Handler h = new Handler(); h.postDelayed(new Runnable() { @Override public void run() { try { AlertDialogWrapper.Builder builder = createAlertBuilder(); builder.setTitle(context.getString(title) + " " + customPostfix).setMessage(message) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (listener != null) listener.onClick(dialog, which); displayedAlerts.remove(message); } }).setCancelable(isCancelable).setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK || event.getAction() == KeyEvent.ACTION_UP) { if (listener != null) listener.onClick(dialog, INVALID_VALUE); } displayedAlerts.remove(message); return false; } }).show(); displayedAlerts.add(message); } catch (BadTokenException e) { Log.e("debug", "error: ", e); } } }, 500); } private AlertDialogWrapper.Builder createAlertBuilder() { return new AlertDialogWrapper.Builder(context); } public void showAlert(final int message, int title, boolean isCancelable, final DialogInterface.OnClickListener listener) { showAlert(context.getString(message), title, isCancelable, listener); } public void showAlert(final String message, boolean isCancelable, final DialogInterface.OnClickListener listener) { try { AlertDialogWrapper.Builder builder = createAlertBuilder(); builder.setTitle(context.getString(customAlertTitle) + " " + customPostfix).setMessage(message) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (listener != null) listener.onClick(dialog, which); displayedAlerts.remove(message); } }).setCancelable(isCancelable).setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK || event.getAction() == KeyEvent.ACTION_UP) { if (listener != null) listener.onClick(dialog, INVALID_VALUE); displayedAlerts.remove(message); } return false; } }).show(); displayedAlerts.add(message); } catch (BadTokenException e) { Log.e("debug", "error: ", e); } } public void showAlertYesNo(final String message, final DialogInterface.OnClickListener yesListener) { try { AlertDialogWrapper.Builder builder = createAlertBuilder(); builder.setTitle(context.getString(customAlertTitle) + " " + customPostfix).setMessage(message) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (yesListener != null) yesListener.onClick(dialog, which); displayedAlerts.remove(message); } }).setNegativeButton(android.R.string.no, null).show(); displayedAlerts.add(message); } catch (BadTokenException e) { Log.e("debug", "error: ", e); } } public void showDialogList(final String title, final CharSequence[] items, final TextView tv, final DialogInterface.OnClickListener listener) { try { AlertDialogWrapper.Builder builder = createAlertBuilder(); builder.setTitle(title).setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (tv != null) tv.setText(items[which]); if (listener != null) listener.onClick(dialog, which); displayedAlerts.remove(title); } }).show(); displayedAlerts.add(title); } catch (BadTokenException e) { Log.e("debug", "error: ", e); } } public void showRadioList(final String title, final CharSequence[] items, final TextView tv, final DialogInterface.OnClickListener listener) { new MaterialDialog.Builder(context) .title(title) .items(items) .itemsCallbackSingleChoice(-1, new MaterialDialog.ListCallbackSingleChoice() { @Override public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) { /** * If you use alwaysCallSingleChoiceCallback(), which is discussed below, * returning false here won't allow the newly selected radio button to actually be selected. **/ if (tv != null) tv.setText(items[which]); if (listener != null) listener.onClick(dialog, which); dialog.dismiss(); dialog.cancel(); return true; } }) .alwaysCallSingleChoiceCallback() .positiveText(android.R.string.cancel) .callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { dialog.dismiss(); } }) .show(); } public void showDialogList(final CharSequence[] items, final TextView tv, final DialogInterface.OnClickListener listener) { showDialogList(context.getString(customAlertTitle) + " " + customPostfix, items, tv, listener); } public void showTimePicker(int hours, int minutes, final TimePickerDialog.OnTimeSetListener onTimeSetListener) { final TimePicker timePicker = new TimePicker(context); timePicker.setIs24HourView(true); timePicker.setCurrentHour(hours); timePicker.setCurrentMinute(minutes); AlertDialogWrapper.Builder builder = createAlertBuilder(); builder.setTitle(context.getString(R.string.set_time)) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { onTimeSetListener.onTimeSet(timePicker, timePicker.getCurrentHour(), timePicker.getCurrentMinute()); } }).setView(timePicker).show(); } public void showDatePicker(final DatePickerDialog.OnDateSetListener onDateSetListener) { showDatePicker(-1, -1, -1, onDateSetListener); } public void showCalendarPicker(final MaterialDialog.ButtonCallback callback) { new MaterialDialog.Builder(context) .customView(R.layout.dialog_calendar, false) .positiveText("Ok") .negativeText("Отмена") .callback(callback).show(); } public void showDatePicker(final int year, final int month, final int day, long maxDate, final DatePickerDialog.OnDateSetListener onDateSetListener) { final DatePicker datePicker = new DatePicker(context); datePicker.updateDate(year, month - 1, day); datePicker.setCalendarViewShown(false); if (maxDate > 0) datePicker.setMaxDate(maxDate); final AlertDialogWrapper.Builder builder = createAlertBuilder(); builder.setTitle(context.getString(R.string.check_date)) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { onDateSetListener.onDateSet(datePicker, datePicker.getYear(), datePicker.getMonth() + 1, datePicker.getDayOfMonth()); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .setView(datePicker).show(); } public void showDatePicker(final int year, final int month, final int day, final DatePickerDialog.OnDateSetListener onDateSetListener) { showDatePicker(year, month, day, 0, onDateSetListener); } public void showBirthDatePicker(final int year, final int month, final int day, final DatePickerDialog.OnDateSetListener onDateSetListener) { showDatePicker(year, month, day, new Date().getTime(), onDateSetListener); } }
package com.github.aidanPB.text.ansi; public class SGRTest { private static final String CSI = "\033["; public static void main(String[] args) { for(TextAttributeModifier tam : TextAttributeModifier.values()){ if(tam == TextAttributeModifier.RESET || tam == TextAttributeModifier.DEUNDERLINE || tam == TextAttributeModifier.SET_BG_EXTENDED || tam == TextAttributeModifier.SET_FG_EXTENDED || tam == TextAttributeModifier.UNBLINKING || tam == TextAttributeModifier.UNBOLD || tam == TextAttributeModifier.UNCROSSED || tam == TextAttributeModifier.UNFRATALIC || tam == TextAttributeModifier.UNINVERSE || tam == TextAttributeModifier.UNOVERLINE || tam == TextAttributeModifier.NOSURROUND) continue; System.out.printf("This is a test of the %1$s%2$dm%3$s%1$s0m SGR code.%n", CSI, tam.getCodeNumber(), tam.toString()); } System.out.println(); System.out.println(CSI + "32m"+CSI+"41mRerunning some of the tests with green-on-red text."); System.out.printf("This is a test of the %1$s%2$dm%3$s%1$s32m%1$s41m SGR code.%n", CSI, TextAttributeModifier.SET_FG_BLACK.getCodeNumber(), TextAttributeModifier.SET_FG_BLACK.toString()); System.out.printf("This is a test of the %1$s%2$dm%3$s%1$s32m%1$s41m SGR code.%n", CSI, TextAttributeModifier.SET_FG_DEFAULT.getCodeNumber(), TextAttributeModifier.SET_FG_DEFAULT.toString()); System.out.printf("This is a test of the %1$s%2$dm%3$s%1$s32m%1$s41m SGR code.%n", CSI, TextAttributeModifier.SET_BG_BLACK.getCodeNumber(), TextAttributeModifier.SET_BG_BLACK.toString()); System.out.printf("This is a test of the %1$s%2$dm%3$s%1$s32m%1$s41m SGR code.%1$s0m%n", CSI, TextAttributeModifier.SET_BG_DEFAULT.getCodeNumber(), TextAttributeModifier.SET_BG_DEFAULT.toString()); System.out.println(); System.out.println("Test complete."); } }
package com.gmail.nossr50.party; import java.io.File; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import org.bukkit.OfflinePlayer; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.events.party.McMMOPartyChangeEvent; import com.gmail.nossr50.events.party.McMMOPartyChangeEvent.EventReason; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.player.UserManager; public final class PartyManager { private static String partiesFilePath = mcMMO.p.getDataFolder().getPath() + File.separator + "FlatFileStuff" + File.separator + "parties.yml"; private static List<Party> parties = new ArrayList<Party>(); private PartyManager() {} public static boolean checkPartyExistence(Player player, Party party, String partyName) { if (party == null) { return false; } player.sendMessage(LocaleLoader.getString("Commands.Party.AlreadyExists", partyName)); return true; } public static boolean changeOrJoinParty(McMMOPlayer mcMMOPlayer, Player player, Party oldParty, String newPartyName) { if (mcMMOPlayer.inParty()) { if (!handlePartyChangeEvent(player, oldParty.getName(), newPartyName, EventReason.CHANGED_PARTIES)) { return false; } removeFromParty(player, oldParty); } else if (!handlePartyChangeEvent(player, null, newPartyName, EventReason.JOINED_PARTY)) { return false; } return true; } /** * Check if two online players are in the same party. * * @param firstPlayer The first player * @param secondPlayer The second player * @return true if they are in the same party, false otherwise */ public static boolean inSameParty(Player firstPlayer, Player secondPlayer) { McMMOPlayer firstMcMMOPlayer = UserManager.getPlayer(firstPlayer); McMMOPlayer secondMcMMOPlayer = UserManager.getPlayer(secondPlayer); if (firstMcMMOPlayer == null || secondMcMMOPlayer == null) { return false; } Party firstParty = firstMcMMOPlayer.getParty(); Party secondParty = secondMcMMOPlayer.getParty(); if (firstParty == null || secondParty == null || firstParty != secondParty) { return false; } return true; } /** * Get the near party members. * * @param player The player to check * @param range The distance * @return the near party members */ public static List<Player> getNearMembers(Player player, Party party, double range) { List<Player> nearMembers = new ArrayList<Player>(); if (party != null) { for (Player member : party.getOnlineMembers()) { if (!player.getName().equalsIgnoreCase(member.getName()) && !member.isDead() && Misc.isNear(player.getLocation(), member.getLocation(), range)) { nearMembers.add(member); } } } return nearMembers; } /** * Get a list of all players in this player's party. * * @param player The player to check * @return all the players in the player's party */ public static LinkedHashSet<String> getAllMembers(Player player) { Party party = UserManager.getPlayer(player).getParty(); if (party == null) { return null; } return party.getMembers(); } /** * Get a list of all online players in this party. * * @param partyName The party to check * @return all online players in this party */ public static List<Player> getOnlineMembers(String partyName) { Party party = getParty(partyName); if (party == null) { return null; } return party.getOnlineMembers(); } /** * Get a list of all online players in this party. * * @param player The player to check * @return all online players in this party */ public static List<Player> getOnlineMembers(Player player) { Party party = getPlayerParty(player.getName()); if (party == null) { return null; } return getOnlineMembers(party.getName()); } /** * Retrieve a party by its name * * @param partyName The party name * @return the existing party, null otherwise */ public static Party getParty(String partyName) { for (Party party : parties) { if (party.getName().equals(partyName)) { return party; } } return null; } /** * Retrieve a party by a member name * * @param playerName The member name * @return the existing party, null otherwise */ public static Party getPlayerParty(String playerName) { for (Party party : parties) { for (String memberName : party.getMembers()) { if (memberName.equalsIgnoreCase(playerName)) { return party; } } } return null; } /** * Get a list of all current parties. * * @return the list of parties. */ public static List<Party> getParties() { return parties; } /** * Remove a player from a party. * * @param player The player to remove * @param party The party */ public static void removeFromParty(OfflinePlayer player, Party party) { LinkedHashSet<String> members = party.getMembers(); members.remove(player.getName()); if (members.isEmpty()) { parties.remove(party); } else { // If the leaving player was the party leader, appoint a new leader from the party members if (party.getLeader().equalsIgnoreCase(player.getName())) { String newLeader = members.iterator().next(); party.setLeader(newLeader); } informPartyMembersQuit(player, party); } McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player.getName()); if (mcMMOPlayer != null) { mcMMOPlayer.removeParty(); mcMMOPlayer.setItemShareModifier(10); } } /** * Disband a party. Kicks out all members and removes the party. * * @param party The party to remove */ public static void disbandParty(Party party) { LinkedHashSet<String> members = party.getMembers(); for (String memberName : members) { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(memberName); if (mcMMOPlayer != null) { mcMMOPlayer.removeParty(); mcMMOPlayer.setItemShareModifier(10); } } members.clear(); parties.remove(party); } /** * Create a new party * * @param player The player to add to the party * @param mcMMOPlayer The player to add to the party * @param partyName The party to add the player to * @param password The password for this party, null if there was no password */ public static void createParty(Player player, McMMOPlayer mcMMOPlayer, String partyName, String password) { partyName = partyName.replace(".", ""); Party party = getParty(partyName); if (party == null) { party = new Party(); party.setName(partyName); party.setLeader(player.getName()); party.setLocked(true); // Parties are now invite-only by default, can be set to open with /party unlock if (password != null) { party.setPassword(password); player.sendMessage(LocaleLoader.getString("Party.Password.Set", password)); } parties.add(party); } else { player.sendMessage(LocaleLoader.getString("Commands.Party.AlreadyExists")); return; } player.sendMessage(LocaleLoader.getString("Commands.Party.Create", party.getName())); addToParty(player, mcMMOPlayer, party); } /** * Add a player to a party. * * @param player The player to add to the party * @param mcMMOPlayer The player to add to the party * @param party The party to add the player to * @param password the password for this party, null if there was no password */ public static void joinParty(Player player, McMMOPlayer mcMMOPlayer, Party party, String password) { if (!checkPartyPassword(player, party, password)) { return; } if (mcMMOPlayer.getParty() == party) { return; } player.sendMessage(LocaleLoader.getString("Commands.Party.Join", party.getName())); addToParty(player, mcMMOPlayer, party); } /** * Check if a player can join a party * * @param player The player trying to join a party * @param party The party * @param password The password provided by the player * @return true if the player can join the party */ public static boolean checkPartyPassword(Player player, Party party, String password) { // Don't care about passwords if it isn't locked if (party.isLocked()) { String partyPassword = party.getPassword(); if (partyPassword != null) { if (password == null) { player.sendMessage(LocaleLoader.getString("Party.Password.None")); return false; } else if (!password.equals(partyPassword)) { player.sendMessage(LocaleLoader.getString("Party.Password.Incorrect")); return false; } } else { player.sendMessage(LocaleLoader.getString("Party.Locked")); return false; } } return true; } /** * Accept a party invitation * * @param Player The plaer to add to the party * @param mcMMOPlayer The player to add to the party */ public static void joinInvitedParty(Player player, McMMOPlayer mcMMOPlayer) { Party invite = mcMMOPlayer.getPartyInvite(); if (mcMMOPlayer.getParty() == invite) { return; } if (!parties.contains(invite)) { parties.add(invite); } player.sendMessage(LocaleLoader.getString("Commands.Invite.Accepted", invite.getName())); mcMMOPlayer.removePartyInvite(); addToParty(player, mcMMOPlayer, invite); } /** * Add a player to a party * * @param player The player to add to a party * @param mcMMOPlayer The player to add to the party * @param party The party */ public static void addToParty(OfflinePlayer player, McMMOPlayer mcMMOPlayer, Party party) { if (mcMMOPlayer.getParty() == party) { return; } informPartyMembersJoin(player, party); mcMMOPlayer.setParty(party); party.getMembers().add(player.getName()); } /** * Get the leader of a party. * * @param partyName The party name * @return the leader of the party */ public static String getPartyLeader(String partyName) { Party party = getParty(partyName); if (party == null) { return null; } return party.getLeader(); } /** * Set the leader of a party. * * @param playerName The name of the player to set as leader * @param party The party */ public static void setPartyLeader(String playerName, Party party) { String leaderName = party.getLeader(); for (Player member : party.getOnlineMembers()) { if (member.getName().equalsIgnoreCase(playerName)) { member.sendMessage(LocaleLoader.getString("Party.Owner.Player")); } else if (member.getName().equalsIgnoreCase(leaderName)) { member.sendMessage(LocaleLoader.getString("Party.Owner.NotLeader")); } else { member.sendMessage(LocaleLoader.getString("Party.Owner.New", playerName)); } } party.setLeader(playerName); } /** * Check if a player can invite others to his party. * * @param player The player to check * @param mcMMOPlayer The player to check * @return true if the player can invite */ public static boolean canInvite(Player player, Party party) { if (party.isLocked() && !party.getLeader().equalsIgnoreCase(player.getName())) { return false; } return true; } /** * Check if a string is a valid party name. * * @param partyName The party name to check * @return true if this is a valid party, false otherwise */ public static boolean isParty(String partyName) { for (Party party : parties) { if (party.getName().equals(partyName)) { return true; } } return false; } /** * Load party file. */ public static void loadParties() { File file = new File(partiesFilePath); if (!file.exists()) { return; } YamlConfiguration partiesFile = YamlConfiguration.loadConfiguration(file); for (String partyName : partiesFile.getConfigurationSection("").getKeys(false)) { Party party = new Party(); party.setName(partyName); party.setLeader(partiesFile.getString(partyName + ".Leader")); party.setPassword(partiesFile.getString(partyName + ".Password")); party.setLocked(partiesFile.getBoolean(partyName + ".Locked")); party.setXpShareMode(ShareHandler.ShareMode.getShareMode(partiesFile.getString(partyName + ".ExpShareMode", "NONE"))); party.setItemShareMode(ShareHandler.ShareMode.getShareMode(partiesFile.getString(partyName + ".ItemShareMode", "NONE"))); List<String> memberNames = partiesFile.getStringList(partyName + ".Members"); LinkedHashSet<String> members = party.getMembers(); for (String memberName : memberNames) { members.add(memberName); } parties.add(party); } } /** * Save party file. */ public static void saveParties() { File file = new File(partiesFilePath); if (file.exists()) { file.delete(); } YamlConfiguration partiesFile = new YamlConfiguration(); for (Party party : parties) { String partyName = party.getName(); partiesFile.set(partyName + ".Leader", party.getLeader()); partiesFile.set(partyName + ".Password", party.getPassword()); partiesFile.set(partyName + ".Locked", party.isLocked()); partiesFile.set(partyName + ".ExpShareMode", party.getXpShareMode().toString()); partiesFile.set(partyName + ".ItemShareMode", party.getItemShareMode().toString()); List<String> memberNames = new ArrayList<String>(); for (String member : party.getMembers()) { if (!memberNames.contains(member)) { memberNames.add(member); } } partiesFile.set(partyName + ".Members", memberNames); } try { partiesFile.save(new File(partiesFilePath)); } catch (Exception e) { e.printStackTrace(); } } /** * Handle party change event. * * @param player The player changing parties * @param oldPartyName The name of the old party * @param newPartyName The name of the new party * @param reason The reason for changing parties * @return true if the change event was successful, false otherwise */ public static boolean handlePartyChangeEvent(Player player, String oldPartyName, String newPartyName, EventReason reason) { McMMOPartyChangeEvent event = new McMMOPartyChangeEvent(player, oldPartyName, newPartyName, reason); mcMMO.p.getServer().getPluginManager().callEvent(event); return !event.isCancelled(); } /** * Notify party members when a player joins * * @param player The player that joins * @param party The concerned party */ private static void informPartyMembersJoin(OfflinePlayer player, Party party) { for (Player member : party.getOnlineMembers()) { if (!member.equals(player)) { member.sendMessage(LocaleLoader.getString("Party.InformedOnJoin", player.getName())); } } } /** * Notify party members when a party member quits. * * @param player The player that quits * @param party The concerned party */ private static void informPartyMembersQuit(OfflinePlayer player, Party party) { for (Player member : party.getOnlineMembers()) { if (!member.equals(player)) { member.sendMessage(LocaleLoader.getString("Party.InformedOnQuit", player.getName())); } } } }
package com.hubspot.jinjava.lib.fn; import static com.hubspot.jinjava.util.Logging.ENGINE_LOG; import java.time.Instant; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Objects; import org.apache.commons.lang3.BooleanUtils; import com.google.common.collect.Lists; import com.hubspot.jinjava.JinjavaConfig; import com.hubspot.jinjava.doc.annotations.JinjavaDoc; import com.hubspot.jinjava.doc.annotations.JinjavaParam; import com.hubspot.jinjava.doc.annotations.JinjavaSnippet; import com.hubspot.jinjava.interpret.InterpretException; import com.hubspot.jinjava.interpret.JinjavaInterpreter; import com.hubspot.jinjava.objects.date.PyishDate; import com.hubspot.jinjava.objects.date.StrftimeFormatter; import com.hubspot.jinjava.tree.Node; public class Functions { public static final int RANGE_LIMIT = 1000; @JinjavaDoc(value = "Only usable within blocks, will render the contents of the parent block by calling super.", snippets = { @JinjavaSnippet(desc = "This gives back the results of the parent block", code = "{% block sidebar %}\n" + " <h3>Table Of Contents</h3>\n\n" + " ...\n" + " {{ super() }}\n" + "{% endblock %}") }) public static String renderSuperBlock() { JinjavaInterpreter interpreter = JinjavaInterpreter.getCurrent(); StringBuilder result = new StringBuilder(); List<? extends Node> superBlock = interpreter.getContext().getSuperBlock(); if (superBlock != null) { for (Node n : superBlock) { result.append(n.render(interpreter)); } } return result.toString(); } public static List<Object> immutableListOf(Object... items) { return Collections.unmodifiableList(Lists.newArrayList(items)); } @JinjavaDoc(value = "formats a date to a string", params = { @JinjavaParam(value = "var", type = "date", defaultValue = "current time"), @JinjavaParam(value = "format", defaultValue = StrftimeFormatter.DEFAULT_DATE_FORMAT) }) public static String dateTimeFormat(Object var, String... format) { ZonedDateTime d = null; if (var == null) { d = ZonedDateTime.now(ZoneOffset.UTC); } else if (var instanceof Number) { d = ZonedDateTime.ofInstant(Instant.ofEpochMilli(((Number) var).longValue()), ZoneOffset.UTC); } else if (var instanceof PyishDate) { d = ((PyishDate) var).toDateTime(); } else if (var instanceof ZonedDateTime) { d = (ZonedDateTime) var; } else if (!ZonedDateTime.class.isAssignableFrom(var.getClass())) { throw new InterpretException("Input to datetimeformat function must be a date object, was: " + var.getClass()); } if (d == null) { return ""; } Locale locale = JinjavaInterpreter.getCurrentMaybe() .map(JinjavaInterpreter::getConfig) .map(JinjavaConfig::getLocale) .orElse(Locale.ENGLISH); if (format.length > 0) { return StrftimeFormatter.format(d, format[0], locale); } else { return StrftimeFormatter.format(d, locale); } } private static final int DEFAULT_TRUNCATE_LENGTH = 255; private static final String DEFAULT_END = "..."; @JinjavaDoc(value = "truncates a given string to a specified length", params = { @JinjavaParam("s"), @JinjavaParam(value = "length", type = "number", defaultValue = "255"), @JinjavaParam(value = "end", defaultValue = "...") }) public static Object truncate(Object var, Object... arg) { if (var instanceof String) { int length = DEFAULT_TRUNCATE_LENGTH; boolean killwords = false; String ends = DEFAULT_END; if (arg.length > 0) { try { length = Integer.parseInt(Objects.toString(arg[0])); } catch (Exception e) { ENGINE_LOG.warn("truncate(): error setting length for {}, using default {}", arg[0], DEFAULT_TRUNCATE_LENGTH); } } if (arg.length > 1) { try { killwords = BooleanUtils.toBoolean(Objects.toString(arg[1])); } catch (Exception e) { ENGINE_LOG.warn("truncate(); error setting killwords for {}", arg[1]); } } if (arg.length > 2) { ends = Objects.toString(arg[2]); } String string = (String) var; if (string.length() > length) { if (!killwords) { length = movePointerToJustBeforeLastWord(length, string); } return string.substring(0, length) + ends; } else { return string; } } return var; } public static int movePointerToJustBeforeLastWord(int pointer, String s) { while (pointer > 0 && pointer < s.length()) { if (Character.isWhitespace(s.charAt(--pointer))) { break; } } return pointer + 1; } @JinjavaDoc(value = "<p>Return a list containing an arithmetic progression of integers.</p>" + "<p>With one parameter, range will return a list from 0 up to (but not including) the value. " + " With two parameters, the range will start at the first value and increment by 1 up to (but not including) the second value. " + " The third parameter specifies the step increment.</p> <p>All values can be negative. Impossible ranges will return an empty list.</p>" + "<p>Ranges can generate a maximum of " + RANGE_LIMIT + " values.</p>", params = { @JinjavaParam(value = "start", type = "number", defaultValue = "0"), @JinjavaParam(value = "end", type = "number"), @JinjavaParam(value = "step", type = "number", defaultValue = "1")}) public static List<Integer> range(Object arg1, Object... args) { List<Integer> result = new ArrayList<>(); int start = 0; int end; int step = 1; switch (args.length) { case 0: end = Integer.parseInt(arg1.toString()); break; case 1: start = Integer.parseInt(arg1.toString()); end = Integer.parseInt(args[0].toString()); break; default: start = Integer.parseInt(arg1.toString()); end = Integer.parseInt(args[0].toString()); step = Integer.parseInt(args[1].toString()); } if (step == 0) { return result; } if (start < end) { if (step < 0) { return result; } for (int i = start; i < end; i += step) { if (result.size() >= RANGE_LIMIT) { break; } result.add(i); } } else { if (step > 0) { return result; } for (int i = start; i > end; i += step) { if (result.size() >= RANGE_LIMIT) { break; } result.add(i); } } return result; } }
package com.learning.ads.search; public class BinarySearch { public <T extends Comparable<T>> int search(T[] array, T element) { int first = 0, last = array.length - 1, position = -1; while (first <= last) { int mid = (first + last) / 2; int r = element.compareTo(array[mid]); if (r == 0) { position = mid; break; } if (r == -1) { last = mid - 1; } else if (r == 1) { first = mid + 1; } } return position; } }
import java.io.*; import java.util.*; import java.util.regex.*; import java.text.SimpleDateFormat; import javax.xml.bind.annotation.XmlNs; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; public class Main { public static final class VertexAttribute { public final int usage; public final int numComponents; public String alias; public VertexAttribute (int usage, int numComponents, String alias) { this.usage = usage; this.numComponents = numComponents; this.alias = alias; } } public enum FileType { obj, dae; } public static void main(String [] args) throws Exception { //init int i; int ii; String fileInPath = null; String fileOutPath = null; FileType fileType = FileType.obj; //args if(args.length <= 0) { System.out.println("error: No input file\nsee --help"); return; } for(i = 0; i < args.length; i++) { if(args[i].equals("-h") || args[i].equals("--help")) { System.out.println("help"); return; } else if(args[i].equals("-i") || args[i].equals("--input")) { fileInPath = args[i+1]; i++; } else if(args[i].equals("-o") || args[i].equals("--output")) { fileOutPath = args[i+1]; i++; } else if(args[i].equals("-t") || args[i].equals("--type")) { if(args[i+1].equalsIgnoreCase("obj")) fileType = FileType.obj; else if(args[i+1].equalsIgnoreCase("dae")) fileType = FileType.dae; i++; } else if(fileInPath == null) { fileInPath = args[i]; } else if(fileOutPath == null) { fileOutPath = args[i]; } } if(fileInPath == null) { System.out.println("error: No input file\nsee --help"); return; } FileInputStream fileIn; boolean flag; ObjectInputStream objectinputstream; float af[]; short aword0[]; short aword1[]; VertexAttribute avertexattribute[]; String _fld02CA; String _fld02CB; String _fld02CE[]; try { if(!new File(fileInPath).exists()) { System.out.println("error: File does not exist"); return; } fileIn = new FileInputStream(fileInPath); objectinputstream = new ObjectInputStream(fileIn); af = (float[])objectinputstream.readObject(); aword0 = (short[])objectinputstream.readObject(); aword1 = (short[])objectinputstream.readObject(); avertexattribute = new VertexAttribute[objectinputstream.readInt()]; } catch(IOException ei) { ei.printStackTrace(); return; } catch(ClassNotFoundException c) { System.out.println("Employee class not found"); c.printStackTrace(); return; } for(i = 0; i < avertexattribute.length; i++) { avertexattribute[i] = new VertexAttribute(objectinputstream.readInt(), objectinputstream.readInt(), objectinputstream.readUTF()); } flag = objectinputstream.readBoolean(); if(flag) { _fld02CA = objectinputstream.readUTF(); _fld02CB = objectinputstream.readUTF(); _fld02CE = (String[])objectinputstream.readObject(); } objectinputstream.close(); fileIn.close(); int vlen = 0; int vtlen = 0; int vnlen = 0; float [] v = null; float [] vt = null; float [] vn = null; short [] f = null; short [] l = null; //v/vt/vn for(i = 0; i < avertexattribute.length; i++) { if(avertexattribute[i].alias.equals("a_position")) { vlen = avertexattribute[i].numComponents; } if(avertexattribute[i].alias.equals("a_texCoord0")) { vtlen = avertexattribute[i].numComponents; } if(avertexattribute[i].alias.equals("a_normal")) { vnlen = avertexattribute[i].numComponents; } } v = new float[af.length / (vlen+vtlen+vnlen) * vlen]; vt = new float[af.length / (vlen+vtlen+vnlen) * vtlen]; vn = new float[af.length / (vlen+vtlen+vnlen) * vnlen]; f = aword0; l = aword1; for(i = 0; i < (af.length / (vlen+vtlen+vnlen)); i++) { for(ii = 0; ii < vlen; ii++) v[i*vlen + ii] = af[i * (vlen+vtlen+vnlen) + ii]; for(ii = 0; ii < vtlen; ii++) vt[i*vtlen + ii] = af[i * (vlen+vtlen+vnlen) + vlen + vnlen + ii]; for(ii = 0; ii < vnlen; ii++) vn[i*vnlen + ii] = af[i * (vlen+vtlen+vnlen) + vlen + ii]; } String fileOutText = ""; if(fileType == FileType.obj) //obj { fileOutText += "# Create by IngressModelExport" + "\n"; fileOutText += "# Develop by YJBeetle" + "\n"; fileOutText += "# Model name: " + fileInPath.replaceAll(".*[/\\\\]", "").replaceAll("\\..*", "") + "\n"; fileOutText += "# Created: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\n"; fileOutText += "\n"; fileOutText += "# Ingress obj info:" + "\n"; fileOutText += "# af.length = " + af.length + "\n"; // fileOutText += "# aword0.length = " + aword0.length + "\n"; // fileOutText += "# aword1.length = " + aword1.length + "\n"; // fileOutText += "# avertexattribute.length = " + avertexattribute.length + "\n"; for(i = 0; i < avertexattribute.length; i++) { fileOutText += "# avertexattribute[" + i + "].usage = " + avertexattribute[i].usage + "\n"; fileOutText += "# avertexattribute[" + i + "].numComponents = " + avertexattribute[i].numComponents + "\n"; fileOutText += "# avertexattribute[" + i + "].alias = " + avertexattribute[i].alias + "\n"; } fileOutText += "\n"; fileOutText += "# Model info:" + "\n"; fileOutText += "# Vertex count: "+ af.length / (vlen+vtlen+vnlen) + "\n"; fileOutText += "# Surface count: "+ aword0.length / 3 + "\n"; fileOutText += "# Line count: "+ aword1.length / 2 + "\n"; fileOutText += "\n"; fileOutText += "# Geometric vertices (v):" + "\n"; for(i = 0; i < v.length; i++) { if(i % vlen == 0) { fileOutText += "v"; } fileOutText += " " + v[i]; if((i+1) % vlen == 0) { fileOutText += "\n"; } } fileOutText += "\n"; fileOutText += "# Texture vertices (vt):" + "\n"; for(i = 0; i < vt.length; i++) { if(i % vtlen == 0) { fileOutText += "vt"; } fileOutText += " " + vt[i]; if((i+1) % vtlen == 0) { fileOutText += "\n"; } } fileOutText += "\n"; fileOutText += "# Vertex normals (vn):" + "\n"; for(i = 0; i < vn.length; i++) { if(i % vnlen == 0) { fileOutText += "vn"; } fileOutText += " " + vn[i]; if((i+1) % vnlen == 0) { fileOutText += "\n"; } } fileOutText += "\n"; fileOutText += "# Surface (f):" + "\n"; for(i = 0; i < f.length; i++) { if(i % 3 == 0) { fileOutText += "f"; } fileOutText += " " + (f[i]+1); if(vtlen > 0 || vnlen > 0) { fileOutText += "/"; if(vtlen > 0) { fileOutText += (f[i]+1); } if(vnlen > 0) { fileOutText += "/"; fileOutText += (f[i]+1); } } if((i+1) % 3 == 0) { fileOutText += "\n"; } } fileOutText += "\n"; fileOutText += "# Line (l):" + "\n"; for(i = 0; i < (l.length/2); i++) { fileOutText += "l " + (l[i*2]+1) + " " + (l[i*2+1]+1) + "\n"; } fileOutText += "\n"; } else if(fileType == FileType.dae) //dae { String tmpString; int [] tmpintArray; Document document = null; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.newDocument(); Element COLLADA = document.createElement("COLLADA"); document.appendChild(COLLADA); COLLADA.setAttribute("xmlns", "http: COLLADA.setAttribute("version", "1.4.1"); Element asset = document.createElement("asset"); COLLADA.appendChild(asset); Element contributor = document.createElement("contributor"); asset.appendChild(contributor); Element authoring_tool = document.createElement("authoring_tool"); contributor.appendChild(authoring_tool); authoring_tool.appendChild(document.createTextNode("IngressModelExport Develop by YJBeetle")); Element created = document.createElement("created"); asset.appendChild(created); created.appendChild(document.createTextNode(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(new Date()))); Element modified = document.createElement("modified"); asset.appendChild(modified); modified.appendChild(document.createTextNode(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(new Date()))); Element keywords = document.createElement("keywords"); asset.appendChild(keywords); keywords.appendChild(document.createTextNode("ingress " + fileInPath.replaceAll(".*[/\\\\]", "").replaceAll("\\..*", "") )); Element title = document.createElement("title"); asset.appendChild(title); title.appendChild(document.createTextNode(fileInPath.replaceAll(".*[/\\\\]", "").replaceAll("\\..*", ""))); Element unit = document.createElement("unit"); asset.appendChild(unit); unit.setAttribute("meter", "0.01"); unit.setAttribute("name", "centimeter"); Element up_axis = document.createElement("up_axis"); asset.appendChild(up_axis); up_axis.appendChild(document.createTextNode("Y_UP")); Element library_images = document.createElement("library_images"); COLLADA.appendChild(library_images); Element image = document.createElement("image"); library_images.appendChild(image); image.setAttribute("id", "genericModTexture_image"); Element init_from = document.createElement("init_from"); image.appendChild(init_from); init_from.appendChild(document.createTextNode("genericModTexture.png")); Element library_effects = document.createElement("library_effects"); COLLADA.appendChild(library_effects); Element effect = document.createElement("effect"); library_effects.appendChild(effect); effect.setAttribute("id", "genericModTexture_effect"); Element profile_COMMON = document.createElement("profile_COMMON"); effect.appendChild(profile_COMMON); Element newparam1 = document.createElement("newparam"); profile_COMMON.appendChild(newparam1); newparam1.setAttribute("sid", "genericModTexture_newparam1"); Element surface = document.createElement("surface"); newparam1.appendChild(surface); surface.setAttribute("type", "2D"); Element init_from2 = document.createElement("init_from"); surface.appendChild(init_from2); init_from2.appendChild(document.createTextNode("genericModTexture_image")); Element newparam2 = document.createElement("newparam"); profile_COMMON.appendChild(newparam2); newparam2.setAttribute("sid", "genericModTexture_newparam2"); Element sampler2D = document.createElement("sampler2D"); newparam2.appendChild(sampler2D); Element source2 = document.createElement("source"); sampler2D.appendChild(source2); source2.appendChild(document.createTextNode("genericModTexture_newparam1")); Element technique = document.createElement("technique"); profile_COMMON.appendChild(technique); technique.setAttribute("sid", "COMMON"); Element blinn = document.createElement("blinn"); technique.appendChild(blinn); Element diffuse = document.createElement("diffuse"); blinn.appendChild(diffuse); Element texture = document.createElement("texture"); diffuse.appendChild(texture); texture.setAttribute("texture", "genericModTexture_newparam2"); texture.setAttribute("texcoord", "UVSET0"); Element library_materials = document.createElement("library_materials"); COLLADA.appendChild(library_materials); Element material = document.createElement("material"); library_materials.appendChild(material); material.setAttribute("id", "genericModTexture"); material.setAttribute("name", "genericModTexture"); Element instance_effect = document.createElement("instance_effect"); material.appendChild(instance_effect); instance_effect.setAttribute("url", "#genericModTexture_effect"); Element library_geometries = document.createElement("library_geometries"); COLLADA.appendChild(library_geometries); Element geometry = document.createElement("geometry"); library_geometries.appendChild(geometry); geometry.setAttribute("id", "geometry"); Element mesh = document.createElement("mesh"); geometry.appendChild(mesh); if(vlen > 0) { Element source_v = document.createElement("source"); mesh.appendChild(source_v); source_v.setAttribute("id", "source_v"); Element float_array_v = document.createElement("float_array"); source_v.appendChild(float_array_v); float_array_v.setAttribute("id", "float_array_v"); float_array_v.setAttribute("count", String.valueOf(v.length)); float_array_v.appendChild(document.createTextNode(Arrays.toString(v).replaceAll("[\\,\\[\\]]", ""))); Element technique_common_v = document.createElement("technique_common"); source_v.appendChild(technique_common_v); Element accessor_v = document.createElement("accessor"); technique_common_v.appendChild(accessor_v); accessor_v.setAttribute("count", String.valueOf(v.length / vlen)); accessor_v.setAttribute("source", "#float_array_v"); accessor_v.setAttribute("stride", String.valueOf(vlen)); Element [] param_v = new Element[vlen]; for(i = 0; i < vlen; i++) { switch(i) { case 0: tmpString = "X"; break; case 1: tmpString = "Y"; break; case 2: tmpString = "Z"; break; case 3: tmpString = "W"; break; default: tmpString = String.valueOf(i); break; } param_v[i] = document.createElement("param"); accessor_v.appendChild(param_v[i]); param_v[i].setAttribute("name", tmpString); param_v[i].setAttribute("type", "float"); } } if(vnlen > 0) { Element source_vn = document.createElement("source"); mesh.appendChild(source_vn); source_vn.setAttribute("id", "source_vn"); Element float_array_vn = document.createElement("float_array"); source_vn.appendChild(float_array_vn); float_array_vn.setAttribute("id", "float_array_vn"); float_array_vn.setAttribute("count", String.valueOf(vn.length)); float_array_vn.appendChild(document.createTextNode(Arrays.toString(vn).replaceAll("[\\,\\[\\]]", ""))); Element technique_common_vn = document.createElement("technique_common"); source_vn.appendChild(technique_common_vn); Element accessor_vn = document.createElement("accessor"); technique_common_vn.appendChild(accessor_vn); accessor_vn.setAttribute("count", String.valueOf(vn.length / vnlen)); accessor_vn.setAttribute("source", "#float_array_vn"); accessor_vn.setAttribute("stride", String.valueOf(vnlen)); Element [] param_vn = new Element[vnlen]; for(i = 0; i < vnlen; i++) { switch(i) { case 0: tmpString = "X"; break; case 1: tmpString = "Y"; break; case 2: tmpString = "Z"; break; default: tmpString = String.valueOf(i); break; } param_vn[i] = document.createElement("param"); accessor_vn.appendChild(param_vn[i]); param_vn[i].setAttribute("name", tmpString); param_vn[i].setAttribute("type", "float"); } } if(vtlen > 0) { Element source_vt = document.createElement("source"); mesh.appendChild(source_vt); source_vt.setAttribute("id", "source_vt"); Element float_array_vt = document.createElement("float_array"); source_vt.appendChild(float_array_vt); float_array_vt.setAttribute("id", "float_array_vt"); float_array_vt.setAttribute("count", String.valueOf(vt.length)); float_array_vt.appendChild(document.createTextNode(Arrays.toString(vt).replaceAll("[\\,\\[\\]]", ""))); Element technique_common_vt = document.createElement("technique_common"); source_vt.appendChild(technique_common_vt); Element accessor_vt = document.createElement("accessor"); technique_common_vt.appendChild(accessor_vt); accessor_vt.setAttribute("count", String.valueOf(vt.length / vtlen)); accessor_vt.setAttribute("source", "#float_array_vt"); accessor_vt.setAttribute("stride", String.valueOf(vtlen)); Element [] param_vt = new Element[vtlen]; for(i = 0; i < vtlen; i++) { switch(i) { case 0: tmpString = "S"; break; case 1: tmpString = "T"; break; default: tmpString = String.valueOf(i); break; } param_vt[i] = document.createElement("param"); accessor_vt.appendChild(param_vt[i]); param_vt[i].setAttribute("name", tmpString); param_vt[i].setAttribute("type", "float"); } } Element vertices = document.createElement("vertices"); mesh.appendChild(vertices); vertices.setAttribute("id", "vertices"); Element vertices_input = document.createElement("input"); vertices.appendChild(vertices_input); vertices_input.setAttribute("semantic", "POSITION"); vertices_input.setAttribute("source", "#source_v"); Element polylist = document.createElement("polylist"); mesh.appendChild(polylist); polylist.setAttribute("count", String.valueOf(f.length / 3)); polylist.setAttribute("material", "Material1"); i = 0; if(vlen > 0) { Element polylist_input1 = document.createElement("input"); polylist.appendChild(polylist_input1); polylist_input1.setAttribute("offset", String.valueOf(i)); polylist_input1.setAttribute("semantic", "VERTEX"); polylist_input1.setAttribute("source", "#vertices"); i++; } if(vnlen > 0) { Element polylist_input2 = document.createElement("input"); polylist.appendChild(polylist_input2); polylist_input2.setAttribute("offset", String.valueOf(i)); polylist_input2.setAttribute("semantic", "NORMAL"); polylist_input2.setAttribute("source", "#source_vn"); i++; } if(vtlen > 0) { Element polylist_input3 = document.createElement("input"); polylist.appendChild(polylist_input3); polylist_input3.setAttribute("offset", String.valueOf(i)); polylist_input3.setAttribute("semantic", "TEXCOORD"); polylist_input3.setAttribute("source", "#source_vt"); polylist_input3.setAttribute("set", "0"); i++; } Element vcount = document.createElement("vcount"); polylist.appendChild(vcount); tmpintArray = new int[f.length / 3]; Arrays.fill(tmpintArray, 3); vcount.appendChild(document.createTextNode(Arrays.toString(tmpintArray).replaceAll("[\\,\\[\\]]", ""))); Element polylist_p = document.createElement("p"); polylist.appendChild(polylist_p); tmpString = ""; for(i = 0; i < f.length; i++) { if(vlen > 0) { tmpString += String.valueOf(f[i]) + " "; } if(vnlen > 0) { tmpString += String.valueOf(f[i]) + " "; } if(vtlen > 0) { tmpString += String.valueOf(f[i]); } if(i+1 < f.length) tmpString += " "; } polylist_p.appendChild(document.createTextNode(tmpString)); Element library_visual_scenes = document.createElement("library_visual_scenes"); COLLADA.appendChild(library_visual_scenes); Element visual_scene = document.createElement("visual_scene"); library_visual_scenes.appendChild(visual_scene); visual_scene.setAttribute("id", "visual_scene"); Element node = document.createElement("node"); visual_scene.appendChild(node); node.setAttribute("name", "Default"); node.setAttribute("id", "node"); Element translate = document.createElement("translate"); node.appendChild(translate); translate.setAttribute("sid", "translate"); translate.appendChild(document.createTextNode("0 0 -0")); Element rotate1 = document.createElement("rotate"); node.appendChild(rotate1); rotate1.setAttribute("sid", "rotateY"); rotate1.appendChild(document.createTextNode("0 1 0 -0")); Element rotate2 = document.createElement("rotate"); node.appendChild(rotate2); rotate2.setAttribute("sid", "rotateX"); rotate2.appendChild(document.createTextNode("1 0 0 0")); Element rotate3 = document.createElement("rotate"); node.appendChild(rotate3); rotate3.setAttribute("sid", "rotateZ"); rotate3.appendChild(document.createTextNode("0 0 1 -0")); Element scale = document.createElement("scale"); node.appendChild(scale); scale.setAttribute("sid", "scale"); scale.appendChild(document.createTextNode("1 1 1")); Element instance_geometry = document.createElement("instance_geometry"); node.appendChild(instance_geometry); instance_geometry.setAttribute("url", "#geometry"); Element bind_material = document.createElement("bind_material"); instance_geometry.appendChild(bind_material); Element technique_common = document.createElement("technique_common"); bind_material.appendChild(technique_common); Element instance_material = document.createElement("instance_material"); technique_common.appendChild(instance_material); instance_material.setAttribute("symbol", "Material1"); instance_material.setAttribute("target", "#genericModTexture"); Element bind_vertex_input = document.createElement("bind_vertex_input"); instance_material.appendChild(bind_vertex_input); bind_vertex_input.setAttribute("semantic", "UVSET0"); bind_vertex_input.setAttribute("input_semantic", "TEXCOORD"); bind_vertex_input.setAttribute("input_set", "0"); Element scene = document.createElement("scene"); COLLADA.appendChild(scene); Element instance_visual_scene = document.createElement("instance_visual_scene"); scene.appendChild(instance_visual_scene); instance_visual_scene.setAttribute("url", "#visual_scene"); Source source = new DOMSource(document); StringWriter stringWriter = new StringWriter(); Result result = new StreamResult(stringWriter); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(source, result); fileOutText += stringWriter.getBuffer().toString(); } if(fileOutPath == null) { System.out.println(fileOutText); } else { FileOutputStream fileOut = new FileOutputStream(fileOutPath); fileOut.write(fileOutText.getBytes()); fileOut.close(); } return; } }
import uucki.game.reversi.Board; import uucki.game.reversi.PossibleMoves; import uucki.algorithm.Algorithm; import uucki.algorithm.Minimax; import uucki.type.FieldValue; import uucki.type.Move; import uucki.type.Position; import uucki.heuristic.reversi.Basic; import uucki.graphics.reversi.Window; import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { System.out.println("Board position, is black top left? (y/n)"); boolean blackTopLeft = br.readLine().equals("y"); System.out.println("Am I starting? (y/n)"); boolean imStarting = br.readLine().equals("y"); System.out.println("Am I black? (y/n)"); FieldValue myColor = br.readLine().equals("y") ? FieldValue.BLACK : FieldValue.WHITE; Board board = initialBoard(blackTopLeft); game(board, imStarting, myColor); } catch (IOException e) { System.out.println("IO error, start again"); } } public static void game(Board board, boolean imStarting, FieldValue color) { FieldValue opponentColor = FieldValue.WHITE == color ? FieldValue.BLACK : FieldValue.WHITE; board.print(); Window window = new Window(); window.update(board); Algorithm minimax = new Minimax(); if(imStarting) { Move move = minimax.run(board, color); board = board.makeMove(move); window.update(board); } while(!board.isFinished()) { if(PossibleMoves.getValidPositions(board, opponentColor).size() > 0) { List<Position> validPositions = PossibleMoves.getValidPositions(board, opponentColor); Position newPosition = null; while(newPosition == null) { System.out.println("Make your move"); newPosition = window.getPosition(); if(!validPositions.contains(newPosition)) { newPosition = null; } } board = board.makeMove(new Move(newPosition, opponentColor)); window.update(board); } //Computer move Move move = minimax.run(board, color); board = board.makeMove(move); window.update(board); } } public static Board initialBoard(boolean blackTopLeft) { Board board = new Board(); if(blackTopLeft) { board = board.makeMove(new Move(3,3,FieldValue.BLACK)); board = board.makeMove(new Move(4,4,FieldValue.BLACK)); board = board.makeMove(new Move(3,4,FieldValue.WHITE)); board = board.makeMove(new Move(4,3,FieldValue.WHITE)); } else { board = board.makeMove(new Move(3,3,FieldValue.WHITE)); board = board.makeMove(new Move(4,4,FieldValue.WHITE)); board = board.makeMove(new Move(3,4,FieldValue.BLACK)); board = board.makeMove(new Move(4,3,FieldValue.BLACK)); } return board; } }
package com.oneliang.util.logging; import com.oneliang.Constant; import com.oneliang.util.common.StringUtil; import com.oneliang.util.common.TimeUtil; public class BaseLogger extends AbstractLogger { /** * constructor * * @param level */ public BaseLogger(Level level) { super(level); } /** * log * * @param level * @param message * @param throwable */ protected void log(Level level, Object message, Throwable throwable) { System.out.println(processMessage(level, message, throwable)); if (throwable != null) { throwable.printStackTrace(); } } /** * process message * * @param level * @param message * @param throwable * @return String */ protected String processMessage(Level level, Object message, Throwable throwable) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(Constant.Symbol.MIDDLE_BRACKET_LEFT); stringBuilder.append(TimeUtil.dateToString(TimeUtil.getTime(), TimeUtil.YEAR_MONTH_DAY_HOUR_MINUTE_SECOND_MILLISECOND)); stringBuilder.append(Constant.Symbol.MIDDLE_BRACKET_RIGHT); stringBuilder.append(StringUtil.SPACE); stringBuilder.append(Constant.Symbol.MIDDLE_BRACKET_LEFT); stringBuilder.append(level.name()); stringBuilder.append(Constant.Symbol.MIDDLE_BRACKET_RIGHT); stringBuilder.append(StringUtil.SPACE); stringBuilder.append(Constant.Symbol.MIDDLE_BRACKET_LEFT); stringBuilder.append(Thread.currentThread().getName()); stringBuilder.append(Constant.Symbol.MIDDLE_BRACKET_RIGHT); stringBuilder.append(StringUtil.SPACE); stringBuilder.append(Constant.Symbol.MIDDLE_BRACKET_LEFT); stringBuilder.append(message); stringBuilder.append(Constant.Symbol.MIDDLE_BRACKET_RIGHT); return stringBuilder.toString(); } }
package com.openlattice.postgres; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Iterator; import java.util.NoSuchElementException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Matthew Tamayo-Rios &lt;matthew@openlattice.com&gt; */ public class KeyIterator<T> implements Iterator<T> { private static final Logger logger = LoggerFactory.getLogger( KeyIterator.class ); private final ResultSet rs; private final CountdownConnectionCloser closer; private final SqlFunction<ResultSet, T> mapper; private boolean next; public KeyIterator( ResultSet rs, CountdownConnectionCloser closer, SqlFunction<ResultSet, T> mapper ) { this.closer = closer; this.rs = rs; this.mapper = mapper; try { next = rs.next(); countDownIfExhausted(); } catch ( SQLException e ) { logger.error( "Unable to execute sql for load all keys for data map store" ); throw new IllegalStateException( "Unable to execute sql statement", e ); } } @Override public boolean hasNext() { return next; } @Override public T next() { T key; try { if ( next ) { key = mapper.apply( rs ); } else { throw new NoSuchElementException( "No more elements available in iterator" ); } next = rs.next(); } catch ( SQLException e ) { logger.error( "Unable to retrieve next result from result set." ); next = false; throw new IllegalStateException( "Unable to retrieve next result from result set.", e ); } finally { countDownIfExhausted(); } return key; } public void countDownIfExhausted() { if ( !next ) { closer.countDown(); } } }
package com.sixtyfour.compression; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Locale; import com.sixtyfour.Assembler; import com.sixtyfour.Loader; import com.sixtyfour.config.CompilerConfig; import com.sixtyfour.system.FileWriter; import com.sixtyfour.system.Program; import com.sixtyfour.system.ProgramPart; /** * A simple compressor that can compress and uncompress byte[]-arrays based on a * simple and most likely inefficient sliding window pattern matching algorithm * that I came up with while being half asleep. It uses a pattern based * approach, no huffman encoding. That's why it's less efficient but should * decompress rather quickly. * * @author EgonOlsen * */ public class Compressor { private static final boolean FAST = true; private static final int MAX_WINDOW_SIZE_1 = 32; private static final int MAX_WINDOW_SIZE_2 = 128; private static final int MIN_WINDOW_SIZE = 12; private static final int CHUNK_SIZE = 32768; public static void main(String[] args) throws Exception { testCompressor("E:\\src\\workspace2018\\Adventure\\build\\++xam.prg", "C:\\Users\\EgonOlsen\\Desktop\\++xam_c.prg", -1); testCompressor("E:\\src\\workspace2018\\Adventure\\build\\++brotquest.prg", "C:\\Users\\EgonOlsen\\Desktop\\++brotquest_c.prg", -1); testCompressor("E:\\src\\workspace2018\\basicv2\\compiled\\++affine.prg", "C:\\Users\\EgonOlsen\\Desktop\\++affine_c.prg", -1); testCompressor("E:\\src\\workspace2018\\basicv2\\compiled\\+xtris2.prg", "C:\\Users\\EgonOlsen\\Desktop\\++xtris2_c.prg", -1); testCompressor("E:\\src\\workspace2018\\basicv2\\compiled\\+19 - StarDuel.prg", "C:\\Users\\EgonOlsen\\Desktop\\++StarDuel_c.prg", -1); testCompressor("E:\\src\\workspace2018\\basicv2\\compiled\\+30 - Invaders_15000.prg", "C:\\Users\\EgonOlsen\\Desktop\\++Invaders_c.prg", 15000); } private static void testCompressor(String fileName, String resultFile, int startAddr) throws Exception { byte[] bytes = loadProgram(fileName); Program prg = compressAndLinkNative(bytes, startAddr); if (prg != null) { FileWriter.writeAsPrg(prg, resultFile, false); } } /** * Compresses a given byte array and returns the comressed array or null, if no * compression has been performed. * * @param dump the byte array to compress * @param windowSize the size of the sliding window * @param watchSize if true, no compression will be performed if the result * will actually increase in size * @return the compressed array or null */ public static byte[] compress(byte[] dump, int windowSize, boolean watchSize) { long time = System.currentTimeMillis(); int minSize = MIN_WINDOW_SIZE; int len = dump.length; if (len > 65536) { throw new RuntimeException("This compressor can't compress anything larger than 64KB!"); } byte[] window = new byte[windowSize]; fillWindow(dump, window, 0); List<Part> parts = findMatches(dump, windowSize, minSize, len, window, FAST); byte[] bos = compress(parts, dump); if (bos.length >= len && watchSize) { log("No further compression possible!"); return null; } log("Binary compressed from " + len + " to " + bos.length + " bytes in " + (System.currentTimeMillis() - time) + "ms"); DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ENGLISH); DecimalFormat decFor = new DecimalFormat("###.##", symbols); log("Bytes saved: " + (len - bos.length)); log("Compression ratio: 1:" + decFor.format(((float) len / bos.length))); return bos; } /** * Decompresses the compressed data * * @param bytes * @return */ public static byte[] decompress(byte[] bytes) { long time = System.currentTimeMillis(); int clen = bytes.length; int data = readLowHigh(bytes, 0); int compLen = readLowHigh(bytes, 2); int ucLen = readLowHigh(bytes, 4); int headerOffset = 6; int dataPos = headerOffset; byte[] res = new byte[65536]; int pos = 0; for (int i = data; i < clen;) { int start = readLowHigh(bytes, i); int target = 0; i += 2; do { int len = bytes[i] & 0xFF; i++; target = 0; if (len != 0) { target = readLowHigh(bytes, i); int copyLen = target - pos; if (copyLen > 0) { System.arraycopy(bytes, dataPos, res, pos, copyLen); dataPos += copyLen; pos = target; } System.arraycopy(res, start, res, target, len); pos += len; i += 2; } else { i++; } } while (target > 0); } if (dataPos < data) { int len = data - dataPos; System.arraycopy(bytes, dataPos, res, pos, len); pos += len; } if (pos != ucLen) { throw new RuntimeException("Failed to decompress, size mismatch: " + pos + "/" + ucLen); } log("Decompressed from " + compLen + " to " + ucLen + " bytes in " + (System.currentTimeMillis() - time) + "ms!"); return Arrays.copyOf(res, pos); } /** * Decompresses the compressed data but unlike decompress(), it does that in one * block of 64K memory just like the real machine would have to do it. * * @param bytes the compressed data * @return the uncompressed data */ public static byte[] decompressInMemory(byte[] bytes) { long time = System.currentTimeMillis(); int data = readLowHigh(bytes, 0); int compLen = readLowHigh(bytes, 2); int ucLen = readLowHigh(bytes, 4); int memStart = 2049; int memEnd = 53248; int headerOffset = 6; int byteCount = 0; int totalLen = compLen - headerOffset; try { byte[] res = new byte[65536]; // Copy into memory just like it would be located on a real machine... System.arraycopy(bytes, headerOffset, res, memStart, totalLen); // Copy compressed data to the end of memory... int dataPos = memEnd - totalLen; data -= headerOffset; int compPos = dataPos + data; System.arraycopy(res, memStart, res, dataPos, totalLen); int pos = memStart; for (int i = compPos; i < memEnd;) { int start = readLowHigh(res, i) + memStart; int target = 0; i += 2; do { int len = res[i] & 0xFF; i++; target = 0; if (len != 0) { target = readLowHigh(res, i) + memStart; int copyLen = target - pos; if (copyLen != 0) { // Copy uncompressed data back down into memory... byteCount += moveData(res, dataPos, pos, copyLen); dataPos += copyLen; pos = target; } byteCount += moveData(res, start, target, len); pos += len; i += 2; } else { i++; } } while (target != 0); } int left = compPos - dataPos; if (left > 0) { byteCount += moveData(res, dataPos, pos, left); pos += left; } int newLen = pos - memStart; if (newLen != ucLen) { return null; } log("Decompressed from " + compLen + " to " + ucLen + " bytes in " + (System.currentTimeMillis() - time) + "ms! (" + byteCount + " bytes moved)"); return Arrays.copyOfRange(res, memStart, memStart + ucLen); } catch (ArrayIndexOutOfBoundsException e) { return null; } } /** * Compress a compiled program and link the decompressor onto it. * * @param bytes the program * @param startAddr the start address of the program. If given, the decompressed * program will be copied to that memory address and started * directly. If not given, the program will reside on the start * of BASIC memory and started with RUN. * @return the executable, compressed program or null, if no compression was * possible */ public static Program compressAndLinkNative(byte[] bytes, int startAddr) { log("Trying to find best compression settings..."); byte[] compressedBytes = compress(bytes, MAX_WINDOW_SIZE_1, startAddr == -1); byte[] compressedBytes2 = compress(bytes, MAX_WINDOW_SIZE_2, startAddr == -1); if (compressedBytes == null) { compressedBytes = compressedBytes2; } else if (compressedBytes2 == null) { compressedBytes2 = compressedBytes; } if (compressedBytes == null) { return null; } if (compressedBytes2.length < compressedBytes.length) { compressedBytes = compressedBytes2; log("Setting 2 used!"); } else { log("Setting 1 used!"); } byte[] uncompressed = decompressInMemory(compressedBytes); if (uncompressed == null || !Arrays.equals(uncompressed, bytes)) { log("Uncompressed data and data table overlap, no compression performed!"); return null; } Program prg = compileHeader(startAddr); ProgramPart first = prg.getParts().get(0); ProgramPart pp = new ProgramPart(); pp.setBytes(convert(compressedBytes)); pp.setAddress(first.getEndAddress()); pp.setEndAddress(pp.getAddress() + pp.getBytes().length); prg.addPart(pp); int size = pp.getEndAddress() - first.getAddress(); if (size >= bytes.length) { log("No further compression possible!"); if (startAddr == -1) { return null; } } return prg; } /** * Loads a file into a byte array. * * @param fileName * @return the file in a byte array */ public static byte[] loadProgram(String fileName) { log("Compressing " + fileName); byte[] bytes = Loader.loadBlob(fileName); // Remove the prg header in this case... bytes = Arrays.copyOfRange(bytes, 2, bytes.length); return bytes; } private static Program compileHeader(int startAddr) { log("Assembling decompressor..."); String[] decrunchCode = Loader.loadProgram(Compressor.class.getResourceAsStream("/compressor/decruncher.asm")); if (startAddr > 0) { // set SYSADDR flag/value if needed. Otherwise, the decruncher will just call // RUN List<String> code = new ArrayList<>(Arrays.asList(decrunchCode)); code.add(1, "SYSADDR=" + startAddr); decrunchCode = code.toArray(new String[code.size()]); } Assembler assy = new Assembler(decrunchCode); assy.compile(new CompilerConfig()); ProgramPart prg = assy.getProgram().getParts().get(0); log("Assembling decompression header..."); String[] headerCode = Loader.loadProgram(Compressor.class.getResourceAsStream("/compressor/header.asm")); List<String> code = new ArrayList<>(Arrays.asList(headerCode)); List<String> res = new ArrayList<>(); for (int i = 0; i < code.size(); i++) { String line = code.get(i); if (line.contains("{code}")) { int[] bytes = prg.getBytes(); int cnt = 0; String nl = ".byte"; for (int p = 0; p < bytes.length; p++) { nl += " $" + Integer.toHexString(bytes[p] & 0xff); cnt++; if (cnt == 16) { res.add(nl); nl = ".byte"; cnt = 0; } } if (nl.length() > 5) { res.add(nl); } } else { res.add(line); } } // res.forEach(p -> System.out.println(p)); assy = new Assembler(res.toArray(new String[res.size()])); assy.compile(new CompilerConfig()); return assy.getProgram(); } private static int moveData(byte[] res, int dataPos, int pos, int dataLen) { System.arraycopy(res, dataPos, res, pos, dataLen); return dataLen; } private static byte[] compress(List<Part> parts, byte[] dump) { ByteArrayOutputStream footer = new ByteArrayOutputStream(); ByteArrayOutputStream data = new ByteArrayOutputStream(); int pos = 0; int lastStart = -1; for (Part part : parts) { int start = part.sourceAddress; int target = part.targetAddress; if (target > pos) { data.write(dump, pos, target - pos); pos = target; } pos += part.size; if (start != lastStart) { if (lastStart != -1) { writeEndFlag(footer); } writeLowHigh(footer, start); } lastStart = start; footer.write(part.size); writeLowHigh(footer, part.targetAddress); } data.write(dump, pos, dump.length - pos); writeEndFlag(footer); ByteArrayOutputStream res = new ByteArrayOutputStream(); int dataLen = data.size() + 6; writeLowHigh(res, dataLen); writeLowHigh(res, dataLen + footer.size()); writeLowHigh(res, dump.length); try { res.write(data.toByteArray()); res.write(footer.toByteArray()); } catch (IOException e) { } return res.toByteArray(); } private static void writeEndFlag(ByteArrayOutputStream header) { header.write(0); header.write(0); } private static int readLowHigh(byte[] bytes, int pos) { return (bytes[pos] & 0xFF) + ((bytes[pos + 1] & 0xFF) << 8); } private static void writeLowHigh(ByteArrayOutputStream header, int start) { header.write((start & 0xFF)); header.write((start >> 8)); } /** * This is O(n*n) and therefore quite inefficient...anyway, it will do for * now... * * @param dump * @param windowSize * @param minSize * @param len * @param windowPos * @param window * @param fastMode Less compression, but a lot faster. * @return */ private static List<Part> findMatches(byte[] dump, int windowSize, int minSize, int len, byte[] window, boolean fastMode) { int curSize = windowSize; int largest = 0; int windowPos = 0; List<Part> parts = new ArrayList<>(); byte[] covered = new byte[len]; int chunkSize = CHUNK_SIZE; for (int lenPart = Math.min(len, chunkSize); lenPart <= len;) { do { for (int i = windowPos + curSize; i < lenPart - curSize; i++) { if (covered[i] > 0) { continue; } boolean match = true; for (int p = 0; p < curSize; p++) { if (covered[i + p] != 0) { match = false; break; } if (dump[i + p] != window[p]) { match = false; if (p > largest) { largest = p; } break; } } if (match) { for (int h = i; h < i + curSize; h++) { covered[h] = 1; } Part part = new Part(windowPos, i, curSize); parts.add(part); i += curSize - 1; } } if (largest >= minSize) { curSize = largest; largest = 0; } else { if (fastMode) { windowPos += Math.max(largest >> 1, 1); if (windowPos + windowSize >= lenPart) { windowPos -= (windowPos + windowSize - lenPart); } } else { windowPos++; } curSize = windowSize; largest = 0; fillWindow(dump, window, windowPos); } } while (windowPos + curSize < lenPart); windowPos = lenPart - curSize; if (lenPart < len && lenPart + chunkSize > len) { lenPart = len; } else { lenPart += chunkSize; } } Collections.sort(parts, new Comparator<Part>() { @Override public int compare(Part p1, Part p2) { return p1.targetAddress - p2.targetAddress; } }); // parts.forEach(p -> System.out.println(p)); // log("Iterations taken: " + cnt); return parts; } private static void fillWindow(byte[] dump, byte[] window, int pos) { System.arraycopy(dump, pos, window, 0, window.length); } private static void log(String txt) { System.out.println(txt); } private static int[] convert(byte[] bytes) { int[] res = new int[bytes.length]; for (int i = 0; i < bytes.length; i++) { res[i] = bytes[i] & 0xff; } return res; } private static class Part { Part(int source, int target, int size) { this.sourceAddress = source; this.targetAddress = target; this.size = size; } int sourceAddress; int targetAddress; int size; @Override public String toString() { return "block@ " + sourceAddress + "/" + targetAddress + "/" + size; } } }
package com.wimbli.WorldBorder.cmd; import java.util.List; import org.bukkit.command.*; import org.bukkit.entity.Player; import com.wimbli.WorldBorder.*; public class CmdRadius extends WBCmd { public CmdRadius() { name = permission = "radius"; hasWorldNameInput = true; minParams = 1; maxParams = 2; addCmdExample(nameEmphasizedW() + "<radiusX> [radiusZ] - change radius."); helpText = "Using this command you can adjust the radius of an existing border. If [radiusZ] is not " + "specified, the radiusX value will be used for both."; } @Override public void execute(CommandSender sender, Player player, List<String> params, String worldName) { if (worldName == null) worldName = player.getWorld().getName(); BorderData border = Config.Border(worldName); if (border == null) { sendErrorAndHelp(sender, "This world (\"" + worldName + "\") must first have a border set normally."); return; } double x = border.getX(); double z = border.getZ(); int radiusX; int radiusZ; try { if (params.get(0).startsWith('+')){ // Add to the current radius radiusX = Config.getBorder(worldName).getRadiusX(); radiusX += Integer.parseInt(params.get(0).substring(1)); }else if(params.get(0).startsWith('-')){ // Subtract from the current radius radiusX = Config.getBorder(worldName).getRadiusX(); radiusX -= Integer.parseInt(params.get(0).substring(1)); }else{ radiusX = Integer.parseInt(params.get(0)); } if (params.size() == 2) if (params.get(0).startsWith('+')){ // Add to the current radius radiusZ = Config.getBorder(worldName).getRadiusZ(); radiusZ += Integer.parseInt(params.get(1).substring(1)); }else if(params.get(0).startsWith('-')){ // Subtract from the current radius radiusZ = Config.getBorder(worldName).getRadiusZ(); radiusZ -= Integer.parseInt(params.get(1).substring(1)); }else{ radiusZ = Integer.parseInt(params.get(1)); } else radiusZ = radiusX; } catch(NumberFormatException ex) { sendErrorAndHelp(sender, "The radius value(s) must be integers."); return; } Config.setBorder(worldName, radiusX, radiusZ, x, z); if (player != null) sender.sendMessage("Radius has been set. " + Config.BorderDescription(worldName)); } }
package cz.janys.app.person; import cz.janys.app.AbstractController; import cz.janys.app.person.converter.PersonPtoToDtoConverter; import cz.janys.app.person.converter.PersonDtoToPtoConverter; import cz.janys.app.person.pto.PersonPto; import cz.janys.iface.dto.PersonDto; import cz.janys.iface.service.PersonService; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.validation.Valid; import static cz.janys.app.person.PersonConstants.*; /** * @author Martin Janys */ @Controller @RequestMapping("/person") public class PersonController extends AbstractController { private static final Logger LOG = Logger.getLogger(PersonController.class); @Autowired private PersonService service; @Autowired private PersonPtoToDtoConverter ptoToDto; @Autowired private PersonDtoToPtoConverter dtoToPto; @RequestMapping public String defaultView( Model model, ServletRequest request, ServletResponse response) { model.addAttribute(ATTR_ITEMS, service.findAllPersons()); return VIEW_MAIN; } @RequestMapping(PERSON_DETAIL_PAGE) public String detail( @PathVariable(PARAM_ID) long id, Model model, ServletRequest request, ServletResponse response) { model.addAttribute(ATTR_PERSON_DTO, service.findPersonById(id)); return VIEW_DETAIL; } @RequestMapping(PERSON_CREATE_PAGE) public String create( Model model, ServletRequest request, ServletResponse response) { if (!model.containsAttribute(ATTR_PERSON_PTO)) { model.addAttribute(ATTR_PERSON_PTO, new PersonPto()); } return VIEW_CREATE_FORM; } @RequestMapping(PERSON_FORM_EDIT_PAGE) public String editForm( @PathVariable(PARAM_ID) Long id, Model model, ServletRequest request, ServletResponse response) { if (!model.containsAttribute(ATTR_PERSON_PTO)) { PersonDto s = service.findPersonById(id); PersonPto pto = dtoToPto.convert(s); model.addAttribute(ATTR_PERSON_PTO, pto); } return VIEW_EDIT_FORM; } @RequestMapping(value = ACTION_CREATE, method = RequestMethod.POST) public String createPerson( @Valid @ModelAttribute(ATTR_PERSON_PTO) PersonPto pto, BindingResult result, ServletRequest request, ServletResponse response, Model model, RedirectAttributes redirectAttrs) { if (!result.hasErrors()) { PersonDto dto = ptoToDto.convert(pto); if (dto.getId() == null) { dto = service.createPerson(dto); addSuccessMessage(model, "msg-person-saved"); } else { dto = service.updatePerson(dto); addSuccessMessage(model, "msg-person-created"); } redirectAttrs.addAttribute(PARAM_ID, dto.getId().toString()); return redirect(PERSON_CONTEXT_PATH + PERSON_DETAIL_PAGE); } else { addErrorMessage(model, "msg-common-err-form-contains-errors"); return VIEW_CREATE_FORM; } } @RequestMapping(value = ACTION_UPDATE, method = RequestMethod.POST) public String savePerson( @Valid @ModelAttribute(ATTR_PERSON_PTO) PersonPto pto, BindingResult result, ServletRequest request, ServletResponse response, Model model, RedirectAttributes redirectAttrs) { if (!result.hasErrors()) { PersonDto dto = service.findPersonById(pto.getId()); PersonDto updatedDto = ptoToDto.convert(pto); updatedDto.setId(dto.getId()); service.updatePerson(dto); redirectAttrs.addAttribute(PARAM_ID, String.valueOf(dto.getId())); return redirect(PERSON_DETAIL_PAGE); } else { addErrorMessage(model, "msg-common-err-form-contains-errors"); redirectAttrs.addAttribute(PARAM_ID, pto.getId().toString()); return redirect(PERSON_FORM_EDIT_PAGE); } } @RequestMapping(value = ACTION_DELETE, method = RequestMethod.POST) public String deletePerson( @RequestParam(PARAM_ID) Long id, ServletRequest request, ServletResponse response, Model model) { PersonDto dto = service.findPersonById(id); service.deletePersonById(id); addSuccessMessage(model, "msg-hello-person-deleted", dto.getName()); return redirect(PERSON_CONTEXT_PATH); } }
package cz.jcu.prf.uai.javamugs.logic; import sun.reflect.generics.reflectiveObjects.NotImplementedException; public class Parser { public Parser() { // TODO Auto-generated constructor stub } public PressChart parseFile(String fileName, double timeOffset) { throw new NotImplementedException(); } }
package fgis.server.services; import fgis.server.entity.fgis.Resource; import fgis.server.entity.fgis.ResourceTrack; import fgis.server.entity.fgis.Resource_; import fgis.server.entity.fgis.dao.ResourceRepository; import fgis.server.entity.fgis.dao.ResourceTrackRepository; import fgis.server.support.FieldFilter; import java.io.StringWriter; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.annotation.Nullable; import javax.ejb.ConcurrencyManagement; import javax.ejb.ConcurrencyManagementType; import javax.ejb.EJB; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.json.stream.JsonGenerator; import javax.json.stream.JsonGeneratorFactory; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.ParameterExpression; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.ws.rs.Consumes; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import org.geolatte.geom.DimensionalFlag; import org.geolatte.geom.Geometry; import org.geolatte.geom.PointSequenceBuilder; import org.geolatte.geom.PointSequenceBuilders; import org.geolatte.geom.Polygon; import org.geolatte.geom.crs.CrsId; import org.glassfish.json.JsonGeneratorFactoryImpl; @SuppressWarnings( { "UnusedDeclaration", "JavaDoc" } ) @TransactionAttribute( TransactionAttributeType.REQUIRED ) @Startup @Singleton @ConcurrencyManagement( ConcurrencyManagementType.BEAN ) @Path( "/resource" ) @Produces( { MediaType.APPLICATION_JSON } ) @Consumes( { MediaType.APPLICATION_JSON } ) public class ResourceService { @PersistenceContext( unitName = "FGIS" ) private EntityManager _em; @EJB private ResourceRepository _resourceService; @EJB private ResourceTrackRepository _resourceTrackService; @GET @Produces( { MediaType.APPLICATION_JSON } ) public String getResources( @QueryParam( "types" ) @Nullable final String types, @QueryParam( "fields" ) @Nullable final String fields, @QueryParam( "bbox" ) @Nullable final String bbox, @QueryParam( "offset" ) @DefaultValue( "0" ) final int offset, @QueryParam( "limit" ) @DefaultValue( "50" ) final int limit ) throws ParseException { final FieldFilter filter = FieldFilter.parse( fields ); final CriteriaBuilder b = _em.getCriteriaBuilder(); final CriteriaQuery<Resource> query = b.createQuery( Resource.class ); final Root<Resource> entity = query.from( Resource.class ); query.select( entity ); final ArrayList<Predicate> predicates = new ArrayList<Predicate>(); final Map<String, Object> params = new HashMap<String, Object>(); if ( null != bbox ) { final Polygon extents = parseBBox( bbox ); final ParameterExpression<String> extent = b.parameter( String.class, "Extent" ); predicates.add( b.isTrue( b.function( "ST_Intersects", Boolean.class, b.function( "ST_GeomFromText", Geometry.class, extent ), entity.get( Resource_.Location ) ) ) ); params.put( "Extent", extents.asText() ); } if ( null != types ) { predicates.add( entity.get( Resource_.Type ).in( (Object[]) types.split( "," ) ) ); } query.where( b.and( predicates.toArray( new Predicate[ predicates.size() ] ) ) ); final TypedQuery<Resource> typedQuery = _em.createQuery( query ); typedQuery.setFirstResult( offset ); typedQuery.setMaxResults( limit ); for ( final Entry<String, Object> entry : params.entrySet() ) { typedQuery.setParameter( entry.getKey(), entry.getValue() ); } final List<Resource> resources = typedQuery.getResultList(); final ArrayList<ResourceEntry> entries = new ArrayList<>( resources.size() ); for ( final Resource resource : resources ) { final List<ResourceTrack> tracks = getResourceTracks( resource.getID() ); entries.add( new ResourceEntry( resource, tracks ) ); } return toGeoJson( filter, entries ); } private Polygon parseBBox( final String bbox ) throws ParseException { final String[] points = bbox.split( "," ); if ( 4 != points.length ) { throw new ParseException( "Unable to split 4 points", 0 ); } final double x1 = Double.parseDouble( points[ 0 ] ); final double y1 = Double.parseDouble( points[ 1 ] ); final double x2 = Double.parseDouble( points[ 2 ] ); final double y2 = Double.parseDouble( points[ 3 ] ); final PointSequenceBuilder builder = PointSequenceBuilders.variableSized( DimensionalFlag.d2D, CrsId.UNDEFINED ); builder.add( x1, y1 ); builder.add( x2, y1 ); builder.add( x2, y2 ); builder.add( x1, y2 ); builder.add( x1, y1 ); return new Polygon( builder.toPointSequence() ); } @GET @Path( "/{id}" ) @Produces( { MediaType.APPLICATION_JSON } ) public String getResource( @PathParam( "id" ) final int resourceID, @QueryParam( "fields" ) @Nullable final String fields ) throws ParseException { final FieldFilter filter = FieldFilter.parse( fields ); final Resource resource = _resourceService.findByID( resourceID ); if ( null == resource ) { throw new WebApplicationException( ResponseUtil.entityNotFoundResponse() ); } final List<ResourceTrack> tracks = getResourceTracks( resourceID ); return toGeoJson( filter, new ResourceEntry( resource, tracks ) ); } private List<ResourceTrack> getResourceTracks( final int resourceID ) { final Calendar calendar = Calendar.getInstance(); calendar.roll( Calendar.MINUTE, -1 ); return _resourceTrackService.findAllByResourceSince( resourceID, calendar.getTime() ); } private String toGeoJson( final FieldFilter filter, final ResourceEntry resource ) { final StringWriter writer = new StringWriter(); final JsonGenerator g = newGenerator( writer ); writeResource( g, filter, resource ); g.close(); return writer.toString(); } private String toGeoJson( final FieldFilter filter, final List<ResourceEntry> entries ) { final StringWriter writer = new StringWriter(); final JsonGenerator g = newGenerator( writer ); g.writeStartArray(); for ( final ResourceEntry entry : entries ) { writeResource( g, filter, entry ); } g.writeEnd(); g.close(); return writer.toString(); } private JsonGenerator newGenerator( final StringWriter writer ) { final JsonGeneratorFactory factory = new JsonGeneratorFactoryImpl(); return factory.createGenerator( writer ); } private void writeResource( final JsonGenerator g, final FieldFilter filter, final ResourceEntry entry ) { final Resource resource = entry.getResource(); final List<ResourceTrack> tracks = entry.getTracks(); g.writeStartObject(); if ( filter.allow( "id" ) ) { g.write( "id", resource.getID() ); } if ( filter.allow( "title" ) ) { g.write( "title", resource.getName() ); } if ( filter.allow( "description" ) ) { g.write( "description", resource.getName() ); } if ( filter.allow( "geo" ) ) { g.writeStartObject( "geo" ). write( "type", "FeatureCollection" ). writeStartArray( "features" ). writeStartObject(). write( "type", "Feature" ). writeStartObject( "properties" ). write( "type", resource.getName() + "'s Trail" ). write( "description", resource.getName() + "'s Trail" ). write( "color", "blue" ). write( "date_created", tracks.get( 0 ).getCollectedAt().getTime() ). writeEnd(). writeStartObject( "geometry" ). write( "type", "LineString" ). writeStartArray( "coordinates" ); for ( final ResourceTrack track : tracks ) { writePoint( g, track.getLocation().getX(), track.getLocation().getY() ); } g. writeEnd(). writeEnd(). writeStartObject( "crs" ). write( "type", "name" ). writeStartObject( "properties" ). write( "name", "urn:ogc:def:crs:OGC:1.3:CRS84" ). writeEnd(). writeEnd(). writeEnd(). writeEnd(). writeEnd(); } g.writeEnd(); } private void writePoint( final JsonGenerator g, final double x, final double y ) { g.writeStartArray().write( x ).write( y ).writeEnd(); } }
package function.genotype.base; import function.genotype.base.Carrier; import function.genotype.base.NonCarrier; import function.genotype.base.Sample; import function.variant.base.Variant; import global.Data; import utils.CommandValue; import utils.DBManager; import utils.ErrorManager; import utils.LogManager; import java.io.*; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; /** * * @author nick */ public class SampleManager { public static final int[] Region_Length = {511, 255}; private static ArrayList<Sample> sampleList = new ArrayList<Sample>(); private static Hashtable<Integer, Sample> sampleTable = new Hashtable<Integer, Sample>(); private static HashSet<Integer> chgvSampleIdSet = new HashSet<Integer>(); private static int listSize; private static StringBuilder allSampleId = new StringBuilder(); private static int caseNum = 0; private static int ctrlNum = 0; private static HashSet<Integer> evsSampleIdSet = new HashSet<Integer>(); private static HashSet<Integer> evsEaSampleIdSet = new HashSet<Integer>(); private static HashSet<Integer> evsAaSampleIdSet = new HashSet<Integer>(); private static HashSet<Integer> evsIndelSampleIdSet = new HashSet<Integer>(); private static HashSet<Integer> evsIndelEaSampleIdSet = new HashSet<Integer>(); private static HashSet<Integer> evsIndelAaSampleIdSet = new HashSet<Integer>(); private static ArrayList<Sample> failedSampleList = new ArrayList<Sample>(); private static ArrayList<Sample> diffTypeSampleList = new ArrayList<Sample>(); private static ArrayList<Sample> notExistSampleList = new ArrayList<Sample>(); private static ArrayList<Sample> deletedSampleList = new ArrayList<Sample>(); private static ArrayList<Sample> replacedSampleList = new ArrayList<Sample>(); private static String tempCovarFile; private static String covariateFileTitle = ""; // temp hack solution - phs000473 coverage restriction public static HashSet<Integer> phs000473SampleIdSet = new HashSet<Integer>(); public static void init() { if (!CommandValue.isNonSampleAnalysis) { checkSampleFile(); initAllTempTable(); initEvsIndelSampleIdSetFromAnnoDB(); if (CommandValue.isAllSample) { initAllSampleFromAnnoDB(); } else { if (!CommandValue.sampleFile.isEmpty()) { initFromSampleFile(); } if (!CommandValue.evsSample.isEmpty()) { initEvsSampleFromAnnoDB(); } } initCovariate(); initQuantitative(); initSampleIndexAndSize(); for (Sample sample : sampleList) { insertId2AllTable(sample); } outputSampleList(); evsIndelSampleIdSet = null; } } private static void checkSampleFile() { if (CommandValue.sampleFile.isEmpty() && !CommandValue.isAllSample && CommandValue.evsSample.isEmpty()) { ErrorManager.print("Please specify your sample file: --sample $PATH"); } } private static void initSampleIndexAndSize() { int index = 0; for (Sample sample : sampleList) { sample.setIndex(index++); } listSize = sampleList.size(); } private static void initEvsIndelSampleIdSetFromAnnoDB() { try { String sqlCode = "SELECT distinct s.sample_name, s.sample_id " + "FROM sample s, sample_attrib sa, sample_pipeline_step p " + "WHERE s.sample_id = p.sample_id " + "AND s.sample_id = sa.sample_id " + "AND sample_attrib_type_id = 2 " + "AND value_int > 0 " + "AND pipeline_step_id = 10 " + "AND step_status = 'completed' " + "AND sample_name like 'evs_%' "; ResultSet rs = DBManager.executeQuery(sqlCode); while (rs.next()) { evsIndelSampleIdSet.add(rs.getInt("sample_id")); } rs.close(); } catch (Exception e) { ErrorManager.send(e); } } private static void initAllSampleFromAnnoDB() { String sqlCode = "SELECT * FROM sample s, sample_pipeline_step p " + "WHERE s.sample_id = p.sample_id " + "AND p.pipeline_step_id = 10 " + "AND p.step_status = 'completed'"; initSampleFromAnnoDB(sqlCode); } private static void initFromSampleFile() { String lineStr = ""; int lineNum = 0; try { File f = new File(CommandValue.sampleFile); FileInputStream fstream = new FileInputStream(f); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); while ((lineStr = br.readLine()) != null) { lineNum++; if (lineStr.isEmpty()) { continue; } String[] values = lineStr.split("\t"); String familyId = values[0].trim(); String individualId = values[1].trim(); String paternalId = values[2].trim(); String maternalId = values[3].trim(); int sex = Integer.valueOf(values[4].trim()); double pheno = Double.valueOf(values[5].trim()); String sampleType = values[6].trim(); String captureKit = values[7].trim(); if (sampleType.equalsIgnoreCase("genome")) { captureKit = "N/A"; } int sampleId = getSampleId(individualId, sampleType, captureKit); if (sampleTable.containsKey(sampleId)) { continue; } Sample sample = new Sample(sampleId, familyId, individualId, paternalId, maternalId, sex, pheno, sampleType, captureKit); if (sampleId == Data.NA) { checkSampleList(sample); continue; } if (sample.getName().startsWith("phs000473_")) { phs000473SampleIdSet.add(sample.getId()); } sampleList.add(sample); sampleTable.put(sampleId, sample); if (sample.getName().startsWith("evs_ea")) { evsEaSampleIdSet.add(sampleId); if (evsIndelSampleIdSet.contains(sampleId)) { evsIndelEaSampleIdSet.add(sampleId); } } else if (sample.getName().startsWith("evs_aa")) { evsAaSampleIdSet.add(sampleId); if (evsIndelSampleIdSet.contains(sampleId)) { evsIndelAaSampleIdSet.add(sampleId); } } else { chgvSampleIdSet.add(sampleId); } countSampleNum(sample); } br.close(); in.close(); fstream.close(); } catch (Exception e) { LogManager.writeAndPrintNoNewLine("\nError line (" + lineNum + ") in sample file: " + lineStr); ErrorManager.send(e); } } private static void initEvsSampleFromAnnoDB() { if (!evsEaSampleIdSet.isEmpty() || !evsAaSampleIdSet.isEmpty()) { ErrorManager.print("evs samples in the sample file is not compatable with " + "--include-evs-sample option"); } String evsPop = ""; // all if (!CommandValue.evsSample.equals("all")) { evsPop = CommandValue.evsSample; } String sqlCode = "SELECT * FROM sample s, sample_pipeline_step p " + "WHERE s.sample_id = p.sample_id " + "AND p.pipeline_step_id = 10 " + "AND p.step_status = 'completed' " + "AND s.sample_name like 'evs_" + evsPop + "%'"; initSampleFromAnnoDB(sqlCode); } private static void initSampleFromAnnoDB(String sqlCode) { try { ResultSet rs = DBManager.executeQuery(sqlCode); while (rs.next()) { int sampleId = rs.getInt("sample_id"); String familyId = rs.getString("sample_name").trim(); String individualId = rs.getString("sample_name").trim(); String paternalId = "0"; String maternalId = "0"; String gender = rs.getString("gender").trim(); int sex = 1; if (gender.equals("F")) { sex = 2; } double pheno = 1; String sampleType = rs.getString("sample_type").trim(); String captureKit = rs.getString("capture_kit").trim(); Sample sample = new Sample(sampleId, familyId, individualId, paternalId, maternalId, sex, pheno, sampleType, captureKit); if (sample.getName().startsWith("phs000473_")) { phs000473SampleIdSet.add(sample.getId()); } sampleList.add(sample); sampleTable.put(sampleId, sample); if (sample.getName().startsWith("evs_ea")) { evsEaSampleIdSet.add(sampleId); if (evsIndelSampleIdSet.contains(sampleId)) { evsIndelEaSampleIdSet.add(sampleId); } } else if (sample.getName().startsWith("evs_aa")) { evsAaSampleIdSet.add(sampleId); if (evsIndelSampleIdSet.contains(sampleId)) { evsIndelAaSampleIdSet.add(sampleId); } } else { chgvSampleIdSet.add(sampleId); } countSampleNum(sample); } rs.close(); } catch (Exception e) { ErrorManager.send(e); } } private static void checkSampleList(Sample sample) { try { String sqlCode = "SELECT * FROM sample " + "WHERE sample_name = '" + sample.getName() + "' " + "AND sample_type = '" + sample.getType() + "' " + "AND capture_kit = '" + sample.getCaptureKit() + "' " + "AND sample_id IN (SELECT sample_id FROM sample_pipeline_step AS b " + "WHERE pipeline_step_id = 10 AND step_status != 'completed')"; ResultSet rs = DBManager.executeQuery(sqlCode); if (rs.next()) { failedSampleList.add(sample); } else { sqlCode = "SELECT * FROM sample " + "WHERE sample_name = '" + sample.getName() + "' " + "AND sample_id IN (SELECT sample_id FROM sample_pipeline_step AS b " + "WHERE pipeline_step_id = 10 AND step_status = 'completed')"; rs = DBManager.executeQuery(sqlCode); if (rs.next()) { diffTypeSampleList.add(sample); } else { notExistSampleList.add(sample); } } rs.close(); } catch (Exception e) { ErrorManager.send(e); } } private static void outputSampleList() { printSampleList("The following samples are included in the analysis:", sampleList, "\nThe number of samples included in the analysis is " + sampleList.size() + " (" + caseNum + " cases and " + ctrlNum + " controls).\n\n"); printSampleList("The following samples are labeled as failed in annodb:", failedSampleList, "\n"); printSampleList("The following samples are in annodb but with a different seqtype or capture kit:", diffTypeSampleList, "\n"); printSampleList("The following samples are not exist in annodb:", notExistSampleList, "\n"); } private static void printSampleList(String startMessage, ArrayList<Sample> sampleList, String endMessage) { if (!sampleList.isEmpty()) { LogManager.writeLog(startMessage); for (Sample sample : sampleList) { LogManager.writeLog( sample.getPrepId() + "\t" + sample.getName() + "\t" + sample.getType() + "\t" + sample.getCaptureKit()); } LogManager.writeLog(endMessage); } } private static void initCovariate() { if (CommandValue.covariateFile.isEmpty()) { return; } String lineStr = ""; int lineNum = 0; try { File f = new File(CommandValue.covariateFile); FileInputStream fstream = new FileInputStream(f); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); while ((lineStr = br.readLine()) != null) { lineNum++; if (lineStr.isEmpty()) { continue; } if (covariateFileTitle.isEmpty()) { covariateFileTitle = lineStr; } lineStr = lineStr.toLowerCase(); String[] values = lineStr.split("\t"); Sample sample = getSampleByName(values[1]); if (sample != null) { sample.initCovariate(values); } } } catch (Exception e) { LogManager.writeAndPrintNoNewLine("\nError line (" + lineNum + ") in covariate file: " + lineStr); ErrorManager.send(e); } resetSampleListByCovariate(); } private static void resetSampleListByCovariate() { Iterator<Sample> it = sampleList.iterator(); while (it.hasNext()) { Sample sample = it.next(); if (sample.getCovariateList().isEmpty()) { it.remove(); sampleTable.remove(sample.getId()); chgvSampleIdSet.remove(sample.getId()); } } } private static void initQuantitative() { if (CommandValue.quantitativeFile.isEmpty()) { return; } String lineStr = ""; int lineNum = 0; try { File f = new File(CommandValue.quantitativeFile); FileInputStream fstream = new FileInputStream(f); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); while ((lineStr = br.readLine()) != null) { lineNum++; if (lineStr.isEmpty()) { continue; } lineStr = lineStr.toLowerCase(); String[] values = lineStr.split("\t"); String name = values[0]; double value = Double.valueOf(values[1]); Sample sample = getSampleByName(name); if (sample != null) { sample.setQuantitativeTrait(value); } } } catch (Exception e) { LogManager.writeAndPrintNoNewLine("\nError line (" + lineNum + ") in quantitative file: " + lineStr); ErrorManager.send(e); } resetSampleListByQuantitative(); resetSamplePheno4Linear(); } private static void resetSampleListByQuantitative() { Iterator<Sample> it = sampleList.iterator(); while (it.hasNext()) { Sample sample = it.next(); if (sample.getQuantitativeTrait() == Data.NA) { it.remove(); sampleTable.remove(sample.getId()); chgvSampleIdSet.remove(sample.getId()); } } } public static void generateCovariateFile() { if (CommandValue.isCollapsingDoLogistic || CommandValue.isCollapsingDoLinear) { try { tempCovarFile = CommandValue.outputPath + "covariate.txt"; BufferedWriter bwCov = new BufferedWriter(new FileWriter(tempCovarFile)); bwCov.write("Family" + "\t" + "Sample" + "\t" + "Pheno"); String[] titles = covariateFileTitle.split("\t"); for (int i = 2; i < titles.length; i++) { bwCov.write("\t" + titles[i]); } bwCov.newLine(); for (Sample sample : sampleList) { bwCov.write(sample.getFamilyId() + "\t" + sample.getName() + "\t"); if (CommandValue.isCollapsingDoLogistic) { bwCov.write(String.valueOf((int) (sample.getPheno() + 1))); } else if (CommandValue.isCollapsingDoLinear) { bwCov.write(String.valueOf(sample.getQuantitativeTrait())); } for (String covar : sample.getCovariateList()) { bwCov.write("\t" + covar); } bwCov.newLine(); } bwCov.flush(); bwCov.close(); } catch (Exception e) { ErrorManager.send(e); } } } public static String getTempCovarPath() { return tempCovarFile; } private static Sample getSampleByName(String name) { for (Sample sample : sampleList) { if (sample.getName().equalsIgnoreCase(name)) { return sample; } } return null; } public static void recheckSampleList() { initDeletedAndReplacedSampleList(); outputOutofDateSampleList(deletedSampleList, "Deleted"); outputOutofDateSampleList(replacedSampleList, "Replaced"); if (!deletedSampleList.isEmpty() || !replacedSampleList.isEmpty()) { LogManager.writeAndPrint("\nAlert: the data for the deleted/replaced " + "sample used in the analysis is BAD data."); } } private static void initDeletedAndReplacedSampleList() { try { for (Sample sample : sampleList) { if (!sample.getName().startsWith("evs")) { String time = getSampleFinishTime(sample.getId()); if (time.isEmpty()) { deletedSampleList.add(sample); } else if (!time.equals(sample.getFinishTime())) { replacedSampleList.add(sample); } } } } catch (Exception e) { ErrorManager.send(e); } } private static void outputOutofDateSampleList(ArrayList<Sample> list, String name) { if (!list.isEmpty()) { LogManager.writeAndPrintNoNewLine("\n" + name + " sample list from Annotation database during the analysis:\n"); for (Sample sample : list) { LogManager.writeAndPrintNoNewLine( sample.getName() + "\t" + sample.getType() + "\t" + sample.getCaptureKit()); } } } private static void countSampleNum(Sample sample) { if (sample.isCase()) { caseNum++; } else { ctrlNum++; } } public static int getCaseNum() { return caseNum; } public static int getCtrlNum() { return ctrlNum; } private static void initAllTempTable() { createSqlTempTable(Data.ALL_SAMPLE_ID_TABLE); createSqlTempTable(Data.GENOME_SAMPLE_ID_TABLE); createSqlTempTable(Data.EXOME_SAMPLE_ID_TABLE); } private static void createSqlTempTable(String sqlTable) { try { Statement stmt = DBManager.createStatement(); String sqlQuery = "CREATE TEMPORARY TABLE " + sqlTable + "(id int, PRIMARY KEY (id)) ENGINE=TokuDB"; stmt.executeUpdate(sqlQuery); } catch (Exception e) { ErrorManager.send(e); } } private static void insertId2AllTable(Sample sample) { if (CommandValue.isCoverageSummary || CommandValue.isSiteCoverageSummary || CommandValue.isCoverageComparison) { insertId2Table(sample.getId(), Data.ALL_SAMPLE_ID_TABLE); } else { if (chgvSampleIdSet.contains(sample.getId())) { if (sample.getType().equalsIgnoreCase("genome")) { insertId2Table(sample.getId(), Data.GENOME_SAMPLE_ID_TABLE); } else { insertId2Table(sample.getId(), Data.EXOME_SAMPLE_ID_TABLE); } } } } private static void insertId2Table(int id, String table) { try { DBManager.executeUpdate("INSERT IGNORE INTO " + table + " VALUES (" + id + ")"); } catch (Exception e) { ErrorManager.send(e); } } private static int getSampleId(String sampleName, String sampleType, String captureKit) throws Exception { int sampleId = Data.NA; try { String sqlCode = "SELECT sample_id FROM sample " + "WHERE sample_name = '" + sampleName + "' " + "AND sample_type = '" + sampleType + "' " + "AND capture_kit = '" + captureKit + "' " + "AND sample_id IN (SELECT sample_id FROM sample_pipeline_step AS b " + "WHERE pipeline_step_id = 10 AND step_status = 'completed')"; ResultSet rs = DBManager.executeQuery(sqlCode); if (rs.next()) { sampleId = rs.getInt("sample_id"); } rs.close(); } catch (Exception e) { ErrorManager.send(e); } return sampleId; } public static int getSamplePrepId(int sampleId) { int prepId = Data.NA; try { String sqlCode = "SELECT prep_id FROM sample WHERE sample_id = " + sampleId; ResultSet rs = DBManager.executeReadOnlyQuery(sqlCode); if (rs.next()) { prepId = rs.getInt("prep_id"); } rs.close(); } catch (Exception e) { ErrorManager.send(e); } return prepId; } public static String getSampleFinishTime(int sampleId) { String time = ""; try { String sqlCode = "SELECT exec_finish_time FROM sample_pipeline_step " + "WHERE pipeline_step_id = 10 AND step_status = 'completed' " + "AND sample_id = " + sampleId; ResultSet rs = DBManager.executeReadOnlyQuery(sqlCode); if (rs.next()) { time = rs.getString("exec_finish_time"); } rs.close(); } catch (Exception e) { ErrorManager.send(e); } return time; } public static int getIdByName(String sampleName) { for (Sample sample : sampleList) { if (sample.getName().equals(sampleName)) { return sample.getId(); } } return Data.NA; } public static int getIndexById(int sampleId) { Sample sample = sampleTable.get(sampleId); if (sample != null) { return sample.getIndex(); } else { return Data.NA; } } public static ArrayList<Sample> getList() { return sampleList; } public static Hashtable<Integer, Sample> getTable() { return sampleTable; } public static int getListSize() { return listSize; } public static void initNonCarrierMap(Variant var, HashMap<Integer, Carrier> carrierMap, HashMap<Integer, NonCarrier> noncarrierMap) { ResultSet rs = null; String sql = ""; int posIndex = var.getRegion().getStartPosition() % Data.COVERAGE_BLOCK_SIZE; // coverage data block size is 1024 if (posIndex == 0) { posIndex = Data.COVERAGE_BLOCK_SIZE; // block boundary is ( ] } int endPos = var.getRegion().getStartPosition() - posIndex + Data.COVERAGE_BLOCK_SIZE; try { for (int i = 0; i < Data.SAMPLE_TYPE.length; i++) { sql = "SELECT sample_id, min_coverage " + "FROM " + Data.SAMPLE_TYPE[i] + "_read_coverage_" + Data.COVERAGE_BLOCK_SIZE + "_chr" + var.getRegion().getChrStr() + " c," + Data.SAMPLE_TYPE[i] + "_sample_id t " + "WHERE c.position = " + endPos + " AND c.sample_id = t.id"; rs = DBManager.executeQuery(sql); while (rs.next()) { NonCarrier noncarrier = new NonCarrier(); noncarrier.init(rs, posIndex); if (!carrierMap.containsKey(noncarrier.getSampleId())) { noncarrier.checkCoverageFilter(CommandValue.minCaseCoverageNoCall, CommandValue.minCtrlCoverageNoCall); noncarrier.checkValidOnXY(var); if (noncarrier.getGenotype() != Data.NA) { noncarrierMap.put(noncarrier.getSampleId(), noncarrier); } } } } rs.close(); } catch (Exception e) { ErrorManager.send(e); } } public static void initCarrierMap(Variant var, HashMap<Integer, Carrier> carrierMap, HashMap<Integer, Carrier> evsEaCarrierMap, HashMap<Integer, Carrier> evsAaCarrierMap) { String sqlCarrier = "SELECT * " + "FROM called_" + var.getType() + " va," + Data.ALL_SAMPLE_ID_TABLE + " t " + "WHERE va." + var.getType() + "_id = " + var.getVariantId() + " AND va.sample_id = t.id"; ResultSet rs = null; try { rs = DBManager.executeQuery(sqlCarrier); while (rs.next()) { Carrier carrier = new Carrier(); carrier.init(rs); carrier.checkCoverageFilter(CommandValue.minCaseCoverageCall, CommandValue.minCtrlCoverageCall); carrier.checkQualityFilter(); carrier.checkValidOnXY(var); if (evsEaSampleIdSet.contains(carrier.getSampleId())) { evsEaCarrierMap.put(carrier.getSampleId(), carrier); } else if (evsAaSampleIdSet.contains(carrier.getSampleId())) { evsAaCarrierMap.put(carrier.getSampleId(), carrier); } carrierMap.put(carrier.getSampleId(), carrier); } rs.close(); } catch (Exception e) { ErrorManager.send(e); } } public static String getAllSampleId() { if (allSampleId.length() == 0) { boolean isFirst = true; int sampleId; for (Sample sample : sampleList) { sampleId = sample.getId(); if (isFirst) { allSampleId.append("(").append(sampleId); isFirst = false; } else { allSampleId.append(",").append(sampleId); } } allSampleId.append(")"); } return allSampleId.toString(); } public static boolean isEvsEaSampleId(int id, boolean isIndel) { if (isIndel) { return evsIndelEaSampleIdSet.contains(id); } return evsEaSampleIdSet.contains(id); } public static boolean isEvsAaSampleId(int id, boolean isIndel) { if (isIndel) { return evsIndelAaSampleIdSet.contains(id); } return evsAaSampleIdSet.contains(id); } public static int getEvsSampleNum(String evsSample, boolean isIndel) { if (evsSample.equals("ea")) { return getEvsEaSampleNum(isIndel); } else if (evsSample.equals("aa")) { return getEvsAaSampleNum(isIndel); } return Data.NA; } public static int getEvsEaSampleNum(boolean isIndel) { if (isIndel) { return evsIndelEaSampleIdSet.size(); } return evsEaSampleIdSet.size(); } public static int getEvsAaSampleNum(boolean isIndel) { if (isIndel) { return evsIndelAaSampleIdSet.size(); } return evsAaSampleIdSet.size(); } public static boolean isMale(int sampleId) { return sampleTable.get(sampleId).isMale(); } public static HashSet<Integer> getEvsSampleIdSet() { if (evsSampleIdSet.isEmpty()) { evsSampleIdSet.addAll(evsEaSampleIdSet); evsSampleIdSet.addAll(evsAaSampleIdSet); } return evsSampleIdSet; } private static void resetSamplePheno4Linear() { for (Sample sample : sampleList) { sample.setPheno(0); } ctrlNum = sampleList.size(); caseNum = 0; } }
package function.variant.base; import function.annotation.base.GeneManager; import function.external.knownvar.ClinVar; import function.external.knownvar.DBDSM; import function.external.knownvar.HGMD; import function.external.knownvar.KnownVarManager; import function.genotype.trio.TrioCommand; import utils.ErrorManager; import utils.LogManager; import java.io.*; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashSet; import utils.DBManager; /** * * @author nick */ public class VariantManager { private static final String ARTIFACTS_Variant_PATH = "data/artifacts_variant.txt"; public static final String[] VARIANT_TYPE = {"snv", "indel"}; private static HashSet<String> includeVariantSet = new HashSet<>(); private static HashSet<String> includeRsNumberSet = new HashSet<>(); private static HashSet<String> excludeVariantSet = new HashSet<>(); private static ArrayList<String> includeVariantPosList = new ArrayList<>(); private static ArrayList<String> includeVariantTypeList = new ArrayList<>(); private static ArrayList<String> includeChrList = new ArrayList<>(); private static int maxIncludeNum = 10000000; public static void init() throws FileNotFoundException, Exception, SQLException { if (TrioCommand.isListTrio) { // disable process region as variant by varaint way maxIncludeNum = 0; } initByVariantId(VariantLevelFilterCommand.includeVariantId, includeVariantSet, true); initByRsNumber(VariantLevelFilterCommand.includeRsNumber, includeRsNumberSet, true); initByVariantId(VariantLevelFilterCommand.excludeVariantId, excludeVariantSet, false); if (VariantLevelFilterCommand.isExcludeArtifacts) { initByVariantId(ARTIFACTS_Variant_PATH, excludeVariantSet, false); } if (!VariantLevelFilterCommand.includeVariantId.isEmpty() || !VariantLevelFilterCommand.includeRsNumber.isEmpty()) { resetRegionList(); } } public static void initByVariantId(String input, HashSet<String> variantSet, boolean isInclude) throws Exception { if (input.isEmpty()) { return; } File f = new File(input); if (f.isFile()) { initFromVariantFile(f, variantSet, isInclude); } else { String[] list = input.split(","); for (String str : list) { addVariantToList(str, variantSet, isInclude); } } } public static void initByRsNumber(String input, HashSet<String> rsNumberSet, boolean isInclude) throws Exception { if (input.isEmpty()) { return; } File f = new File(input); if (f.isFile()) { initFromRsNumberFile(f, rsNumberSet, isInclude); } else { String[] list = input.split(","); for (String str : list) { addRsNumberToList(str, rsNumberSet, isInclude); } } } private static void initFromVariantFile(File f, HashSet<String> variantSet, boolean isInclude) { String lineStr = ""; int lineNum = 0; try { FileInputStream fstream = new FileInputStream(f); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); while ((lineStr = br.readLine()) != null) { lineNum++; if (lineStr.isEmpty()) { continue; } addVariantToList(lineStr, variantSet, isInclude); } } catch (Exception e) { LogManager.writeAndPrintNoNewLine("\nError line (" + lineNum + ") in variant file: " + lineStr); ErrorManager.send(e); } } private static void initFromRsNumberFile(File f, HashSet<String> rsNumberSet, boolean isInclude) { String lineStr = ""; int lineNum = 0; try { FileInputStream fstream = new FileInputStream(f); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); while ((lineStr = br.readLine()) != null) { lineNum++; if (lineStr.isEmpty()) { continue; } addRsNumberToList(lineStr, rsNumberSet, isInclude); } } catch (Exception e) { LogManager.writeAndPrintNoNewLine("\nError line (" + lineNum + ") in rs number file: " + lineStr); ErrorManager.send(e); } } public static void reset2KnownVarSet() throws SQLException { clearIncludeVarSet(); // init ClinVar variants set for (ClinVar clinvar : KnownVarManager.getClinVarMultiMap().values()) { addVariantToList(clinvar.getVariantId(), includeVariantSet, true); } // init HGMD variants set for (HGMD hgmd : KnownVarManager.getHGMDMultiMap().values()) { addVariantToList(hgmd.getVariantId(), includeVariantSet, true); } // init DBDSM variants set for (DBDSM dbDSM : KnownVarManager.getDBDSMMultiMap().values()) { addVariantToList(dbDSM.getVariantId(), includeVariantSet, true); } resetRegionList(); } private static void addVariantToList(String str, HashSet<String> variantSet, boolean isInclude) throws SQLException { if (str.startsWith("rs")) { ErrorManager.print("warning: rs number is no longer support in --variant option, " + "please use --rs-number instead."); } str = str.replaceAll("( )+", ""); if (str.startsWith("chr")) { str = str.substring(3, str.length()); } if (!variantSet.contains(str)) { if (isInclude) { String[] values = str.split("-"); String varPos = values[0] + "-" + values[1]; if (values[2].length() == 1 && values[3].length() == 1) { varPos += "-snv"; } else { varPos += "-indel"; } add2IncludeVariantPosSet(varPos); } str = getPARVariantId(str); variantSet.add(str); } } private static void addRsNumberToList(String str, HashSet<String> rsNumberSet, boolean isInclude) throws SQLException { str = str.replaceAll("( )+", ""); if (!rsNumberSet.contains(str)) { String varPos = VariantManager.getVariantPositionByRS(str); if (!varPos.isEmpty()) { if (isInclude) { add2IncludeVariantPosSet(varPos); } rsNumberSet.add(str); } } } private static String getVariantPositionByRS(String rs) throws SQLException { String varPos = getVariantPositionByRS(rs, "snv"); if (varPos.isEmpty()) { varPos = getVariantPositionByRS(rs, "indel"); } return varPos; } private static String getVariantPositionByRS(String rs, String type) throws SQLException { String sql = "select name, seq_region_pos from " + type + " v, seq_region s " + "where rs_number = '" + rs + "' and " + "coord_system_id = 2 and " + "v.seq_region_id = s.seq_region_id"; ResultSet rset = DBManager.executeQuery(sql); String chr = ""; int pos = 0; if (rset.next()) { chr = rset.getString("name"); pos = rset.getInt("seq_region_pos"); return chr + "-" + pos + "-" + type; } return ""; } private static String getPARVariantId(String str) { if (!str.contains("X") || str.contains("XY")) { return str; } String[] temp = str.split("-"); String chr = temp[0]; int pos = Integer.valueOf(temp[1]); Region region = new Region(chr, pos, pos); if (region.isInsideXPseudoautosomalRegions()) { return "XY" + str.substring(str.indexOf("-")); } return str; } private static void add2IncludeVariantPosSet(String str) { String chr = str.split("-")[0]; if (!includeChrList.contains(chr)) { includeChrList.add(chr); } if (!includeVariantPosList.contains(str)) { includeVariantPosList.add(str); } } private static void resetRegionList() throws SQLException { if (!RegionManager.isUsed() && !GeneManager.isUsed()) { RegionManager.clear(); if (includeVariantSet.size() <= maxIncludeNum) { for (String varPos : includeVariantPosList) { RegionManager.addRegionByVariantPos(varPos); } } else { includeVariantTypeList.clear(); RegionManager.initChrRegionList(includeChrList.toArray(new String[includeChrList.size()])); RegionManager.sortRegionList(); } } } public static boolean isValid(Variant var) { return (isVariantIdIncluded(var.getVariantIdStr()) && isRsNumberIncluded(var.getRsNumber())) && !isExcluded(var.getVariantIdStr()); } public static boolean isVariantIdIncluded(String varId) { if (includeVariantSet.isEmpty() && VariantLevelFilterCommand.includeVariantId.isEmpty()) { // only when --variant option not used, return true return true; } else { if (includeVariantSet.contains(varId)) { includeVariantSet.remove(varId); return true; } return false; } } private static boolean isRsNumberIncluded(String rs) { if (includeRsNumberSet.isEmpty()) { // only when --rs-number option not used, return true return true; } else { return includeRsNumberSet.contains(rs); } } private static boolean isExcluded(String varId) { return excludeVariantSet.contains(varId); } public static boolean isVariantTypeValid(int index, String type) { boolean check = false; try { if (type.equals(VARIANT_TYPE[0])) // snv { if (VariantLevelFilterCommand.isExcludeSnv) { return false; } } else // indel if (VariantLevelFilterCommand.isExcludeIndel) { return false; } if (includeVariantTypeList.isEmpty()) { return true; } check = includeVariantTypeList.get(index).equalsIgnoreCase(type); } catch (Exception e) { ErrorManager.send(e); } return check; } public static void addType(String type) { includeVariantTypeList.add(type); } public static ArrayList<String> getIncludeVariantList() { return includeVariantPosList; } private static void clearIncludeVarSet() { includeVariantSet.clear(); includeRsNumberSet.clear(); includeVariantPosList.clear(); includeVariantTypeList.clear(); includeChrList.clear(); } }
package gov.nih.nci.evs.api.aop; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import com.fasterxml.jackson.databind.ObjectMapper; import gov.nih.nci.evs.api.model.Metric; import gov.nih.nci.evs.api.properties.ElasticServerProperties; /** * Handle record metric annotations via AOP. */ @Component @Aspect @ConditionalOnProperty(name = "nci.evs.application.metricsEnabled") public class MetricAdvice { /** The logger. */ private static final Logger logger = LoggerFactory.getLogger(MetricAdvice.class); /** The elastic server properties. */ @Autowired ElasticServerProperties elasticServerProperties; /** The mapper. */ private static ObjectMapper mapper = initMapper(); /** * Inits the mapper. * * @return the object mapper */ private static ObjectMapper initMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")); return mapper; } /** * Record metric. * * @param pjp the pjp * @param recordMetric the record metric * @return the object * @throws Throwable the throwable */ @Around("execution(* gov.nih.nci.evs.api.controller.*.*(..)) && @annotation(recordMetric)") private Object recordMetric(final ProceedingJoinPoint pjp, final RecordMetric recordMetric) throws Throwable { // get the request final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); return recordMetricHelper(pjp, request, request.getParameterMap()); } /** * Record metric helper. * * @param pjp the pjp * @param request the request * @param params the params * @return the object * @throws Throwable the throwable */ public Object recordMetricHelper(final ProceedingJoinPoint pjp, final HttpServletRequest request, final Map<String, String[]> params) throws Throwable { // get the start time final long startTime = System.currentTimeMillis(); final Date startDate = new Date(); final long endTime = System.currentTimeMillis(); final long duration = endTime - startTime; final Date endDate = new Date(); final Metric metric = new Metric(); metric.setDuration(duration); // get the ip address of the remote user final ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); final String userIpAddress = attr.getRequest().getRemoteAddr(); metric.setRemoteIpAddress(userIpAddress); final String hostName = attr.getRequest().getRemoteHost(); metric.setHostName(hostName); final String url = request.getRequestURL().toString(); metric.setEndPoint(url); metric.setQueryParams(params); metric.setStartTime(startDate); metric.setEndTime(endDate); // get the parameters final RestTemplate restTemplate = new RestTemplate(); final String metricStr = mapper.writeValueAsString(metric); final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); final HttpEntity<String> metricData = new HttpEntity<String>(metricStr, headers); restTemplate.postForObject(elasticServerProperties.getUrl(), metricData, String.class); logger.debug("metric = " + metric); return pjp.proceed(); } }
package info.u_team.u_team_core.util; import java.util.*; import java.util.stream.Stream; import net.minecraft.block.Block; import net.minecraft.entity.EntityType; import net.minecraft.fluid.Fluid; import net.minecraft.item.*; import net.minecraft.item.crafting.Ingredient; import net.minecraft.item.crafting.Ingredient.TagList; import net.minecraft.tags.*; import net.minecraft.tags.ITag.INamedTag; import net.minecraft.util.ResourceLocation; public class TagUtil { public static INamedTag<Block> createBlockTag(String modid, String name) { return createBlockTag(new ResourceLocation(modid, name)); } public static INamedTag<Block> createBlockTag(ResourceLocation location) { return BlockTags.makeWrapperTag(location.toString()); } public static INamedTag<Item> createItemTag(String modid, String name) { return createItemTag(new ResourceLocation(modid, name)); } public static INamedTag<Item> createItemTag(ResourceLocation location) { return ItemTags.makeWrapperTag(location.toString()); } public static INamedTag<Fluid> createFluidTag(String modid, String name) { return createFluidTag(new ResourceLocation(modid, name)); } public static INamedTag<Fluid> createFluidTag(ResourceLocation location) { return FluidTags.makeWrapperTag(location.toString()); } public static INamedTag<EntityType<?>> createEntityTypeTag(String modid, String name) { return createEntityTypeTag(new ResourceLocation(modid, name)); } public static INamedTag<EntityType<?>> createEntityTypeTag(ResourceLocation location) { return EntityTypeTags.func_232896_a_(location.toString()); } public static INamedTag<Block> fromItemTag(INamedTag<Item> block) { return BlockTags.makeWrapperTag(block.func_230234_a_().toString()); } public static INamedTag<Item> fromBlockTag(INamedTag<Block> block) { return ItemTags.makeWrapperTag(block.func_230234_a_().toString()); } public static Ingredient getSerializableIngredientOfTag(ITag<Item> tag) { return Ingredient.fromItemListStream(Stream.of(new TagList(tag) { @Override public Collection<ItemStack> getStacks() { return Arrays.asList(new ItemStack(Items.ACACIA_BOAT)); // Return default value, so the ingredient will serialize our tag. } })); } }
package io.badgeup.sponge; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.json.JSONObject; import org.spongepowered.api.Sponge; import org.spongepowered.api.entity.living.player.Player; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; import io.badgeup.sponge.event.BadgeUpEvent; import io.badgeup.sponge.service.AchievementPersistenceService; import io.badgeup.sponge.service.AwardPersistenceService; public class PostEventsRunnable implements Runnable { private BadgeUpSponge plugin; public PostEventsRunnable(BadgeUpSponge plugin) { this.plugin = plugin; } @Override public void run() { Config config = BadgeUpSponge.getConfig(); // build the base API URL String baseURL = ""; if (!config.getBadgeUpConfig().getBaseAPIURL().isEmpty()) { // override other config settings with this base URL baseURL = config.getBadgeUpConfig().getBaseAPIURL(); } else { // region provided baseURL = "https://api." + config.getBadgeUpConfig().getRegion() + ".badgeup.io/v1/apps/"; } String appId = Util.parseAppIdFromAPIKey(config.getBadgeUpConfig().getAPIKey()).get(); plugin.getLogger().info("Started BadgeUp event consumer"); try { while (true) { final BadgeUpEvent event = BadgeUpSponge.getEventQueue().take(); event.setDiscardable(true); try { HttpResponse<JsonNode> response = Unirest.post(baseURL + appId + "/events").body(event.build()) .asJson(); if (response.getStatus() == 413) { System.out.println("Event too large: " + event.build().getString("key")); continue; } final JSONObject body = response.getBody().getObject(); List<JSONObject> completedAchievements = new ArrayList<>(); body.getJSONArray("progress").forEach(progressObj -> { JSONObject record = (JSONObject) progressObj; if (record.getBoolean("isComplete")) { // record.getBoolean("isNew") completedAchievements.add(record); } }); for (JSONObject record : completedAchievements) { final String earnedAchievementId = record.getString("earnedAchievementId"); final JSONObject earnedAchievementRecord = Unirest .get(baseURL + appId + "/earnedachievements/" + earnedAchievementId).asJson().getBody() .getObject(); final String achievementId = earnedAchievementRecord.getString("achievementId"); final JSONObject achievement = Unirest.get(baseURL + appId + "/achievements/" + achievementId) .asJson().getBody().getObject(); final Optional<Player> subjectOpt = Sponge.getServer().getPlayer(event.getSubject()); AwardPersistenceService awardPS = Sponge.getServiceManager() .provide(AwardPersistenceService.class).get(); List<String> awardIds = new ArrayList<>(); achievement.getJSONArray("awards") .forEach(award -> awardIds.add(((JSONObject) award).getString("id"))); for (String awardId : awardIds) { final JSONObject award = Unirest.get(baseURL + appId + "/awards/" + awardId).asJson() .getBody().getObject(); awardPS.addPendingAward(event.getSubject(), award); boolean autoRedeem = Util.safeGetBoolean(award.getJSONObject("data"), "autoRedeem").orElse(false); if (subjectOpt.isPresent() && autoRedeem) { // Check if the award is auto-redeemable and send the redeem command if it is Sponge.getCommandManager().process(subjectOpt.get(), "redeem " + awardId); } } if (!subjectOpt.isPresent()) { // Store the achievement to be presented later AchievementPersistenceService achPS = Sponge.getServiceManager() .provide(AchievementPersistenceService.class).get(); achPS.addUnpresentedAchievement(event.getSubject(), achievement); } else { // Present the achievement to the player BadgeUpSponge.presentAchievement(subjectOpt.get(), achievement); } } } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); plugin.getLogger().error("Could not connect to BadgeUp API!"); continue; } } } catch (Exception e) { System.err.println(e); e.printStackTrace(); } } }
package net.floodlightcontroller.simpleft; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Random; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import net.floodlightcontroller.core.FloodlightContext; import net.floodlightcontroller.core.IFloodlightProviderService; import net.floodlightcontroller.core.IOFMessageListener; import net.floodlightcontroller.core.IOFSwitch; import net.floodlightcontroller.core.module.FloodlightModuleContext; import net.floodlightcontroller.core.module.FloodlightModuleException; import net.floodlightcontroller.core.module.IFloodlightModule; import net.floodlightcontroller.core.module.IFloodlightService; import net.floodlightcontroller.core.util.SingletonTask; import net.floodlightcontroller.storage.IStorageSourceService; import net.floodlightcontroller.threadpool.IThreadPoolService; import net.floodlightcontroller.threadpool.ThreadPool; import org.projectfloodlight.openflow.protocol.OFMessage; import org.projectfloodlight.openflow.protocol.OFType; import org.sdnplatform.sync.IStoreClient; import org.sdnplatform.sync.IStoreListener; import org.sdnplatform.sync.ISyncService; import org.sdnplatform.sync.ISyncService.Scope; import org.sdnplatform.sync.error.SyncException; import org.sdnplatform.sync.internal.SyncManager; import org.sdnplatform.sync.internal.config.Node; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; public class FT implements IOFMessageListener, IFloodlightModule, IStoreListener<String> { private ISyncService syncService; private IStoreClient<String, Object> storeClient; protected FloodlightModuleContext[] moduleContexts; protected SyncManager[] syncManagers; protected final static ObjectMapper mapper = new ObjectMapper(); protected String nodeString; ArrayList<Node> nodes; ThreadPool tp; protected static Logger logger = LoggerFactory.getLogger(FT.class); protected static IThreadPoolService threadPoolService; protected static SingletonTask testTask; @Override public String getName() { // TODO Auto-generated method stub return FT.class.getSimpleName(); } @Override public boolean isCallbackOrderingPrereq(OFType type, String name) { // TODO Auto-generated method stub return false; } @Override public boolean isCallbackOrderingPostreq(OFType type, String name) { // TODO Auto-generated method stub return false; } @Override public Collection<Class<? extends IFloodlightService>> getModuleServices() { // TODO Auto-generated method stub Collection<Class<? extends IFloodlightService>> l = new ArrayList<Class<? extends IFloodlightService>>(); return l; } @Override public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() { // TODO Auto-generated method stub Map<Class<? extends IFloodlightService>, IFloodlightService> m = new HashMap<Class<? extends IFloodlightService>, IFloodlightService>(); return m; } @Override public Collection<Class<? extends IFloodlightService>> getModuleDependencies() { // TODO Auto-generated method stub Collection<Class<? extends IFloodlightService>> l = new ArrayList<Class<? extends IFloodlightService>>(); l.add(IFloodlightProviderService.class); l.add(IStorageSourceService.class); l.add(ISyncService.class); l.add(IThreadPoolService.class); return l; } @Override public void init(FloodlightModuleContext context) throws FloodlightModuleException { // TODO Auto-generated method stub this.syncService = context.getServiceImpl(ISyncService.class); threadPoolService = context.getServiceImpl(IThreadPoolService.class); } @Override public void startUp(FloodlightModuleContext context) throws FloodlightModuleException { try { this.syncService.registerStore("NIB", Scope.GLOBAL); this.storeClient = this.syncService .getStoreClient("NIB", String.class, Object.class); this.storeClient.put("NIB", new String("Algo aqui...")); this.storeClient.addStoreListener(this); } catch (SyncException e) { throw new FloodlightModuleException("Error while setting up sync service", e); } //logger.debug("Iniciado SYNC, testing now:"); String obj; try { obj = this.storeClient.getValue("NIB").toString(); logger.debug("Sync retrieve: {}", obj); this.storeClient.put("NIB", new String("B")); } catch (SyncException e) { // TODO Auto-generated catch block e.printStackTrace(); } ScheduledExecutorService ses = threadPoolService.getScheduledExecutor(); testTask = new SingletonTask(ses, new Runnable() { int counter=0; @Override public void run() { Random r = new Random(); try { storeClient.put("NIB", new String("vl:"+r.nextInt(1000))); //storeClient.put("NIB", new String(""+counter++)); } catch (SyncException e) { // TODO Auto-generated catch block e.printStackTrace(); } testTask.reschedule(4, TimeUnit.SECONDS); } }); testTask.reschedule(3, TimeUnit.SECONDS); } @Override public net.floodlightcontroller.core.IListener.Command receive( IOFSwitch sw, OFMessage msg, FloodlightContext cntx) { // TODO Auto-generated method stub return null; } @Override public void keysModified(Iterator<String> keys, org.sdnplatform.sync.IStoreListener.UpdateType type) { // TODO Auto-generated method stub while(keys.hasNext()){ String k = keys.next(); try { logger.debug("keysModified: Key:{}, Value:{}, Type: {}", new Object[] {k, storeClient.get(k).getValue().toString(), type.name()} ); //logger.debug("localNodeID: {}",this.syncService.getLocalNodeId()); } catch (SyncException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
package net.osten.watermap.convert; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.charset.Charset; import java.text.ParseException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Logger; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import net.osten.watermap.model.WaterReport; import net.osten.watermap.pct.xml.GpxType; import net.osten.watermap.pct.xml.WptType; import net.osten.watermap.util.RegexUtils; import org.apache.commons.lang3.time.FastDateFormat; import com.google.common.io.Files; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; /** * Parser for PCT water report based on the PCT Google Sheets downloaded using the API. */ @Singleton @Startup public class PCTReport { private static final FastDateFormat dateFormatter = FastDateFormat.getInstance("M/dd/yy"); private static final String SOURCE_TITLE = "PCT Water Report"; private static final String SOURCE_URL = "http://pctwater.com/"; private String dataDir = null; private String[] stateChars = new String[] { "CA", "OR", "WA" }; private char[] sectionChars = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G' , 'M', 'N', 'O', 'P', 'Q', 'R'}; private List<WptType> waypoints = new ArrayList<WptType>(); private static Logger log = Logger.getLogger(PCTReport.class.getName()); /** * Default constructor. */ public PCTReport() { initialize(); } /** * Parse the PCT water report Google docs files. * * @return set of water reports */ public synchronized Set<WaterReport> convert() throws IOException { Set<WaterReport> results = new HashSet<WaterReport>(); log.fine("dataDir=" + dataDir); // parse json files if (dataDir != null) { for (String stateChar : stateChars) { for (char sectionChar : sectionChars) { try { String fileName = "pct-" +stateChar + "-" + sectionChar + ".json"; File jsonFile = new File(dataDir + File.separator + fileName); if (jsonFile.exists() && jsonFile.canRead()) { log.fine("reading json file " + jsonFile); String htmlSource = Files.toString(jsonFile, Charset.forName("UTF-8")); JsonParser parser = new JsonParser(); JsonElement root = parser.parse(htmlSource); log.finest("json root is obj=" + root.isJsonObject()); results.addAll(parseDocument(root.getAsJsonObject())); } } catch (IOException e) { log.severe(e.getLocalizedMessage()); } } } } return results; } public void initialize() { log.info("initializing PCT report..."); setDataDir(System.getenv("OPENSHIFT_DATA_DIR")); // parse waypoints XML files if (dataDir != null) { for (String stateChar : stateChars) { for (char sectionChar : sectionChars) { try { JAXBContext jc = JAXBContext.newInstance("net.osten.watermap.pct.xml"); Unmarshaller u = jc.createUnmarshaller(); @SuppressWarnings("unchecked") GpxType waypointList = ((JAXBElement<GpxType>) u.unmarshal(new FileInputStream(dataDir + File.separator + stateChar + "_Sec_" + sectionChar + "_waypoints.gpx"))).getValue(); log.info("found " + waypointList.getWpt().size() + " waypoints for section " + sectionChar); waypoints.addAll(waypointList.getWpt()); } catch (JAXBException | IOException e) { log.severe(e.getLocalizedMessage()); } } } } log.info("imported " + waypoints.size() + " waypoints"); log.info("done initializing PCT report"); } /** * Sets the directory where the data files are. * * @param dataDir data directory */ public void setDataDir(String dataDir) { this.dataDir = dataDir; } /** * There are discrepencies between some of the water report names and the waypoint names. * * @param waterReportName name from the water report * @return mapped name in waypoint file */ private String fixNames(String waterReportName) { String result = null; if (waterReportName.equalsIgnoreCase("LkMorenaCG")) { result = "LakeMorenaCG"; } else if (waterReportName.equalsIgnoreCase("BoulderOaksCG")) { result = "BoulderOakCG"; } else if (waterReportName.equalsIgnoreCase("WRCS091")) { result = "WR091"; } else if (waterReportName.equalsIgnoreCase("WR016B")) { result = "WR106B"; } else if (waterReportName.equalsIgnoreCase("CS183B")) { result = "CS0183"; } else if (waterReportName.equalsIgnoreCase("Fuller Ridge")) { result = "FullerRidgeTH"; } else if (waterReportName.equalsIgnoreCase("WRCS219")) { result = "WhitewaterTr"; } else if (waterReportName.equalsIgnoreCase("WR233")) { result = "WR234"; } else if (waterReportName.equalsIgnoreCase("WR239")) { result = "WRCS0239"; } else if (waterReportName.equalsIgnoreCase("WR256")) { result = "WRCS056"; } return result; } private Set<WaterReport> parseDocument(JsonObject reportJson) { Set<WaterReport> results = new HashSet<WaterReport>(); log.finer("json children=" + reportJson.getAsJsonArray("values").size()); JsonArray currentRow = null; for (JsonElement row : reportJson.getAsJsonArray("values")) { if (row.isJsonArray()) { currentRow = row.getAsJsonArray(); if (currentRow.size() >= 6) { String waypoint = currentRow.get(2).getAsJsonPrimitive().getAsString(); String desc = currentRow.get(3).getAsJsonPrimitive().getAsString(); String rpt = currentRow.get(4).getAsJsonPrimitive().getAsString(); String date = currentRow.get(5).getAsJsonPrimitive().getAsString(); String[] names = waypoint.split(","); for (String name : names) { name = name.trim(); WaterReport report = processWaypoint(name, desc, date, rpt); if (report.getLat() == null) { // DEO try prefixing the name (this is for split names: "WR127,B") name = names[0] + name; report = processWaypoint(name, desc, date, rpt); if (report.getLat() == null) { log.fine("cannot find coords for " + waypoint); } else { log.finest(report.toString()); results.add(report); } } else { log.finest(report.toString()); results.add(report); } } } else { log.finer("skipping row " + row.toString()); } } else { log.warning("row is not json array but " + row.getClass().getName()); } } log.info("returning " + results.size() + " pct reports"); return results; } private WaterReport processWaypoint(String waypoint, String desc, String date, String rpt) { log.finer("waypoint=" + waypoint); WaterReport report = new WaterReport(); report.setDescription(rpt); report.setLocation(desc); report.setName(waypoint); if (date != null && !date.isEmpty()) { try { report.setLastReport(dateFormatter.parse(date)); } catch (ParseException e) { log.severe(e.getLocalizedMessage()); } } report.setSource(SOURCE_TITLE); report.setUrl(SOURCE_URL); report.setState(WaterStateParser.parseState(rpt)); // TODO replace with something more elegant than this brute force search for (WptType wpt : waypoints) { if (wpt.getName().equalsIgnoreCase(waypoint)) { // System.out.println("found matching lat/lon"); report.setLat(wpt.getLat()); report.setLon(wpt.getLon()); break; } } // if coords not found, try adding leading 0 (e.g. WRCS292 -> WRCS0292) if (report.getLat() == null) { String modifiedWaypoint = RegexUtils.addLeadingZerosToWaypoint(waypoint); for (WptType wpt : waypoints) { if (wpt.getName().equalsIgnoreCase(modifiedWaypoint)) { // System.out.println("found matching lat/lon"); report.setLat(wpt.getLat()); report.setLon(wpt.getLon()); break; } } } // if coords not found, try with leading 0 in waypoint (i.e. WR0213); this happens in Section B waypoint file if (report.getLat() == null && waypoint.length() > 2) { String modifiedWaypoint = "WR0" + waypoint.substring(2); for (WptType wpt : waypoints) { if (wpt.getName().equalsIgnoreCase(modifiedWaypoint)) { // System.out.println("found matching lat/lon"); report.setLat(wpt.getLat()); report.setLon(wpt.getLon()); break; } } } // if coords still not found, try with mapped name if (report.getLat() == null) { String modifiedName = fixNames(report.getName()); for (WptType wpt : waypoints) { if (wpt.getName().equalsIgnoreCase(modifiedName)) { // System.out.println("found matching lat/lon"); report.setLat(wpt.getLat()); report.setLon(wpt.getLon()); break; } } } return report; } }
package net.sf.xenqtt.message; import java.nio.ByteBuffer; /** * A PUBLISH message is sent by a client to a server for distribution to interested subscribers. Each PUBLISH message is associated with a topic name (also * known as the Subject or Channel). This is a hierarchical name space that defines a taxonomy of information sources for which subscribers can register an * interest. A message that is published to a specific topic name is delivered to connected subscribers for that topic. * <p> * If a client subscribes to one or more topics, any message published to those topics are sent by the server to the client as a PUBLISH message. */ public final class PublishMessage extends MqttMessage { private int messageIdIndex = -1; /** * Used to construct a received message. */ public PublishMessage(ByteBuffer buffer, int remainingLength) { super(buffer, remainingLength); } /** * Used to construct a message for sending */ public PublishMessage(boolean duplicate, QoS qos, boolean retain, String topicName, int messageId, byte[] payload) { this(duplicate, qos, retain, stringToUtf8(topicName), messageId, payload); } /** * This must not contain Topic wildcard characters. * <p> * When received by a client that subscribed using wildcard characters, this string will be the absolute topic specified by the originating publisher and * not the subscription string used by the client. */ public String getTopicName() { return getString(fixedHeaderEndOffset); } /** * The message identifier is present in the variable header of the following MQTT messages: PUBLISH, PUBACK, PUBREC, PUBREL, PUBCOMP, SUBSCRIBE, SUBACK, * UNSUBSCRIBE, UNSUBACK. * <p> * The Message Identifier (Message ID) field is only present in messages where the QoS bits in the fixed header indicate QoS levels 1 or 2. See section on * Quality of Service levels and flows for more information. * <p> * The Message ID is a 16-bit unsigned integer that must be unique amongst the set of "in flight" messages in a particular direction of communication. It * typically increases by exactly one from one message to the next, but is not required to do so. * <p> * A client will maintain its own list of Message IDs separate to the Message IDs used by the server it is connected to. It is possible for a client to send * a PUBLISH with Message ID 1 at the same time as receiving a PUBLISH with Message ID 1. * <p> * Do not use Message ID 0. It is reserved as an invalid Message ID. */ public int getMessageId() { return buffer.getShort(getMessageIdIndex()) & 0xffff; } /** * Contains the data for publishing. The content and format of the data is application specific. It is valid for a PUBLISH to contain a 0-length payload. */ public byte[] getPayload() { int pos = buffer.position(); buffer.position(getMessageIdIndex() + 2); byte[] payload = new byte[buffer.limit() - buffer.position()]; buffer.get(payload); buffer.position(pos); return payload; } /** * Sets the message ID */ public void setMessageId(int messageId) { buffer.putShort(getMessageIdIndex(), (short) messageId); } private int getMessageIdIndex() { if (messageIdIndex == -1) { messageIdIndex = fixedHeaderEndOffset + 2 + (buffer.getShort(fixedHeaderEndOffset) & 0xffff); } return messageIdIndex; } private PublishMessage(boolean duplicate, QoS qos, boolean retain, byte[] topicNameUtf8, int messageId, byte[] payload) { super(MessageType.PUBLISH, duplicate, qos, retain, 2 + mqttStringSize(topicNameUtf8) + payload.length); putString(topicNameUtf8); buffer.putShort((short) messageId); buffer.put(payload); buffer.flip(); } }
package net.vexelon.bgrates.remote; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import com.google.common.base.Charsets; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.io.ByteStreams; import net.vexelon.bgrates.db.models.CurrencyData; import net.vexelon.bgrates.db.models.CurrencyLocales; import net.vexelon.bgrates.utils.IOUtils; public class BNBSource implements Source { // Addresses on BNB for get on XML file public final static String URL_BNB_FORMAT_BG = "http: public final static String URL_BNB_FORMAT_EN = "http: public final static String URL_BNB_INDEX = "http: public final static String URL_BNB_FIXED_RATES = "http: public final static String URI_CACHE_NAME_INDEXHTM = "BGRatesDownloadCacheHTM"; public final static String XML_TAG_ROWSET = "ROWSET"; public final static String XML_TAG_ROW = "ROW"; public final static String XML_TAG_GOLD = "GOLD"; public final static String XML_TAG_NAME = "NAME_"; public final static String XML_TAG_CODE = "CODE"; public final static String XML_TAG_RATIO = "RATIO"; public final static String XML_TAG_REVERSERATE = "REVERSERATE"; public final static String XML_TAG_RATE = "RATE"; public final static String XML_TAG_EXTRAINFO = "EXTRAINFO"; public final static String XML_TAG_CURR_DATE = "CURR_DATE"; public final static String XML_TAG_TITLE = "TITLE"; public final static String XML_TAG_F_STAR = "F_STAR"; private CurrencyData currencyData; private String text; public BNBSource() { } public List<CurrencyData> getRatesFromUrl(String ratesUrl) throws SourceException { List<CurrencyData> listCurrencyData = Lists.newArrayList(); InputStream is = null; XmlPullParserFactory factory = null; XmlPullParser parser = null; URL url = null; int header = 0; DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy"); Date currencyDate = new Date(); try { url = new URL(ratesUrl); URLConnection connection = url.openConnection(); connection.setDoInput(true); HttpURLConnection httpConn = (HttpURLConnection) connection; if (httpConn.getResponseCode() != HttpURLConnection.HTTP_OK) { // read error and throw it to caller is = httpConn.getErrorStream(); throw new SourceException(new String(ByteStreams.toByteArray(is), Charsets.UTF_8.name())); } is = httpConn.getInputStream(); // getEuroValue(); factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); parser = factory.newPullParser(); parser.setInput(is, Charsets.UTF_8.name()); int eventType = parser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { String tagname = parser.getName(); switch (eventType) { case XmlPullParser.START_TAG: if (tagname.equalsIgnoreCase(XML_TAG_ROW)) { if (header == 0) { header = 1; } else { header = 2; } // create a new instance of CurrencyData if (header > 1) { currencyData = new CurrencyData(); // defaults currencyData.setRate("0"); currencyData.setReverseRate("0"); } } break; case XmlPullParser.TEXT: if (header > 1) { text = parser.getText(); } break; case XmlPullParser.END_TAG: if (header > 1) { if (tagname.equalsIgnoreCase(XML_TAG_ROW)) { // add employee object to list listCurrencyData.add(currencyData); } else if (tagname.equalsIgnoreCase(XML_TAG_GOLD)) { currencyData.setGold(Integer.parseInt(text)); } else if (tagname.equalsIgnoreCase(XML_TAG_NAME)) { currencyData.setName(text); eventType = parser.next(); } else if (tagname.equalsIgnoreCase(XML_TAG_CODE)) { currencyData.setCode(text); } else if (tagname.equalsIgnoreCase(XML_TAG_RATIO)) { currencyData.setRatio(Integer.parseInt(text)); } else if (tagname.equalsIgnoreCase(XML_TAG_REVERSERATE)) { currencyData.setReverseRate(text); } else if (tagname.equalsIgnoreCase(XML_TAG_RATE)) { currencyData.setRate(text); } else if (tagname.equalsIgnoreCase(XML_TAG_EXTRAINFO)) { currencyData.setExtraInfo(text); } else if (tagname.equalsIgnoreCase(XML_TAG_CURR_DATE)) { try { currencyDate = dateFormat.parse(text); } catch (ParseException e1) { e1.printStackTrace(); // use default (today) currencyDate = new Date(); } currencyData.setCurrDate(currencyDate); } else if (tagname.equalsIgnoreCase(XML_TAG_TITLE)) { currencyData.setTitle(text); } else if (tagname.equalsIgnoreCase(XML_TAG_F_STAR)) { currencyData.setfStar(Integer.parseInt(text)); } } break; default: break; } eventType = parser.next(); } // setFixedCurrency(); // listCurrencyData.add(setEuroCurrency(localeName, currencyDate)); return listCurrencyData; } catch (Exception e) { throw new SourceException("Failed loading currencies from BNB source!", e); } finally { IOUtils.closeQuitely(is); } } private List<CurrencyData> getFixedRates(String language) throws SourceException { List<CurrencyData> listFixedCurrencyData = Lists.newArrayList(); CurrencyData fixedCurrencyData = new CurrencyData(); Date currentYear = getCurrentYear(); String fixedRatesUrl = URL_BNB_FIXED_RATES + language; InputStream is = null; try { URL url = new URL(fixedRatesUrl); URLConnection connection = url.openConnection(); connection.setDoInput(true); HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setRequestProperty("Cookie", "userLanguage=" + language); if (httpConn.getResponseCode() != HttpURLConnection.HTTP_OK) { // read error and throw it to caller is = httpConn.getErrorStream(); throw new SourceException(new String(ByteStreams.toByteArray(is), Charsets.UTF_8.name())); } is = httpConn.getInputStream(); Document doc = Jsoup.parse(is, Charsets.UTF_8.name(), fixedRatesUrl); // Element element = // doc.select("div#more_information > div.box > div.top > div > ul > li").first(); Element div = doc.select("div#content_box.content > div.doc_entry > div > table > tbody").first(); Elements divChildren = div.children(); int lineNumber = 1; for (Element table : divChildren) { if (lineNumber > 1) { // System.out.println(table.tagName()); Elements tableChildren = table.children(); int elementNumber = 1; fixedCurrencyData.setGold(1); fixedCurrencyData.setfStar(0); fixedCurrencyData.setCurrDate(currentYear); fixedCurrencyData.setIsFixed(true); for (Element elem : tableChildren) { // System.out.println(elem.tagName()); Element elemChild = elem.children().first(); // System.out.print(elemChild.text());// // elemChild.text() switch (elementNumber) { case 1: fixedCurrencyData.setName(elemChild.text()); break; case 2: fixedCurrencyData.setCode(elemChild.text()); break; case 3: fixedCurrencyData.setRatio(Integer.parseInt(elemChild.text())); break; case 4: fixedCurrencyData.setRate(elemChild.text()); break; case 5: fixedCurrencyData.setReverseRate(elemChild.text()); break; } elementNumber++; } listFixedCurrencyData.add(fixedCurrencyData); fixedCurrencyData = new CurrencyData(); } lineNumber++; } System.out.println(listFixedCurrencyData); // Element euroValue = element.getElementsByTag("strong").first(); // String euroValuReturn = euroValue.text(); return listFixedCurrencyData; } catch (Exception e) { throw new SourceException("Failed loading currencies from BNB source!", e); } finally { IOUtils.closeQuitely(is); } } private Date getCurrentYear() { int year = Calendar.getInstance().get(Calendar.YEAR); SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy"); String dateInString = "01.01." + year; Date currentYear = null; try { currentYear = sdf.parse(dateInString); System.out.print(currentYear); } catch (ParseException e1) { e1.printStackTrace(); // use default (today) } return currentYear; } @Deprecated private CurrencyData setEuroCurrency(CurrencyLocales currencyName, Date currencyDate) throws SourceException { CurrencyData euroValue = new CurrencyData(); String euro = getEuroValue(); euroValue.setGold(1); if (currencyName == CurrencyLocales.BG) { euroValue.setName("Евро"); } else { euroValue.setName("Euro"); } euroValue.setCode("EUR"); euroValue.setRatio(1); euroValue.setReverseRate("0.511292"); // TODO parse from webpage euroValue.setRate(euro.substring(0, 7)); euroValue.setCurrDate(currencyDate); euroValue.setfStar(0); return euroValue; } private String getEuroValue() throws SourceException { InputStream is = null; URL url = null; try { url = new URL(URL_BNB_INDEX); URLConnection connection = url.openConnection(); connection.setDoInput(true); HttpURLConnection httpConn = (HttpURLConnection) connection; if (httpConn.getResponseCode() != HttpURLConnection.HTTP_OK) { // read error and throw it to caller is = httpConn.getErrorStream(); throw new SourceException(new String(ByteStreams.toByteArray(is), Charsets.UTF_8.name())); } is = httpConn.getInputStream(); Document doc = Jsoup.parse(is, Charsets.UTF_8.name(), URL_BNB_INDEX); Element element = doc.select("div#more_information > div.box > div.top > div > ul > li").first(); Element euroValue = element.getElementsByTag("strong").first(); // String euroValuReturn = euroValue.text(); return euroValue.text(); } catch (Exception e) { throw new SourceException("Failed loading currencies from BNB source!", e); } finally { IOUtils.closeQuitely(is); } } @Override public Map<CurrencyLocales, List<CurrencyData>> downloadRates(boolean getFixedRates) throws SourceException { Map<CurrencyLocales, List<CurrencyData>> result = Maps.newHashMap(); List<CurrencyData> ratesEN = getRatesFromUrl(URL_BNB_FORMAT_EN); if (getFixedRates) { ratesEN.addAll(getFixedRates("EN")); } result.put(CurrencyLocales.EN, ratesEN); List<CurrencyData> ratesBG = getRatesFromUrl(URL_BNB_FORMAT_BG); if (getFixedRates) { ratesBG.addAll(getFixedRates("BG")); } result.put(CurrencyLocales.BG, ratesBG); return result; } }
package net.zero918nobita.Xemime.entity; import net.zero918nobita.Xemime.NodeType; import net.zero918nobita.Xemime.ast.FatalException; import net.zero918nobita.Xemime.ast.Node; public class Bool extends Node { private boolean bool; public static Bool T = new Bool(true); public static Bool Nil = new Bool(false); public Bool(int location, boolean bool) { super(location); this.bool = bool; } @Override public NodeType recognize() { return NodeType.BOOL; } public Bool(boolean bool) { this(0, bool); } @Override public String toString() { return (bool) ? "T" : "NIL"; } @Override public boolean equals(Object obj) { return (obj instanceof Bool) && (((Bool)obj).isTrue() == this.bool); } public boolean isTrue() { return bool; } @Override public Bool and(int location, Node rhs) throws FatalException { if (rhs instanceof Bool) return (bool && (((Bool)rhs).isTrue())) ? Bool.T : Bool.Nil; else throw new FatalException(location, 117); } @Override public Bool or(int location, Node rhs) throws FatalException { if (rhs instanceof Bool) return (bool || (((Bool) rhs).isTrue())) ? Bool.T : Bool.Nil; else throw new FatalException(location, 118); } @Override public Bool xor(int location, Node rhs) throws FatalException { if (rhs instanceof Bool) return (bool ^ (((Bool) rhs).isTrue())) ? Bool.T : Bool.Nil; else throw new FatalException(location, 119); } }
package nl.homeserver.klimaat; import static java.lang.String.format; import static java.math.BigDecimal.ZERO; import static java.math.RoundingMode.HALF_UP; import static java.time.LocalDateTime.now; import static java.util.Comparator.comparing; import static java.util.stream.Collectors.toList; import static nl.homeserver.DatePeriod.aPeriodWithToDate; import java.math.BigDecimal; import java.time.Clock; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Month; import java.time.Year; import java.time.YearMonth; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.IntStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import nl.homeserver.DatePeriod; @Service public class KlimaatService { private static final Logger LOGGER = LoggerFactory.getLogger(KlimaatService.class); protected static final String REALTIME_KLIMAAT_TOPIC = "/topic/klimaat"; private static final int NR_OF_MINUTES_TO_DETERMINE_TREND_FOR = 18; private static final int NR_OF_MINUTES_TO_SAVE_AVERAGE_KLIMAAT_FOR = 15; private static final String EVERY_15_MINUTES_PAST_THE_HOUR = "0 0/" + NR_OF_MINUTES_TO_SAVE_AVERAGE_KLIMAAT_FOR + " * * * ?"; private static final int TEMPERATURE_SCALE = 2; private static final int HUMIDITY_SCALE = 1; private final Map<String, List<Klimaat>> recentlyReceivedKlimaatsPerKlimaatSensorCode = new ConcurrentHashMap<>(); @Autowired private KlimaatService klimaatServiceProxyWithEnabledCaching; // Needed to make use of use caching annotations private final KlimaatRepos klimaatRepository; private final KlimaatSensorRepository klimaatSensorRepository; private final KlimaatSensorValueTrendService klimaatSensorValueTrendService; private final SimpMessagingTemplate messagingTemplate; private final Clock clock; public KlimaatService(KlimaatRepos klimaatRepository, KlimaatSensorRepository klimaatSensorRepository, KlimaatSensorValueTrendService klimaatSensorValueTrendService, SimpMessagingTemplate messagingTemplate, Clock clock) { this.klimaatRepository = klimaatRepository; this.klimaatSensorRepository = klimaatSensorRepository; this.klimaatSensorValueTrendService = klimaatSensorValueTrendService; this.messagingTemplate = messagingTemplate; this.clock = clock; } private void cleanUpRecentlyReceivedKlimaatsPerSensorCode() { int maxNrOfMinutes = IntStream.of(NR_OF_MINUTES_TO_DETERMINE_TREND_FOR, NR_OF_MINUTES_TO_SAVE_AVERAGE_KLIMAAT_FOR).max().getAsInt(); LocalDateTime cleanUpAllBefore = now(clock).minusMinutes(maxNrOfMinutes); LOGGER.info("cleanUpRecentlyReceivedKlimaats before {}", cleanUpAllBefore); recentlyReceivedKlimaatsPerKlimaatSensorCode.values().forEach(klimaats -> klimaats.removeIf(klimaat -> klimaat.getDatumtijd().isBefore(cleanUpAllBefore))); } @Scheduled(cron = EVERY_15_MINUTES_PAST_THE_HOUR) public void save() { LocalDateTime referenceDateTime = now(clock).truncatedTo(ChronoUnit.MINUTES); recentlyReceivedKlimaatsPerKlimaatSensorCode .forEach((klimaatSensorCode, klimaats) -> this.saveKlimaatWithAveragedRecentSensorValues(referenceDateTime, klimaatSensorCode)); } private void saveKlimaatWithAveragedRecentSensorValues(LocalDateTime referenceDateTime, String klimaatSensorCode) { List<Klimaat> klimaatsReceivedInLastNumberOfMinutes = getKlimaatsReceivedInLastNumberOfMinutes(klimaatSensorCode, NR_OF_MINUTES_TO_SAVE_AVERAGE_KLIMAAT_FOR); List<BigDecimal> validTemperaturesFromLastQuarter = getValidTemperatures(klimaatsReceivedInLastNumberOfMinutes); List<BigDecimal> validHumiditiesFromLastQuarter = getValidHumidities(klimaatsReceivedInLastNumberOfMinutes); KlimaatSensor klimaatSensor = getOrCreateIfNonExists(klimaatSensorCode); BigDecimal averageTemperature = getAverage(validTemperaturesFromLastQuarter); if (averageTemperature != null) { averageTemperature = averageTemperature.setScale(TEMPERATURE_SCALE, HALF_UP); } BigDecimal averageHumidity = getAverage(validHumiditiesFromLastQuarter); if (averageHumidity != null) { averageHumidity = averageHumidity.setScale(HUMIDITY_SCALE, HALF_UP); } if (averageTemperature != null || averageHumidity != null) { Klimaat klimaatToSave = new Klimaat(); klimaatToSave.setDatumtijd(referenceDateTime); klimaatToSave.setTemperatuur(averageTemperature); klimaatToSave.setLuchtvochtigheid(averageHumidity); klimaatToSave.setKlimaatSensor(klimaatSensor); klimaatRepository.save(klimaatToSave); } } private List<Klimaat> getKlimaatsReceivedInLastNumberOfMinutes(String klimaatSensorCode, int nrOfMinutes) { LocalDateTime from = now(clock).minusMinutes(nrOfMinutes); return recentlyReceivedKlimaatsPerKlimaatSensorCode.getOrDefault(klimaatSensorCode, new ArrayList<>()).stream() .filter(klimaat -> klimaat.getDatumtijd().isAfter(from)) .collect(toList()); } private BigDecimal getAverage(List<BigDecimal> decimals) { BigDecimal average = null; if (!decimals.isEmpty()) { BigDecimal total = decimals.stream().reduce(ZERO, BigDecimal::add); average = total.divide(BigDecimal.valueOf(decimals.size()), HALF_UP); } return average; } private KlimaatSensor getOrCreateIfNonExists(String klimaatSensorCode) { return klimaatSensorRepository.findFirstByCode(klimaatSensorCode) .orElseGet(() -> createKlimaatSensor(klimaatSensorCode)); } private KlimaatSensor createKlimaatSensor(String klimaatSensorCode) { KlimaatSensor klimaatSensor = new KlimaatSensor(); klimaatSensor.setCode(klimaatSensorCode); return klimaatSensorRepository.save(klimaatSensor); } public List<Klimaat> getInPeriod(String klimaatSensorCode, DatePeriod period) { LocalDate today = LocalDate.now(clock); if (period.getEndDate().isBefore(today)) { return klimaatServiceProxyWithEnabledCaching.getPotentiallyCachedAllInPeriod(klimaatSensorCode, period); } else { return this.getNotCachedAllInPeriod(klimaatSensorCode, period); } } private BigDecimal getAverage(String sensorCode, SensorType sensorType, DatePeriod period) { if (sensorType == SensorType.TEMPERATUUR) { return klimaatRepository.getAverageTemperatuur(sensorCode, period.getFromDate().atStartOfDay(), period.getToDate().atStartOfDay()); } else if (sensorType == SensorType.LUCHTVOCHTIGHEID) { return klimaatRepository.getAverageLuchtvochtigheid(sensorCode, period.getFromDate().atStartOfDay(), period.getToDate().atStartOfDay()); } else { throw new IllegalArgumentException(createUnexpectedSensorTypeErrorMessage(sensorType)); } } public RealtimeKlimaat getMostRecent(String klimaatSensorCode) { List<Klimaat> recentlyReceivedKlimaatForSensor = recentlyReceivedKlimaatsPerKlimaatSensorCode.getOrDefault(klimaatSensorCode, new ArrayList<>()); return getMostRecent(recentlyReceivedKlimaatForSensor).map(this::mapToRealtimeKlimaat) .orElse(null); } private Optional<Klimaat> getMostRecent(List<Klimaat> klimaats) { return klimaats.stream().max(comparing(Klimaat::getDatumtijd)); } public void add(Klimaat klimaat) { publishEvent(klimaat); recentlyReceivedKlimaatsPerKlimaatSensorCode.computeIfAbsent(klimaat.getKlimaatSensor().getCode(), klimaatSensorCode -> new ArrayList<>()).add(klimaat); cleanUpRecentlyReceivedKlimaatsPerSensorCode(); } public List<List<GemiddeldeKlimaatPerMaand>> getAveragePerMonthInYears(String sensorCode, SensorType sensorType, int[] years) { return IntStream.of(years) .mapToObj(Year::of) .map(year -> getAveragePerMonthInYear(sensorCode, sensorType, year)) .collect(toList()); } private List<GemiddeldeKlimaatPerMaand> getAveragePerMonthInYear(String sensorCode, SensorType sensorType, Year year) { return IntStream.rangeClosed(1, Month.values().length) .mapToObj(maand -> getAverageInMonthOfYear(sensorCode, sensorType, YearMonth.of(year.getValue(), maand))) .collect(toList()); } private GemiddeldeKlimaatPerMaand getAverageInMonthOfYear(String sensorCode, SensorType sensorType, YearMonth yearMonth) { LocalDate from = yearMonth.atDay(1); LocalDate to = from.plusMonths(1); DatePeriod period = aPeriodWithToDate(from, to); return new GemiddeldeKlimaatPerMaand(from, getAverage(sensorCode, sensorType, period)); } private List<BigDecimal> getValidHumidities(List<Klimaat> klimaatList) { return klimaatList.stream() .filter(klimaat -> klimaat.getLuchtvochtigheid() != null && klimaat.getLuchtvochtigheid().compareTo(ZERO) != 0) .map(Klimaat::getLuchtvochtigheid) .collect(toList()); } private List<BigDecimal> getValidTemperatures(List<Klimaat> klimaatList) { return klimaatList.stream() .filter(klimaat -> klimaat.getTemperatuur() != null && klimaat.getTemperatuur().compareTo(ZERO) != 0) .map(Klimaat::getTemperatuur) .collect(toList()); } public List<Klimaat> getHighest(String sensorCode, SensorType sensorType, DatePeriod period, int limit) { switch (sensorType) { case TEMPERATUUR: return getHighestTemperature(sensorCode, period, limit); case LUCHTVOCHTIGHEID: return getHighestHumidity(sensorCode, period, limit); default: throw new IllegalArgumentException(createUnexpectedSensorTypeErrorMessage(sensorType)); } } public List<Klimaat> getLowest(String sensorCode, SensorType sensorType, DatePeriod period, int limit) { switch (sensorType) { case TEMPERATUUR: return getLowestTemperature(sensorCode, period, limit); case LUCHTVOCHTIGHEID: return getLowestHumidity(sensorCode, period, limit); default: throw new IllegalArgumentException(createUnexpectedSensorTypeErrorMessage(sensorType)); } } private String createUnexpectedSensorTypeErrorMessage(SensorType sensorType) { return format("Unexpected SensorType [%s]", sensorType); } private List<Klimaat> getLowestTemperature(String sensorCode, DatePeriod period, int limit) { return klimaatRepository.getPeakLowTemperatureDates(sensorCode, period.getFromDate(), period.getToDate(), limit) .stream() .map(java.sql.Date::toLocalDate) .map(day -> klimaatRepository.earliestLowestTemperatureOnDay(sensorCode, day)) .collect(toList()); } private List<Klimaat> getLowestHumidity(String sensorCode, DatePeriod period, int limit) { return klimaatRepository.getPeakLowHumidityDates(sensorCode, period.getFromDate(), period.getToDate(), limit) .stream() .map(java.sql.Date::toLocalDate) .map(day -> klimaatRepository.earliestLowestHumidityOnDay(sensorCode, day)) .collect(toList()); } private List<Klimaat> getHighestTemperature(String sensorCode, DatePeriod period, int limit) { return klimaatRepository.getPeakHighTemperatureDates(sensorCode, period.getFromDate(), period.getToDate(), limit) .stream() .map(java.sql.Date::toLocalDate) .map(day -> klimaatRepository.earliestHighestTemperatureOnDay(sensorCode, day)) .collect(toList()); } private List<Klimaat> getHighestHumidity(String sensorCode, DatePeriod period, int limit) { return klimaatRepository.getPeakHighHumidityDates(sensorCode, period.getFromDate(), period.getToDate(), limit) .stream() .map(java.sql.Date::toLocalDate) .map(day -> klimaatRepository.earliestHighestHumidityOnDay(sensorCode, day)) .collect(toList()); } private void publishEvent(Klimaat klimaat) { RealtimeKlimaat realtimeKlimaat = mapToRealtimeKlimaat(klimaat); messagingTemplate.convertAndSend(REALTIME_KLIMAAT_TOPIC, realtimeKlimaat); } private RealtimeKlimaat mapToRealtimeKlimaat(Klimaat klimaat) { RealtimeKlimaat realtimeKlimaat = new RealtimeKlimaat(); realtimeKlimaat.setDatumtijd(klimaat.getDatumtijd()); realtimeKlimaat.setLuchtvochtigheid(klimaat.getLuchtvochtigheid()); realtimeKlimaat.setTemperatuur(klimaat.getTemperatuur()); List<Klimaat> klimaatsToDetermineTrendFor = getKlimaatsReceivedInLastNumberOfMinutes(klimaat.getKlimaatSensor().getCode(), NR_OF_MINUTES_TO_DETERMINE_TREND_FOR); realtimeKlimaat.setTemperatuurTrend(klimaatSensorValueTrendService.determineValueTrend(klimaatsToDetermineTrendFor, Klimaat::getTemperatuur)); realtimeKlimaat.setLuchtvochtigheidTrend(klimaatSensorValueTrendService.determineValueTrend(klimaatsToDetermineTrendFor, Klimaat::getLuchtvochtigheid)); return realtimeKlimaat; } private List<Klimaat> getNotCachedAllInPeriod(String klimaatSensorCode, DatePeriod period) { return klimaatRepository.findByKlimaatSensorCodeAndDatumtijdBetweenOrderByDatumtijd(klimaatSensorCode, period.toDateTimePeriod().getFromDateTime(), period.toDateTimePeriod().getEndDateTime()); } @Cacheable(cacheNames = "klimaatInPeriod") public List<Klimaat> getPotentiallyCachedAllInPeriod(String klimaatSensorCode, DatePeriod period) { return klimaatRepository.findByKlimaatSensorCodeAndDatumtijdBetweenOrderByDatumtijd(klimaatSensorCode, period.toDateTimePeriod().getFromDateTime(), period.toDateTimePeriod().getEndDateTime()); } public Optional<KlimaatSensor> getKlimaatSensorByCode(String klimaatSensorCode) { return klimaatSensorRepository.findFirstByCode(klimaatSensorCode); } public List<KlimaatSensor> getAllKlimaatSensors() { return klimaatSensorRepository.findAll(); } }
package org.arachb.owlbuilder.lib; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.semanticweb.owlapi.model.IRI; /** * Utility class for OWL IRI constants * @author pmidford * */ public class Vocabulary { private Vocabulary() {} // prevent instantiation public static final IRI pubAboutInvestigation = IRI.create("http://purl.obolibrary.org/obo/IAO_0000312"); public static final IRI denotesProperty = IRI.create("http://purl.obolibrary.org/obo/IAO_0000219"); public static final IRI informationContentEntity = IRI.create("http://purl.obolibrary.org/obo/IAO_0000030"); public static final IRI textualEntity = IRI.create("http://purl.obolibrary.org/obo/IAO_0000300"); private static final Set<IRI> iaoImports_mod = new HashSet<IRI>(); static { iaoImports_mod.add(pubAboutInvestigation); iaoImports_mod.add(denotesProperty); iaoImports_mod.add(informationContentEntity); } public static final Set<IRI> iaoImports = Collections.unmodifiableSet(iaoImports_mod); public static final IRI partOfProperty = IRI.create("http://purl.obolibrary.org/obo/BFO_0000050"); // Suppress hasPart - current ontology set allows some reasoners to actually // equate this with its inverse. Predictable stupidity ensues. // public static final IRI hasPartProperty = public static final IRI participatesInProperty = IRI.create("http://purl.obolibrary.org/obo/RO_0000056"); public static final IRI hasParticipantProperty = IRI.create("http://purl.obolibrary.org/obo/RO_0000057"); public static final IRI hasActiveParticipantProperty = IRI.create("http://purl.obolibrary.org/obo/RO_0002218"); public static final IRI hasParticipantAtSomeTimeProperty = IRI.create("http://purl.obolibrary.org/obo/BFO_0000057"); public static final IRI overlapsProperty = IRI.create("http://purl.obolibrary.org/obo/BFO_0002131"); public static final IRI activelyParticipatesInProperty = IRI.create("http://purl.obolibrary.org/obo/RO_0002217"); public static final IRI mereotopologicallyRelatedToProperty = IRI.create("http://purl.obolibrary.org/obo/BFO_0002323"); public static final IRI hasMaterialContributionProperty = IRI.create("http://purl.obolibrary.org/obo/RO_0002507"); public static final IRI determinesProperty = IRI.create("http://purl.obolibrary.org/obo/RO_0002508"); private static final Set<IRI> bfoImports_mod = new HashSet<IRI>(); static { bfoImports_mod.add(partOfProperty); bfoImports_mod.add(hasParticipantProperty); } public static final Set<IRI> bfoImports = Collections.unmodifiableSet(bfoImports_mod); public static final IRI arachnidaTaxon = IRI.create("http://purl.obolibrary.org/obo/NCBITaxon_6854"); }
package org.basex.gui.view.xquery; import static org.basex.core.Text.*; import static org.basex.gui.GUIConstants.*; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; import javax.swing.Box; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import org.basex.data.Nodes; import org.basex.gui.GUICommands; import org.basex.gui.GUIConstants; import org.basex.gui.GUIProp; import org.basex.gui.GUIConstants.Fill; import org.basex.gui.dialog.Dialog; import org.basex.gui.layout.BaseXBack; import org.basex.gui.layout.BaseXButton; import org.basex.gui.layout.BaseXLabel; import org.basex.gui.layout.BaseXLayout; import org.basex.gui.layout.BaseXTextField; import org.basex.gui.layout.TableLayout; import org.basex.gui.view.View; import org.basex.gui.view.ViewNotifier; import org.basex.io.IO; import org.basex.util.Util; public final class XQueryView extends View { /** Execute Button. */ final BaseXButton stop; /** Info label. */ final BaseXLabel info; /** Text Area. */ final XQueryText text; /** Modified flag. */ boolean modified; /** Header string. */ final BaseXLabel header; /** Scroll Pane. */ private final BaseXBack south; /** Execute button. */ private final BaseXButton go; /** Filter button. */ private final BaseXButton filter; /** * Default constructor. * @param man view manager */ public XQueryView(final ViewNotifier man) { super(XQUERYVIEW, HELPXQUERYY, man); setLayout(new BorderLayout()); setBorder(6, 8, 8, 8); setFocusable(false); header = new BaseXLabel(XQUERYTIT, true, false); final BaseXBack b = new BaseXBack(Fill.NONE); b.setLayout(new BorderLayout()); b.add(header, BorderLayout.CENTER); final BaseXButton open = BaseXButton.command(GUICommands.XQOPEN, gui); // hidden buttons for actions final BaseXButton hsave = BaseXButton.command(GUICommands.XQSAVE, gui); final BaseXButton hsaveAs = BaseXButton.command(GUICommands.XQSAVEAS, gui); final BaseXButton save = new BaseXButton(gui, "xqsaveas", HELPSAVE); save.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final JPopupMenu popup = new JPopupMenu(GUISAVE); final ActionListener al = new ActionListener() { @Override public void actionPerformed(final ActionEvent ac) { if(ac.getActionCommand().equals(GUISAVE)) { hsave.doClick(); } else { hsaveAs.doClick(); } } }; final JMenuItem saving = new JMenuItem(GUISAVE); final JMenuItem saveAs = new JMenuItem(GUISAVEAS + DOTS); saving.addActionListener(al); saveAs.addActionListener(al); popup.add(saving); popup.add(saveAs); popup.show(save, 0, save.getHeight()); } }); final BaseXTextField find = new BaseXTextField(gui); BaseXLayout.setHeight(find, (int) open.getPreferredSize().getHeight()); final BaseXButton hist = new BaseXButton(gui, "hist", HELPRECENT); hist.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final JPopupMenu popup = new JPopupMenu("History"); final ActionListener al = new ActionListener() { @Override public void actionPerformed(final ActionEvent ac) { confirm(); setQuery(IO.get(ac.getActionCommand())); } }; if(gui.prop.strings(GUIProp.QUERIES).length == 0) { popup.add(new JMenuItem("- No recently opened files -")); } for(final String en : gui.prop.strings(GUIProp.QUERIES)) { final JMenuItem jmi = new JMenuItem(en); jmi.addActionListener(al); popup.add(jmi); } popup.show(hist, 0, hist.getHeight()); } }); final BaseXButton close = new BaseXButton(gui, "close", HELPQCLOSE); close.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { if(header.getText().endsWith("*")) { if (Dialog.confirm(gui, Util.info( XQUERYCONF, gui.context.query.name()))) hsave.doClick(); } text.setText(new byte[0]); header.setText(XQUERYTIT); gui.context.query = null; } }); BaseXBack sp = new BaseXBack(Fill.NONE); sp.setLayout(new TableLayout(1, 9)); sp.add(find); sp.add(Box.createHorizontalStrut(5)); sp.add(open); sp.add(Box.createHorizontalStrut(1)); sp.add(save); sp.add(Box.createHorizontalStrut(1)); sp.add(hist); sp.add(Box.createHorizontalStrut(1)); sp.add(close); b.add(sp, BorderLayout.EAST); add(b, BorderLayout.NORTH); text = new XQueryText(this); add(text, BorderLayout.CENTER); text.addSearch(find); south = new BaseXBack(Fill.NONE); south.setLayout(new BorderLayout()); info = new BaseXLabel(" "); info.setCursor(GUIConstants.CURSORHAND); info.setText(OK, Msg.SUCCESS); info.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(final MouseEvent e) { if(info.getName() == null) return; text.setCaret(Integer.parseInt(info.getName())); text.requestFocusInWindow(); } }); south.add(info, BorderLayout.CENTER); stop = new BaseXButton(gui, "stop", HELPSTOP); stop.addKeyListener(this); stop.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { stop.setEnabled(false); gui.stop(); } }); stop.setEnabled(false); go = new BaseXButton(gui, "go", HELPGO); go.addKeyListener(this); go.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { text.query(); } }); filter = BaseXButton.command(GUICommands.FILTER, gui); filter.addKeyListener(this); sp = new BaseXBack(Fill.NONE); sp.setLayout(new TableLayout(1, 5)); sp.setBorder(4, 0, 0, 0); sp.add(stop); sp.add(Box.createHorizontalStrut(1)); sp.add(go); sp.add(Box.createHorizontalStrut(1)); sp.add(filter); south.add(sp, BorderLayout.EAST); add(south, BorderLayout.SOUTH); refreshLayout(); } @Override public void refreshInit() { } @Override public void refreshFocus() { } @Override public void refreshMark() { go.setEnabled(!gui.prop.is(GUIProp.EXECRT)); final Nodes marked = gui.context.marked; filter.setEnabled(!gui.prop.is(GUIProp.FILTERRT) && marked != null && marked.size() != 0); } @Override public void refreshContext(final boolean more, final boolean quick) { } @Override public void refreshLayout() { header.setFont(GUIConstants.lfont); text.setFont(GUIConstants.mfont); refreshMark(); } @Override public void refreshUpdate() { } @Override public boolean visible() { return gui.prop.is(GUIProp.SHOWXQUERY); } @Override public void visible(final boolean v) { gui.prop.set(GUIProp.SHOWXQUERY, v); } @Override protected boolean db() { return false; } /** * Sets a new query file. * @param file query file */ public void setQuery(final IO file) { gui.prop.files(file); gui.context.query = file; try { if(!visible()) GUICommands.SHOWXQUERY.execute(gui); modified(false, true); final byte[] query = file.content(); text.setText(query); if(gui.prop.is(GUIProp.EXECRT)) text.query(); } catch(final IOException ex) { Dialog.error(gui, NOTOPENED); } } /** * Returns the last XQuery input. * @return XQuery */ public byte[] getQuery() { modified(false, true); return text.getText(); } /** * Handles info messages resulting from a query execution. * @param inf info message * @param ok true if query was successful */ public void info(final String inf, final boolean ok) { final int error = text.error(inf, ok); info.setName(error != -1 ? Integer.toString(error) : null); info.setCursor(error != -1 ? GUIConstants.CURSORHAND : GUIConstants.CURSORARROW); info.setText(ok ? OK : inf.replaceAll(STOPPED + ".*\\r?\\n", ""), ok ? Msg.SUCCESS : Msg.ERROR); info.setToolTipText(ok ? null : inf); stop.setEnabled(false); } /** * Shows a quit dialog for saving the opened XQuery. */ public void confirm() { if(gui.context.query != null && modified && Dialog.confirm(gui, Util.info( XQUERYCONF, gui.context.query.name()))) GUICommands.XQSAVE.execute(gui); } /** * Returns the modified flag. * @return modified flag */ public boolean modified() { return modified; } /** * Sets the query modification flag. * @param mod modification flag * @param force action */ void modified(final boolean mod, final boolean force) { if(modified != mod || force) { String title = XQUERYTIT; if(gui.context.query != null) { title += " - " + gui.context.query.name(); if(mod) title += "*"; } header.setText(title); modified = mod; gui.refreshControls(); } } }
package org.concord.energy3d.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.HierarchyBoundsAdapter; import java.awt.event.HierarchyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.concurrent.CancellationException; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.SpinnerDateModel; import javax.swing.SpinnerNumberModel; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.concord.energy3d.model.Door; import org.concord.energy3d.model.Floor; import org.concord.energy3d.model.Foundation; import org.concord.energy3d.model.HousePart; import org.concord.energy3d.model.Roof; import org.concord.energy3d.model.SolarPanel; import org.concord.energy3d.model.Tree; import org.concord.energy3d.scene.Scene; import org.concord.energy3d.scene.SceneManager; import org.concord.energy3d.shapes.Heliodon; import org.concord.energy3d.simulation.CityData; import org.concord.energy3d.simulation.Cost; import org.concord.energy3d.simulation.HeatLoad; import org.concord.energy3d.simulation.SolarIrradiation; import org.concord.energy3d.util.Util; import com.ardor3d.math.ColorRGBA; import com.ardor3d.math.type.ReadOnlyColorRGBA; public class EnergyPanel extends JPanel { public static final ReadOnlyColorRGBA[] solarColors = { ColorRGBA.BLUE, ColorRGBA.GREEN, ColorRGBA.YELLOW, ColorRGBA.RED }; private static final long serialVersionUID = 1L; private static final EnergyPanel instance = new EnergyPanel(); private final DecimalFormat twoDecimals = new DecimalFormat(); private final DecimalFormat noDecimals = new DecimalFormat(); private static boolean keepHeatmapOn = false; public enum UpdateRadiation { ALWAYS, ONLY_IF_SLECTED_IN_GUI }; private final JComboBox<String> wallsComboBox; private final JComboBox<String> doorsComboBox; private final JComboBox<String> windowsComboBox; private final JComboBox<String> roofsComboBox; private final JComboBox<String> cityComboBox; private final JComboBox<String> solarPanelEfficiencyComboBox; private final JComboBox<String> windowSHGCComboBox; private final JTextField heatingTodayTextField; private final JTextField coolingTodayTextField; private final JTextField totalTodayTextField; private final JSpinner insideTemperatureSpinner; private final JSpinner outsideTemperatureSpinner; private final JLabel dateLabel; private final JLabel timeLabel; private final JSpinner dateSpinner; private final JSpinner timeSpinner; private final JLabel latitudeLabel; private final JSpinner latitudeSpinner; private final JPanel heatMapPanel; private final JSlider colorMapSlider; private final JProgressBar progressBar; private final ColorBar costBar; private final JPanel costPanel; private Thread thread; private boolean computeRequest; private boolean disableActions = false; private boolean alreadyRenderedHeatmap = false; private UpdateRadiation updateRadiation; private boolean computeEnabled = true; private final List<PropertyChangeListener> propertyChangeListeners = Collections.synchronizedList(new ArrayList<PropertyChangeListener>()); private JPanel partPanel; private JLabel partEnergyLabel; private JTextField partEnergyTextField; private JPanel buildingPanel; private JPanel geometryPanel; private JLabel lblPosition; private JTextField positionTextField; private JLabel lblArea; private JTextField areaTextField; private JLabel lblHeight; private JTextField heightTextField; private JLabel lblVolume; private JTextField volumnTextField; private JTextField passiveSolarTextField; private JTextField photovoltaicTextField; private JPanel partPropertiesPanel; private JLabel lblWidth; private JTextField partWidthTextField; private JLabel lblHeight_1; private JTextField partHeightTextField; public static EnergyPanel getInstance() { return instance; } private EnergyPanel() { twoDecimals.setMaximumFractionDigits(2); noDecimals.setMaximumFractionDigits(0); setLayout(new BorderLayout()); final JPanel dataPanel = new JPanel(); dataPanel.setLayout(new BoxLayout(dataPanel, BoxLayout.Y_AXIS)); add(new JScrollPane(dataPanel), BorderLayout.CENTER); final JPanel timeAndLocationPanel = new JPanel(); timeAndLocationPanel.setToolTipText("<html>The outside temperature and the sun path<br>differ from time to time and from location to location.</html>"); timeAndLocationPanel.setBorder(new TitledBorder(null, "Time & Location", TitledBorder.LEADING, TitledBorder.TOP)); dataPanel.add(timeAndLocationPanel); final GridBagLayout gbl_panel_3 = new GridBagLayout(); timeAndLocationPanel.setLayout(gbl_panel_3); dateLabel = new JLabel("Date: "); final GridBagConstraints gbc_dateLabel = new GridBagConstraints(); gbc_dateLabel.gridx = 0; gbc_dateLabel.gridy = 0; timeAndLocationPanel.add(dateLabel, gbc_dateLabel); dateSpinner = new JSpinner(); dateSpinner.setModel(new SpinnerDateModel(new Date(1380427200000L), null, null, Calendar.MONTH)); dateSpinner.setEditor(new JSpinner.DateEditor(dateSpinner, "MMMM dd")); dateSpinner.addHierarchyBoundsListener(new HierarchyBoundsAdapter() { @Override public void ancestorResized(final HierarchyEvent e) { dateSpinner.setMinimumSize(dateSpinner.getPreferredSize()); dateSpinner.setPreferredSize(dateSpinner.getPreferredSize()); dateSpinner.removeHierarchyBoundsListener(this); } }); dateSpinner.addChangeListener(new ChangeListener() { boolean firstCall = true; @Override public void stateChanged(final ChangeEvent e) { if (firstCall) { firstCall = false; return; } if (disableActions) return; final Heliodon heliodon = Heliodon.getInstance(); if (heliodon != null) heliodon.setDate((Date) dateSpinner.getValue()); compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); Scene.getInstance().setEdited(true); Scene.getInstance().redrawAllNow(); // XIE: 4/11: This needs to be called for trees to have the right seasonal texture } }); final GridBagConstraints gbc_dateSpinner = new GridBagConstraints(); gbc_dateSpinner.insets = new Insets(0, 0, 1, 1); gbc_dateSpinner.gridx = 1; gbc_dateSpinner.gridy = 0; timeAndLocationPanel.add(dateSpinner, gbc_dateSpinner); cityComboBox = new JComboBox<String>(); cityComboBox.setModel(new DefaultComboBoxModel<String>(CityData.getInstance().getCities())); cityComboBox.setSelectedItem("Boston"); cityComboBox.setMaximumRowCount(15); cityComboBox.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent e) { if (cityComboBox.getSelectedItem().equals("")) compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); else { final Integer newLatitude = CityData.getInstance().getCityLatitutes().get(cityComboBox.getSelectedItem()); if (newLatitude.equals(latitudeSpinner.getValue())) compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); else latitudeSpinner.setValue(newLatitude); } Scene.getInstance().setEdited(true); } }); final GridBagConstraints gbc_cityComboBox = new GridBagConstraints(); gbc_cityComboBox.gridwidth = 2; gbc_cityComboBox.fill = GridBagConstraints.HORIZONTAL; gbc_cityComboBox.gridx = 2; gbc_cityComboBox.gridy = 0; timeAndLocationPanel.add(cityComboBox, gbc_cityComboBox); timeLabel = new JLabel("Time: "); final GridBagConstraints gbc_timeLabel = new GridBagConstraints(); gbc_timeLabel.gridx = 0; gbc_timeLabel.gridy = 1; timeAndLocationPanel.add(timeLabel, gbc_timeLabel); timeSpinner = new JSpinner(new SpinnerDateModel()); timeSpinner.setEditor(new JSpinner.DateEditor(timeSpinner, "H:mm")); timeSpinner.addChangeListener(new ChangeListener() { private boolean firstCall = true; @Override public void stateChanged(final ChangeEvent e) { // ignore the first event if (firstCall) { firstCall = false; return; } final Heliodon heliodon = Heliodon.getInstance(); if (heliodon != null) heliodon.setTime((Date) timeSpinner.getValue()); updateOutsideTemperature(); Scene.getInstance().setEdited(true); SceneManager.getInstance().changeSkyTexture(); } }); final GridBagConstraints gbc_timeSpinner = new GridBagConstraints(); gbc_timeSpinner.insets = new Insets(0, 0, 0, 1); gbc_timeSpinner.fill = GridBagConstraints.HORIZONTAL; gbc_timeSpinner.gridx = 1; gbc_timeSpinner.gridy = 1; timeAndLocationPanel.add(timeSpinner, gbc_timeSpinner); latitudeLabel = new JLabel("Latitude: "); final GridBagConstraints gbc_altitudeLabel = new GridBagConstraints(); gbc_altitudeLabel.insets = new Insets(0, 1, 0, 0); gbc_altitudeLabel.gridx = 2; gbc_altitudeLabel.gridy = 1; timeAndLocationPanel.add(latitudeLabel, gbc_altitudeLabel); latitudeSpinner = new JSpinner(); latitudeSpinner.setModel(new SpinnerNumberModel(Heliodon.DEFAULT_LATITUDE, -90, 90, 1)); latitudeSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { if (!cityComboBox.getSelectedItem().equals("") && !CityData.getInstance().getCityLatitutes().values().contains(latitudeSpinner.getValue())) cityComboBox.setSelectedItem(""); Heliodon.getInstance().setLatitude(((Integer) latitudeSpinner.getValue()) / 180.0 * Math.PI); compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); Scene.getInstance().setEdited(true); } }); final GridBagConstraints gbc_latitudeSpinner = new GridBagConstraints(); gbc_latitudeSpinner.fill = GridBagConstraints.HORIZONTAL; gbc_latitudeSpinner.gridx = 3; gbc_latitudeSpinner.gridy = 1; timeAndLocationPanel.add(latitudeSpinner, gbc_latitudeSpinner); timeAndLocationPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, timeAndLocationPanel.getPreferredSize().height)); final JPanel temperaturePanel = new JPanel(); temperaturePanel.setToolTipText("<html>Temperature difference between inside and outside<br>drives heat transfer across.</html>"); temperaturePanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Temperature \u00B0C", TitledBorder.LEADING, TitledBorder.TOP)); dataPanel.add(temperaturePanel); final GridBagLayout gbl_temperaturePanel = new GridBagLayout(); temperaturePanel.setLayout(gbl_temperaturePanel); final JLabel insideTemperatureLabel = new JLabel("Inside: "); insideTemperatureLabel.setToolTipText(""); final GridBagConstraints gbc_insideTemperatureLabel = new GridBagConstraints(); gbc_insideTemperatureLabel.gridx = 1; gbc_insideTemperatureLabel.gridy = 0; temperaturePanel.add(insideTemperatureLabel, gbc_insideTemperatureLabel); insideTemperatureSpinner = new JSpinner(); insideTemperatureSpinner.setToolTipText("Thermostat temperature setting for the inside of the house"); insideTemperatureSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { if (disableActions) return; compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); } }); insideTemperatureSpinner.setModel(new SpinnerNumberModel(20, -70, 60, 1)); final GridBagConstraints gbc_insideTemperatureSpinner = new GridBagConstraints(); gbc_insideTemperatureSpinner.gridx = 2; gbc_insideTemperatureSpinner.gridy = 0; temperaturePanel.add(insideTemperatureSpinner, gbc_insideTemperatureSpinner); final JLabel outsideTemperatureLabel = new JLabel(" Outside: "); outsideTemperatureLabel.setToolTipText(""); final GridBagConstraints gbc_outsideTemperatureLabel = new GridBagConstraints(); gbc_outsideTemperatureLabel.gridx = 3; gbc_outsideTemperatureLabel.gridy = 0; temperaturePanel.add(outsideTemperatureLabel, gbc_outsideTemperatureLabel); temperaturePanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, temperaturePanel.getPreferredSize().height)); outsideTemperatureSpinner = new JSpinner(); outsideTemperatureSpinner.setToolTipText("Outside temperature at this time and day"); outsideTemperatureSpinner.setEnabled(false); outsideTemperatureSpinner.setModel(new SpinnerNumberModel(10, -70, 60, 1)); outsideTemperatureSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { if (disableActions) return; compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); } }); final GridBagConstraints gbc_outsideTemperatureSpinner = new GridBagConstraints(); gbc_outsideTemperatureSpinner.gridx = 4; gbc_outsideTemperatureSpinner.gridy = 0; temperaturePanel.add(outsideTemperatureSpinner, gbc_outsideTemperatureSpinner); final JPanel uFactorPanel = new JPanel(); uFactorPanel.setToolTipText("<html><b>U-factor</b><br>measures how well a building element conducts heat.</html>"); uFactorPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "U-Factor W/(m\u00B2.\u00B0C)", TitledBorder.LEADING, TitledBorder.TOP)); dataPanel.add(uFactorPanel); final GridBagLayout gbl_uFactorPanel = new GridBagLayout(); uFactorPanel.setLayout(gbl_uFactorPanel); final JLabel wallsLabel = new JLabel("Walls:"); final GridBagConstraints gbc_wallsLabel = new GridBagConstraints(); gbc_wallsLabel.anchor = GridBagConstraints.EAST; gbc_wallsLabel.insets = new Insets(0, 0, 5, 5); gbc_wallsLabel.gridx = 0; gbc_wallsLabel.gridy = 0; uFactorPanel.add(wallsLabel, gbc_wallsLabel); wallsComboBox = new WideComboBox(); wallsComboBox.setEditable(true); wallsComboBox.setModel(new DefaultComboBoxModel<String>(new String[] { "0.28 ", "0.67 (Concrete 8\")", "0.41 (Masonary Brick 8\")", "0.04 (Flat Metal 8\" Fiberglass Insulation)" })); wallsComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); } }); final GridBagConstraints gbc_wallsComboBox = new GridBagConstraints(); gbc_wallsComboBox.insets = new Insets(0, 0, 5, 5); gbc_wallsComboBox.gridx = 1; gbc_wallsComboBox.gridy = 0; uFactorPanel.add(wallsComboBox, gbc_wallsComboBox); final JLabel doorsLabel = new JLabel("Doors:"); final GridBagConstraints gbc_doorsLabel = new GridBagConstraints(); gbc_doorsLabel.anchor = GridBagConstraints.EAST; gbc_doorsLabel.insets = new Insets(0, 0, 5, 5); gbc_doorsLabel.gridx = 2; gbc_doorsLabel.gridy = 0; uFactorPanel.add(doorsLabel, gbc_doorsLabel); doorsComboBox = new WideComboBox(); doorsComboBox.setEditable(true); doorsComboBox.setModel(new DefaultComboBoxModel<String>(new String[] { "1.14 ", "1.20 (Steel)", "0.64 (Wood)" })); doorsComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); } }); final GridBagConstraints gbc_doorsComboBox = new GridBagConstraints(); gbc_doorsComboBox.insets = new Insets(0, 0, 5, 0); gbc_doorsComboBox.gridx = 3; gbc_doorsComboBox.gridy = 0; uFactorPanel.add(doorsComboBox, gbc_doorsComboBox); final JLabel windowsLabel = new JLabel("Windows:"); final GridBagConstraints gbc_windowsLabel = new GridBagConstraints(); gbc_windowsLabel.anchor = GridBagConstraints.EAST; gbc_windowsLabel.insets = new Insets(0, 0, 0, 5); gbc_windowsLabel.gridx = 0; gbc_windowsLabel.gridy = 1; uFactorPanel.add(windowsLabel, gbc_windowsLabel); windowsComboBox = new WideComboBox(); windowsComboBox.setEditable(true); windowsComboBox.setModel(new DefaultComboBoxModel<String>(new String[] { "1.0", "0.35 (Double Pane)", "0.15 (Triple Pane)" })); windowsComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); } }); final GridBagConstraints gbc_windowsComboBox = new GridBagConstraints(); gbc_windowsComboBox.insets = new Insets(0, 0, 0, 5); gbc_windowsComboBox.gridx = 1; gbc_windowsComboBox.gridy = 1; uFactorPanel.add(windowsComboBox, gbc_windowsComboBox); final JLabel roofsLabel = new JLabel("Roofs:"); final GridBagConstraints gbc_roofsLabel = new GridBagConstraints(); gbc_roofsLabel.anchor = GridBagConstraints.EAST; gbc_roofsLabel.insets = new Insets(0, 0, 0, 5); gbc_roofsLabel.gridx = 2; gbc_roofsLabel.gridy = 1; uFactorPanel.add(roofsLabel, gbc_roofsLabel); roofsComboBox = new WideComboBox(); roofsComboBox.setEditable(true); roofsComboBox.setModel(new DefaultComboBoxModel<String>(new String[] { "0.14 ", "0.23 (Concrete 3\")", "0.11 (Flat Metal 3\" Fiberglass Insulation)", "0.10 (Wood 3\" Fiberglass Insulation)" })); roofsComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); } }); final GridBagConstraints gbc_roofsComboBox = new GridBagConstraints(); gbc_roofsComboBox.gridx = 3; gbc_roofsComboBox.gridy = 1; uFactorPanel.add(roofsComboBox, gbc_roofsComboBox); uFactorPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, uFactorPanel.getPreferredSize().height)); final JPanel solarConversionPercentagePanel = new JPanel(); solarConversionPercentagePanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, solarConversionPercentagePanel.getPreferredSize().height)); solarConversionPercentagePanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Solar Conversion (%)", TitledBorder.LEADING, TitledBorder.TOP)); dataPanel.add(solarConversionPercentagePanel); JLabel labelSHGC = new JLabel("Window (SHGC): "); labelSHGC.setToolTipText("<html><b>SHGC - Solar heat gain coefficient</b><br>measures the fraction of solar energy transmitted through a window.</html>"); solarConversionPercentagePanel.add(labelSHGC); windowSHGCComboBox = new WideComboBox(); windowSHGCComboBox.setEditable(true); windowSHGCComboBox.setModel(new DefaultComboBoxModel<String>(new String[] { "25", "50", "80" })); windowSHGCComboBox.setSelectedIndex(1); windowSHGCComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { // validate the input final String s = (String) windowSHGCComboBox.getSelectedItem(); double eff = 50; try { eff = Float.parseFloat(s); } catch (final NumberFormatException ex) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "Wrong format: must be 25-80.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (eff < 25 || eff > 80) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "Wrong range: must be 25-80.", "Error", JOptionPane.ERROR_MESSAGE); return; } Scene.getInstance().setWindowSolarHeatGainCoefficient(eff); } }); solarConversionPercentagePanel.add(windowSHGCComboBox); JLabel labelPV = new JLabel("Solar Panel: "); labelPV.setToolTipText("<html><b>Solar photovoltaic efficiency</b><br>measures the fraction of solar energy converted into electricity by a solar panel.</html>"); solarConversionPercentagePanel.add(labelPV); solarPanelEfficiencyComboBox = new WideComboBox(); solarPanelEfficiencyComboBox.setEditable(true); solarPanelEfficiencyComboBox.setModel(new DefaultComboBoxModel<String>(new String[] { "10", "20", "30" })); solarPanelEfficiencyComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { // validate the input final String s = (String) solarPanelEfficiencyComboBox.getSelectedItem(); double eff = 10; try { eff = Float.parseFloat(s); } catch (final NumberFormatException ex) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "Wrong format: must be 10-50.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (eff < 10 || eff > 50) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "Wrong range: must be 10-50.", "Error", JOptionPane.ERROR_MESSAGE); return; } Scene.getInstance().setSolarPanelEfficiency(eff); } }); solarConversionPercentagePanel.add(solarPanelEfficiencyComboBox); heatMapPanel = new JPanel(new BorderLayout()); heatMapPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Heat Map Contrast", TitledBorder.LEADING, TitledBorder.TOP)); dataPanel.add(heatMapPanel); colorMapSlider = new MySlider(); colorMapSlider.setToolTipText("<html>Increase or decrease the color contrast of the heat map.</html>"); colorMapSlider.setMinimum(10); colorMapSlider.setMaximum(90); colorMapSlider.setMinimumSize(colorMapSlider.getPreferredSize()); colorMapSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { if (!colorMapSlider.getValueIsAdjusting()) { compute(SceneManager.getInstance().isSolarColorMap() ? UpdateRadiation.ALWAYS : UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); Scene.getInstance().setEdited(true, false); } } }); colorMapSlider.setSnapToTicks(true); colorMapSlider.setMinorTickSpacing(1); colorMapSlider.setMajorTickSpacing(5); heatMapPanel.add(colorMapSlider, BorderLayout.CENTER); heatMapPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, heatMapPanel.getPreferredSize().height)); partPanel = new JPanel(); partPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Part", TitledBorder.LEADING, TitledBorder.TOP)); dataPanel.add(partPanel); buildingPanel = new JPanel(); buildingPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Building", TitledBorder.LEADING, TitledBorder.TOP)); dataPanel.add(buildingPanel); buildingPanel.setLayout(new BoxLayout(buildingPanel, BoxLayout.Y_AXIS)); // geometry info for the selected building geometryPanel = new JPanel(); buildingPanel.add(geometryPanel); final GridBagLayout gbl_panel_2 = new GridBagLayout(); geometryPanel.setLayout(gbl_panel_2); lblPosition = new JLabel("Position:"); final GridBagConstraints gbc_lblPosition = new GridBagConstraints(); gbc_lblPosition.anchor = GridBagConstraints.EAST; gbc_lblPosition.insets = new Insets(0, 5, 5, 5); gbc_lblPosition.gridx = 0; gbc_lblPosition.gridy = 0; geometryPanel.add(lblPosition, gbc_lblPosition); positionTextField = new JTextField(); positionTextField.setEditable(false); final GridBagConstraints gbc_positionTextField = new GridBagConstraints(); gbc_positionTextField.weightx = 1.0; gbc_positionTextField.fill = GridBagConstraints.HORIZONTAL; gbc_positionTextField.anchor = GridBagConstraints.NORTH; gbc_positionTextField.insets = new Insets(0, 0, 5, 5); gbc_positionTextField.gridx = 1; gbc_positionTextField.gridy = 0; geometryPanel.add(positionTextField, gbc_positionTextField); positionTextField.setColumns(8); lblHeight = new JLabel("Height:"); final GridBagConstraints gbc_lblHeight = new GridBagConstraints(); gbc_lblHeight.anchor = GridBagConstraints.EAST; gbc_lblHeight.insets = new Insets(0, 0, 5, 5); gbc_lblHeight.gridx = 2; gbc_lblHeight.gridy = 0; geometryPanel.add(lblHeight, gbc_lblHeight); heightTextField = new JTextField(); heightTextField.setEditable(false); final GridBagConstraints gbc_heightTextField = new GridBagConstraints(); gbc_heightTextField.weightx = 1.0; gbc_heightTextField.fill = GridBagConstraints.HORIZONTAL; gbc_heightTextField.insets = new Insets(0, 0, 5, 0); gbc_heightTextField.anchor = GridBagConstraints.NORTH; gbc_heightTextField.gridx = 3; gbc_heightTextField.gridy = 0; geometryPanel.add(heightTextField, gbc_heightTextField); heightTextField.setColumns(5); lblArea = new JLabel("Area:"); final GridBagConstraints gbc_lblArea = new GridBagConstraints(); gbc_lblArea.anchor = GridBagConstraints.EAST; gbc_lblArea.insets = new Insets(0, 0, 10, 5); gbc_lblArea.gridx = 0; gbc_lblArea.gridy = 1; geometryPanel.add(lblArea, gbc_lblArea); areaTextField = new JTextField(); areaTextField.setEditable(false); final GridBagConstraints gbc_areaTextField = new GridBagConstraints(); gbc_areaTextField.fill = GridBagConstraints.HORIZONTAL; gbc_areaTextField.insets = new Insets(0, 0, 10, 5); gbc_areaTextField.gridx = 1; gbc_areaTextField.gridy = 1; geometryPanel.add(areaTextField, gbc_areaTextField); areaTextField.setColumns(5); lblVolume = new JLabel("Volume:"); final GridBagConstraints gbc_lblVolume = new GridBagConstraints(); gbc_lblVolume.anchor = GridBagConstraints.EAST; gbc_lblVolume.insets = new Insets(0, 0, 10, 5); gbc_lblVolume.gridx = 2; gbc_lblVolume.gridy = 1; geometryPanel.add(lblVolume, gbc_lblVolume); volumnTextField = new JTextField(); volumnTextField.setEditable(false); final GridBagConstraints gbc_volumnTextField = new GridBagConstraints(); gbc_volumnTextField.insets = new Insets(0, 0, 10, 0); gbc_volumnTextField.fill = GridBagConstraints.HORIZONTAL; gbc_volumnTextField.gridx = 3; gbc_volumnTextField.gridy = 1; geometryPanel.add(volumnTextField, gbc_volumnTextField); volumnTextField.setColumns(5); // cost for the selected building costPanel = new JPanel(new BorderLayout()); costPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Cost ($)", TitledBorder.LEADING, TitledBorder.TOP)); buildingPanel.add(costPanel); costBar = new ColorBar(Color.WHITE, Color.GRAY); costBar.setPreferredSize(new Dimension(200, 16)); costBar.setMaximum(Cost.getInstance().getBudget()); costBar.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() > 1) Cost.getInstance().show(); } }); costPanel.add(costBar, BorderLayout.CENTER); final Component verticalGlue = Box.createVerticalGlue(); dataPanel.add(verticalGlue); progressBar = new JProgressBar(); add(progressBar, BorderLayout.SOUTH); JPanel target = buildingPanel; target.setMaximumSize(new Dimension(target.getMaximumSize().width, target.getPreferredSize().height)); final JPanel energyTodayPanel = new JPanel(); buildingPanel.add(energyTodayPanel); energyTodayPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Energy Today (kWh)", TitledBorder.LEADING, TitledBorder.TOP)); final GridBagLayout gbl_panel_1 = new GridBagLayout(); energyTodayPanel.setLayout(gbl_panel_1); final JLabel sunLabel = new JLabel("Windows"); sunLabel.setToolTipText("Energy gained through windows"); sunLabel.setHorizontalAlignment(SwingConstants.CENTER); final GridBagConstraints gbc_sunLabel = new GridBagConstraints(); gbc_sunLabel.fill = GridBagConstraints.HORIZONTAL; gbc_sunLabel.insets = new Insets(0, 0, 5, 5); gbc_sunLabel.gridx = 0; gbc_sunLabel.gridy = 0; energyTodayPanel.add(sunLabel, gbc_sunLabel); final JLabel solarLabel = new JLabel("Solar Panels"); solarLabel.setToolTipText("Energy harvested from solar panels"); solarLabel.setHorizontalAlignment(SwingConstants.CENTER); final GridBagConstraints gbc_solarLabel = new GridBagConstraints(); gbc_solarLabel.fill = GridBagConstraints.HORIZONTAL; gbc_solarLabel.insets = new Insets(0, 0, 5, 5); gbc_solarLabel.gridx = 1; gbc_solarLabel.gridy = 0; energyTodayPanel.add(solarLabel, gbc_solarLabel); final JLabel heatingLabel = new JLabel("Heater"); heatingLabel.setHorizontalAlignment(SwingConstants.CENTER); final GridBagConstraints gbc_heatingLabel = new GridBagConstraints(); gbc_heatingLabel.fill = GridBagConstraints.HORIZONTAL; gbc_heatingLabel.insets = new Insets(0, 0, 5, 5); gbc_heatingLabel.gridx = 2; gbc_heatingLabel.gridy = 0; energyTodayPanel.add(heatingLabel, gbc_heatingLabel); final JLabel coolingLabel = new JLabel("AC"); coolingLabel.setHorizontalAlignment(SwingConstants.CENTER); final GridBagConstraints gbc_coolingLabel = new GridBagConstraints(); gbc_coolingLabel.fill = GridBagConstraints.HORIZONTAL; gbc_coolingLabel.insets = new Insets(0, 0, 5, 5); gbc_coolingLabel.gridx = 3; gbc_coolingLabel.gridy = 0; energyTodayPanel.add(coolingLabel, gbc_coolingLabel); final JLabel totalLabel = new JLabel("Net"); totalLabel.setHorizontalAlignment(SwingConstants.CENTER); final GridBagConstraints gbc_totalLabel = new GridBagConstraints(); gbc_totalLabel.fill = GridBagConstraints.HORIZONTAL; gbc_totalLabel.insets = new Insets(0, 0, 5, 0); gbc_totalLabel.gridx = 4; gbc_totalLabel.gridy = 0; energyTodayPanel.add(totalLabel, gbc_totalLabel); passiveSolarTextField = new JTextField(); final GridBagConstraints gbc_passiveSolarTextField = new GridBagConstraints(); gbc_passiveSolarTextField.weightx = 1.0; gbc_passiveSolarTextField.fill = GridBagConstraints.HORIZONTAL; gbc_passiveSolarTextField.insets = new Insets(0, 0, 0, 5); gbc_passiveSolarTextField.gridx = 0; gbc_passiveSolarTextField.gridy = 1; energyTodayPanel.add(passiveSolarTextField, gbc_passiveSolarTextField); passiveSolarTextField.setEditable(false); passiveSolarTextField.setColumns(5); photovoltaicTextField = new JTextField(); final GridBagConstraints gbc_photovoltaicTextField = new GridBagConstraints(); gbc_photovoltaicTextField.weightx = 1.0; gbc_photovoltaicTextField.fill = GridBagConstraints.HORIZONTAL; gbc_photovoltaicTextField.insets = new Insets(0, 0, 0, 5); gbc_photovoltaicTextField.gridx = 1; gbc_photovoltaicTextField.gridy = 1; energyTodayPanel.add(photovoltaicTextField, gbc_photovoltaicTextField); photovoltaicTextField.setEditable(false); photovoltaicTextField.setColumns(5); heatingTodayTextField = new JTextField(); heatingTodayTextField.setEditable(false); final GridBagConstraints gbc_heatingTodayTextField = new GridBagConstraints(); gbc_heatingTodayTextField.weightx = 1.0; gbc_heatingTodayTextField.insets = new Insets(0, 0, 0, 5); gbc_heatingTodayTextField.fill = GridBagConstraints.HORIZONTAL; gbc_heatingTodayTextField.gridx = 2; gbc_heatingTodayTextField.gridy = 1; energyTodayPanel.add(heatingTodayTextField, gbc_heatingTodayTextField); heatingTodayTextField.setColumns(5); coolingTodayTextField = new JTextField(); coolingTodayTextField.setEditable(false); final GridBagConstraints gbc_coolingTodayTextField = new GridBagConstraints(); gbc_coolingTodayTextField.weightx = 1.0; gbc_coolingTodayTextField.insets = new Insets(0, 0, 0, 5); gbc_coolingTodayTextField.fill = GridBagConstraints.HORIZONTAL; gbc_coolingTodayTextField.gridx = 3; gbc_coolingTodayTextField.gridy = 1; energyTodayPanel.add(coolingTodayTextField, gbc_coolingTodayTextField); coolingTodayTextField.setColumns(5); totalTodayTextField = new JTextField(); totalTodayTextField.setEditable(false); final GridBagConstraints gbc_totalTodayTextField = new GridBagConstraints(); gbc_totalTodayTextField.weightx = 1.0; gbc_totalTodayTextField.fill = GridBagConstraints.HORIZONTAL; gbc_totalTodayTextField.gridx = 4; gbc_totalTodayTextField.gridy = 1; energyTodayPanel.add(totalTodayTextField, gbc_totalTodayTextField); totalTodayTextField.setColumns(5); energyTodayPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, energyTodayPanel.getPreferredSize().height)); final Dimension size = heatingLabel.getMinimumSize(); sunLabel.setMinimumSize(size); solarLabel.setMinimumSize(size); coolingLabel.setMinimumSize(size); totalLabel.setMinimumSize(size); target = partPanel; target.setMaximumSize(new Dimension(target.getMaximumSize().width, target.getPreferredSize().height)); partPanel.setLayout(new BoxLayout(partPanel, BoxLayout.Y_AXIS)); partPropertiesPanel = new JPanel(); partPanel.add(partPropertiesPanel); lblWidth = new JLabel("Width:"); partPropertiesPanel.add(lblWidth); partWidthTextField = new JTextField(); partWidthTextField.setEditable(false); partPropertiesPanel.add(partWidthTextField); partWidthTextField.setColumns(3); lblHeight_1 = new JLabel("Height:"); partPropertiesPanel.add(lblHeight_1); partHeightTextField = new JTextField(); partHeightTextField.setEditable(false); partPropertiesPanel.add(partHeightTextField); partHeightTextField.setColumns(3); partEnergyLabel = new JLabel("Insolation:"); partPropertiesPanel.add(partEnergyLabel); partEnergyTextField = new JTextField(); partPropertiesPanel.add(partEnergyTextField); partEnergyTextField.setEditable(false); partEnergyTextField.setColumns(5); } public void compute(final UpdateRadiation updateRadiation) { if (!computeEnabled) return; updateOutsideTemperature(); // TODO: There got to be a better way to do this this.updateRadiation = updateRadiation; if (thread != null && thread.isAlive()) computeRequest = true; else { thread = new Thread("Energy Computer") { @Override public void run() { do { computeRequest = false; /* since this thread can accept multiple computeRequest, cannot use updateRadiationColorMap parameter directly */ try { if (EnergyPanel.this.updateRadiation == UpdateRadiation.ALWAYS || (SceneManager.getInstance().isSolarColorMap() && (!alreadyRenderedHeatmap || keepHeatmapOn))) { alreadyRenderedHeatmap = true; computeNow(); } else { if (SceneManager.getInstance().isSolarColorMap()) MainPanel.getInstance().getSolarButton().setSelected(false); int numberOfHouses = 0; synchronized (Scene.getInstance().getParts()) { // XIE: This needs to be synchronized to avoid concurrent modification exceptions for (final HousePart part : Scene.getInstance().getParts()) { if (part instanceof Foundation && !part.getChildren().isEmpty() && !part.isFrozen()) numberOfHouses++; if (numberOfHouses >= 2) break; } for (final HousePart part : Scene.getInstance().getParts()) if (part instanceof Foundation) ((Foundation) part).setSolarLabelValue(numberOfHouses >= 2 && !part.getChildren().isEmpty() && !part.isFrozen() ? -1 : -2); } } } catch (final Throwable e) { e.printStackTrace(); Util.reportError(e); } try { Thread.sleep(500); } catch (final InterruptedException e) { e.printStackTrace(); } progressBar.setValue(0); progressBar.setStringPainted(false); } while (computeRequest); thread = null; } }; thread.start(); } } public void computeNow() { try { System.out.println("EnergyPanel.computeNow()"); progressBar.setValue(0); progressBar.setStringPainted(false); updateOutsideTemperature(); HeatLoad.getInstance().computeEnergyToday((Calendar) Heliodon.getInstance().getCalender().clone(), (Integer) insideTemperatureSpinner.getValue()); SolarIrradiation.getInstance().compute(); notifyPropertyChangeListeners(new PropertyChangeEvent(EnergyPanel.this, "Solar energy calculation completed", 0, 1)); updatePartEnergy(); // XIE: This needs to be called for trees to change texture when the month changes synchronized (Scene.getInstance().getParts()) { for (final HousePart p : Scene.getInstance().getParts()) if (p instanceof Tree) p.updateTextureAndColor(); } SceneManager.getInstance().refresh(); progressBar.setValue(100); } catch (final CancellationException e) { System.out.println("Energy compute cancelled."); } } // TODO: There should be a better way to do this. public void clearIrradiationHeatMap() { compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); } private void updateOutsideTemperature() { if (cityComboBox.getSelectedItem().equals("")) outsideTemperatureSpinner.setValue(15); else outsideTemperatureSpinner.setValue(Math.round(CityData.getInstance().computeOutsideTemperature(Heliodon.getInstance().getCalender()))); } public JSpinner getDateSpinner() { return dateSpinner; } public JSpinner getTimeSpinner() { return timeSpinner; } public void progress() { if (progressBar.getValue() < 100) { progressBar.setStringPainted(progressBar.getValue() > 0); progressBar.setValue(progressBar.getValue() + 1); } else { // progress() can be called once after it reaches 100% to reset progressBar.setStringPainted(false); progressBar.setValue(0); } } public void setLatitude(final int latitude) { latitudeSpinner.setValue(latitude); } public int getLatitude() { return (Integer) latitudeSpinner.getValue(); } public JSlider getColorMapSlider() { return colorMapSlider; } public void clearAlreadyRendered() { alreadyRenderedHeatmap = false; } public static void setKeepHeatmapOn(final boolean on) { keepHeatmapOn = on; } public void setComputeEnabled(final boolean computeEnabled) { this.computeEnabled = computeEnabled; } @Override public void addPropertyChangeListener(final PropertyChangeListener pcl) { propertyChangeListeners.add(pcl); } @Override public void removePropertyChangeListener(final PropertyChangeListener pcl) { propertyChangeListeners.remove(pcl); } private void notifyPropertyChangeListeners(final PropertyChangeEvent evt) { if (!propertyChangeListeners.isEmpty()) { synchronized (propertyChangeListeners) { for (final PropertyChangeListener x : propertyChangeListeners) { x.propertyChange(evt); } } } } public void updatePartEnergy() { final boolean iradiationEnabled = MainPanel.getInstance().getSolarButton().isSelected(); final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); lblHeight_1.setText(selectedPart instanceof Foundation ? "Length:" : "Height:"); ((TitledBorder) partPanel.getBorder()).setTitle("Part" + (selectedPart == null ? "" : (" - " + selectedPart.toString().substring(0, selectedPart.toString().indexOf(')') + 1)))); partPanel.repaint(); if (!iradiationEnabled || selectedPart == null || selectedPart instanceof Foundation || selectedPart instanceof Door) partEnergyTextField.setText(""); else partEnergyTextField.setText(twoDecimals.format(selectedPart.getSolarPotentialToday())); if (selectedPart != null && !(selectedPart instanceof Roof || selectedPart instanceof Floor || selectedPart instanceof Tree)) { if (selectedPart instanceof SolarPanel) { partWidthTextField.setText(twoDecimals.format(SolarPanel.WIDTH)); partHeightTextField.setText(twoDecimals.format(SolarPanel.HEIGHT)); } else { partWidthTextField.setText(twoDecimals.format(selectedPart.getAbsPoint(0).distance(selectedPart.getAbsPoint(2)) * Scene.getInstance().getAnnotationScale())); partHeightTextField.setText(twoDecimals.format(selectedPart.getAbsPoint(0).distance(selectedPart.getAbsPoint(1)) * Scene.getInstance().getAnnotationScale())); } } else { partWidthTextField.setText(""); partHeightTextField.setText(""); } final Foundation selectedBuilding; if (selectedPart == null) selectedBuilding = null; else if (selectedPart instanceof Foundation) selectedBuilding = (Foundation) selectedPart; else selectedBuilding = (Foundation) selectedPart.getTopContainer(); if (selectedBuilding != null) { if (iradiationEnabled) { passiveSolarTextField.setText(twoDecimals.format(selectedBuilding.getPassiveSolarToday())); photovoltaicTextField.setText(twoDecimals.format(selectedBuilding.getPhotovoltaicToday())); heatingTodayTextField.setText(twoDecimals.format(selectedBuilding.getHeatingToday())); coolingTodayTextField.setText(twoDecimals.format(selectedBuilding.getCoolingToday())); totalTodayTextField.setText(twoDecimals.format(selectedBuilding.getTotalEnergyToday())); } else { passiveSolarTextField.setText(""); photovoltaicTextField.setText(""); heatingTodayTextField.setText(""); coolingTodayTextField.setText(""); totalTodayTextField.setText(""); } final double[] buildingGeometry = selectedBuilding.getBuildingGeometry(); if (buildingGeometry != null) { positionTextField.setText("(" + twoDecimals.format(buildingGeometry[3]) + ", " + twoDecimals.format(buildingGeometry[4]) + ")"); heightTextField.setText(twoDecimals.format(buildingGeometry[0])); areaTextField.setText(twoDecimals.format(buildingGeometry[1])); volumnTextField.setText(twoDecimals.format(buildingGeometry[2])); } else { positionTextField.setText(""); heightTextField.setText(""); areaTextField.setText(""); volumnTextField.setText(""); } } else { passiveSolarTextField.setText(""); photovoltaicTextField.setText(""); heatingTodayTextField.setText(""); coolingTodayTextField.setText(""); totalTodayTextField.setText(""); positionTextField.setText(""); heightTextField.setText(""); areaTextField.setText(""); volumnTextField.setText(""); } } public void updateCost() { final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); final Foundation selectedBuilding; if (selectedPart == null) selectedBuilding = null; else if (selectedPart instanceof Foundation) selectedBuilding = (Foundation) selectedPart; else selectedBuilding = (Foundation) selectedPart.getTopContainer(); int n = 0; if (selectedBuilding != null) n = Cost.getInstance().getBuildingCost(selectedBuilding); costBar.setValue(n); costBar.repaint(); } /** Currently this applies only to the date spinner when it is set programmatically (not by the user) */ public void disableActions(final boolean b) { disableActions = b; } public boolean isComputeRequest() { return computeRequest; } public JComboBox<String> getWallsComboBox() { return wallsComboBox; } public JComboBox<String> getDoorsComboBox() { return doorsComboBox; } public JComboBox<String> getWindowsComboBox() { return windowsComboBox; } public JComboBox<String> getRoofsComboBox() { return roofsComboBox; } public JComboBox<String> getCityComboBox() { return cityComboBox; } public JComboBox<String> getSolarPanelEfficiencyComboBox() { return solarPanelEfficiencyComboBox; } public JComboBox<String> getWindowSHGCComboBox() { return windowSHGCComboBox; } public void setBudget(int budget) { costPanel.setBorder(BorderFactory.createTitledBorder(UIManager.getBorder("TitledBorder.border"), "Construction Cost (Maximum: $" + budget + ")", TitledBorder.LEADING, TitledBorder.TOP)); costBar.setMaximum(budget); costBar.repaint(); } }
package org.databene.commons.tree; import org.databene.commons.Filter; import org.databene.commons.TreeModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Logs the structure represented by a {@link org.databene.commons.TreeModel} implementor.<br/><br/> * Created: 10.11.2010 10:21:59 * @since 0.5.4 * @author Volker Bergmann */ public class TreeLogger { private static final Logger LOGGER = LoggerFactory.getLogger(TreeLogger.class); String indent = ""; public <T> void log(TreeModel<T> model) { log(model.getRoot(), false, model, null); } public <T> void log(TreeModel<T> model, Filter<T> filter) { log(model.getRoot(), false, model, filter); } private <T> void log(T node, boolean hasSiblings, TreeModel<T> model, Filter<T> filter) { if (filter != null && !filter.accept(node)) return; LOGGER.info(indent + node); if (!model.isLeaf(node)) { increaseIndent(hasSiblings); int n = model.getChildCount(node); for (int i = 0; i < n; i++) log(model.getChild(node, i), i < n - 1, model, filter); reduceIndent(); } } private void increaseIndent(boolean hasSuccessors) { if (indent.length() == 0) indent = "+-"; else if (hasSuccessors) indent = indent.substring(0, indent.length() - 2) + "| " + indent.substring(indent.length() - 2); else indent = indent.substring(0, indent.length() - 2) + " " + indent.substring(indent.length() - 2); } private void reduceIndent() { if (indent.length() >= 4) indent = indent.substring(0, indent.length() - 4) + indent.substring(indent.length() - 2); else indent = ""; } }