diff
stringlengths 164
2.11M
| is_single_chunk
bool 2
classes | is_single_function
bool 2
classes | buggy_function
stringlengths 0
335k
⌀ | fixed_function
stringlengths 23
335k
⌀ |
---|---|---|---|---|
diff --git a/core/src/main/java/edu/northwestern/bioinformatics/studycalendar/configuration/Configuration.java b/core/src/main/java/edu/northwestern/bioinformatics/studycalendar/configuration/Configuration.java
index 951af0745..dd95a8336 100644
--- a/core/src/main/java/edu/northwestern/bioinformatics/studycalendar/configuration/Configuration.java
+++ b/core/src/main/java/edu/northwestern/bioinformatics/studycalendar/configuration/Configuration.java
@@ -1,99 +1,105 @@
package edu.northwestern.bioinformatics.studycalendar.configuration;
import gov.nih.nci.cabig.ctms.tools.configuration.ConfigurationEntry;
import gov.nih.nci.cabig.ctms.tools.configuration.ConfigurationProperties;
import gov.nih.nci.cabig.ctms.tools.configuration.ConfigurationProperty;
import gov.nih.nci.cabig.ctms.tools.configuration.DatabaseBackedConfiguration;
import gov.nih.nci.cabig.ctms.tools.configuration.DefaultConfigurationProperties;
import gov.nih.nci.cabig.ctms.tools.configuration.DefaultConfigurationProperty;
import org.restlet.util.Template;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
/**
* @author Rhett Sutphin
*/
public class Configuration extends DatabaseBackedConfiguration {
public static final DefaultConfigurationProperties PROPERTIES
= new DefaultConfigurationProperties(new ClassPathResource("details.properties", Configuration.class));
public static final ConfigurationProperty<String>
DEPLOYMENT_NAME = PROPERTIES.add(new DefaultConfigurationProperty.Text("deploymentName"));
public static final ConfigurationProperty<String>
MAIL_REPLY_TO = PROPERTIES.add(new DefaultConfigurationProperty.Text("replyTo"));
public static final ConfigurationProperty<List<String>>
MAIL_EXCEPTIONS_TO = PROPERTIES.add(new DefaultConfigurationProperty.Csv("mailExceptionsTo"));
public static final ConfigurationProperty<String>
SMTP_HOST = PROPERTIES.add(new DefaultConfigurationProperty.Text("smtpHost"));
public static final ConfigurationProperty<Integer>
SMTP_PORT = PROPERTIES.add(new DefaultConfigurationProperty.Int("smtpPort"));
public static final ConfigurationProperty<Boolean>
SHOW_DEBUG_INFORMATION = PROPERTIES.add(new DefaultConfigurationProperty.Bool("showDebugInformation"));
public static final ConfigurationProperty<Template>
CAAERS_BASE_URL = PROPERTIES.add(new TemplateConfigurationProperty("caAERSBaseUrl"));
public static final ConfigurationProperty<Template>
SMOKE_SERVICE_BASE_URL = PROPERTIES.add(new TemplateConfigurationProperty("smokeServiceBaseUrl"));
public static final ConfigurationProperty<Template>
LABVIEWER_BASE_URL = PROPERTIES.add(new TemplateConfigurationProperty("labViewerBaseUrl"));
public static final ConfigurationProperty<Template>
PATIENT_PAGE_URL = PROPERTIES.add(new TemplateConfigurationProperty("patientPageUrl"));
public static final ConfigurationProperty<String>
CTMS_NAME = PROPERTIES.add(new DefaultConfigurationProperty.Text("ctmsName"));
public static final ConfigurationProperty<String>
BASE_CTMS_URL = PROPERTIES.add(new DefaultConfigurationProperty.Text("ctmsUrl"));
public static final ConfigurationProperty<String>
LOGO_IMAGE_URL = PROPERTIES.add(new DefaultConfigurationProperty.Text("logoImageUrl"));
public static final ConfigurationProperty<String>
+ LOGO_DIMENSIONS_WIDTH = PROPERTIES.add(new DefaultConfigurationProperty.Text("logoDimensionsWidth"));
+ public static final ConfigurationProperty<String>
+ LOGO_DIMENSIONS_HEIGHT = PROPERTIES.add(new DefaultConfigurationProperty.Text("logoDimensionsHeight"));
+
+
+ public static final ConfigurationProperty<String>
LOGO_ALT_TEXT = PROPERTIES.add(new DefaultConfigurationProperty.Text("logoAltText"));
public static final ConfigurationProperty<Template>
STUDY_PAGE_URL = PROPERTIES.add(new TemplateConfigurationProperty("studyPageUrl"));
// use target?
public static final ConfigurationProperty<Boolean>
APP_LINKS_IN_ANOTHER_WINDOW = PROPERTIES.add(new DefaultConfigurationProperty.Bool("applicationLinksInAnotherWindow"));
// use target=_blank vs. target=appname
public static final ConfigurationProperty<Boolean>
APP_LINKS_IN_NEW_WINDOWS = PROPERTIES.add(new DefaultConfigurationProperty.Bool("applicationLinksInNewWindows"));
public static final ConfigurationProperty<Boolean>
ENABLE_ASSIGNING_SUBJECT = PROPERTIES.add(new DefaultConfigurationProperty.Bool("enableAssigningSubject"));
public static final ConfigurationProperty<Boolean>
ENABLE_CREATING_TEMPLATE = PROPERTIES.add(new DefaultConfigurationProperty.Bool("enableCreatingTemplate"));
public static final ConfigurationProperty<String>
DISPLAY_DATE_FORMAT = PROPERTIES.add(new DefaultConfigurationProperty.Text("displayDateFormat"));
////// PSC-SPECIFIC LOGIC
public boolean getExternalAppsConfigured() {
return get(CAAERS_BASE_URL) != null || get(LABVIEWER_BASE_URL) != null || get(PATIENT_PAGE_URL) != null;
}
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public boolean getCtmsConfigured() {
return get(CTMS_NAME) != null && get(BASE_CTMS_URL) != null;
}
public boolean getStudyPageUrlConfigured() {
return get(STUDY_PAGE_URL) != null;
}
public ConfigurationProperties getProperties() {
return PROPERTIES;
}
protected Class<? extends ConfigurationEntry> getConfigurationEntryClass() {
return PscConfigurationEntry.class;
}
@Override
@Transactional(propagation = Propagation.SUPPORTS)
public Map<String, Object> getMap() {
return super.getMap();
}
}
| true | false | null | null |
diff --git a/plugins/org.eclipse.tm.tcf.core/src/org/eclipse/tm/tcf/core/Command.java b/plugins/org.eclipse.tm.tcf.core/src/org/eclipse/tm/tcf/core/Command.java
index bc3f32e5a..1ad251012 100644
--- a/plugins/org.eclipse.tm.tcf.core/src/org/eclipse/tm/tcf/core/Command.java
+++ b/plugins/org.eclipse.tm.tcf.core/src/org/eclipse/tm/tcf/core/Command.java
@@ -1,233 +1,232 @@
/*******************************************************************************
* Copyright (c) 2007, 2008 Wind River Systems, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tm.tcf.core;
import java.io.IOException;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import org.eclipse.tm.internal.tcf.core.Token;
import org.eclipse.tm.tcf.protocol.IChannel;
import org.eclipse.tm.tcf.protocol.IErrorReport;
import org.eclipse.tm.tcf.protocol.IService;
import org.eclipse.tm.tcf.protocol.IToken;
import org.eclipse.tm.tcf.protocol.JSON;
import org.eclipse.tm.tcf.protocol.Protocol;
/**
* This is utility class that helps to implement sending a command and receiving
* command result over TCF communication channel. The class uses JSON to encode
* command arguments and to decode result data.
*
* The class also provides support for TCF standard error report encoding.
*
* Clients are expected to subclass <code>Command</code> and override <code>done</code> method.
*
* Note: most clients don't need to handle protocol commands directly and
* can use service APIs instead. Service API does all command encoding/decoding
* for a client.
*
* Typical usage example:
*
* public IToken getContext(String id, final DoneGetContext done) {
* return new Command(channel, IService.this, "getContext", new Object[]{ id }) {
* @Override
* public void done(Exception error, Object[] args) {
* Context ctx = null;
* if (error == null) {
* assert args.length == 2;
* error = toError(args[0]);
* if (args[1] != null) ctx = new Context(args[1]);
* }
* done.doneGetContext(token, error, ctx);
* }
* }.token;
* }
*/
public abstract class Command implements IChannel.ICommandListener {
private final IService service;
private final String command;
private final Object[] args;
public final IToken token;
private boolean done;
private static final SimpleDateFormat timestamp_format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
public Command(IChannel channel, IService service, String command, Object[] args) {
this.service = service;
this.command = command;
this.args = args;
IToken t = null;
try {
boolean zero_copy = ((AbstractChannel)channel).isZeroCopySupported();
t = channel.sendCommand(service, command, JSON.toJSONSequence(args, zero_copy), this);
}
catch (Throwable y) {
t = new Token();
final Exception x = y instanceof Exception ? (Exception)y : new Exception(y);
Protocol.invokeLater(new Runnable() {
public void run() {
assert !done;
done = true;
done(x, null);
}
});
}
token = t;
}
public void progress(IToken token, byte[] data) {
assert this.token == token;
}
public void result(IToken token, byte[] data) {
assert this.token == token;
Exception error = null;
Object[] args = null;
try {
args = JSON.parseSequence(data);
}
catch (Exception e) {
error = e;
}
assert !done;
done = true;
done(error, args);
}
public void terminated(IToken token, Exception error) {
assert this.token == token;
assert !done;
done = true;
done(error, null);
}
public abstract void done(Exception error, Object[] args);
public String getCommandString() {
StringBuffer buf = new StringBuffer();
buf.append(service.getName());
buf.append(' ');
buf.append(command);
if (args != null) {
for (int i = 0; i < args.length; i++) {
buf.append(i == 0 ? " " : ", ");
try {
buf.append(JSON.toJSON(args[i]));
}
catch (IOException x) {
buf.append("***");
buf.append(x.getMessage());
buf.append("***");
}
}
}
return buf.toString();
}
@SuppressWarnings({ "unchecked" })
public static String toErrorString(Object data) {
if (data == null) return null;
Map<String,Object> map = (Map<String,Object>)data;
String fmt = (String)map.get(IErrorReport.ERROR_FORMAT);
if (fmt != null) {
Collection<Object> c = (Collection<Object>)map.get(IErrorReport.ERROR_PARAMS);
if (c != null) return new MessageFormat(fmt).format(c.toArray());
return fmt;
}
Number code = (Number)map.get(IErrorReport.ERROR_CODE);
if (code != null) {
if (code.intValue() == IErrorReport.TCF_ERROR_OTHER) {
String alt_org = (String)map.get(IErrorReport.ERROR_ALT_ORG);
Number alt_code = (Number)map.get(IErrorReport.ERROR_ALT_CODE);
if (alt_org != null && alt_code != null) {
return alt_org + " Error " + alt_code;
}
}
return "TCF Error " + code;
}
return "Invalid error report format";
}
static void appendErrorProps(StringBuffer bf, Map<String,Object> map) {
Number time = (Number)map.get(IErrorReport.ERROR_TIME);
Number code = (Number)map.get(IErrorReport.ERROR_CODE);
String service = (String)map.get(IErrorReport.ERROR_SERVICE);
Number severity = (Number)map.get(IErrorReport.ERROR_SEVERITY);
Number alt_code = (Number)map.get(IErrorReport.ERROR_ALT_CODE);
String alt_org = (String)map.get(IErrorReport.ERROR_ALT_ORG);
if (time != null) {
bf.append('\n');
bf.append("Time: ");
bf.append(timestamp_format.format(new Date(time.longValue())));
}
if (severity != null) {
bf.append('\n');
bf.append("Severity: ");
- bf.append(toErrorString(map));
switch (severity.intValue()) {
case IErrorReport.SEVERITY_ERROR: bf.append("Error");
case IErrorReport.SEVERITY_FATAL: bf.append("Fatal");
case IErrorReport.SEVERITY_WARNING: bf.append("Warning");
default: bf.append("Unknown");
}
}
bf.append('\n');
bf.append("Error text: ");
bf.append(toErrorString(map));
bf.append('\n');
bf.append("Error code: ");
bf.append(code);
if (service != null) {
bf.append('\n');
bf.append("Service: ");
bf.append(service);
}
if (alt_code != null) {
bf.append('\n');
bf.append("Alt code: ");
bf.append(alt_code);
if (alt_org != null) {
bf.append('\n');
bf.append("Alt org: ");
bf.append(alt_org);
}
}
}
public Exception toError(Object data) {
return toError(data, true);
}
@SuppressWarnings("unchecked")
public Exception toError(Object data, boolean include_command_text) {
if (data == null) return null;
Map<String,Object> map = (Map<String,Object>)data;
StringBuffer bf = new StringBuffer();
bf.append("TCF error report:");
bf.append('\n');
if (include_command_text) {
String cmd = getCommandString();
if (cmd.length() > 72) cmd = cmd.substring(0, 72) + "...";
bf.append("Command: ");
bf.append(cmd);
}
appendErrorProps(bf, map);
return new ErrorReport(bf.toString(), map);
}
}
diff --git a/plugins/org.eclipse.tm.tcf.debug.ui/src/org/eclipse/tm/internal/tcf/debug/ui/model/TCFModel.java b/plugins/org.eclipse.tm.tcf.debug.ui/src/org/eclipse/tm/internal/tcf/debug/ui/model/TCFModel.java
index f88e86768..b6a3baff0 100644
--- a/plugins/org.eclipse.tm.tcf.debug.ui/src/org/eclipse/tm/internal/tcf/debug/ui/model/TCFModel.java
+++ b/plugins/org.eclipse.tm.tcf.debug.ui/src/org/eclipse/tm/internal/tcf/debug/ui/model/TCFModel.java
@@ -1,1065 +1,1065 @@
/*******************************************************************************
* Copyright (c) 2007, 2008 Wind River Systems, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tm.internal.tcf.debug.ui.model;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.commands.IDisconnectHandler;
import org.eclipse.debug.core.commands.IResumeHandler;
import org.eclipse.debug.core.commands.IStepIntoHandler;
import org.eclipse.debug.core.commands.IStepOverHandler;
import org.eclipse.debug.core.commands.IStepReturnHandler;
import org.eclipse.debug.core.commands.ISuspendHandler;
import org.eclipse.debug.core.commands.ITerminateHandler;
import org.eclipse.debug.core.model.IDebugModelProvider;
import org.eclipse.debug.core.model.IMemoryBlockRetrieval;
import org.eclipse.debug.core.model.IMemoryBlockRetrievalExtension;
import org.eclipse.debug.core.model.ISourceLocator;
import org.eclipse.debug.core.sourcelookup.ISourceLookupDirector;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IChildrenCountUpdate;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IChildrenUpdate;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IColumnPresentation;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IColumnPresentationFactory;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IElementContentProvider;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IElementLabelProvider;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IHasChildrenUpdate;
import org.eclipse.debug.internal.ui.viewers.model.provisional.ILabelUpdate;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelDelta;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelProxy;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelProxyFactory;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelSelectionPolicy;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelSelectionPolicyFactory;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.debug.ui.IDebugView;
import org.eclipse.debug.ui.ISourcePresentation;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleConstants;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.IConsoleView;
import org.eclipse.ui.console.IOConsole;
import org.eclipse.ui.console.IOConsoleInputStream;
import org.eclipse.ui.console.IOConsoleOutputStream;
import org.eclipse.debug.ui.contexts.ISuspendTrigger;
import org.eclipse.debug.ui.contexts.ISuspendTriggerListener;
import org.eclipse.debug.ui.sourcelookup.CommonSourceNotFoundEditorInput;
import org.eclipse.debug.ui.sourcelookup.ISourceDisplay;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.graphics.Device;
import org.eclipse.tm.internal.tcf.debug.model.ITCFConstants;
import org.eclipse.tm.internal.tcf.debug.model.TCFContextState;
import org.eclipse.tm.internal.tcf.debug.model.TCFLaunch;
import org.eclipse.tm.internal.tcf.debug.model.TCFSourceRef;
import org.eclipse.tm.internal.tcf.debug.ui.Activator;
import org.eclipse.tm.internal.tcf.debug.ui.ImageCache;
import org.eclipse.tm.internal.tcf.debug.ui.commands.DisconnectCommand;
import org.eclipse.tm.internal.tcf.debug.ui.commands.ResumeCommand;
import org.eclipse.tm.internal.tcf.debug.ui.commands.StepIntoCommand;
import org.eclipse.tm.internal.tcf.debug.ui.commands.StepOverCommand;
import org.eclipse.tm.internal.tcf.debug.ui.commands.StepReturnCommand;
import org.eclipse.tm.internal.tcf.debug.ui.commands.SuspendCommand;
import org.eclipse.tm.internal.tcf.debug.ui.commands.TerminateCommand;
import org.eclipse.tm.tcf.core.Command;
import org.eclipse.tm.tcf.protocol.IChannel;
import org.eclipse.tm.tcf.protocol.IErrorReport;
import org.eclipse.tm.tcf.protocol.Protocol;
import org.eclipse.tm.tcf.services.ILineNumbers;
import org.eclipse.tm.tcf.services.IMemory;
import org.eclipse.tm.tcf.services.IProcesses;
import org.eclipse.tm.tcf.services.IRegisters;
import org.eclipse.tm.tcf.services.IRunControl;
import org.eclipse.tm.tcf.services.ISymbols;
import org.eclipse.tm.tcf.util.TCFDataCache;
import org.eclipse.tm.tcf.util.TCFTask;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditor;
/**
* TCFModel represents remote target state as it is known to host.
* The main job of the model is caching remote data,
* keeping the cache in a coherent state, and feeding UI with up-to-date data.
*/
public class TCFModel implements IElementContentProvider, IElementLabelProvider,
IModelProxyFactory, IColumnPresentationFactory, ISourceDisplay, ISuspendTrigger {
private final TCFLaunch launch;
private final Display display;
private final List<ISuspendTriggerListener> suspend_trigger_listeners =
new LinkedList<ISuspendTriggerListener>();
private int suspend_trigger_generation;
private final Set<String> running_actions = new HashSet<String>();
private final Map<String,String> finished_actions = new HashMap<String,String>();
private final Map<IPresentationContext,TCFModelProxy> model_proxies =
new HashMap<IPresentationContext,TCFModelProxy>();
private final Map<String,TCFNode> id2node = new HashMap<String,TCFNode>();
@SuppressWarnings("unchecked")
private final Map<Class,Object> adapters = new HashMap<Class,Object>();
private final Map<String,IMemoryBlockRetrievalExtension> mem_retrieval =
new HashMap<String,IMemoryBlockRetrievalExtension>();
private final Map<String,String> cast_to_type_map =
new HashMap<String,String>();
private class Console {
final IOConsole console;
final Map<Integer,IOConsoleOutputStream> out;
Console(final IOConsole console) {
this.console = console;
out = new HashMap<Integer,IOConsoleOutputStream>();
Thread t = new Thread() {
public void run() {
try {
IOConsoleInputStream inp = console.getInputStream();
final byte[] buf = new byte[0x100];
for (;;) {
final int len = inp.read(buf);
if (len < 0) break;
Protocol.invokeAndWait(new Runnable() {
public void run() {
launch.writeProcessInputStream(buf, 0, len);
}
});
}
}
catch (Throwable x) {
Activator.log("Cannot read console input", x);
}
}
};
t.setName("TCF Launch Console Input");
t.start();
}
void close() {
for (IOConsoleOutputStream stream : out.values()) {
try {
stream.close();
}
catch (IOException x) {
Activator.log("Cannot close console stream", x);
}
}
try {
console.getInputStream().close();
}
catch (IOException x) {
Activator.log("Cannot close console stream", x);
}
}
}
private Console console;
private static final Map<ILaunchConfiguration,IEditorInput> editor_not_found =
new HashMap<ILaunchConfiguration,IEditorInput>();
private final IModelSelectionPolicyFactory model_selection_factory = new IModelSelectionPolicyFactory() {
public IModelSelectionPolicy createModelSelectionPolicyAdapter(
Object element, IPresentationContext context) {
return selection_policy;
}
};
private final IModelSelectionPolicy selection_policy;
private IChannel channel;
private TCFNodeLaunch launch_node;
private boolean disposed;
private static int display_source_cnt;
private final IMemory.MemoryListener mem_listener = new IMemory.MemoryListener() {
public void contextAdded(IMemory.MemoryContext[] contexts) {
for (int i = 0; i < contexts.length; i++) {
String id = contexts[i].getParentID();
if (id == null) {
launch_node.onContextAdded(contexts[i]);
}
else {
TCFNode node = getNode(id);
if (node instanceof TCFNodeExecContext) {
((TCFNodeExecContext)node).onContextAdded(contexts[i]);
}
}
}
}
public void contextChanged(IMemory.MemoryContext[] contexts) {
for (int i = 0; i < contexts.length; i++) {
TCFNode node = getNode(contexts[i].getID());
if (node instanceof TCFNodeExecContext) {
((TCFNodeExecContext)node).onContextChanged(contexts[i]);
}
}
}
public void contextRemoved(final String[] context_ids) {
onContextRemoved(context_ids);
}
public void memoryChanged(String context_id, Number[] addr, long[] size) {
TCFNode node = getNode(context_id);
if (node instanceof TCFNodeExecContext) {
((TCFNodeExecContext)node).onMemoryChanged(addr, size);
}
}
};
private final IRunControl.RunControlListener run_listener = new IRunControl.RunControlListener() {
public void containerResumed(String[] context_ids) {
for (int i = 0; i < context_ids.length; i++) {
TCFNode node = getNode(context_ids[i]);
if (node instanceof TCFNodeExecContext) {
((TCFNodeExecContext)node).onContainerResumed();
}
}
}
public void containerSuspended(String context, String pc, String reason,
Map<String,Object> params, String[] suspended_ids) {
for (int i = 0; i < suspended_ids.length; i++) {
TCFNode node = getNode(suspended_ids[i]);
if (node instanceof TCFNodeExecContext) {
((TCFNodeExecContext)node).onContainerSuspended();
}
}
TCFNode node = getNode(context);
if (node instanceof TCFNodeExecContext) {
((TCFNodeExecContext)node).onContextSuspended(pc, reason, params);
}
runSuspendTrigger(node);
finished_actions.remove(context);
}
public void contextAdded(IRunControl.RunControlContext[] contexts) {
for (int i = 0; i < contexts.length; i++) {
String id = contexts[i].getParentID();
if (id == null) {
launch_node.onContextAdded(contexts[i]);
}
else {
TCFNode node = getNode(id);
if (node instanceof TCFNodeExecContext) {
((TCFNodeExecContext)node).onContextAdded(contexts[i]);
}
}
}
}
public void contextChanged(IRunControl.RunControlContext[] contexts) {
for (int i = 0; i < contexts.length; i++) {
TCFNode node = getNode(contexts[i].getID());
if (node instanceof TCFNodeExecContext) {
((TCFNodeExecContext)node).onContextChanged(contexts[i]);
}
}
}
public void contextException(String context, String msg) {
TCFNode node = getNode(context);
if (node instanceof TCFNodeExecContext) {
((TCFNodeExecContext)node).onContextException(msg);
}
}
public void contextRemoved(final String[] context_ids) {
onContextRemoved(context_ids);
}
public void contextResumed(final String context) {
TCFNode node = getNode(context);
if (node instanceof TCFNodeExecContext) {
((TCFNodeExecContext)node).onContextResumed();
}
display.asyncExec(new Runnable() {
public void run() {
Activator.getAnnotationManager().onContextResumed(TCFModel.this, context);
}
});
}
public void contextSuspended(final String context, String pc, String reason, Map<String,Object> params) {
TCFNode node = getNode(context);
if (node instanceof TCFNodeExecContext) {
final TCFNodeExecContext exe = (TCFNodeExecContext)node;
exe.onContextSuspended(pc, reason, params);
}
setDebugViewSelection(context);
runSuspendTrigger(node);
finished_actions.remove(context);
}
};
private final IRegisters.RegistersListener reg_listener = new IRegisters.RegistersListener() {
public void contextChanged() {
for (TCFNode node : id2node.values()) {
if (node instanceof TCFNodeExecContext) {
((TCFNodeExecContext)node).onRegistersChanged();
}
}
}
public void registerChanged(String context) {
TCFNode node = getNode(context);
if (node instanceof TCFNodeRegister) {
((TCFNodeRegister)node).onValueChanged();
}
}
};
private final IProcesses.ProcessesListener prs_listener = new IProcesses.ProcessesListener() {
public void exited(String process_id, int exit_code) {
IProcesses.ProcessContext prs = launch.getProcessContext();
if (prs != null && process_id.equals(prs.getID())) onLastContextRemoved();
}
};
private final IDebugModelProvider debug_model_provider = new IDebugModelProvider() {
public String[] getModelIdentifiers() {
return new String[] { ITCFConstants.ID_TCF_DEBUG_MODEL };
}
};
TCFModel(TCFLaunch launch) {
this.launch = launch;
display = PlatformUI.getWorkbench().getDisplay();
selection_policy = new TCFModelSelectionPolicy(this);
adapters.put(ILaunch.class, launch);
adapters.put(IModelSelectionPolicy.class, selection_policy);
adapters.put(IModelSelectionPolicyFactory.class, model_selection_factory);
adapters.put(IDebugModelProvider.class, debug_model_provider);
adapters.put(ISuspendHandler.class, new SuspendCommand(this));
adapters.put(IResumeHandler.class, new ResumeCommand(this));
adapters.put(ITerminateHandler.class, new TerminateCommand(this));
adapters.put(IDisconnectHandler.class, new DisconnectCommand(this));
adapters.put(IStepIntoHandler.class, new StepIntoCommand(this));
adapters.put(IStepOverHandler.class, new StepOverCommand(this));
adapters.put(IStepReturnHandler.class, new StepReturnCommand(this));
}
@SuppressWarnings("unchecked")
public Object getAdapter(final Class adapter, final TCFNode node) {
synchronized (adapters) {
Object o = adapters.get(adapter);
if (o != null) return o;
}
if (adapter == IMemoryBlockRetrieval.class || adapter == IMemoryBlockRetrievalExtension.class) {
return new TCFTask<Object>() {
public void run() {
Object o = null;
TCFNode n = node;
while (n != null && !n.isDisposed()) {
if (n instanceof TCFNodeExecContext) {
TCFNodeExecContext e = (TCFNodeExecContext)n;
TCFDataCache<IMemory.MemoryContext> cache = e.getMemoryContext();
if (!cache.validate(this)) return;
if (cache.getData() != null) {
o = mem_retrieval.get(e.id);
if (o == null) {
TCFMemoryBlockRetrieval m = new TCFMemoryBlockRetrieval(e);
mem_retrieval.put(e.id, m);
o = m;
}
break;
}
}
n = n.parent;
}
assert o == null || adapter.isInstance(o);
done(o);
}
}.getE();
}
return null;
}
void onConnected() {
assert Protocol.isDispatchThread();
assert launch_node == null;
channel = launch.getChannel();
launch_node = new TCFNodeLaunch(this);
IMemory mem = launch.getService(IMemory.class);
if (mem != null) mem.addListener(mem_listener);
IRunControl run = launch.getService(IRunControl.class);
if (run != null) run.addListener(run_listener);
IRegisters reg = launch.getService(IRegisters.class);
if (reg != null) reg.addListener(reg_listener);
IProcesses prs = launch.getService(IProcesses.class);
if (prs != null) prs.addListener(prs_listener);
launchChanged();
}
void onDisconnected() {
assert Protocol.isDispatchThread();
if (launch_node != null) {
launch_node.dispose();
launch_node = null;
}
refreshLaunchView();
assert id2node.size() == 0;
}
void onProcessOutput(String process_id, final int stream_id, byte[] data) {
try {
IProcesses.ProcessContext prs = launch.getProcessContext();
if (prs == null || !process_id.equals(prs.getID())) return;
if (console == null) {
final IOConsole c = new IOConsole("TCF " + process_id, null,
ImageCache.getImageDescriptor(ImageCache.IMG_TCF), "UTF-8", true);
display.asyncExec(new Runnable() {
public void run() {
try {
IConsoleManager manager = ConsolePlugin.getDefault().getConsoleManager();
manager.addConsoles(new IConsole[]{ c });
IWorkbenchWindow w = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (w == null) return;
IWorkbenchPage page = w.getActivePage();
if (page == null) return;
IConsoleView view = (IConsoleView)page.showView(IConsoleConstants.ID_CONSOLE_VIEW);
view.display(c);
}
catch (Throwable x) {
Activator.log("Cannot open console view", x);
}
}
});
console = new Console(c);
}
IOConsoleOutputStream stream = console.out.get(stream_id);
if (stream == null) {
final IOConsoleOutputStream s = stream = console.console.newOutputStream();
display.asyncExec(new Runnable() {
public void run() {
try {
int color_id = SWT.COLOR_BLACK;
switch (stream_id) {
case 1: color_id = SWT.COLOR_RED; break;
case 2: color_id = SWT.COLOR_BLUE; break;
case 3: color_id = SWT.COLOR_GREEN; break;
}
s.setColor(display.getSystemColor(color_id));
}
catch (Throwable x) {
Activator.log("Cannot open console view", x);
}
}
});
console.out.put(stream_id, stream);
}
stream.write(data, 0, data.length);
}
catch (Throwable x) {
Activator.log("Cannot write to console", x);
}
}
void onContextActionsStart(String id) {
running_actions.add(id);
}
void onContextActionsDone(String id, String result) {
running_actions.remove(id);
for (TCFModelProxy p : model_proxies.values()) p.run();
finished_actions.put(id, result);
setDebugViewSelection(id);
}
String getContextActionResult(String id) {
return finished_actions.get(id);
}
boolean isContextActionResultAvailable(String id) {
return finished_actions.containsKey(id);
}
void onProxyInstalled(final IPresentationContext p, final TCFModelProxy mp) {
model_proxies.put(p, mp);
}
void onProxyDisposed(final IPresentationContext p) {
assert model_proxies.containsKey(p);
model_proxies.remove(p);
}
private void onContextRemoved(final String[] context_ids) {
boolean close_channel = false;
for (String id : context_ids) {
launch.removeContextActions(id, null);
TCFNode node = getNode(id);
if (node instanceof TCFNodeExecContext) {
((TCFNodeExecContext)node).onContextRemoved();
if (node.parent == launch_node) close_channel = true;
}
finished_actions.remove(id);
}
if (close_channel) {
// Close debug session if the last context is removed:
onLastContextRemoved();
}
display.asyncExec(new Runnable() {
public void run() {
for (String id : context_ids) {
Activator.getAnnotationManager().onContextRemoved(TCFModel.this, id);
}
}
});
}
private void onLastContextRemoved() {
Protocol.invokeLater(1000, new Runnable() {
public void run() {
if (launch_node == null) return;
if (launch_node.isDisposed()) return;
TCFChildrenExecContext children = launch_node.getChildren();
if (!children.validate(this)) return;
if (children.size() != 0) return;
launch.onLastContextRemoved();
}
});
}
/**
* Create and post ModelDelta for changes in this node.
* @param flags - description of what has changed: IModelDelta.ADDED, IModelDelta.REMOVED, etc.
*/
final void addDelta(TCFNode node, int flags) {
for (TCFModelProxy p : model_proxies.values()) {
int f = flags & node.getRelevantModelDeltaFlags(p.getPresentationContext());
if (f != 0) p.addDelta(node, f);
}
}
void launchChanged() {
if (launch_node != null) {
launch_node.addModelDelta(IModelDelta.STATE | IModelDelta.CONTENT);
}
else {
refreshLaunchView();
}
}
void dispose() {
if (console != null) {
display.asyncExec(new Runnable() {
public void run() {
console.close();
IConsoleManager manager = ConsolePlugin.getDefault().getConsoleManager();
manager.removeConsoles(new IOConsole[]{ console.console });
}
});
}
}
void addNode(String id, TCFNode node) {
assert id != null;
assert Protocol.isDispatchThread();
assert id2node.get(id) == null;
assert !node.isDisposed();
id2node.put(id, node);
}
void removeNode(String id) {
assert id != null;
assert Protocol.isDispatchThread();
id2node.remove(id);
mem_retrieval.remove(id);
}
public Display getDisplay() {
return display;
}
public TCFLaunch getLaunch() {
return launch;
}
public IChannel getChannel() {
return channel;
}
public TCFNode getRootNode() {
return launch_node;
}
public TCFNode getNode(String id) {
if (id == null) return null;
if (id.equals("")) return launch_node;
assert Protocol.isDispatchThread();
return id2node.get(id);
}
public String getCastToType(String id) {
return cast_to_type_map.get(id);
}
public void setCastToType(String id, String type) {
if (type != null && type.trim().length() == 0) type = null;
if (type == null) cast_to_type_map.remove(id);
else cast_to_type_map.put(id, type);
TCFNode node = id2node.get(id);
if (node instanceof ICastToType) {
((ICastToType)node).onCastToTypeChanged();
}
}
public TCFDataCache<ISymbols.Symbol> getSymbolInfoCache(final String sym_id) {
if (sym_id == null) return null;
TCFNodeSymbol n = (TCFNodeSymbol)getNode(sym_id);
if (n == null) n = new TCFNodeSymbol(launch_node, sym_id);
return n.getContext();
}
public TCFDataCache<String[]> getSymbolChildrenCache(final String sym_id) {
if (sym_id == null) return null;
TCFNodeSymbol n = (TCFNodeSymbol)getNode(sym_id);
if (n == null) n = new TCFNodeSymbol(launch_node, sym_id);
return n.getChildren();
}
public void update(IChildrenCountUpdate[] updates) {
for (int i = 0; i < updates.length; i++) {
Object o = updates[i].getElement();
if (o instanceof TCFLaunch) {
if (launch_node != null) {
launch_node.update(updates[i]);
}
else {
updates[i].setChildCount(0);
updates[i].done();
}
}
else {
((TCFNode)o).update(updates[i]);
}
}
}
public void update(IChildrenUpdate[] updates) {
for (int i = 0; i < updates.length; i++) {
Object o = updates[i].getElement();
if (o instanceof TCFLaunch) {
if (launch_node != null) {
launch_node.update(updates[i]);
}
else {
updates[i].done();
}
}
else {
((TCFNode)o).update(updates[i]);
}
}
}
public void update(IHasChildrenUpdate[] updates) {
for (int i = 0; i < updates.length; i++) {
Object o = updates[i].getElement();
if (o instanceof TCFLaunch) {
if (launch_node != null) {
launch_node.update(updates[i]);
}
else {
updates[i].setHasChilren(false);
updates[i].done();
}
}
else {
((TCFNode)o).update(updates[i]);
}
}
}
public void update(ILabelUpdate[] updates) {
for (int i = 0; i < updates.length; i++) {
Object o = updates[i].getElement();
// Launch label is provided by TCFLaunchLabelProvider class.
assert !(o instanceof TCFLaunch);
((TCFNode)o).update(updates[i]);
}
}
public IModelProxy createModelProxy(Object element, IPresentationContext context) {
return new TCFModelProxy(this);
}
public IColumnPresentation createColumnPresentation(IPresentationContext context, Object element) {
String id = getColumnPresentationId(context, element);
if (id == null) return null;
if (id.equals(TCFColumnPresentationRegister.PRESENTATION_ID)) return new TCFColumnPresentationRegister();
if (id.equals(TCFColumnPresentationExpression.PRESENTATION_ID)) return new TCFColumnPresentationExpression();
return null;
}
public String getColumnPresentationId(IPresentationContext context, Object element) {
if (IDebugUIConstants.ID_REGISTER_VIEW.equals(context.getId())) {
return TCFColumnPresentationRegister.PRESENTATION_ID;
}
if (IDebugUIConstants.ID_VARIABLE_VIEW.equals(context.getId())) {
return TCFColumnPresentationExpression.PRESENTATION_ID;
}
if (IDebugUIConstants.ID_EXPRESSION_VIEW.equals(context.getId())) {
return TCFColumnPresentationExpression.PRESENTATION_ID;
}
return null;
}
public void setDebugViewSelection(final String node_id) {
assert Protocol.isDispatchThread();
Protocol.invokeLater(new Runnable() {
public void run() {
TCFNode node = getNode(node_id);
if (node == null) return;
if (node.disposed) return;
if (running_actions.contains(node_id)) return;
for (TCFModelProxy proxy : model_proxies.values()) {
if (proxy.getPresentationContext().getId().equals(IDebugUIConstants.ID_DEBUG_VIEW)) {
proxy.setSelection(node);
}
}
}
});
}
/**
* Reveal source code associated with given model element.
* The method is part of ISourceDisplay interface.
* The method is normally called from SourceLookupService.
*/
public void displaySource(Object model_element, final IWorkbenchPage page, boolean forceSourceLookup) {
final int cnt = ++display_source_cnt;
/* Because of racing in Eclipse Debug infrastructure, 'model_element' value can be invalid.
* As a workaround, get current debug view selection.
*/
if (page != null) {
ISelection context = DebugUITools.getDebugContextManager().getContextService(page.getWorkbenchWindow()).getActiveContext();
if (context instanceof IStructuredSelection) {
IStructuredSelection selection = (IStructuredSelection)context;
if (!selection.isEmpty()) model_element = selection.getFirstElement();
}
}
final Object element = model_element;
Protocol.invokeLater(new Runnable() {
public void run() {
if (cnt != display_source_cnt) return;
TCFNodeExecContext exec_ctx = null;
TCFNodeStackFrame stack_frame = null;
if (!disposed && channel.getState() == IChannel.STATE_OPEN) {
if (element instanceof TCFNodeExecContext) {
exec_ctx = (TCFNodeExecContext)element;
if (!exec_ctx.disposed) {
TCFDataCache<TCFContextState> state_cache = exec_ctx.getState();
if (!state_cache.validate(this)) return;
TCFContextState state_data = state_cache.getData();
if (state_data != null && state_data.is_suspended) {
TCFChildrenStackTrace stack_trace = exec_ctx.getStackTrace();
if (!stack_trace.validate(this)) return;
stack_frame = stack_trace.getTopFrame();
}
}
}
else if (element instanceof TCFNodeStackFrame) {
TCFNodeStackFrame f = (TCFNodeStackFrame)element;
exec_ctx = (TCFNodeExecContext)f.parent;
if (!f.disposed && !exec_ctx.disposed) {
TCFDataCache<TCFContextState> state_cache = exec_ctx.getState();
if (!state_cache.validate(this)) return;
TCFContextState state_data = state_cache.getData();
if (state_data != null && state_data.is_suspended) {
stack_frame = f;
}
}
}
}
if (stack_frame != null) {
TCFDataCache<TCFSourceRef> line_info = stack_frame.getLineInfo();
if (!line_info.validate(this)) return;
Throwable error = line_info.getError();
TCFSourceRef src_ref = line_info.getData();
if (error == null && src_ref != null) error = src_ref.error;
if (error != null) Activator.log("Error retrieving source mapping for a stack frame", error);
ILineNumbers.CodeArea area = src_ref == null ? null : src_ref.area;
displaySource(cnt, page, stack_frame.parent.id, stack_frame.getFrameNo() == 0, area);
}
else {
displaySource(cnt, page, null, false, null);
}
}
});
}
private void displaySource(final int cnt, final IWorkbenchPage page,
final String exe_id, final boolean top_frame, final ILineNumbers.CodeArea area) {
display.asyncExec(new Runnable() {
public void run() {
if (cnt != display_source_cnt) return;
String editor_id = null;
IEditorInput editor_input = null;
int line = 0;
if (area != null) {
ISourceLocator locator = getLaunch().getSourceLocator();
Object source_element = null;
if (locator instanceof ISourceLookupDirector) {
source_element = ((ISourceLookupDirector)locator).getSourceElement(area);
}
if (source_element != null) {
ISourcePresentation presentation = TCFModelPresentation.getDefault();
if (presentation != null) {
editor_input = presentation.getEditorInput(source_element);
}
if (editor_input != null) {
editor_id = presentation.getEditorId(editor_input, source_element);
}
line = area.start_line;
}
if (cnt != display_source_cnt) return;
}
if (area != null && (editor_input == null || editor_id == null)) {
ILaunchConfiguration cfg = launch.getLaunchConfiguration();
editor_id = IDebugUIConstants.ID_COMMON_SOURCE_NOT_FOUND_EDITOR;
editor_input = editor_not_found.get(cfg);
if (editor_input == null) {
editor_input = new CommonSourceNotFoundEditorInput(cfg);
editor_not_found.put(cfg, editor_input);
}
}
ITextEditor text_editor = null;
IRegion region = null;
if (editor_input != null && editor_id != null && page != null) {
IEditorPart editor = openEditor(editor_input, editor_id, page);
if (editor instanceof ITextEditor) {
text_editor = (ITextEditor)editor;
}
else {
text_editor = (ITextEditor)editor.getAdapter(ITextEditor.class);
}
}
if (text_editor != null) {
region = getLineInformation(text_editor, line);
if (region != null) text_editor.selectAndReveal(region.getOffset(), 0);
}
Activator.getAnnotationManager().addStackFrameAnnotation(TCFModel.this,
exe_id, top_frame, page, text_editor, region);
}
});
}
/*
* Refresh Launch View.
* Normally the view is updated by sending deltas through model proxy.
* This method is used only when launch is not yet connected or already disconnected.
*/
private void refreshLaunchView() {
// TODO: there should be a better way to refresh Launch View
final Throwable error = launch.getError();
if (error != null) launch.setError(null);
synchronized (Device.class) {
if (display.isDisposed()) return;
display.asyncExec(new Runnable() {
public void run() {
IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows();
if (windows == null) return;
for (IWorkbenchWindow window : windows) {
IDebugView view = (IDebugView)window.getActivePage().findView(IDebugUIConstants.ID_DEBUG_VIEW);
if (view != null) ((StructuredViewer)view.getViewer()).refresh(launch);
}
}
});
if (error != null) showMessageBox("TCF Launch Error", error);
}
}
/**
* Show error message box in active workbench window.
* @param title - message box title.
* @param error - error to be shown.
*/
public void showMessageBox(final String title, final Throwable error) {
display.asyncExec(new Runnable() {
public void run() {
Shell shell = display.getActiveShell();
if (shell == null) {
Shell[] shells = display.getShells();
HashSet<Shell> set = new HashSet<Shell>();
for (Shell s : shells) set.add(s);
for (Shell s : shells) {
if (s.getParent() != null) set.remove(s.getParent().getShell());
}
for (Shell s : shells) shell = s;
}
MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
mb.setText(title);
mb.setMessage(getErrorMessage(error, true));
mb.open();
}
});
}
/**
* Create human readable error message from a Throwable object.
* @param error - a Throwable object.
* @param multiline - true if multi-line text is allowed.
* @return
*/
public static String getErrorMessage(Throwable error, boolean multiline) {
StringBuffer buf = new StringBuffer();
while (error != null) {
String msg = null;
- if (error instanceof IErrorReport) {
+ if (!multiline && error instanceof IErrorReport) {
msg = Command.toErrorString(((IErrorReport)error).getAttributes());
}
else {
msg = error.getLocalizedMessage();
}
if (msg == null || msg.length() == 0) msg = error.getClass().getName();
buf.append(msg);
error = error.getCause();
if (error != null) {
char ch = buf.charAt(buf.length() - 1);
if (multiline && ch != '\n') {
buf.append('\n');
}
else if (ch != '.' && ch != ';') {
buf.append(';');
}
buf.append("Caused by:");
buf.append(multiline ? '\n' : ' ');
}
}
if (buf.length() > 0) {
char ch = buf.charAt(buf.length() - 1);
if (multiline && ch != '\n') {
buf.append('\n');
}
}
return buf.toString();
}
/*
* Open an editor for given editor input.
* @param input - IEditorInput representing a source file to be shown in the editor
* @param id - editor type ID
* @param page - workbench page that will contain the editor
* @return - IEditorPart if the editor was opened successfully, or null otherwise.
*/
private IEditorPart openEditor(final IEditorInput input, final String id, final IWorkbenchPage page) {
final IEditorPart[] editor = new IEditorPart[]{ null };
Runnable r = new Runnable() {
public void run() {
if (!page.getWorkbenchWindow().getWorkbench().isClosing()) {
try {
editor[0] = page.openEditor(input, id, false, IWorkbenchPage.MATCH_ID|IWorkbenchPage.MATCH_INPUT);
}
catch (PartInitException e) {
Activator.log("Cannot open editor", e);
}
}
}
};
BusyIndicator.showWhile(display, r);
return editor[0];
}
/*
* Returns the line information for the given line in the given editor
*/
private IRegion getLineInformation(ITextEditor editor, int lineNumber) {
IDocumentProvider provider = editor.getDocumentProvider();
IEditorInput input = editor.getEditorInput();
try {
provider.connect(input);
}
catch (CoreException e) {
return null;
}
try {
IDocument document = provider.getDocument(input);
if (document != null)
return document.getLineInformation(lineNumber - 1);
}
catch (BadLocationException e) {
}
finally {
provider.disconnect(input);
}
return null;
}
public synchronized void addSuspendTriggerListener(ISuspendTriggerListener listener) {
suspend_trigger_listeners.add(listener);
}
public synchronized void removeSuspendTriggerListener(ISuspendTriggerListener listener) {
suspend_trigger_listeners.remove(listener);
}
private synchronized void runSuspendTrigger(final TCFNode node) {
final int generation = ++suspend_trigger_generation;
final ISuspendTriggerListener[] listeners = suspend_trigger_listeners.toArray(
new ISuspendTriggerListener[suspend_trigger_listeners.size()]);
if (listeners.length == 0) return;
display.asyncExec(new Runnable() {
public void run() {
synchronized (TCFModel.this) {
if (generation != suspend_trigger_generation) return;
}
for (final ISuspendTriggerListener listener : listeners) {
try {
listener.suspended(launch, node);
}
catch (Throwable x) {
Activator.log(x);
}
}
}
});
}
}
| false | false | null | null |
diff --git a/src/com/herocraftonline/dev/heroes/persistence/HeroManager.java b/src/com/herocraftonline/dev/heroes/persistence/HeroManager.java
index 1cae8ca4..d8cf9c3c 100644
--- a/src/com/herocraftonline/dev/heroes/persistence/HeroManager.java
+++ b/src/com/herocraftonline/dev/heroes/persistence/HeroManager.java
@@ -1,638 +1,642 @@
package com.herocraftonline.dev.heroes.persistence;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import com.herocraftonline.dev.heroes.party.HeroParty;
import com.herocraftonline.dev.heroes.party.PartyManager;
import com.herocraftonline.dev.heroes.ui.MapAPI;
import com.herocraftonline.dev.heroes.ui.MapInfo;
import com.herocraftonline.dev.heroes.ui.TextRenderer;
import com.herocraftonline.dev.heroes.ui.TextRenderer.CharacterSprite;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.config.Configuration;
import com.herocraftonline.dev.heroes.Heroes;
import com.herocraftonline.dev.heroes.classes.HeroClass;
import com.herocraftonline.dev.heroes.command.Command;
import com.herocraftonline.dev.heroes.effects.Effect;
import com.herocraftonline.dev.heroes.effects.Expirable;
import com.herocraftonline.dev.heroes.effects.Periodic;
import com.herocraftonline.dev.heroes.skill.OutsourcedSkill;
import com.herocraftonline.dev.heroes.skill.PassiveSkill;
import com.herocraftonline.dev.heroes.util.Messaging;
/**
* Player management
*
* @author Herocraft's Plugin Team
*/
public class HeroManager {
private Heroes plugin;
private Set<Hero> heroes;
protected Map<Creature, Set<Effect>> creatureEffects;
private File playerFolder;
private final static int effectInterval = 2;
private final static int manaInterval = 5;
private final static int partyUpdateInterval = 5;
public HeroManager(Heroes plugin) {
this.plugin = plugin;
this.heroes = new HashSet<Hero>();
this.creatureEffects = new HashMap<Creature, Set<Effect>>();
playerFolder = new File(plugin.getDataFolder(), "players"); // Setup our Player Data Folder
playerFolder.mkdirs(); // Create the folder if it doesn't exist.
Runnable effectTimer = new EffectUpdater(this);
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, effectTimer, 0, effectInterval);
Runnable manaTimer = new ManaUpdater(this);
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, manaTimer, 0, manaInterval);
Runnable partyUpdater = new PartyUpdater(this, plugin, plugin.getPartyManager());
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, partyUpdater, 0, partyUpdateInterval);
}
public boolean addHero(Hero hero) {
return heroes.add(hero);
}
public boolean containsPlayer(Player player) {
return getHero(player) != null;
}
public Hero createNewHero(Player player) {
Hero hero = new Hero(plugin, player, plugin.getClassManager().getDefaultClass());
hero.setMana(100);
hero.setHealth(hero.getMaxHealth());
hero.syncHealth();
addHero(hero);
return hero;
}
public Hero getHero(Player player) {
for (Hero hero : getHeroes()) {
if (hero == null || hero.getPlayer() == null) {
removeHero(hero); // Seeing as it's null we might as well remove it.
continue;
}
if (player.getName().equalsIgnoreCase(hero.getPlayer().getName())) return hero;
}
// If it gets to this stage then clearly the HeroManager doesn't have it so we create it...
return loadHero(player);
}
public Set<Hero> getHeroes() {
return new HashSet<Hero>(heroes);
}
/**
* Load the given Players Data file.
*
* @param player
* @return
*/
public Hero loadHero(Player player) {
File playerFile = new File(playerFolder, player.getName() + ".yml"); // Setup our Players Data File.
// Check if it already exists, if so we load the data.
if (playerFile.exists()) {
Configuration playerConfig = new Configuration(playerFile); // Setup the Configuration
playerConfig.load(); // Load the Config File
HeroClass playerClass = loadClass(player, playerConfig);
if (playerClass == null) {
Heroes.log(Level.INFO, "Invalid class found for " + player.getName() + ". Resetting player.");
return createNewHero(player);
}
Hero playerHero = new Hero(plugin, player, playerClass);
loadCooldowns(playerHero, playerConfig);
loadExperience(playerHero, playerConfig);
loadRecoveryItems(playerHero, playerConfig);
loadBinds(playerHero, playerConfig);
loadSkillSettings(playerHero, playerConfig);
playerHero.setMana(playerConfig.getInt("mana", 0));
playerHero.setHealth(playerConfig.getDouble("health", playerClass.getBaseMaxHealth()));
playerHero.setVerbose(playerConfig.getBoolean("verbose", true));
playerHero.suppressedSkills = new HashSet<String>(playerConfig.getStringList("suppressed", null));
addHero(playerHero);
playerHero.syncHealth();
performSkillChecks(playerHero);
Heroes.log(Level.INFO, "Loaded hero: " + player.getName());
return playerHero;
} else {
// Create a New Hero with the Default Setup.
Heroes.log(Level.INFO, "Created hero: " + player.getName());
return createNewHero(player);
}
}
public boolean removeHero(Hero hero) {
if (hero != null && hero.hasParty()) {
HeroParty party = hero.getParty();
party.removeMember(hero);
if (party.getMembers().size() == 0) {
this.plugin.getPartyManager().removeParty(party);
}
}
return heroes.remove(hero);
}
/**
* Save the given Players Data to a file.
*
* @param player
*/
public void saveHero(Player player) {
File playerFile = new File(playerFolder, player.getName() + ".yml");
Configuration playerConfig = new Configuration(playerFile);
// Save the players stuff
Hero hero = getHero(player);
playerConfig.setProperty("class", hero.getHeroClass().toString());
playerConfig.setProperty("verbose", hero.isVerbose());
playerConfig.setProperty("suppressed", new ArrayList<String>(hero.getSuppressedSkills()));
playerConfig.setProperty("mana", hero.getMana());
playerConfig.removeProperty("itemrecovery");
playerConfig.setProperty("health", hero.getHealth());
saveSkillSettings(hero, playerConfig);
saveCooldowns(hero, playerConfig);
saveExperience(hero, playerConfig);
saveRecoveryItems(hero, playerConfig);
saveBinds(hero, playerConfig);
playerConfig.save();
Heroes.log(Level.INFO, "Saved hero: " + player.getName());
}
public void stopTimers() {
plugin.getServer().getScheduler().cancelTasks(plugin);
}
private void loadBinds(Hero hero, Configuration config) {
Map<Material, String[]> binds = new HashMap<Material, String[]>();
List<String> bindKeys = config.getKeys("binds");
if (bindKeys != null && bindKeys.size() > 0) {
for (String material : bindKeys) {
try {
Material item = Material.valueOf(material);
String bind = config.getString("binds." + material, "");
if (bind.length() > 0) {
binds.put(item, bind.split(" "));
}
} catch (IllegalArgumentException e) {
this.plugin.debugLog(Level.WARNING, material + " isn't a valid Item to bind a Skill to.");
continue;
}
}
}
hero.binds = binds;
}
private HeroClass loadClass(Player player, Configuration config) {
HeroClass playerClass = null;
if (config.getString("class") != null) {
playerClass = plugin.getClassManager().getClass(config.getString("class"));
if (Heroes.Permissions != null && playerClass != plugin.getClassManager().getDefaultClass()) {
if (!Heroes.Permissions.has(player, "heroes.classes." + playerClass.getName().toLowerCase())) {
playerClass = plugin.getClassManager().getDefaultClass();
}
}
} else {
playerClass = plugin.getClassManager().getDefaultClass();
}
return playerClass;
}
private void loadSkillSettings(Hero hero, Configuration config) {
String path = "skill-settings";
if (config.getKeys(path) != null) {
for (String skill : config.getKeys(path)) {
if (config.getNode(path).getKeys(skill) != null) {
for (String node : config.getNode(path).getKeys(skill)) {
hero.setSkillSetting(skill, node, config.getNode(path).getNode(skill).getString(node));
}
}
}
}
}
private void loadCooldowns(Hero hero, Configuration config) {
HeroClass heroClass = hero.getHeroClass();
String path = "cooldowns";
List<String> storedCooldowns = config.getKeys(path);
if (storedCooldowns != null) {
long time = System.currentTimeMillis();
Map<String, Long> cooldowns = new HashMap<String, Long>();
for (String skillName : storedCooldowns) {
long cooldown = (long) config.getDouble(path + "." + skillName, 0);
if (heroClass.hasSkill(skillName) && cooldown > time) {
cooldowns.put(skillName, cooldown);
}
}
hero.cooldowns = cooldowns;
}
}
+
+ HashMap<Creature, Set<Effect>> getCreatureEffects() {
+ return new HashMap<Creature, Set<Effect>>(creatureEffects);
+ }
private void loadExperience(Hero hero, Configuration config) {
if (hero == null || hero.getClass() == null || config == null) return;
String root = "experience";
List<String> expList = config.getKeys(root);
if (expList != null) {
for (String className : expList) {
double exp = config.getDouble(root + "." + className, 0);
HeroClass heroClass = plugin.getClassManager().getClass(className);
if (heroClass != null) {
if (hero.getExperience(heroClass) == 0) {
hero.setExperience(heroClass, exp);
if (!heroClass.isPrimary() && exp > 0) {
hero.setExperience(heroClass.getParent(), plugin.getConfigManager().getProperties().maxExp);
}
}
}
}
}
}
private void loadRecoveryItems(Hero hero, Configuration config) {
List<ItemStack> itemRecovery = new ArrayList<ItemStack>();
List<String> itemKeys = config.getKeys("itemrecovery");
if (itemKeys != null && itemKeys.size() > 0) {
for (String item : itemKeys) {
try {
Short durability = Short.valueOf(config.getString("itemrecovery." + item, "0"));
Material type = Material.valueOf(item);
itemRecovery.add(new ItemStack(type, 1, durability));
} catch (IllegalArgumentException e) {
this.plugin.debugLog(Level.WARNING, "Either '" + item + "' doesn't exist or the durability is of an incorrect value!");
}
}
}
hero.setRecoveryItems(itemRecovery);
}
private void performSkillChecks(Hero hero) {
HeroClass playerClass = hero.getHeroClass();
List<Command> commands = plugin.getCommandHandler().getCommands();
if (Heroes.Permissions != null) {
for (Command cmd : commands) {
if (cmd instanceof OutsourcedSkill) {
OutsourcedSkill skill = (OutsourcedSkill) cmd;
if (playerClass.hasSkill(skill.getName())) {
skill.tryLearningSkill(hero);
}
}
}
}
for (Command cmd : commands) {
if (cmd instanceof PassiveSkill) {
PassiveSkill skill = (PassiveSkill) cmd;
if (playerClass.hasSkill(skill.getName())) {
skill.tryApplying(hero);
}
}
}
}
private void saveBinds(Hero hero, Configuration config) {
config.removeProperty("binds");
Map<Material, String[]> binds = hero.getBinds();
for (Material material : binds.keySet()) {
String[] bindArgs = binds.get(material);
StringBuilder bind = new StringBuilder();
for (String arg : bindArgs) {
bind.append(arg).append(" ");
}
config.setProperty("binds." + material.toString(), bind.toString().substring(0, bind.toString().length() - 1));
}
}
private void saveSkillSettings(Hero hero, Configuration config) {
String path = "skill-settings";
for (Entry<String, Map<String, String>> entry : hero.skillSettings.entrySet()) {
for(Entry<String, String> node : entry.getValue().entrySet()) {
config.setProperty(path + "." + entry.getKey() + "." + node.getKey(), node.getValue());
}
}
}
private void saveCooldowns(Hero hero, Configuration config) {
String path = "cooldowns";
long time = System.currentTimeMillis();
Map<String, Long> cooldowns = hero.getCooldowns();
for (Map.Entry<String, Long> entry : cooldowns.entrySet()) {
String skillName = entry.getKey();
long cooldown = entry.getValue();
if (cooldown > time) {
System.out.println(path + "." + skillName);
config.setProperty(path + "." + skillName, cooldown);
}
}
}
private void saveExperience(Hero hero, Configuration config) {
if (hero == null || hero.getClass() == null || config == null) return;
String root = "experience";
for (Map.Entry<String, Double> entry : hero.experience.entrySet()) {
config.setProperty(root + "." + entry.getKey(), (double) entry.getValue());
}
}
private void saveRecoveryItems(Hero hero, Configuration config) {
for (ItemStack item : hero.getRecoveryItems()) {
String durability = Short.toString(item.getDurability());
config.setProperty("itemrecovery." + item.getType().toString(), durability);
}
}
/**
* Adds a new effect to the specific creature
*
* @param creature
* @param effect
*/
public void addCreatureEffect(Creature creature, Effect effect) {
Set<Effect> cEffects = creatureEffects.get(creature);
if (cEffects == null) {
cEffects = new HashSet<Effect>();
creatureEffects.put(creature, cEffects);
}
cEffects.add(effect);
effect.apply(creature);
}
/**
* Removes an effect from a creature
*
* @param creature
* @param effect
*/
public void removeCreatureEffect(Creature creature, Effect effect) {
Set<Effect> cEffects = creatureEffects.get(creature);
if (cEffects != null) {
effect.remove(creature);
cEffects.remove(effect);
//If the creature has no effects left
if (cEffects.isEmpty()) {
creatureEffects.remove(creature);
}
}
}
/**
* Clears all effects from the creature
*
* @param creature
*/
public void clearCreatureEffects(Creature creature) {
if (creatureEffects.containsKey(creature)) {
for(Effect effect : creatureEffects.get(creature)) {
removeCreatureEffect(creature, effect);
}
}
}
/**
* Checks if a creature has the effect
*
* @param creature
* @param effect
* @return
*/
public boolean creatureHasEffect(Creature creature, String name) {
if (!creatureEffects.containsKey(creature)) return false;
for (Effect effect : creatureEffects.get(creature)) {
if (effect.getName().equalsIgnoreCase(name)) {
return true;
}
}
return false;
}
/**
* Gets a set view of all effects currently applied to the specified creature
*
* @param creature
* @return
*/
public Set<Effect> getCreatureEffects(Creature creature) {
return creatureEffects.get(creature);
}
public Effect getCreatureEffect(Creature creature, String name) {
if (creatureEffects.get(creature) == null) return null;
for (Effect effect : creatureEffects.get(creature)) {
if (effect.getName().equals(name)) {
return effect;
}
}
return null;
}
}
class EffectUpdater implements Runnable {
private final HeroManager heroManager;
EffectUpdater(HeroManager heroManager) {
this.heroManager = heroManager;
}
public void run() {
for (Hero hero : heroManager.getHeroes()) {
for (Effect effect : hero.getEffects()) {
if (effect instanceof Expirable) {
Expirable expirable = (Expirable) effect;
if (expirable.isExpired()) {
hero.removeEffect(effect);
continue;
}
}
if (effect instanceof Periodic) {
Periodic periodic = (Periodic) effect;
if (periodic.isReady()) {
periodic.tick(hero);
}
}
}
}
- for (Entry<Creature, Set<Effect>> cEntry : heroManager.creatureEffects.entrySet()) {
+ for (Entry<Creature, Set<Effect>> cEntry : heroManager.getCreatureEffects().entrySet()) {
for (Effect effect : cEntry.getValue()) {
if (effect instanceof Expirable) {
Expirable expirable = (Expirable) effect;
if (expirable.isExpired()) {
heroManager.removeCreatureEffect(cEntry.getKey(), effect);
continue;
}
}
if (effect instanceof Periodic) {
Periodic periodic = (Periodic) effect;
if (periodic.isReady()) {
periodic.tick(cEntry.getKey());
}
}
}
}
}
}
class ManaUpdater implements Runnable {
private final HeroManager manager;
private final long updateInterval = 5000;
private long lastUpdate = 0;
ManaUpdater(HeroManager manager) {
this.manager = manager;
}
public void run() {
long time = System.currentTimeMillis();
if (time < lastUpdate + updateInterval) {
return;
}
lastUpdate = time;
Set<Hero> heroes = manager.getHeroes();
for (Hero hero : heroes) {
if (hero == null) {
continue;
}
int mana = hero.getMana();
hero.setMana(mana > 100 ? mana : mana > 95 ? 100 : mana + 5); // Hooray for the ternary operator!
if (mana != 100 && hero.isVerbose()) {
Messaging.send(hero.getPlayer(), ChatColor.BLUE + "MANA " + Messaging.createManaBar(hero.getMana()));
}
}
}
}
class PartyUpdater implements Runnable {
private final HeroManager manager;
private final Heroes plugin;
private final PartyManager partyManager;
PartyUpdater(HeroManager manager, Heroes plugin, PartyManager partyManager) {
this.manager = manager;
this.plugin = plugin;
this.partyManager = partyManager;
}
public void run() {
if (!this.plugin.getConfigManager().getProperties().mapUI) return;
// System.out.print("Size - " + partyManager.getParties().size() + " Tick - " +
// Bukkit.getServer().getWorlds().get(0).getTime());
if (partyManager.getParties().size() == 0) return;
for (HeroParty party : partyManager.getParties()) {
if (party.updateMapDisplay()) {
party.setUpdateMapDisplay(false);
Player[] players = new Player[party.getMembers().size()];
int count = 0;
for (Hero heroes : party.getMembers()) {
players[count] = heroes.getPlayer();
count++;
}
updateMapView(players);
}
}
}
private void updateMapView(Player[] players) {
MapAPI mapAPI = new MapAPI();
short mapId = this.plugin.getConfigManager().getProperties().mapID;
TextRenderer text = new TextRenderer(this.plugin);
CharacterSprite sword = CharacterSprite.make(" XX", " XXX", " XXX ", "X XXX ", " XXXX ", " XX ", " X X ", "X X ");
CharacterSprite crown = CharacterSprite.make(" ", " ", "XX XX XX", "X XXXX X", "XX XX XX", " XXXXXX ", " XXXXXX ", " ");
CharacterSprite shield = CharacterSprite.make(" XX ", "X XX X", "XXXXXXXX", "XXXXXXXX", "XXXXXXXX", " XXXXXX ", " XXXX ", " XX ");
CharacterSprite heal = CharacterSprite.make(" ", " XXX ", " XXX ", "XXXXXXX ", "XXXXXXX ", "XXXXXXX ", " XXX ", " XXX ");
CharacterSprite bow = CharacterSprite.make("XXXX X", "X XX X ", " X X ", " X X X ", " X XX", " X X X", "XX X X", " X XX");
text.setChar('\u0001', crown);
text.setChar('\u0002', sword);
text.setChar('\u0003', shield);
text.setChar('\u0004', heal);
text.setChar('\u0005', bow);
MapInfo info = mapAPI.loadMap(Bukkit.getServer().getWorlds().get(0), mapId);
mapAPI.getWorldMap(Bukkit.getServer().getWorlds().get(0), mapId).map = (byte) 9;
info.setData(new byte[128 * 128]);
String map = "§22;Party Members -\n";
for (int i = 0; i < players.length; i++) {
Hero hero = this.manager.getHero(players[i]);
if (hero.getParty().getLeader().equals(hero)) {
map += "§42;\u0001";
} else {
map += "§27;\u0002";
}
boolean damage = plugin.getConfigManager().getProperties().damageSystem;
double currentHP;
double maxHP;
if (damage) {
currentHP = hero.getHealth();
maxHP = hero.getMaxHealth();
} else {
currentHP = hero.getPlayer().getHealth();
maxHP = 20;
}
map += " §12;" + players[i].getName() + "\n" + createHealthBar(currentHP, maxHP) + "\n";
}
text.fancyRender(info, 10, 3, map);
for (int i = 0; i < players.length; i++) {
mapAPI.sendMap(players[i], mapId, info.getData(), this.plugin.getConfigManager().getProperties().mapPacketInterval);
}
}
private static String createHealthBar(double health, double maxHealth) {
String manaBar = com.herocraftonline.dev.heroes.ui.MapColor.DARK_RED + "[" + com.herocraftonline.dev.heroes.ui.MapColor.DARK_GREEN;
int bars = 40;
int progress = (int) (health / maxHealth * bars);
for (int i = 0; i < progress; i++) {
manaBar += "|";
}
manaBar += com.herocraftonline.dev.heroes.ui.MapColor.DARK_GRAY;
for (int i = 0; i < bars - progress; i++) {
manaBar += "|";
}
manaBar += com.herocraftonline.dev.heroes.ui.MapColor.RED + "]";
double percent = (health / maxHealth * 100);
DecimalFormat df = new DecimalFormat("#.##");
return manaBar + " - " + com.herocraftonline.dev.heroes.ui.MapColor.GREEN + df.format(percent) + "%";
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/server/src/org/bedework/caldav/server/CaldavBWIntf.java b/server/src/org/bedework/caldav/server/CaldavBWIntf.java
index e132dfd..95586b4 100644
--- a/server/src/org/bedework/caldav/server/CaldavBWIntf.java
+++ b/server/src/org/bedework/caldav/server/CaldavBWIntf.java
@@ -1,1690 +1,1704 @@
/* **********************************************************************
Copyright 2007 Rensselaer Polytechnic Institute. All worldwide rights reserved.
Redistribution and use of this distribution in source and binary forms,
with or without modification, are permitted provided that:
The above copyright notice and this permission notice appear in all
copies and supporting documentation;
The name, identifiers, and trademarks of Rensselaer Polytechnic
Institute are not used in advertising or publicity without the
express prior written permission of Rensselaer Polytechnic Institute;
DISCLAIMER: The software is distributed" AS IS" without any express or
implied warranty, including but not limited to, any implied warranties
of merchantability or fitness for a particular purpose or any warrant)'
of non-infringement of any current or pending patent rights. The authors
of the software make no representations about the suitability of this
software for any particular purpose. The entire risk as to the quality
and performance of the software is with the user. Should the software
prove defective, the user assumes the cost of all necessary servicing,
repair or correction. In particular, neither Rensselaer Polytechnic
Institute, nor the authors of the software are liable for any indirect,
special, consequential, or incidental damages related to the software,
to the maximum extent the law permits.
*/
package org.bedework.caldav.server;
import org.bedework.caldav.server.PostMethod.RequestPars;
import org.bedework.caldav.server.calquery.CalendarData;
import org.bedework.caldav.server.calquery.FreeBusyQuery;
import org.bedework.caldav.server.filter.FilterHandler;
import org.bedework.caldav.server.get.FreeBusyGetHandler;
import org.bedework.caldav.server.get.GetHandler;
import org.bedework.caldav.server.get.IscheduleGetHandler;
import org.bedework.caldav.server.get.WebcalGetHandler;
import org.bedework.caldav.server.sysinterface.CalPrincipalInfo;
import org.bedework.caldav.server.sysinterface.RetrievalMode;
import org.bedework.caldav.server.sysinterface.SysIntf;
import org.bedework.caldav.util.CalDAVConfig;
import edu.rpi.cct.webdav.servlet.common.AccessUtil;
import edu.rpi.cct.webdav.servlet.common.Headers;
import edu.rpi.cct.webdav.servlet.common.WebdavServlet;
import edu.rpi.cct.webdav.servlet.common.WebdavUtils;
import edu.rpi.cct.webdav.servlet.common.MethodBase.MethodInfo;
import edu.rpi.cct.webdav.servlet.shared.PrincipalPropertySearch;
import edu.rpi.cct.webdav.servlet.shared.WdEntity;
import edu.rpi.cct.webdav.servlet.shared.WebdavBadRequest;
import edu.rpi.cct.webdav.servlet.shared.WebdavException;
import edu.rpi.cct.webdav.servlet.shared.WebdavForbidden;
import edu.rpi.cct.webdav.servlet.shared.WebdavNotFound;
import edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf;
import edu.rpi.cct.webdav.servlet.shared.WebdavNsNode;
import edu.rpi.cct.webdav.servlet.shared.WebdavPrincipalNode;
import edu.rpi.cct.webdav.servlet.shared.WebdavProperty;
import edu.rpi.cct.webdav.servlet.shared.WebdavServerError;
import edu.rpi.cct.webdav.servlet.shared.WebdavUnauthorized;
import edu.rpi.cct.webdav.servlet.shared.WebdavUnsupportedMediaType;
import edu.rpi.cmt.access.AccessException;
import edu.rpi.cmt.access.AccessPrincipal;
import edu.rpi.cmt.access.Ace;
import edu.rpi.cmt.access.AceWho;
import edu.rpi.cmt.access.Acl;
import edu.rpi.cmt.access.PrivilegeDefs;
import edu.rpi.cmt.access.WhoDefs;
import edu.rpi.cmt.access.AccessXmlUtil.AccessXmlCb;
import edu.rpi.sss.util.OptionsI;
import edu.rpi.sss.util.xml.XmlEmit;
import edu.rpi.sss.util.xml.XmlUtil;
import edu.rpi.sss.util.xml.tagdefs.CaldavDefs;
import edu.rpi.sss.util.xml.tagdefs.CaldavTags;
import edu.rpi.sss.util.xml.tagdefs.WebdavTags;
import org.w3c.dom.Element;
import java.io.InputStream;
import java.io.Reader;
import java.io.Serializable;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.namespace.QName;
/** This class implements a namespace interface for the webdav abstract
* servlet. One of these interfaces is associated with each current session.
*
* <p>As a first pass we'll define webdav urls as starting with <br/>
* /user/user-name/calendar-name/<br/>
*
* <p>uri resolution should be made part of the core calendar allowing all
* such distinctions to be removed from this code.
*
* <p>The part following the above prefix probably determines exactly what is
* delivered. We may want the entire calendar (or what we show by default) or
* a single event from the calendar
*
* @author Mike Douglass douglm @ rpi.edu
*/
public class CaldavBWIntf extends WebdavNsIntf {
/** Namespace prefix based on the request url.
*/
private String namespacePrefix;
private AccessUtil accessUtil;
/** Namespace based on the request url.
*/
@SuppressWarnings("unused")
private String namespace;
SysIntf sysi;
private CalDAVConfig config;
/** We store CaldavURI objects here
* /
private HashMap<String, CaldavURI> uriMap = new HashMap<String, CaldavURI>();
*/
/* ====================================================================
* Interface methods
* ==================================================================== */
/** Called before any other method is called to allow initialization to
* take place at the first or subsequent requests
*
* @param servlet
* @param req
* @param debug
* @param methods HashMap table of method info
* @param dumpContent
* @throws WebdavException
*/
@Override
public void init(final WebdavServlet servlet,
final HttpServletRequest req,
final boolean debug,
final HashMap<String, MethodInfo> methods,
final boolean dumpContent) throws WebdavException {
super.init(servlet, req, debug, methods, dumpContent);
try {
HttpSession session = req.getSession();
ServletContext sc = session.getServletContext();
String appName = sc.getInitParameter("bwappname");
if ((appName == null) || (appName.length() == 0)) {
appName = "unknown-app-name";
}
namespacePrefix = WebdavUtils.getUrlPrefix(req);
namespace = namespacePrefix + "/schema";
OptionsI opts = CalDAVOptionsFactory.getOptions(debug);
config = (CalDAVConfig)opts.getAppProperty(appName);
if (config == null) {
config = new CalDAVConfig();
}
sysi = getSysi(config.getSysintfImpl());
sysi.init(req, account, config, debug);
accessUtil = new AccessUtil(namespacePrefix, xml,
new CalDavAccessXmlCb(sysi), debug);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/** See if we can reauthenticate. Use for real-time service which needs to
* authenticate as a particular principal.
*
* @param req
* @param account
* @throws WebdavException
*/
public void reAuth(final HttpServletRequest req,
final String account) throws WebdavException {
try {
if (sysi != null) {
try {
sysi.close();
} catch (Throwable t) {
throw new WebdavException(t);
}
}
this.account = account;
sysi = getSysi(config.getSysintfImpl());
sysi.init(req, account, config, debug);
accessUtil = new AccessUtil(namespacePrefix, xml,
new CalDavAccessXmlCb(sysi), debug);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#getDavHeader(edu.rpi.cct.webdav.servlet.shared.WebdavNsNode)
*/
@Override
public String getDavHeader(final WebdavNsNode node) throws WebdavException {
if (account == null) {
return super.getDavHeader(node) + ", calendar-access";
}
return super.getDavHeader(node) + ", calendar-access, calendar-schedule, calendar-auto-schedule";
}
@Override
public void emitError(final QName errorTag, final String extra,
final XmlEmit xml) throws Throwable {
if (errorTag.equals(CaldavTags.noUidConflict)) {
xml.openTag(errorTag);
xml.property(WebdavTags.href, sysi.getUrlHandler().prefix(extra));
xml.closeTag(errorTag);
} else {
super.emitError(errorTag, extra, xml);
}
}
protected CalDAVConfig getConfig() {
return config;
}
/**
*/
private static class CalDavAccessXmlCb implements AccessXmlCb, Serializable {
private SysIntf sysi;
private QName errorTag;
CalDavAccessXmlCb(final SysIntf sysi) {
this.sysi = sysi;
}
/* (non-Javadoc)
* @see edu.rpi.cmt.access.AccessXmlUtil.AccessXmlCb#makeHref(java.lang.String, int)
*/
public String makeHref(final String id, final int whoType) throws AccessException {
try {
return sysi.makeHref(id, whoType);
} catch (Throwable t) {
throw new AccessException(t);
}
}
public AccessPrincipal getPrincipal() throws AccessException {
try {
return sysi.getPrincipal();
} catch (Throwable t) {
throw new AccessException(t);
}
}
public AccessPrincipal getPrincipal(final String href) throws AccessException {
try {
return sysi.getPrincipal(sysi.getUrlHandler().unprefix(href));
} catch (Throwable t) {
throw new AccessException(t);
}
}
/* (non-Javadoc)
* @see edu.rpi.cmt.access.AccessXmlUtil.AccessXmlCb#setErrorTag(edu.rpi.sss.util.xml.QName)
*/
public void setErrorTag(final QName tag) throws AccessException {
errorTag = tag;
}
/* (non-Javadoc)
* @see edu.rpi.cmt.access.AccessXmlUtil.AccessXmlCb#getErrorTag()
*/
public QName getErrorTag() throws AccessException {
return errorTag;
}
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#getAccessUtil()
*/
@Override
public AccessUtil getAccessUtil() throws WebdavException {
return accessUtil;
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#canPut(edu.rpi.cct.webdav.servlet.shared.WebdavNsNode)
*/
@Override
public boolean canPut(final WebdavNsNode node) throws WebdavException {
CalDAVEvent ev = null;
if (node instanceof CaldavComponentNode) {
CaldavComponentNode comp = (CaldavComponentNode)node;
ev = comp.getEvent();
} else if (!(node instanceof CaldavResourceNode)) {
return false;
}
if (ev != null) {
return sysi.checkAccess(ev,
PrivilegeDefs.privWriteContent,
true).getAccessAllowed();
} else {
return sysi.checkAccess(node.getCollection(true), // deref - we're trying to put into the target
PrivilegeDefs.privBind, true).getAccessAllowed();
}
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#getDirectoryBrowsingDisallowed()
*/
@Override
public boolean getDirectoryBrowsingDisallowed() throws WebdavException {
return sysi.getDirectoryBrowsingDisallowed();
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#close()
*/
@Override
public void close() throws WebdavException {
sysi.close();
}
/**
* @return SysIntf
*/
public SysIntf getSysi() {
return sysi;
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#getSupportedLocks()
*/
@Override
public String getSupportedLocks() {
return null; // No locks
/*
return "<DAV:lockentry>" +
" <DAV:lockscope>" +
" <DAV:exclusive/>" +
" </DAV:lockscope>" +
" <DAV:locktype><DAV:write/></DAV:locktype>" +
"</DAV:lockentry>";
*/
}
@Override
public boolean getAccessControl() {
return true;
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#addNamespace(edu.rpi.sss.util.xml.XmlEmit)
*/
@Override
public void addNamespace(final XmlEmit xml) throws WebdavException {
super.addNamespace(xml);
try {
xml.addNs(CaldavDefs.caldavNamespace);
xml.addNs(CaldavDefs.icalNamespace);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#getNode(java.lang.String, int, int)
*/
@Override
public WebdavNsNode getNode(final String uri,
final int existance,
final int nodeType) throws WebdavException {
return getNodeInt(uri, existance, nodeType, null, null, null);
}
@Override
public void putNode(final WebdavNsNode node)
throws WebdavException {
}
@Override
public void delete(final WebdavNsNode node) throws WebdavException {
try {
if (node instanceof CaldavResourceNode) {
CaldavResourceNode rnode = (CaldavResourceNode)node;
sysi.deleteFile(rnode.getResource());
} else if (node instanceof CaldavComponentNode) {
CaldavComponentNode cnode = (CaldavComponentNode)node;
CalDAVEvent ev = cnode.getEvent();
if (ev != null) {
if (debug) {
trace("About to delete event " + ev);
}
sysi.deleteEvent(ev, CalDavHeaders.scheduleReply(getRequest()));
} else {
if (debug) {
trace("No event object available");
}
}
} else {
if (!(node instanceof CaldavCalNode)) {
throw new WebdavUnauthorized();
}
CaldavCalNode cnode = (CaldavCalNode)node;
CalDAVCollection col = (CalDAVCollection)cnode.getCollection(false); // Don't deref for delete
sysi.deleteCollection(col);
}
} catch (WebdavException we) {
throw we;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#getChildren(edu.rpi.cct.webdav.servlet.shared.WebdavNsNode)
*/
@Override
public Collection<WebdavNsNode> getChildren(final WebdavNsNode node) throws WebdavException {
try {
ArrayList<WebdavNsNode> al = new ArrayList<WebdavNsNode>();
if (!node.isCollection()) {
// Don't think we should have been called
return al;
}
if (debug) {
debugMsg("About to get children for " + node.getUri());
}
Collection<? extends WdEntity> children = node.getChildren();
if (children == null) {
// Perhaps no access
return al;
}
String uri = node.getUri();
CalDAVCollection parent = (CalDAVCollection)node.getCollection(false); // don't deref
for (WdEntity wde: children) {
CalDAVCollection col = null;
CalDAVResource r = null;
CalDAVEvent ev = null;
String name = wde.getName();
int nodeType;
if (wde instanceof CalDAVCollection) {
col = (CalDAVCollection)wde;
nodeType = WebdavNsIntf.nodeTypeCollection;
if (debug) {
debugMsg("Found child " + col);
}
} else if (wde instanceof CalDAVResource) {
col = parent;
r = (CalDAVResource)wde;
nodeType = WebdavNsIntf.nodeTypeEntity;
} else if (wde instanceof CalDAVEvent) {
col = parent;
ev = (CalDAVEvent)wde;
nodeType = WebdavNsIntf.nodeTypeEntity;
} else {
throw new WebdavException("Unexpected return type");
}
al.add(getNodeInt(uri + "/" + name,
WebdavNsIntf.existanceDoesExist,
nodeType, col, ev, r));
}
return al;
} catch (WebdavException we) {
throw we;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
@Override
public WebdavNsNode getParent(final WebdavNsNode node)
throws WebdavException {
return null;
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#getContent(edu.rpi.cct.webdav.servlet.shared.WebdavNsNode)
*/
@Override
public Reader getContent(final WebdavNsNode node) throws WebdavException {
try {
if (!node.getAllowsGet()) {
return null;
}
return node.getContent();
} catch (WebdavException we) {
throw we;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#getBinaryContent(edu.rpi.cct.webdav.servlet.shared.WebdavNsNode)
*/
@Override
public InputStream getBinaryContent(final WebdavNsNode node) throws WebdavException {
try {
if (!node.getAllowsGet()) {
return null;
}
if (!(node instanceof CaldavResourceNode)) {
throw new WebdavException("Unexpected node type");
}
CaldavResourceNode bwnode = (CaldavResourceNode)node;
return bwnode.getContentStream();
} catch (WebdavException we) {
throw we;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#putContent(edu.rpi.cct.webdav.servlet.shared.WebdavNsNode, java.lang.String, java.io.Reader, boolean, java.lang.String)
*/
@Override
public PutContentResult putContent(final WebdavNsNode node,
final String[] contentTypePars,
final Reader contentRdr,
final boolean create,
final String ifEtag) throws WebdavException {
try {
PutContentResult pcr = new PutContentResult();
pcr.node = node;
if (node instanceof CaldavResourceNode) {
throw new WebdavException(HttpServletResponse.SC_PRECONDITION_FAILED);
}
CaldavComponentNode bwnode = (CaldavComponentNode)node;
CalDAVCollection col = (CalDAVCollection)node.getCollection(true); // deref - put into target
boolean calContent = false;
if ((contentTypePars != null) && (contentTypePars.length > 0)) {
calContent = contentTypePars[0].equals("text/calendar");
}
if ((col.getCalType() != CalDAVCollection.calTypeCalendarCollection) ||
!calContent) {
throw new WebdavForbidden(CaldavTags.supportedCalendarData);
}
/** We can only put a single resource - that resource will be an ics file
* containing freebusy information or an event or todo and possible overrides.
*/
boolean fail = false;
+ boolean hadContent = false;
- for (WdEntity ent: sysi.fromIcal(col, contentRdr)) {
+ SysiIcalendar cal = sysi.fromIcal(col, contentRdr);
+ if (cal.getMethod() != null) {
+ throw new WebdavForbidden(CaldavTags.validCalendarObjectResource,
+ "No method on PUT");
+ }
+
+ for (WdEntity ent: cal) {
if (ent instanceof CalDAVEvent) {
+ if (hadContent) {
+ throw new WebdavForbidden(CaldavTags.validCalendarObjectResource,
+ "More than one calendar object for PUT");
+ }
pcr.created = putEvent(bwnode, (CalDAVEvent)ent, create, ifEtag);
+ hadContent = true;
} else {
fail = true;
break;
}
}
if (fail) {
warn("More than one calendar object for PUT or not event");
- throw new WebdavBadRequest("More than one calendar object for PUT or not event");
+ throw new WebdavBadRequest(CaldavTags.validCalendarObjectResource);
+ // "More than one calendar object for PUT or not event");
}
return pcr;
} catch (WebdavException we) {
throw we;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#putBinaryContent(edu.rpi.cct.webdav.servlet.shared.WebdavNsNode, java.lang.String, java.io.InputStream, boolean, java.lang.String)
*/
@Override
public PutContentResult putBinaryContent(final WebdavNsNode node,
final String[] contentTypePars,
final InputStream contentStream,
boolean create,
final String ifEtag) throws WebdavException {
try {
PutContentResult pcr = new PutContentResult();
pcr.node = node;
if (!(node instanceof CaldavResourceNode)) {
throw new WebdavException(HttpServletResponse.SC_PRECONDITION_FAILED);
}
CaldavResourceNode bwnode = (CaldavResourceNode)node;
CalDAVCollection col = (CalDAVCollection)node.getCollection(true);
if ((col == null) ||
(col.getCalType() == CalDAVCollection.calTypeCalendarCollection)) {
throw new WebdavException(HttpServletResponse.SC_PRECONDITION_FAILED);
}
CalDAVResource r = bwnode.getResource();
if (r.isNew()) {
create = true;
}
String contentType = null;
if ((contentTypePars != null) && (contentTypePars.length > 0)) {
for (String c: contentTypePars) {
if (contentType != null) {
contentType += ";";
}
contentType += c;
}
}
r.setContentType(contentType);
r.setBinaryContent(contentStream);
if (create) {
sysi.putFile(col, r);
} else {
sysi.updateFile(r, true);
}
return pcr;
} catch (WebdavException we) {
throw we;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
private boolean putEvent(final CaldavComponentNode bwnode,
final CalDAVEvent ev,
final boolean create,
final String ifEtag) throws WebdavException {
//BwEvent ev = evinfo.getEvent();
String entityName = bwnode.getEntityName();
CalDAVCollection col = (CalDAVCollection)bwnode.getCollection(true); // deref
boolean created = false;
ev.setParentPath(col.getPath());
if (debug) {
debugMsg("putContent: intf has event with name " + entityName +
" and summary " + ev.getSummary() +
" new event = " + ev.isNew());
}
if (ev.isNew()) {
created = true;
ev.setName(entityName);
boolean noInvites = false; // based on header?
/* Collection<BwEventProxy>failedOverrides = */
sysi.addEvent(ev, noInvites, true);
bwnode.setEvent(ev);
} else if (create) {
/* Resource already exists */
throw new WebdavException(HttpServletResponse.SC_PRECONDITION_FAILED);
} else {
if (!entityName.equals(ev.getName())) {
- throw new WebdavBadRequest("Mismatched names");
+ /* Probably specifying a different uid */
+ throw new WebdavForbidden(CaldavTags.noUidConflict);
}
if ((ifEtag != null) && (!ifEtag.equals(bwnode.getPrevEtagValue(true)))) {
if (debug) {
debugMsg("putContent: etag mismatch if=" + ifEtag +
"prev=" + bwnode.getPrevEtagValue(true));
}
throw new WebdavException(HttpServletResponse.SC_PRECONDITION_FAILED);
}
if (debug) {
debugMsg("putContent: update event " + ev);
}
sysi.updateEvent(ev);
}
return created;
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#create(edu.rpi.cct.webdav.servlet.shared.WebdavNsNode)
*/
@Override
public void create(final WebdavNsNode node) throws WebdavException {
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#createAlias(edu.rpi.cct.webdav.servlet.shared.WebdavNsNode)
*/
@Override
public void createAlias(final WebdavNsNode alias) throws WebdavException {
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#acceptMkcolContent(javax.servlet.http.HttpServletRequest)
*/
@Override
public void acceptMkcolContent(final HttpServletRequest req) throws WebdavException {
throw new WebdavUnsupportedMediaType();
}
/** Create an empty collection at the given location.
*
* <pre>
* 201 (Created) - The calendar collection resource was created in its entirety.
* 403 (Forbidden) - This indicates at least one of two conditions: 1) the
* server does not allow the creation of calendar collections at the
* given location in its namespace, or 2) the parent collection of the
* Request-URI exists but cannot accept members.
* 405 (Method Not Allowed) - MKCALENDAR can only be executed on a null resource.
* 409 (Conflict) - A collection cannot be made at the Request-URI until one
* or more intermediate collections have been created.
* 415 (Unsupported Media Type)- The server does not support the request type
* of the body.
* 507 (Insufficient Storage) - The resource does not have sufficient space
* to record the state of the resource after the execution of this method.
*
* @param req HttpServletRequest
* @param node node to create
* @throws WebdavException
*/
@Override
public void makeCollection(final HttpServletRequest req,
final HttpServletResponse resp,
final WebdavNsNode node) throws WebdavException {
try {
if (!(node instanceof CaldavCalNode)) {
throw new WebdavBadRequest("Not a valid node object " +
node.getClass().getName());
}
CaldavCalNode bwnode = (CaldavCalNode)node;
/* The uri should have an entity name representing the new collection
* and a collection object representing the parent.
*
* A namepart of null means that the path already exists
*/
CalDAVCollection newCol = (CalDAVCollection)bwnode.getCollection(false); // No deref?
CalDAVCollection parent = getSysi().getCollection(newCol.getParentPath());
if (parent.getCalType() == CalDAVCollection.calTypeCalendarCollection) {
throw new WebdavForbidden(CaldavTags.calendarCollectionLocationOk);
}
if (newCol.getName() == null) {
throw new WebdavForbidden("Forbidden: Null name");
}
resp.setStatus(sysi.makeCollection(newCol));
} catch (WebdavException we) {
throw we;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
@Override
public void copyMove(final HttpServletRequest req,
final HttpServletResponse resp,
final WebdavNsNode from,
final WebdavNsNode to,
final boolean copy,
final boolean overwrite,
final int depth) throws WebdavException {
if (from instanceof CaldavCalNode) {
copyMoveCollection(resp, (CaldavCalNode)from,
to, copy, overwrite, depth);
return;
}
// Copy entity or resource
if ((depth != Headers.depthNone) && (depth != 0)) {
throw new WebdavBadRequest();
}
if (from instanceof CaldavComponentNode) {
copyMoveComponent(resp, (CaldavComponentNode)from,
to, copy, overwrite);
return;
}
if (from instanceof CaldavResourceNode) {
copyMoveResource(resp, (CaldavResourceNode)from,
to, copy, overwrite);
return;
}
throw new WebdavBadRequest();
}
private void copyMoveCollection(final HttpServletResponse resp,
final CaldavCalNode from,
final WebdavNsNode to,
final boolean copy,
final boolean overwrite,
final int depth) throws WebdavException {
if (!(to instanceof CaldavCalNode)) {
throw new WebdavBadRequest();
}
// Copy folder
if ((depth != Headers.depthNone) && (depth != Headers.depthInfinity)) {
throw new WebdavBadRequest();
}
CaldavCalNode fromCalNode = from;
CaldavCalNode toCalNode = (CaldavCalNode)to;
if (toCalNode.getExists() && !overwrite) {
resp.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
return;
}
/* XXX This is NOT rename - we really move or copy.
* For the moment we'll deref both - but I think there are alias issues here
*/
CalDAVCollection fromCol = (CalDAVCollection)fromCalNode.getCollection(true);
CalDAVCollection toCol = (CalDAVCollection)toCalNode.getCollection(true);
if ((fromCol == null) || (toCol == null)) {
// What do we do here?
resp.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
return;
}
getSysi().copyMove(fromCol, toCol, copy, overwrite);
if (toCalNode.getExists()) {
resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
} else {
resp.setStatus(HttpServletResponse.SC_CREATED);
Headers.makeLocation(resp, getLocation(to), debug);
}
}
private void copyMoveComponent(final HttpServletResponse resp,
final CaldavComponentNode from,
final WebdavNsNode to,
final boolean copy,
final boolean overwrite) throws WebdavException {
if (!(to instanceof CaldavComponentNode)) {
throw new WebdavBadRequest();
}
CaldavComponentNode toNode = (CaldavComponentNode)to;
if (toNode.getExists() && !overwrite) {
resp.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
return;
}
/* deref - copy/move into targetted collection */
CalDAVCollection toCol = (CalDAVCollection)toNode.getCollection(true);
if (!getSysi().copyMove(from.getEvent(),
toCol, toNode.getEntityName(), copy,
overwrite)) {
resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
} else {
resp.setStatus(HttpServletResponse.SC_CREATED);
Headers.makeLocation(resp, getLocation(to), debug);
}
}
private void copyMoveResource(final HttpServletResponse resp,
final CaldavResourceNode from,
final WebdavNsNode to,
final boolean copy,
final boolean overwrite) throws WebdavException {
if (!(to instanceof CaldavResourceNode)) {
throw new WebdavBadRequest();
}
CaldavResourceNode toNode = (CaldavResourceNode)to;
if (toNode.getExists() && !overwrite) {
resp.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
return;
}
if (!getSysi().copyMoveFile(from.getResource(),
toNode.getPath(), toNode.getEntityName(), copy,
overwrite)) {
resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
} else {
resp.setStatus(HttpServletResponse.SC_CREATED);
Headers.makeLocation(resp, getLocation(to), debug);
}
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#specialUri(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String)
*/
@Override
public boolean specialUri(final HttpServletRequest req,
final HttpServletResponse resp,
final String resourceUri) throws WebdavException {
RequestPars pars = new RequestPars(req, this, resourceUri);
GetHandler handler = null;
if (pars.iSchedule) {
handler = new IscheduleGetHandler(this);
} else if (pars.freeBusy) {
handler = new FreeBusyGetHandler(this);
} else if (pars.webcal) {
handler = new WebcalGetHandler(this);
}
if (handler == null) {
return false;
}
handler.process(req, resp, pars);
return true;
}
/* ====================================================================
* Access methods
* ==================================================================== */
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#getGroups(java.lang.String, java.lang.String)
*/
@Override
public Collection<WebdavNsNode> getGroups(final String resourceUri,
final String principalUrl)
throws WebdavException {
Collection<WebdavNsNode> res = new ArrayList<WebdavNsNode>();
Collection<String> hrefs = getSysi().getGroups(resourceUri, principalUrl);
for (String href: hrefs) {
if (href.endsWith("/")) {
href = href.substring(0, href.length());
}
res.add(new CaldavUserNode(new CaldavURI(getSysi().getPrincipal(href)),
getSysi(), null, debug));
}
return res;
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#getPrincipalCollectionSet(java.lang.String)
*/
@Override
public Collection<String> getPrincipalCollectionSet(final String resourceUri)
throws WebdavException {
ArrayList<String> al = new ArrayList<String>();
for (String s: getSysi().getPrincipalCollectionSet(resourceUri)) {
al.add(sysi.getUrlHandler().prefix(s));
}
return al;
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#getPrincipals(java.lang.String, edu.rpi.cct.webdav.servlet.shared.PrincipalPropertySearch)
*/
@Override
public Collection<WebdavPrincipalNode> getPrincipals(final String resourceUri,
final PrincipalPropertySearch pps)
throws WebdavException {
ArrayList<WebdavPrincipalNode> pnodes = new ArrayList<WebdavPrincipalNode>();
for (CalPrincipalInfo cui: sysi.getPrincipals(resourceUri, pps)) {
pnodes.add(new CaldavUserNode(new CaldavURI(cui.principal),
getSysi(), cui, debug));
}
return pnodes;
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#makeUserHref(java.lang.String)
*/
@Override
public String makeUserHref(final String id) throws WebdavException {
return getSysi().makeHref(id, Ace.whoTypeUser);
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#updateAccess(edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf.AclInfo)
*/
@Override
public void updateAccess(final AclInfo info) throws WebdavException {
CaldavBwNode node = (CaldavBwNode)getNode(info.what,
WebdavNsIntf.existanceMust,
WebdavNsIntf.nodeTypeUnknown);
try {
// May need a real principal hierarchy
if (node instanceof CaldavCalNode) {
// XXX to dref or not deref?
sysi.updateAccess((CalDAVCollection)node.getCollection(true), info.acl);
} else if (node instanceof CaldavComponentNode) {
sysi.updateAccess(((CaldavComponentNode)node).getEvent(),
info.acl);
} else {
throw new WebdavException(HttpServletResponse.SC_NOT_IMPLEMENTED);
}
} catch (WebdavException wi) {
throw wi;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
@Override
public void emitAcl(final WebdavNsNode node) throws WebdavException {
Acl acl = null;
try {
if (node.isCollection()) {
acl = node.getCurrentAccess().getAcl();
} else if (node instanceof CaldavComponentNode) {
acl = ((CaldavComponentNode)node).getCurrentAccess().getAcl();
}
if (acl != null) {
accessUtil.emitAcl(acl, true);
}
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#getAclPrincipalInfo(edu.rpi.cct.webdav.servlet.shared.WebdavNsNode)
*/
@Override
public Collection<String> getAclPrincipalInfo(final WebdavNsNode node) throws WebdavException {
try {
TreeSet<String> hrefs = new TreeSet<String>();
for (Ace ace: node.getCurrentAccess().getAcl().getAces()) {
AceWho who = ace.getWho();
if (who.getWhoType() == WhoDefs.whoTypeUser) {
hrefs.add(accessUtil.makeUserHref(who.getWho()));
} else if (who.getWhoType() == WhoDefs.whoTypeGroup) {
hrefs.add(accessUtil.makeGroupHref(who.getWho()));
}
}
return hrefs;
} catch (AccessException ae) {
if (debug) {
error(ae);
}
throw new WebdavServerError();
}
}
/* ====================================================================
* Property value methods
* ==================================================================== */
/** Override this to create namespace specific property objects.
*
* @param propnode
* @return WebdavProperty
* @throws WebdavException
*/
@Override
public WebdavProperty makeProp(final Element propnode) throws WebdavException {
if (!XmlUtil.nodeMatches(propnode, CaldavTags.calendarData)) {
return super.makeProp(propnode);
}
/* Handle the calendar-data element */
CalendarData caldata = new CalendarData(new QName(propnode.getNamespaceURI(),
propnode.getLocalName()),
debug);
caldata.parse(propnode);
return caldata;
}
/** Properties we can process */
private static final QName[] knownProperties = {
CaldavTags.calendarData,
CaldavTags.calendarTimezone,
// CaldavTags.maxAttendeesPerInstance,
// CaldavTags.maxDateTime,
// CaldavTags.maxInstances,
CaldavTags.maxResourceSize,
// CaldavTags.minDateTime,
};
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#knownProperty(edu.rpi.cct.webdav.servlet.shared.WebdavNsNode, edu.rpi.cct.webdav.servlet.shared.WebdavProperty)
*/
@Override
public boolean knownProperty(final WebdavNsNode node,
final WebdavProperty pr) {
QName tag = pr.getTag();
if (node.knownProperty(tag)) {
return true;
}
for (int i = 0; i < knownProperties.length; i++) {
if (tag.equals(knownProperties[i])) {
return true;
}
}
/* Try the node for a value */
return super.knownProperty(node, pr);
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf#generatePropValue(edu.rpi.cct.webdav.servlet.shared.WebdavNsNode, edu.rpi.cct.webdav.servlet.shared.WebdavProperty, boolean)
*/
@Override
public boolean generatePropValue(final WebdavNsNode node,
WebdavProperty pr,
final boolean allProp) throws WebdavException {
QName tag = pr.getTag();
String ns = tag.getNamespaceURI();
try {
/* Deal with anything but webdav properties */
if (ns.equals(WebdavTags.namespace)) {
// Not ours
return super.generatePropValue(node, pr, allProp);
}
if (tag.equals(CaldavTags.calendarData)) {
// pr may be a CalendarData object - if not it's probably allprops
if (!(pr instanceof CalendarData)) {
pr = new CalendarData(tag, debug);
}
CalendarData caldata = (CalendarData)pr;
String content = null;
if (debug) {
trace("do CalendarData for " + node.getUri());
}
int status = HttpServletResponse.SC_OK;
try {
content = caldata.process(node);
} catch (WebdavException wde) {
status = wde.getStatusCode();
if (debug && (status != HttpServletResponse.SC_NOT_FOUND)) {
error(wde);
}
}
if (status != HttpServletResponse.SC_OK) {
// XXX should be passing status back
return false;
}
/* Output the (transformed) node.
*/
xml.cdataProperty(CaldavTags.calendarData, content);
return true;
}
if (tag.equals(CaldavTags.maxAttendeesPerInstance)) {
return false;
}
if (tag.equals(CaldavTags.maxDateTime)) {
return false;
}
if (tag.equals(CaldavTags.maxInstances)) {
return false;
}
if (tag.equals(CaldavTags.maxResourceSize)) {
/* e.g.
* <C:max-resource-size
* xmlns:C="urn:ietf:params:xml:ns:caldav">102400</C:max-resource-size>
*/
xml.property(tag, String.valueOf(sysi.getMaxUserEntitySize()));
return true;
}
if (tag.equals(CaldavTags.minDateTime)) {
return false;
}
return node.generatePropertyValue(tag, this, allProp);
} catch (WebdavException wie) {
throw wie;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/* ====================================================================
* Caldav methods
* ==================================================================== */
/** Use the given query to return a collection of nodes. An exception will
* be raised if the entire query fails for some reason (access, etc). An
* empty collection will be returned if no objects match.
*
* @param wdnode WebdavNsNode defining root of search
* @param retrieveList If non-null limit required fields.
* @param retrieveRecur How we retrieve recurring events
* @param fltr Filter object defining search
* @return Collection of result nodes (empty for no result)
* @throws WebdavException
*/
public Collection<WebdavNsNode> query(final WebdavNsNode wdnode,
final List<String> retrieveList,
final RetrievalMode retrieveRecur,
final FilterHandler fltr) throws WebdavException {
CaldavBwNode node = (CaldavBwNode)wdnode;
Collection<CalDAVEvent> events = fltr.query(node,
retrieveList, retrieveRecur);
/* We now need to build a node for each of the events in the collection.
For each event we first determine what calendar it's in. We then take the
incoming uri, strip any calendar names off it and append the calendar
name and event name to create the new uri.
If there is no calendar name for the event we just give it the default.
*/
Collection<WebdavNsNode> evnodes = new ArrayList<WebdavNsNode>();
if (events == null) {
return evnodes;
}
try {
for (CalDAVEvent ev: events) {
CalDAVCollection col = getSysi().getCollection(ev.getParentPath());
String uri = col.getPath();
/* If no name was assigned use the guid */
String evName = ev.getName();
if (evName == null) {
evName = ev.getUid() + ".ics";
}
String evuri = uri + "/" + evName;
CaldavComponentNode evnode = (CaldavComponentNode)getNodeInt(evuri,
WebdavNsIntf.existanceDoesExist,
WebdavNsIntf.nodeTypeEntity,
col, ev, null);
evnodes.add(evnode);
}
return fltr.postFilter(evnodes);
} catch (WebdavException we) {
throw we;
} catch (Throwable t) {
error(t);
throw new WebdavServerError();
}
}
/** The node represents a calendar resource for which we must get free-busy
* information.
*
* @param cnode CaldavCalNode
* @param freeBusy
* @param depth
* @throws WebdavException
*/
public void getFreeBusy(final CaldavCalNode cnode,
final FreeBusyQuery freeBusy,
final int depth) throws WebdavException {
try {
/* We need to deref as the freebusy comes from the target */
CalDAVCollection c = (CalDAVCollection)cnode.getCollection(true);
if (c == null) {
// XXX - exception?
return;
}
cnode.setFreeBusy(freeBusy.getFreeBusy(sysi, c,
cnode.getOwner().getAccount(),
depth));
} catch (WebdavException we) {
throw we;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/* ====================================================================
* Private methods
* ==================================================================== */
private SysIntf getSysi(final String className) throws WebdavException {
try {
Object o = Class.forName(className).newInstance();
if (o == null) {
throw new WebdavException("Class " + className + " not found");
}
if (!SysIntf.class.isInstance(o)) {
throw new WebdavException("Class " + className +
" is not a subclass of " +
SysIntf.class.getName());
}
return (SysIntf)o;
} catch (WebdavException we) {
throw we;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
private WebdavNsNode getNodeInt(final String uri,
final int existance,
final int nodeType,
final CalDAVCollection col,
final CalDAVEvent ev,
final CalDAVResource r) throws WebdavException {
if (debug) {
debugMsg("About to get node for " + uri);
}
if (uri == null) {
return null;
}
try {
CaldavURI wi = findURI(uri, existance, nodeType, col, ev, r);
if (wi == null) {
return null;
}
WebdavNsNode nd = null;
AccessPrincipal ap = wi.getPrincipal();
if (ap != null) {
if (ap.getKind() == Ace.whoTypeUser) {
nd = new CaldavUserNode(wi, sysi, sysi.getCalPrincipalInfo(ap), debug);
} else if (ap.getKind() == Ace.whoTypeGroup) {
nd = new CaldavGroupNode(wi, sysi, sysi.getCalPrincipalInfo(ap), debug);
}
} else if (wi.isCollection()) {
nd = new CaldavCalNode(wi, sysi, debug);
} else if (wi.isResource()) {
nd = new CaldavResourceNode(wi, sysi, debug);
} else {
nd = new CaldavComponentNode(wi, sysi, debug);
}
return nd;
} catch (WebdavNotFound wnf) {
return null;
} catch (WebdavException we) {
throw we;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/** Find the named item by following down the path from the root.
* This requires the names at each level to be unique (and present)
*
* I don't think the name.now has to have an ics suffix. Draft 7 goes as
* far as saying it may have ".ics" or ".ifb"
*
* For the moment enforce one or the other
*
* <p>Uri is at least /user/user-id or <br/>
* /public
* <br/>followed by one or more calendar path elements possibly followed by an
* entity name.
*
* @param uri String uri - just the path part
* @param existance Say's something about the state of existance
* @param nodeType Say's something about the type of node
* @param collection Supplied CalDAVCollection object if we already have it.
* @param ev
* @param rsrc
* @return CaldavURI object representing the uri
* @throws WebdavException
*/
private CaldavURI findURI(String uri,
final int existance,
final int nodeType,
final CalDAVCollection collection,
CalDAVEvent ev,
CalDAVResource rsrc) throws WebdavException {
try {
if ((nodeType == WebdavNsIntf.nodeTypeUnknown) &&
(existance != WebdavNsIntf.existanceMust)) {
// We assume an unknown type must exist
throw new WebdavServerError();
}
uri = normalizeUri(uri);
if (!uri.startsWith("/")) {
return null;
}
CaldavURI curi = null;
/* Look for it in the map * /
* This is stateless so we probably never find it.
CaldavURI curi = getUriPath(uri);
if (curi != null) {
if (debug) {
debugMsg("reuse uri - " + curi.getPath() +
"\" entityName=\"" + curi.getEntityName() + "\"");
}
return curi;
}*/
boolean isPrincipal = sysi.isPrincipal(uri);
if ((nodeType == WebdavNsIntf.nodeTypePrincipal) && !isPrincipal) {
throw new WebdavNotFound(uri);
}
if (isPrincipal) {
AccessPrincipal p = getSysi().getPrincipal(uri);
if (p == null) {
throw new WebdavNotFound(uri);
}
return new CaldavURI(p);
}
if (existance == WebdavNsIntf.existanceDoesExist) {
// Provided with calendar and entity if needed.
String name = null;
if (ev != null) {
name = ev.getName();
curi = new CaldavURI(collection, ev, name, true);
} else if (rsrc != null) {
curi = new CaldavURI(collection, rsrc, true);
} else {
curi = new CaldavURI(collection, ev, name, true);
}
//putUriPath(curi);
return curi;
}
if ((nodeType == WebdavNsIntf.nodeTypeCollection) ||
(nodeType == WebdavNsIntf.nodeTypeUnknown)) {
// For unknown we try the full path first as a calendar.
if (debug) {
debugMsg("search for collection uri \"" + uri + "\"");
}
CalDAVCollection col = sysi.getCollection(uri);
if (col == null) {
if ((nodeType == WebdavNsIntf.nodeTypeCollection) &&
(existance != WebdavNsIntf.existanceNot) &&
(existance != WebdavNsIntf.existanceMay)) {
/* We asked for a collection and it doesn't exist */
throw new WebdavNotFound(uri);
}
// We'll try as an entity for unknown
} else {
if (existance == WebdavNsIntf.existanceNot) {
throw new WebdavForbidden(WebdavTags.resourceMustBeNull);
}
if (debug) {
debugMsg("create collection uri - cal=\"" + col.getPath() + "\"");
}
curi = new CaldavURI(col, true);
//putUriPath(curi);
return curi;
}
}
// Entity or unknown
/* Split name into parent path and entity name part */
SplitResult split = splitUri(uri);
if (split.name == null) {
// No name part
throw new WebdavNotFound(uri);
}
/* Look for the parent */
CalDAVCollection col = sysi.getCollection(split.path);
if (col == null) {
if (nodeType == WebdavNsIntf.nodeTypeCollection) {
// Trying to create calendar/collection with no parent
throw new WebdavException(HttpServletResponse.SC_CONFLICT);
}
throw new WebdavNotFound(uri);
}
if (nodeType == WebdavNsIntf.nodeTypeCollection) {
// Trying to create calendar/collection
CalDAVCollection newCol = getSysi().newCollectionObject(false,
col.getPath());
newCol.setName(split.name);
newCol.setPath(col.getPath() + "/" + newCol.getName());
curi = new CaldavURI(newCol, false);
return curi;
}
int ctype = col.getCalType();
if ((ctype == CalDAVCollection.calTypeCalendarCollection) ||
(ctype == CalDAVCollection.calTypeInbox) ||
(ctype == CalDAVCollection.calTypeOutbox)) {
if (debug) {
debugMsg("find event(s) - cal=\"" + col.getPath() + "\" name=\"" +
split.name + "\"");
}
ev = sysi.getEvent(col, split.name, null);
if ((existance == WebdavNsIntf.existanceMust) && (ev == null)) {
throw new WebdavNotFound(uri);
}
curi = new CaldavURI(col, ev, split.name, ev != null);
} else {
if (debug) {
debugMsg("find resource - cal=\"" + col.getPath() + "\" name=\"" +
split.name + "\"");
}
/* Look for a resource */
rsrc = sysi.getFile(col, split.name);
if ((existance == WebdavNsIntf.existanceMust) && (rsrc == null)) {
throw new WebdavNotFound(uri);
}
boolean exists = rsrc != null;
if (!exists) {
rsrc = getSysi().newResourceObject(col.getPath());
rsrc.setName(split.name);
}
curi = new CaldavURI(col, rsrc, exists);
}
//putUriPath(curi);
return curi;
} catch (WebdavException wde) {
throw wde;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
private static class SplitResult {
String path;
String name;
SplitResult(final String path, final String name) {
this.path = path;
this.name = name;
}
}
/* Split the uri so that result.path is the path up to the name part result.name
*
* NormalizeUri was called previously so we have no trailing "/"
*/
private SplitResult splitUri(final String uri) throws WebdavException {
int pos = uri.lastIndexOf("/");
if (pos < 0) {
// bad uri
throw new WebdavBadRequest("Invalid uri: " + uri);
}
if (pos == 0) {
return new SplitResult(uri, null);
}
return new SplitResult(uri.substring(0, pos), uri.substring(pos + 1));
}
private String normalizeUri(String uri) throws WebdavException {
/*Remove all "." and ".." components */
try {
uri = new URI(null, null, uri, null).toString();
uri = new URI(URLEncoder.encode(uri, "UTF-8")).normalize().getPath();
uri = URLDecoder.decode(uri, "UTF-8");
if ((uri.length() > 1) && uri.endsWith("/")) {
uri = uri.substring(0, uri.length() - 1);
}
if (debug) {
debugMsg("Normalized uri=" + uri);
}
return uri;
} catch (Throwable t) {
if (debug) {
error(t);
}
throw new WebdavBadRequest("Bad uri: " + uri);
}
}
/*
private CaldavURI getUriPath(String path) {
return uriMap.get(path);
}
private void putUriPath(CaldavURI wi) {
uriMap.put(wi.getPath(), wi);
}
*/
}
| false | false | null | null |
diff --git a/hazelcast/src/main/java/com/hazelcast/replicatedmap/record/AbstractReplicatedRecordStore.java b/hazelcast/src/main/java/com/hazelcast/replicatedmap/record/AbstractReplicatedRecordStore.java
index 796bf400b3..6bed08df78 100644
--- a/hazelcast/src/main/java/com/hazelcast/replicatedmap/record/AbstractReplicatedRecordStore.java
+++ b/hazelcast/src/main/java/com/hazelcast/replicatedmap/record/AbstractReplicatedRecordStore.java
@@ -1,730 +1,737 @@
/*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.replicatedmap.record;
import com.hazelcast.config.ListenerConfig;
import com.hazelcast.config.ReplicatedMapConfig;
import com.hazelcast.core.*;
import com.hazelcast.instance.MemberImpl;
import com.hazelcast.monitor.LocalReplicatedMapStats;
import com.hazelcast.monitor.impl.LocalReplicatedMapStatsImpl;
import com.hazelcast.nio.Address;
import com.hazelcast.nio.ClassLoaderUtil;
import com.hazelcast.query.Predicate;
import com.hazelcast.replicatedmap.CleanerRegistrator;
import com.hazelcast.replicatedmap.ReplicatedMapEvictionProcessor;
import com.hazelcast.replicatedmap.ReplicatedMapService;
import com.hazelcast.replicatedmap.messages.MultiReplicationMessage;
import com.hazelcast.replicatedmap.messages.ReplicationMessage;
import com.hazelcast.replicatedmap.operation.ReplicatedMapInitChunkOperation;
import com.hazelcast.replicatedmap.operation.ReplicatedMapPostJoinOperation;
import com.hazelcast.replicatedmap.operation.ReplicatedMapPostJoinOperation.MemberMapPair;
import com.hazelcast.spi.*;
import com.hazelcast.util.ExceptionUtil;
import com.hazelcast.util.ValidationUtil;
import com.hazelcast.util.scheduler.EntryTaskScheduler;
import com.hazelcast.util.scheduler.EntryTaskSchedulerFactory;
import com.hazelcast.util.scheduler.ScheduleType;
import com.hazelcast.util.scheduler.ScheduledEntry;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public abstract class AbstractReplicatedRecordStore<K, V>
implements ReplicatedRecordStore, InitializingObject {
private static final int MAX_MESSAGE_CACHE_SIZE = 1000; // TODO: this constant may be configurable...
protected final ConcurrentMap<K, ReplicatedRecord<K, V>> storage = new ConcurrentHashMap<K, ReplicatedRecord<K, V>>();
private final LocalReplicatedMapStatsImpl mapStats = new LocalReplicatedMapStatsImpl();
private final AtomicBoolean loaded = new AtomicBoolean(false);
private final Lock waitForLoadedLock = new ReentrantLock();
private final Condition waitForLoadedCondition = waitForLoadedLock.newCondition();
private final Random memberRandomizer = new Random(-System.currentTimeMillis());
private final List<ReplicationMessage> replicationMessageCache = new ArrayList<ReplicationMessage>();
private final Lock replicationMessageCacheLock = new ReentrantLock();
private final String name;
private final Member localMember;
private final int localMemberHash;
private final NodeEngine nodeEngine;
private final EventService eventService;
private final ExecutionService executionService;
private final ScheduledExecutorService executorService;
private final EntryTaskScheduler ttlEvictionScheduler;
private final ReplicatedMapService replicatedMapService;
private final ReplicatedMapConfig replicatedMapConfig;
private final ScheduledFuture<?> cleanerFuture;
private final Object[] mutexes;
public AbstractReplicatedRecordStore(String name, NodeEngine nodeEngine,
CleanerRegistrator cleanerRegistrator,
ReplicatedMapService replicatedMapService) {
this.name = name;
this.nodeEngine = nodeEngine;
this.localMember = nodeEngine.getLocalMember();
this.localMemberHash = localMember.getUuid().hashCode();
this.eventService = nodeEngine.getEventService();
this.executionService = nodeEngine.getExecutionService();
this.replicatedMapService = replicatedMapService;
this.replicatedMapConfig = replicatedMapService.getReplicatedMapConfig(name);
this.executorService = getExecutorService(nodeEngine, replicatedMapConfig);
this.ttlEvictionScheduler = EntryTaskSchedulerFactory.newScheduler(
nodeEngine.getExecutionService().getScheduledExecutor(),
new ReplicatedMapEvictionProcessor(nodeEngine, replicatedMapService, name), ScheduleType.POSTPONE);
this.mutexes = new Object[replicatedMapConfig.getConcurrencyLevel()];
for (int i = 0; i < mutexes.length; i++) {
mutexes[i] = new Object();
}
this.cleanerFuture = cleanerRegistrator.registerCleaner(this);
}
@Override
public String getName() {
return name;
}
@Override
public Object remove(Object key) {
ValidationUtil.isNotNull(key, "key");
long time = System.currentTimeMillis();
checkState();
V oldValue;
K marshalledKey = (K) marshallKey(key);
synchronized (getMutex(marshalledKey)) {
final ReplicatedRecord current = storage.get(marshalledKey);
final Vector vector;
if (current == null) {
oldValue = null;
} else {
vector = current.getVector();
oldValue = (V) current.getValue();
current.setValue(null, 0, -1);
incrementClock(vector);
publishReplicatedMessage(new ReplicationMessage(
name, key, null, vector, localMember, localMemberHash, -1));
}
cancelTtlEntry(marshalledKey);
}
Object unmarshalledOldValue = unmarshallValue(oldValue);
fireEntryListenerEvent(key, unmarshalledOldValue, null);
if (replicatedMapConfig.isStatisticsEnabled()) {
mapStats.incrementRemoves(System.currentTimeMillis() - time);
}
return unmarshalledOldValue;
}
@Override
public Object get(Object key) {
ValidationUtil.isNotNull(key, "key");
long time = System.currentTimeMillis();
checkState();
ReplicatedRecord replicatedRecord = storage.get(marshallKey(key));
+
+ // Force return null on ttl expiration (but before cleanup thread run)
+ long ttlMillis = replicatedRecord == null ? 0 : replicatedRecord.getTtlMillis();
+ if (ttlMillis > 0 && System.currentTimeMillis() - replicatedRecord.getUpdateTime() > ttlMillis) {
+ replicatedRecord = null;
+ }
+
Object value = replicatedRecord == null ? null : unmarshallValue(replicatedRecord.getValue());
if (replicatedMapConfig.isStatisticsEnabled()) {
mapStats.incrementGets(System.currentTimeMillis() - time);
}
return value;
}
@Override
public Object put(Object key, Object value) {
ValidationUtil.isNotNull(key, "key");
ValidationUtil.isNotNull(value, "value");
checkState();
return put(key, value, 0, TimeUnit.MILLISECONDS);
}
@Override
public Object put(Object key, Object value, long ttl, TimeUnit timeUnit) {
ValidationUtil.isNotNull(key, "key");
ValidationUtil.isNotNull(value, "value");
ValidationUtil.isNotNull(timeUnit, "timeUnit");
if (ttl < 0) {
throw new IllegalArgumentException("ttl must be a positive integer");
}
long time = System.currentTimeMillis();
checkState();
V oldValue = null;
K marshalledKey = (K) marshallKey(key);
V marshalledValue = (V) marshallValue(value);
synchronized (getMutex(marshalledKey)) {
final long ttlMillis = ttl == 0 ? 0 : timeUnit.toMillis(ttl);
final ReplicatedRecord old = storage.get(marshalledKey);
final Vector vector;
if (old == null) {
vector = new Vector();
ReplicatedRecord<K, V> record = new ReplicatedRecord(
marshalledKey, marshalledValue, vector, localMemberHash, ttlMillis);
storage.put(marshalledKey, record);
} else {
oldValue = (V) old.getValue();
vector = old.getVector();
storage.get(marshalledKey).setValue(marshalledValue, localMemberHash, ttlMillis);
}
if (ttlMillis > 0) {
scheduleTtlEntry(ttlMillis, marshalledKey, null);
} else {
cancelTtlEntry(marshalledKey);
}
incrementClock(vector);
publishReplicatedMessage(new ReplicationMessage(name, key, value, vector,
localMember, localMemberHash, ttlMillis));
}
Object unmarshalledOldValue = unmarshallValue(oldValue);
fireEntryListenerEvent(key, unmarshalledOldValue, value);
if (replicatedMapConfig.isStatisticsEnabled()) {
mapStats.incrementPuts(System.currentTimeMillis() - time);
}
return unmarshalledOldValue;
}
@Override
public boolean containsKey(Object key) {
ValidationUtil.isNotNull(key, "key");
checkState();
mapStats.incrementOtherOperations();
return storage.containsKey(marshallKey(key));
}
@Override
public boolean containsValue(Object value) {
ValidationUtil.isNotNull(value, "value");
checkState();
mapStats.incrementOtherOperations();
for (Map.Entry<K, ReplicatedRecord<K, V>> entry : storage.entrySet()) {
V entryValue = entry.getValue().getValue();
if (value == entryValue
|| (entryValue != null && unmarshallValue(entryValue).equals(value))) {
return true;
}
}
return false;
}
@Override
public Set keySet() {
checkState();
Set keySet = new HashSet(storage.size());
for (K key : storage.keySet()) {
keySet.add(unmarshallKey(key));
}
mapStats.incrementOtherOperations();
return keySet;
}
@Override
public Collection values() {
checkState();
List values = new ArrayList(storage.size());
for (ReplicatedRecord record : storage.values()) {
values.add(unmarshallValue(record.getValue()));
}
mapStats.incrementOtherOperations();
return values;
}
@Override
public Set entrySet() {
checkState();
Set entrySet = new HashSet(storage.size());
for (Map.Entry<K, ReplicatedRecord<K, V>> entry : storage.entrySet()) {
Object key = unmarshallKey(entry.getKey());
Object value = unmarshallValue(entry.getValue().getValue());
entrySet.add(new AbstractMap.SimpleEntry(key, value));
}
mapStats.incrementOtherOperations();
return entrySet;
}
@Override
public ReplicatedRecord getReplicatedRecord(Object key) {
ValidationUtil.isNotNull(key, "key");
checkState();
return storage.get(marshallKey(key));
}
@Override
public boolean isEmpty() {
mapStats.incrementOtherOperations();
return storage.isEmpty();
}
@Override
public int size() {
mapStats.incrementOtherOperations();
return storage.size();
}
@Override
public void clear() {
throw new UnsupportedOperationException("clear is not supported on ReplicatedMap");
}
@Override
public boolean equals(Object o) {
if (o instanceof AbstractReplicatedRecordStore) {
return storage.equals(((AbstractReplicatedRecordStore) o).storage);
}
return storage.equals(o);
}
@Override
public int hashCode() {
return storage.hashCode();
}
@Override
public ReplicatedMapService getReplicatedMapService() {
return replicatedMapService;
}
@Override
public void destroy() {
if (cleanerFuture.isCancelled()) {
return;
}
cleanerFuture.cancel(true);
executorService.shutdownNow();
storage.clear();
replicatedMapService.destroyDistributedObject(getName());
}
@Override
public void publishReplicatedMessage(ReplicationMessage message) {
if (replicatedMapConfig.getReplicationDelayMillis() == 0) {
Collection<EventRegistration> registrations = filterEventRegistrations(eventService.getRegistrations(
ReplicatedMapService.SERVICE_NAME, ReplicatedMapService.EVENT_TOPIC_NAME));
eventService.publishEvent(ReplicatedMapService.SERVICE_NAME, registrations, message, name.hashCode());
} else {
replicationMessageCacheLock.lock();
try {
replicationMessageCache.add(message);
if (replicationMessageCache.size() == 1) {
executorService.schedule(new ReplicationCachedSenderTask(),
replicatedMapConfig.getReplicationDelayMillis(), TimeUnit.MILLISECONDS);
} else {
if (replicationMessageCache.size() > MAX_MESSAGE_CACHE_SIZE) {
processMessageCache();
}
}
} finally {
replicationMessageCacheLock.unlock();
}
}
}
@Override
public String addEntryListener(EntryListener listener, Object key) {
ValidationUtil.isNotNull(listener, "listener");
EventFilter eventFilter = new ReplicatedEntryEventFilter(marshallKey(key));
mapStats.incrementOtherOperations();
return replicatedMapService.addEventListener(listener, eventFilter, name);
}
@Override
public String addEntryListener(EntryListener listener, Predicate predicate, Object key) {
ValidationUtil.isNotNull(listener, "listener");
EventFilter eventFilter = new ReplicatedQueryEventFilter(marshallKey(key), predicate);
mapStats.incrementOtherOperations();
return replicatedMapService.addEventListener(listener, eventFilter, name);
}
@Override
public boolean removeEntryListenerInternal(String id) {
ValidationUtil.isNotNull(id, "id");
mapStats.incrementOtherOperations();
return replicatedMapService.removeEventListener(name, id);
}
@Override
public void initialize() {
initializeListeners();
List<MemberImpl> members = new ArrayList<MemberImpl>(nodeEngine.getClusterService().getMemberList());
members.remove(localMember);
if (members.size() == 0) {
loaded.set(true);
} else {
sendInitialFillupRequest(members);
}
}
public LocalReplicatedMapStats createReplicatedMapStats() {
LocalReplicatedMapStatsImpl stats = mapStats;
stats.setOwnedEntryCount(storage.size());
List<ReplicatedRecord<K, V>> records = new ArrayList<ReplicatedRecord<K, V>>(storage.values());
long hits = 0;
for (ReplicatedRecord<K, V> record : records) {
stats.setLastAccessTime(record.getLastAccessTime());
stats.setLastUpdateTime(record.getUpdateTime());
hits += record.getHits();
}
stats.setHits(hits);
return stats;
}
public LocalReplicatedMapStatsImpl getReplicatedMapStats() {
return mapStats;
}
public Set<ReplicatedRecord> getRecords() {
checkState();
return new HashSet<ReplicatedRecord>(storage.values());
}
public void queueInitialFillup(Address callerAddress, int chunkSize) {
executionService.execute("hz:replicated-map", new RemoteFillupTask(callerAddress, chunkSize));
}
public void queueUpdateMessage(final ReplicationMessage update) {
executorService.execute(new Runnable() {
@Override
public void run() {
processUpdateMessage(update);
}
});
}
public void queueUpdateMessages(final MultiReplicationMessage updates) {
executorService.execute(new Runnable() {
@Override
public void run() {
for (ReplicationMessage update : updates.getReplicationMessages()) {
processUpdateMessage(update);
}
}
});
}
public void finalChunkReceived() {
loaded.set(true);
waitForLoadedLock.lock();
try {
waitForLoadedCondition.signalAll();
} finally {
waitForLoadedLock.unlock();
}
}
public void retryWithDifferentReplicationNode(Member member) {
List<MemberImpl> members = new ArrayList<MemberImpl>(nodeEngine.getClusterService().getMemberList());
members.remove(member);
// If there are less than two members there is not other possible candidate to replicate from
if (members.size() < 2) {
return;
}
sendInitialFillupRequest(members);
}
private void sendInitialFillupRequest(List<MemberImpl> members) {
if (members.size() == 0) {
return;
}
int randomMember = memberRandomizer.nextInt(members.size());
MemberImpl newMember = members.get(randomMember);
MemberMapPair[] memberMapPairs = new MemberMapPair[1];
memberMapPairs[0] = new MemberMapPair(newMember, name);
OperationService operationService = nodeEngine.getOperationService();
operationService.send(new ReplicatedMapPostJoinOperation(
memberMapPairs, ReplicatedMapPostJoinOperation.DEFAULT_CHUNK_SIZE), newMember.getAddress());
}
public boolean isLoaded() {
return loaded.get();
}
protected void incrementClock(Vector vector) {
final AtomicInteger clock = vector.clocks.get(localMember);
if (clock != null) {
clock.incrementAndGet();
} else {
vector.clocks.put(localMember, new AtomicInteger(1));
}
}
protected Object getMutex(final Object key) {
return mutexes[key.hashCode() != Integer.MIN_VALUE ? Math.abs(key.hashCode()) % mutexes.length : 0];
}
private void initializeListeners() {
List<ListenerConfig> listenerConfigs = replicatedMapConfig.getListenerConfigs();
for (ListenerConfig listenerConfig : listenerConfigs) {
EntryListener listener = null;
if (listenerConfig.getImplementation() != null) {
listener = (EntryListener) listenerConfig.getImplementation();
} else if (listenerConfig.getClassName() != null) {
try {
listener = ClassLoaderUtil
.newInstance(nodeEngine.getConfigClassLoader(), listenerConfig.getClassName());
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
if (listener != null) {
if (listener instanceof HazelcastInstanceAware) {
((HazelcastInstanceAware) listener).setHazelcastInstance(nodeEngine.getHazelcastInstance());
}
addEntryListener(listener, null);
}
}
}
private void checkState() {
if (!loaded.get()) {
if (!replicatedMapConfig.isAsyncFillup()) {
waitForLoadedLock.lock();
try {
waitForLoadedCondition.await();
} catch (InterruptedException e) {
throw new IllegalStateException("Synchronous loading of ReplicatedMap '" + name + "' failed.", e);
} finally {
waitForLoadedLock.unlock();
}
}
}
}
private ScheduledEntry<K, V> cancelTtlEntry(K key) {
return ttlEvictionScheduler.cancel(key);
}
private ScheduledEntry<K, V> getTtlEntry(K key) {
return ttlEvictionScheduler.get(key);
}
private boolean scheduleTtlEntry(long delayMillis, K key, V object) {
return ttlEvictionScheduler.schedule(delayMillis, key, object);
}
private void processUpdateMessage(ReplicationMessage update) {
if (localMember.equals(update.getOrigin())) {
return;
}
mapStats.incrementReceivedReplicationEvents();
K marshalledKey = (K) marshallKey(update.getKey());
synchronized (getMutex(marshalledKey)) {
final ReplicatedRecord<K, V> localEntry = storage.get(marshalledKey);
if (localEntry == null) {
if (!update.isRemove()) {
V marshalledValue = (V) marshallValue(update.getValue());
Vector vector = update.getVector();
int updateHash = update.getUpdateHash();
long ttlMillis = update.getTtlMillis();
storage.put(marshalledKey, new ReplicatedRecord<K, V>(
marshalledKey, marshalledValue, vector, updateHash, ttlMillis));
if (ttlMillis > 0) {
scheduleTtlEntry(ttlMillis, marshalledKey, null);
} else {
cancelTtlEntry(marshalledKey);
}
fireEntryListenerEvent(update.getKey(), null, update.getValue());
}
} else {
final Vector currentVector = localEntry.getVector();
final Vector updateVector = update.getVector();
if (Vector.happenedBefore(updateVector, currentVector)) {
// ignore the update. This is an old update
} else if (Vector.happenedBefore(currentVector, updateVector)) {
// A new update happened
applyTheUpdate(update, localEntry);
} else {
// no preceding among the clocks. Lower hash wins..
if (localEntry.getLatestUpdateHash() >= update.getUpdateHash()) {
applyTheUpdate(update, localEntry);
} else {
applyVector(updateVector, currentVector);
publishReplicatedMessage(new ReplicationMessage(name, update.getKey(), localEntry.getValue(),
currentVector, localMember, localEntry.getLatestUpdateHash(), update.getTtlMillis()));
}
}
}
}
}
private void applyTheUpdate(ReplicationMessage<K, V> update, ReplicatedRecord<K, V> localEntry) {
Vector localVector = localEntry.getVector();
Vector remoteVector = update.getVector();
K marshalledKey = (K) marshallKey(update.getKey());
V marshalledValue = (V) marshallValue(update.getValue());
long ttlMillis = update.getTtlMillis();
Object oldValue = localEntry.setValue(marshalledValue, update.getUpdateHash(), ttlMillis);
applyVector(remoteVector, localVector);
if (ttlMillis > 0) {
scheduleTtlEntry(ttlMillis, marshalledKey, null);
} else {
cancelTtlEntry(marshalledKey);
}
fireEntryListenerEvent(update.getKey(), unmarshallValue(oldValue), update.getValue());
}
private void applyVector(Vector update, Vector current) {
for (Member m : update.clocks.keySet()) {
final AtomicInteger currentClock = current.clocks.get(m);
final AtomicInteger updateClock = update.clocks.get(m);
if (smaller(currentClock, updateClock)) {
current.clocks.put(m, new AtomicInteger(updateClock.get()));
}
}
}
private boolean smaller(AtomicInteger int1, AtomicInteger int2) {
int i1 = int1 == null ? 0 : int1.get();
int i2 = int2 == null ? 0 : int2.get();
return i1 < i2;
}
private ScheduledExecutorService getExecutorService(NodeEngine nodeEngine,
ReplicatedMapConfig replicatedMapConfig) {
ScheduledExecutorService es = replicatedMapConfig.getReplicatorExecutorService();
if (es == null) {
es = nodeEngine.getExecutionService().getScheduledExecutor();
}
return new WrappedExecutorService(es);
}
private void fireEntryListenerEvent(Object key, Object oldValue, Object value) {
EntryEventType eventType = value == null ?
EntryEventType.REMOVED : oldValue == null ? EntryEventType.ADDED : EntryEventType.UPDATED;
EntryEvent event = new EntryEvent(name, localMember, eventType.getType(), key, oldValue, value);
Collection<EventRegistration> registrations = eventService.getRegistrations(
ReplicatedMapService.SERVICE_NAME, name);
eventService.publishEvent(ReplicatedMapService.SERVICE_NAME, registrations, event, name.hashCode());
}
private Collection<EventRegistration> filterEventRegistrations(Collection<EventRegistration> eventRegistrations) {
Address address = ((MemberImpl) localMember).getAddress();
List<EventRegistration> registrations = new ArrayList<EventRegistration>(eventRegistrations);
Iterator<EventRegistration> iterator = registrations.iterator();
while (iterator.hasNext()) {
EventRegistration registration = iterator.next();
if (address.equals(registration.getSubscriber())) {
iterator.remove();
}
}
return registrations;
}
private class RemoteFillupTask implements Runnable {
private final OperationService operationService = nodeEngine.getOperationService();
private final Address callerAddress;
private final int chunkSize;
private ReplicatedRecord[] recordCache;
private int recordCachePos = 0;
private RemoteFillupTask(Address callerAddress, int chunkSize) {
this.callerAddress = callerAddress;
this.chunkSize = chunkSize;
}
@Override
public void run() {
recordCache = new ReplicatedRecord[chunkSize];
List<ReplicatedRecord<K, V>> replicatedRecords = new ArrayList<ReplicatedRecord<K, V>>(storage.values());
for (int i = 0; i < replicatedRecords.size(); i++) {
ReplicatedRecord<K, V> replicatedRecord = replicatedRecords.get(i);
processReplicatedRecord(replicatedRecord, i == replicatedRecords.size() - 1);
}
}
private void processReplicatedRecord(ReplicatedRecord<K, V> replicatedRecord, boolean finalRecord) {
Object marshalledKey = marshallKey(replicatedRecord.getKey());
synchronized (getMutex(marshalledKey)) {
pushReplicatedRecord(replicatedRecord, finalRecord);
}
}
private void pushReplicatedRecord(ReplicatedRecord<K, V> replicatedRecord, boolean finalRecord) {
if (recordCachePos == chunkSize) {
sendChunk(finalRecord);
}
int hash = replicatedRecord.getLatestUpdateHash();
Object key = unmarshallKey(replicatedRecord.getKey());
Object value = unmarshallValue(replicatedRecord.getValue());
Vector vector = Vector.copyVector(replicatedRecord.getVector());
long ttlMillis = replicatedRecord.getTtlMillis();
recordCache[recordCachePos++] = new ReplicatedRecord(key, value, vector, hash, ttlMillis);
if (finalRecord) {
sendChunk(finalRecord);
}
}
private void sendChunk(boolean finalChunk) {
if (recordCachePos > 0) {
Operation operation = new ReplicatedMapInitChunkOperation(
name, localMember, recordCache, recordCachePos, finalChunk);
operationService.send(operation, callerAddress);
// Reset chunk cache and pos
recordCache = new ReplicatedRecord[chunkSize];
recordCachePos = 0;
}
}
}
private class ReplicationCachedSenderTask implements Runnable {
@Override
public void run() {
processMessageCache();
}
}
private void processMessageCache() {
ReplicationMessage[] replicationMessages = null;
replicationMessageCacheLock.lock();
try {
final int size = replicationMessageCache.size();
if (size > 0) {
replicationMessages = replicationMessageCache.toArray(new ReplicationMessage[size]);
replicationMessageCache.clear();
}
} finally {
replicationMessageCacheLock.unlock();
}
if (replicationMessages != null) {
MultiReplicationMessage message = new MultiReplicationMessage(name, replicationMessages);
Collection<EventRegistration> registrations = filterEventRegistrations(eventService.getRegistrations(
ReplicatedMapService.SERVICE_NAME, ReplicatedMapService.EVENT_TOPIC_NAME));
eventService.publishEvent(ReplicatedMapService.SERVICE_NAME, registrations, message, name.hashCode());
}
}
}
| true | false | null | null |
diff --git a/src/java/com/idega/servlet/filter/IWAuthenticator.java b/src/java/com/idega/servlet/filter/IWAuthenticator.java
index 2088559c0..61eba185e 100644
--- a/src/java/com/idega/servlet/filter/IWAuthenticator.java
+++ b/src/java/com/idega/servlet/filter/IWAuthenticator.java
@@ -1,558 +1,562 @@
/*
* $Id: IWAuthenticator.java,v 1.39 2008/11/17 08:40:07 laddi Exp $ Created on
* 31.7.2004 in project com.idega.core
*
* Copyright (C) 2004-2005 Idega Software hf. All Rights Reserved.
*
* This software is the proprietary information of Idega hf. Use is subject to
* license terms.
*/
package com.idega.servlet.filter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.idega.business.IBOLookup;
import com.idega.business.IBOLookupException;
import com.idega.core.accesscontrol.business.AuthenticationBusiness;
import com.idega.core.accesscontrol.business.LoggedOnInfo;
import com.idega.core.accesscontrol.business.LoginBusinessBean;
import com.idega.core.accesscontrol.business.ServletFilterChainInterruptException;
import com.idega.core.accesscontrol.jaas.IWCallbackHandler;
import com.idega.core.accesscontrol.jaas.IWJAASAuthenticationRequestWrapper;
import com.idega.core.builder.business.BuilderService;
import com.idega.core.builder.business.BuilderServiceFactory;
import com.idega.idegaweb.IWApplicationContext;
import com.idega.idegaweb.IWException;
import com.idega.idegaweb.IWMainApplication;
import com.idega.idegaweb.IWMainApplicationSettings;
import com.idega.presentation.IWContext;
import com.idega.repository.data.ImplementorRepository;
import com.idega.user.business.UserBusiness;
import com.idega.user.data.User;
import com.idega.util.CoreConstants;
import com.idega.util.CypherText;
import com.idega.util.RequestUtil;
/**
* <p>
* This servletFilter is by default mapped early in the filter chain in idegaWeb
* and calls the idegaWeb Accesscontrol system to log the user in to the
* idegaWeb User system.<br/> When the user has a "remember me" cookie set then
* this filter reads that and logs the user into the system.
* </p>
* Last modified: $Date: 2008/11/17 08:40:07 $ by $Author: laddi $
*
* @author <a href="mailto:[email protected]">Tryggvi Larusson</a>
* @version $Revision: 1.39 $
*/
public class IWAuthenticator extends BaseFilter {
public static final String PROPERTY_FORWARD_PAGE_URI = "FORWARD_PAGE_URI";
/**
* This parameter can be set
*/
public static final String PARAMETER_REDIRECT_USER_TO_PRIMARY_GROUP_HOME_PAGE = "logon_redirect_user";
/**
* This parameter can be set to forward to a certain page when logging in (and
* it is succesful)
*/
public static final String PARAMETER_REDIRECT_URI_ONLOGON = "logon_redirect_uri";
private static final String PERSONAL_ID_PATTERN = "\\$\\{currentUser.personalID\\}";
private static final String TICKET_PATTERN = "\\$\\{currentUser.ticket\\}";
/**
* This parameter can be set to forward to a certain page when logging off
* (and it is succesful)
*/
public static final String PARAMETER_REDIRECT_URI_ONLOGOFF = "logoff_redirect_uri";
public static final String COOKIE_NAME = "iwrbusid";
//public String IW_BUNDLE_IDENTIFIER = "com.idega.block.login";
public static final String PARAMETER_ALLOWS_COOKIE_LOGIN = "icusallows";
// following string are used as keys in the sharedState map used by LoginModules
public static final String SESSION_KEY = "session"; // a HttpSession
public static final String REQUEST_KEY = "request"; // a HttpRequest
private static Logger log = Logger.getLogger(IWAuthenticator.class.getName());
/*
* (non-Javadoc)
*
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig arg0) throws ServletException {
}
/*
* (non-Javadoc)
*
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
* javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) srequest;
HttpServletResponse response = (HttpServletResponse) sresponse;
HttpSession session = request.getSession();
User lastLoggedOnAsUser = null;
LoginBusinessBean loginBusiness = getLoginBusiness(request);
boolean isLoggedOn = loginBusiness.isLoggedOn(request);
//if ((isLoggedOn && loginBusiness.isLogOffAction(request)) || loginBusiness.isLogOnAction(request) || loginBusiness.isTryAgainAction(request)) {
if (isLoggedOn) {
lastLoggedOnAsUser = loginBusiness.getCurrentUser(session);
}
if (useBasicAuthenticationMethod(request)) {
if (!isLoggedOn) {
if (!loginBusiness.authenticateBasicAuthenticationRequest(request)) {
loginBusiness.callForBasicAuthentication(request, response, null);
return;
}
}
}
else {
if (!isLoggedOn) {
loginBusiness.authenticateBasicAuthenticationRequest(request);
}
tryRegularLogin(request);
tryCookieLogin(request, response, loginBusiness);
}
processJAASLogin(request);
if (!isLoggedOn){
isLoggedOn = loginBusiness.isLoggedOn(request);
}
if (lastLoggedOnAsUser == null && isLoggedOn){
lastLoggedOnAsUser = loginBusiness.getCurrentUser(session);
}
boolean didInterrupt = processAuthenticationListeners(request, response, session, lastLoggedOnAsUser, loginBusiness, isLoggedOn);
if (didInterrupt) {
return;
}
boolean didRedirect = processRedirects(request, response, session, loginBusiness);
if (didRedirect) {
return;
}
chain.doFilter(new IWJAASAuthenticationRequestWrapper(request), response);
/*}
else {
chain.doFilter(request, response);
}*/
}
/**
* <p>
* Processes the possibly attatched AuthenticationListeners. Returns true if
* one of the authenticationfilters interrupts the filter chain.
* </p>
*
* @param request
* @param response
* @param session
* @param lastLoggedOnAsUser
* @param loginBusiness
* @param isLoggedOn
* @throws RemoteException
*/
protected boolean processAuthenticationListeners(HttpServletRequest request, HttpServletResponse response, HttpSession session, User lastLoggedOnAsUser, LoginBusinessBean loginBusiness, boolean isLoggedOn) throws RemoteException {
//TODO support also on basic authentication (e.g. webdav) or is that not necessery?
//TODO grab an interrupt exeption and just return; (could be necessery for the methods to be able to use response.sendRedirect)
if (loginBusiness.isLogOnAction(request) && isLoggedOn) {
try {
AuthenticationBusiness authenticationBusiness = getAuthenticationBusiness(request);
User currentUser = loginBusiness.getCurrentUser(session);
IWContext iwc = getIWContext(request, response);
authenticationBusiness.callOnLogonMethodInAllAuthenticationListeners(iwc, currentUser);
}
catch (ServletFilterChainInterruptException e) {
//this is normal behaviour if e.g. the listener issues a response.sendRedirect(...)
System.out.println("[IWAuthenticator] - Filter chain interrupted. The reason was: " + e.getMessage());
return true;
}
}
// else if(loginBusiness.isLogOffAction(request) && !isLoggedOn && lastLoggedOnAsUser!=null){
else if (loginBusiness.isLogOffAction(request) && lastLoggedOnAsUser != null) {
try {
AuthenticationBusiness authenticationBusiness = getAuthenticationBusiness(request);
//TODO: Remove IWContext
IWContext iwc = new IWContext(request, response, request.getSession().getServletContext());
authenticationBusiness.callOnLogoffMethodInAllAuthenticationListeners(iwc, lastLoggedOnAsUser);
}
catch (ServletFilterChainInterruptException e) {
//this is normal behaviour if e.g. the listener issues a response.sendRedirect(...)
System.out.println("[IWAuthenticator] - Filter chain interrupted. The reason was: " + e.getMessage());
return true;
}
}
return false;
}
/**
* <p>
* Processes possible redirects that might happen at login time. Returns true
* if a redirect did happen.
* </p>
*
* @param request
* @param response
* @param session
* @param loginBusiness
* @return
* @throws IOException
* @throws RemoteException
*/
protected boolean processRedirects(HttpServletRequest request, HttpServletResponse response, HttpSession session, LoginBusinessBean loginBusiness) throws IOException, RemoteException {
boolean isLoggedOn = loginBusiness.isLoggedOn(request);
boolean redirectToUserHomePage = false;
if (RequestUtil.isParameterSet(request, PARAMETER_REDIRECT_USER_TO_PRIMARY_GROUP_HOME_PAGE) && isLoggedOn) {
redirectToUserHomePage = true;
}
return processRedirects(request, response, session, loginBusiness, redirectToUserHomePage);
}
/**
* <p>
* Processes possible redirects that might happen at login time. Returns true
* if a redirect did happen.
* </p>
*
* @param request
* @param response
* @param session
* @param loginBusiness
* @return
* @throws IOException
* @throws RemoteException
*/
protected boolean processRedirects(HttpServletRequest request, HttpServletResponse response, HttpSession session, LoginBusinessBean loginBusiness, boolean redirectToUserHomePage) throws IOException, RemoteException {
//We have to call this method again because the user might just have logged on before:
boolean isLoggedOn = loginBusiness.isLoggedOn(request);
if (redirectToUserHomePage) {
return redirectToUserHomepage(request, response, loginBusiness);
}
if (RequestUtil.isParameterSet(request, PARAMETER_REDIRECT_URI_ONLOGON) && isLoggedOn) {
String uri = getLoginRedirectUriOnLogonParsedWithVariables(request);
if (uri != null) {
response.sendRedirect(uri);
return true;
}
}
if (RequestUtil.isParameterSet(request, PARAMETER_REDIRECT_URI_ONLOGOFF) && !isLoggedOn) {
String uri = request.getParameter(PARAMETER_REDIRECT_URI_ONLOGOFF);
if (uri != null) {
response.sendRedirect(uri);
return true;
}
}
return false;
}
/**
* @see com.idega.user.business.UserBusinessBean#getHomePageIDForUser(User)
*
* @param request
* @param response
* @param isLoggedOn
* @throws IOException
* @throws RemoteException
*/
protected boolean redirectToUserHomepage(HttpServletRequest request, HttpServletResponse response, LoginBusinessBean loginBusiness) throws IOException, RemoteException {
HttpSession session = request.getSession();
User user = loginBusiness.getCurrentUser(session);
IWMainApplication iwMainApplication = getIWMainApplication(request);
IWApplicationContext iwac = iwMainApplication.getIWApplicationContext();
UserBusiness userBusiness = (UserBusiness) IBOLookup.getServiceInstance(iwac, UserBusiness.class);
int redirectPageId = userBusiness.getHomePageIDForUser(user);
if (redirectPageId > 0) {
response.sendRedirect(getBuilderService(iwac).getPageURI(redirectPageId));
return true;
}
log.log(Level.INFO, "Didn't find user's " + user.getName() + " home page");
return false;
}
/**
* <p>
* Parses the set RedirectOnLogon URI and replaces with user variables such as
* the variables ${currentUser.personalID}, ${currentUser.ticket} in the URL
* String.
* </p>
*
* @param request
* @return
*/
public static String getLoginRedirectUriOnLogonParsedWithVariables(HttpServletRequest request) {
String uri = request.getParameter(PARAMETER_REDIRECT_URI_ONLOGON);
if (uri != null) {
try {
uri = URLDecoder.decode(uri, CoreConstants.ENCODING_UTF8);
List<String> ignoreParams = new ArrayList<String>();
ignoreParams.add(PARAMETER_REDIRECT_URI_ONLOGON);
ignoreParams.add(LoginBusinessBean.PARAMETER_USERNAME);
ignoreParams.add(LoginBusinessBean.PARAMETER_PASSWORD);
ignoreParams.add(LoginBusinessBean.PARAMETER_PASSWORD2);//whatever that is...
ignoreParams.add(LoginBusinessBean.LoginStateParameter);
ignoreParams.add(LoginBusinessBean.PARAM_LOGIN_BY_UNIQUE_ID);
- uri+="?"+RequestUtil.getParametersStringFromRequest(request,ignoreParams);
+
+ String parameterString = RequestUtil.getParametersStringFromRequest(request,ignoreParams);
+ if (parameterString.length() > 0) {
+ uri += (uri.indexOf("?") == -1 ? "?" : "&") + parameterString;
+ }
}
catch (UnsupportedEncodingException e) {
log.log(Level.WARNING, "Exception while decoding redirect uri parameter: " + PARAMETER_REDIRECT_URI_ONLOGON + " by using " + CoreConstants.ENCODING_UTF8 + " encoding", e);
}
}
uri = getUriParsedWithVariables(request, uri);
return uri;
}
/**
* <p>
* Parses the set RedirectOnLogon URI and replaces with user variables such as
* the variables ${currentUser.personalID}, ${currentUser.ticket} in the URL
* String.
* </p>
*
* @param request
* @return
*/
public static String getUriParsedWithVariables(HttpServletRequest request, String uri) {
LoginBusinessBean loginBean = LoginBusinessBean.getLoginBusinessBean(request);
LoggedOnInfo info = loginBean.getLoggedOnInfo(request.getSession());
User user = loginBean.getCurrentUser(request.getSession());
if (user != null) {
String personalId = user.getPersonalID();
uri = uri.replaceAll(PERSONAL_ID_PATTERN, personalId);
}
String ticket = info.getTicket();
if (ticket != null) {
uri = uri.replaceAll(TICKET_PATTERN, ticket);
}
return uri;
}
/**
* @param iwc
* @return
*/
private boolean useBasicAuthenticationMethod(HttpServletRequest request) {
return IWContext.isWebDavClient(request);
}
/*
* (non-Javadoc)
*
* @see javax.servlet.Filter#destroy()
*/
public void destroy() {
}
public void tryRegularLogin(HttpServletRequest request) {
try {
getLoginBusiness(request).processRequest(request);
}
catch (IWException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* <p>
* Authenticates in/out with reading existing cookie or creating it on login
* or removing it on logout
* </p>
*
* @param request
* @param response
* @param loginBusiness
*/
public void tryCookieLogin(HttpServletRequest request, HttpServletResponse response, LoginBusinessBean loginBusiness) {
if (!loginBusiness.isLoggedOn(request)) {
//No user is logged in, try to authenticate with the cookie:
Cookie userIDCookie = getCookie(request);
//System.err.println("no user is logged on");
if (userIDCookie != null) {
//System.err.println("found the cookie");
if (loginBusiness.isLogOffAction(request)) {
//A cookie is found
//delete it:
userIDCookie.setMaxAge(0);
response.addCookie(userIDCookie);
}
else {
String cypheredLoginName = userIDCookie.getValue();
IWApplicationContext iwac = getIWMainApplication(request).getIWApplicationContext();
String loginName = deCypherUserLogin(iwac, cypheredLoginName);
try {
loginBusiness.logInUnVerified(request, loginName);
}
catch (Exception ex) {
//throw new IWException("Cookie login failed :
// "+ex.getMessage());
log.warning("Cookie login failed for loginName: " + loginName + " :" + ex.getMessage());
}
}
}
else {
}
}
else {
//A user is logged in
if (loginBusiness.isLogOffAction(request)) {
Cookie userIDCookie = getCookie(request);
if (userIDCookie != null) {
//A cookie is found, try to remove it on logout
userIDCookie.setMaxAge(0);
response.addCookie(userIDCookie);
}
}
else if (RequestUtil.isParameterSet(request, PARAMETER_ALLOWS_COOKIE_LOGIN)) {
Cookie userIDCookie = getCookie(request);
HttpSession session = request.getSession();
String login = loginBusiness.getLoggedOnInfo(session).getLogin();
IWMainApplication iwma = getIWMainApplication(request);
IWApplicationContext iwac = iwma.getIWApplicationContext();
String cypheredLogin = cypherUserLogin(iwac, login);
int maxAge = 60 * 60 * 24 * 30;
if (userIDCookie == null) {
//No cookie exists on logon, try to add it:
userIDCookie = new Cookie(COOKIE_NAME, cypheredLogin);
userIDCookie.setMaxAge(maxAge);
response.addCookie(userIDCookie);
}
else {
userIDCookie.setValue(login);
userIDCookie.setMaxAge(maxAge);
}
}
}
}
private Cookie getCookie(HttpServletRequest request) {
Cookie userIDCookie = RequestUtil.getCookie(request, COOKIE_NAME);
return userIDCookie;
}
public String getCypherKey(IWApplicationContext iwc) {
CypherText cyph = new CypherText();
IWMainApplicationSettings settings = iwc.getApplicationSettings();
String cypherKey = settings.getProperty("cypherKey");
if ((cypherKey == null) || (cypherKey.equalsIgnoreCase(""))) {
cypherKey = cyph.getKey(100);
settings.setProperty("cypherKey", cypherKey);
}
return (cypherKey);
}
protected String cypherUserLogin(IWApplicationContext iwc, String userLogin) {
String key = getCypherKey(iwc);
String cypheredId = new CypherText().doCyper(userLogin, key);
log.fine("Cyphered " + userLogin + "to " + cypheredId);
return cypheredId;
}
protected String deCypherUserLogin(IWApplicationContext iwc, String cypheredLogin) {
String key = getCypherKey(iwc);
return new CypherText().doDeCypher(cypheredLogin, key);
}
protected AuthenticationBusiness getAuthenticationBusiness(HttpServletRequest request) {
AuthenticationBusiness authenticationBusiness = null;
try {
IWApplicationContext iwac = getIWMainApplication(request).getIWApplicationContext();
authenticationBusiness = (AuthenticationBusiness) IBOLookup.getServiceInstance(iwac, AuthenticationBusiness.class);
}
catch (IBOLookupException e) {
e.printStackTrace();
}
return authenticationBusiness;
}
protected BuilderService getBuilderService(IWApplicationContext iwac) throws RemoteException {
return BuilderServiceFactory.getBuilderService(iwac);
}
@SuppressWarnings("unchecked")
protected void processJAASLogin(HttpServletRequest request) {
List loginModules = ImplementorRepository.getInstance().newInstances(LoginModule.class, this.getClass());
// just a shortcut
if (loginModules.isEmpty()) {
return;
}
CallbackHandler callbackHandler = new IWCallbackHandler(request);
Map sharedState = new HashMap(3);
HttpSession session = request.getSession();
sharedState.put(IWAuthenticator.REQUEST_KEY, request);
sharedState.put(IWAuthenticator.SESSION_KEY, session);
Iterator iteratorFirst = loginModules.iterator();
while (iteratorFirst.hasNext()) {
LoginModule loginModule = (LoginModule) iteratorFirst.next();
try {
loginModule.initialize(null, callbackHandler, sharedState, null);
loginModule.login();
}
catch (LoginException e) {
e.printStackTrace();
}
}
Iterator iteratorSecond = loginModules.iterator();
while (iteratorSecond.hasNext()) {
LoginModule loginModule = (LoginModule) iteratorSecond.next();
try {
loginModule.commit();
}
catch (LoginException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
try {
String encoded = URLEncoder.encode("http://formbuilder.idega.is/login/?logon_redirect_uri=/workspace/", CoreConstants.ENCODING_UTF8);
System.out.println("encooded: " + encoded);
String decoded = URLDecoder.decode(encoded, CoreConstants.ENCODING_UTF8);
System.out.println("decoded: " + decoded);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/robocode/robocode/peer/ExplosionPeer.java b/robocode/robocode/peer/ExplosionPeer.java
index a4336e8ab..e82a26c97 100644
--- a/robocode/robocode/peer/ExplosionPeer.java
+++ b/robocode/robocode/peer/ExplosionPeer.java
@@ -1,62 +1,63 @@
/*******************************************************************************
* Copyright (c) 2001, 2007 Mathew A. Nelson and Robocode contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://robocode.sourceforge.net/license/cpl-v10.html
*
* Contributors:
* Mathew A. Nelson
* - Initial API and implementation
* Luis Crespo
* - Added states
* Flemming N. Larsen
- * - Added constructor for the BulletPeer in order to support replay feature
* - Code cleanup
+ * - Added constructor for the BulletPeer in order to support replay feature
+ * - Fixed synchronization issue with update()
* Titus Chen
* - Bugfix: Added Battle parameter to the constructor that takes a
* BulletRecord as parameter due to a NullPointerException that was raised
* as the battleField variable was not intialized
*******************************************************************************/
package robocode.peer;
import robocode.battle.Battle;
import robocode.battle.record.BulletRecord;
/**
* @author Mathew A. Nelson (original)
* @author Luis Crespo (contributor)
* @author Flemming N. Larsen (contributor)
* @author Titus Chen (contributor)
*/
public class ExplosionPeer extends BulletPeer {
public ExplosionPeer(RobotPeer owner, Battle battle) {
super(owner, battle);
this.hasHitVictim = true;
this.victim = owner;
this.power = 1;
this.state = STATE_EXPLODED;
this.lastState = STATE_EXPLODED;
explosionImageIndex = 1;
}
public ExplosionPeer(RobotPeer owner, Battle battle, BulletRecord br) {
super(owner, battle, br);
}
@Override
- public final void update() {
- setX(getOwner().getX());
- setY(getOwner().getY());
+ public synchronized final void update() {
+ x = getOwner().getX();
+ y = getOwner().getY();
nextFrame();
if (frame >= getBattle().getManager().getImageManager().getExplosionFrames(explosionImageIndex)) {
battle.removeBullet(this);
}
updateBulletState();
}
}
| false | false | null | null |
diff --git a/src/net/sf/drftpd/master/command/plugins/DataConnectionHandler.java b/src/net/sf/drftpd/master/command/plugins/DataConnectionHandler.java
index 4f865f94..05202275 100644
--- a/src/net/sf/drftpd/master/command/plugins/DataConnectionHandler.java
+++ b/src/net/sf/drftpd/master/command/plugins/DataConnectionHandler.java
@@ -1,1490 +1,1495 @@
/*
* This file is part of DrFTPD, Distributed FTP Daemon.
*
* DrFTPD is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* DrFTPD is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* DrFTPD; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA
*/
package net.sf.drftpd.master.command.plugins;
import net.sf.drftpd.NoAvailableSlaveException;
import net.sf.drftpd.NoSFVEntryException;
import net.sf.drftpd.SlaveUnavailableException;
import net.sf.drftpd.event.TransferEvent;
import net.sf.drftpd.master.BaseFtpConnection;
import net.sf.drftpd.master.FtpRequest;
import net.sf.drftpd.master.command.CommandManager;
import net.sf.drftpd.master.command.CommandManagerFactory;
import net.sf.drftpd.util.ReplacerUtils;
import org.apache.log4j.Logger;
import org.drftpd.Bytes;
import org.drftpd.Checksum;
import org.drftpd.SFVFile;
import org.drftpd.SSLGetContext;
import org.drftpd.commands.CommandHandler;
import org.drftpd.commands.CommandHandlerFactory;
import org.drftpd.commands.Reply;
import org.drftpd.commands.ReplyException;
import org.drftpd.commands.ReplySlaveUnavailableException;
import org.drftpd.commands.UnhandledCommandException;
import org.drftpd.commands.UserManagement;
import org.drftpd.master.RemoteSlave;
import org.drftpd.master.RemoteTransfer;
import org.drftpd.remotefile.LinkedRemoteFile;
import org.drftpd.remotefile.LinkedRemoteFileInterface;
import org.drftpd.remotefile.ListUtils;
import org.drftpd.remotefile.StaticRemoteFile;
import org.drftpd.slave.ConnectInfo;
import org.drftpd.slave.RemoteIOException;
import org.drftpd.slave.Transfer;
import org.drftpd.slave.TransferFailedException;
import org.drftpd.slave.TransferStatus;
import org.drftpd.usermanager.UserFileException;
import org.tanesha.replacer.ReplacerEnvironment;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;
import javax.net.ssl.HandshakeCompletedEvent;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
/**
* @author mog
* @author zubov
* @version $Id$
*/
public class DataConnectionHandler implements CommandHandler, CommandHandlerFactory,
Cloneable, HandshakeCompletedListener {
private static final Logger logger = Logger.getLogger(DataConnectionHandler.class);
private SSLContext _ctx;
private boolean _encryptedDataChannel;
protected boolean _isPasv = false;
protected boolean _isPort = false;
/**
* Holds the address that getDataSocket() should connect to in PORT mode.
*/
private InetSocketAddress _portAddress;
protected boolean _preTransfer = false;
private RemoteSlave _preTransferRSlave;
private long _resumePosition = 0;
private RemoteSlave _rslave;
/**
* ServerSocket for PASV mode.
*/
private ServerSocket _serverSocket;
private RemoteTransfer _transfer;
private LinkedRemoteFileInterface _transferFile;
private char _type = 'A';
private boolean _handshakeCompleted;
public DataConnectionHandler() {
super();
_handshakeCompleted = false;
try {
_ctx = SSLGetContext.getSSLContext();
} catch (FileNotFoundException e) {
_ctx = null;
logger.warn("Couldn't load SSLContext, SSL/TLS disabled");
} catch (Exception e) {
_ctx = null;
logger.warn("Couldn't load SSLContext, SSL/TLS disabled", e);
}
}
private Reply doAUTH(BaseFtpConnection conn) {
if (_ctx == null) {
return new Reply(500, "TLS not configured");
}
Socket s = conn.getControlSocket();
//reply success
conn.getControlWriter().write(new Reply(234,
conn.getRequest().getCommandLine() + " successful").toString());
conn.getControlWriter().flush();
try {
SSLSocket s2;
s2 = (SSLSocket) _ctx.getSocketFactory().createSocket(s,
s.getInetAddress().getHostAddress(), s.getPort(), true);
s2.setUseClientMode(false);
s2.addHandshakeCompletedListener(this);
s2.startHandshake();
while(!_handshakeCompleted) {
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
+ synchronized(this) {
+ try {
+ wait(10000);
+ } catch (InterruptedException e) {
+ conn.stop("Took too long to negotiate SSL");
+ return new Reply(400, "Took too long to negotiate SSL");
+ }
}
}
// reset for possible auth later
_handshakeCompleted = false;
conn.setControlSocket(s2);
} catch (IOException e) {
logger.warn("", e);
conn.stop(e.getMessage());
return null;
}
return null;
}
/**
* <code>MODE <SP> <mode-code> <CRLF></code><br>
*
* The argument is a single Telnet character code specifying the data
* transfer modes described in the Section on Transmission Modes.
*/
private Reply doMODE(BaseFtpConnection conn) {
FtpRequest request = conn.getRequest();
// argument check
if (!request.hasArgument()) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
if (request.getArgument().equalsIgnoreCase("S")) {
return Reply.RESPONSE_200_COMMAND_OK;
}
return Reply.RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM;
}
/**
* <code>PASV <CRLF></code><br>
*
* This command requests the server-DTP to "listen" on a data port (which is
* not its default data port) and to wait for a connection rather than
* initiate one upon receipt of a transfer command. The response to this
* command includes the host and port address this server is listening on.
*/
private Reply doPASV(BaseFtpConnection conn) {
if (!_preTransfer) {
return new Reply(500,
"You need to use a client supporting PRET (PRE Transfer) to use PASV");
}
//reset();
_preTransfer = false;
if (isPort() == true) {
throw new RuntimeException();
}
InetSocketAddress address;
if (_preTransferRSlave == null) {
try {
_serverSocket = conn.getGlobalContext().getPortRange().getPort(getServerSocketFactory(
_encryptedDataChannel));
address = new InetSocketAddress(conn.getControlSocket()
.getLocalAddress(),
_serverSocket.getLocalPort());
_isPasv = true;
} catch (Exception ex) {
logger.warn("", ex);
return new Reply(550, ex.getMessage());
}
} else {
try {
String index = _preTransferRSlave.issueListenToSlave(_encryptedDataChannel);
ConnectInfo ci = _preTransferRSlave.fetchTransferResponseFromIndex(index);
_transfer = _preTransferRSlave.getTransfer(ci.getTransferIndex());
address = new InetSocketAddress(_preTransferRSlave.getInetAddress(),
_transfer.getAddress().getPort());
_isPasv = true;
} catch (SlaveUnavailableException e) {
return Reply.RESPONSE_530_SLAVE_UNAVAILABLE;
} catch (RemoteIOException e) {
_preTransferRSlave.setOffline(
"Slave could not listen for a connection");
logger.error("Slave could not listen for a connection", e);
return new Reply(500,
"Slave could not listen for a connection");
}
}
String addrStr = address.getAddress().getHostAddress().replace('.', ',') +
',' + (address.getPort() >> 8) + ',' + (address.getPort() & 0xFF);
return new Reply(227, "Entering Passive Mode (" + addrStr + ").");
}
private Reply doPBSZ(BaseFtpConnection conn)
throws UnhandledCommandException {
String cmd = conn.getRequest().getArgument();
if ((cmd == null) || !cmd.equals("0")) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
return Reply.RESPONSE_200_COMMAND_OK;
}
/**
* <code>PORT <SP> <host-port> <CRLF></code><br>
*
* The argument is a HOST-PORT specification for the data port to be used in
* data connection. There are defaults for both the user and server data
* ports, and under normal circumstances this command and its reply are not
* needed. If this command is used, the argument is the concatenation of a
* 32-bit internet host address and a 16-bit TCP port address. This address
* information is broken into 8-bit fields and the value of each field is
* transmitted as a decimal number (in character string representation). The
* fields are separated by commas. A port command would be:
*
* PORT h1,h2,h3,h4,p1,p2
*
* where h1 is the high order 8 bits of the internet host address.
*/
private Reply doPORT(BaseFtpConnection conn) {
FtpRequest request = conn.getRequest();
reset();
InetAddress clientAddr = null;
// argument check
if (!request.hasArgument()) {
//Syntax error in parameters or arguments
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
StringTokenizer st = new StringTokenizer(request.getArgument(), ",");
if (st.countTokens() != 6) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
// get data server
String dataSrvName = st.nextToken() + '.' + st.nextToken() + '.' +
st.nextToken() + '.' + st.nextToken();
try {
clientAddr = InetAddress.getByName(dataSrvName);
} catch (UnknownHostException ex) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
String portHostAddress = clientAddr.getHostAddress();
String clientHostAddress = conn.getControlSocket().getInetAddress()
.getHostAddress();
if ((portHostAddress.startsWith("192.168.") &&
!clientHostAddress.startsWith("192.168.")) ||
(portHostAddress.startsWith("10.") &&
!clientHostAddress.startsWith("10."))) {
Reply response = new Reply(501);
response.addComment("==YOU'RE BEHIND A NAT ROUTER==");
response.addComment(
"Configure the firewall settings of your FTP client");
response.addComment(" to use your real IP: " +
conn.getControlSocket().getInetAddress().getHostAddress());
response.addComment("And set up port forwarding in your router.");
response.addComment(
"Or you can just use a PRET capable client, see");
response.addComment(" http://drftpd.org/ for PRET capable clients");
return response;
}
int clientPort;
// get data server port
try {
int hi = Integer.parseInt(st.nextToken());
int lo = Integer.parseInt(st.nextToken());
clientPort = (hi << 8) | lo;
} catch (NumberFormatException ex) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
//out.write(ftpStatus.getResponse(552, request, user, null));
}
_isPort = true;
_portAddress = new InetSocketAddress(clientAddr, clientPort);
if (portHostAddress.startsWith("127.")) {
return new Reply(200,
"Ok, but distributed transfers won't work with local addresses");
}
//Notify the user that this is not his IP.. Good for NAT users that
// aren't aware that their IP has changed.
if (!clientAddr.equals(conn.getControlSocket().getInetAddress())) {
return new Reply(200,
"FXP allowed. If you're not FXPing then set your IP to " +
conn.getControlSocket().getInetAddress().getHostAddress() +
" (usually in firewall settings)");
}
return Reply.RESPONSE_200_COMMAND_OK;
}
private Reply doPRET(BaseFtpConnection conn) {
reset();
FtpRequest request = conn.getRequest();
FtpRequest ghostRequest = new FtpRequest(request.getArgument());
String cmd = ghostRequest.getCommand();
if (cmd.equals("LIST") || cmd.equals("NLST") || cmd.equals("MLSD")) {
_preTransferRSlave = null;
_preTransfer = true;
return new Reply(200, "OK, will use master for upcoming transfer");
} else if (cmd.equals("RETR")) {
try {
LinkedRemoteFileInterface downFile = conn.getCurrentDirectory()
.lookupFile(ghostRequest.getArgument());
_preTransferRSlave = conn.getGlobalContext().getSlaveSelectionManager().getASlave(downFile.getAvailableSlaves(),
Transfer.TRANSFER_SENDING_DOWNLOAD, conn, downFile);
_preTransfer = true;
return new Reply(200,
"OK, will use " + _preTransferRSlave.getName() +
" for upcoming transfer");
} catch (NoAvailableSlaveException e) {
return Reply.RESPONSE_530_SLAVE_UNAVAILABLE;
} catch (FileNotFoundException e) {
return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN;
}
} else if (cmd.equals("STOR")) {
LinkedRemoteFile.NonExistingFile nef = conn.getCurrentDirectory()
.lookupNonExistingFile(ghostRequest.getArgument());
if (nef.exists()) {
return Reply.RESPONSE_530_ACCESS_DENIED;
}
if (!ListUtils.isLegalFileName(nef.getPath())) {
return Reply.RESPONSE_530_ACCESS_DENIED;
}
try {
_preTransferRSlave = conn.getGlobalContext().getSlaveSelectionManager().getASlave(conn.getGlobalContext()
.getSlaveManager()
.getAvailableSlaves(),
Transfer.TRANSFER_RECEIVING_UPLOAD, conn,
nef.getFile());
_preTransfer = true;
return new Reply(200,
"OK, will use " + _preTransferRSlave.getName() +
" for upcoming transfer");
} catch (NoAvailableSlaveException e) {
return Reply.RESPONSE_530_SLAVE_UNAVAILABLE;
}
} else {
return Reply.RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM;
}
}
private Reply doPROT(BaseFtpConnection conn)
throws UnhandledCommandException {
if (_ctx == null) {
return new Reply(500, "TLS not configured");
}
FtpRequest req = conn.getRequest();
if (!req.hasArgument()) {
//clear
_encryptedDataChannel = false;
return Reply.RESPONSE_200_COMMAND_OK;
}
if (!req.hasArgument() || (req.getArgument().length() != 1)) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
switch (Character.toUpperCase(req.getArgument().charAt(0))) {
case 'C':
//clear
_encryptedDataChannel = false;
return Reply.RESPONSE_200_COMMAND_OK;
case 'P':
//private
_encryptedDataChannel = true;
return Reply.RESPONSE_200_COMMAND_OK;
default:
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
}
/**
* <code>REST <SP> <marker> <CRLF></code><br>
*
* The argument field represents the server marker at which file transfer is
* to be restarted. This command does not cause file transfer but skips over
* the file to the specified data checkpoint. This command shall be
* immediately followed by the appropriate FTP service command which shall
* cause file transfer to resume.
*/
private Reply doREST(BaseFtpConnection conn) {
FtpRequest request = conn.getRequest();
// argument check
if (!request.hasArgument()) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
String skipNum = request.getArgument();
try {
_resumePosition = Long.parseLong(skipNum);
} catch (NumberFormatException ex) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
if (_resumePosition < 0) {
_resumePosition = 0;
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
return Reply.RESPONSE_350_PENDING_FURTHER_INFORMATION;
}
private Reply doSITE_RESCAN(BaseFtpConnection conn) {
FtpRequest request = conn.getRequest();
boolean forceRescan = (request.hasArgument() &&
request.getArgument().equalsIgnoreCase("force"));
LinkedRemoteFileInterface directory = conn.getCurrentDirectory();
SFVFile sfv;
try {
sfv = conn.getCurrentDirectory().lookupSFVFile();
} catch (Exception e) {
return new Reply(200, "Error getting SFV File: " +
e.getMessage());
}
PrintWriter out = conn.getControlWriter();
for (Iterator i = sfv.getEntries().entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
String fileName = (String) entry.getKey();
Long checkSum = (Long) entry.getValue();
LinkedRemoteFileInterface file;
try {
file = directory.lookupFile(fileName);
} catch (FileNotFoundException ex) {
out.write("200- SFV: " +
Checksum.formatChecksum(checkSum.longValue()) + " SLAVE: " +
fileName + " MISSING" + BaseFtpConnection.NEWLINE);
continue;
}
String status;
long fileCheckSum = 0;
try {
if (forceRescan) {
fileCheckSum = file.getCheckSumFromSlave();
} else {
fileCheckSum = file.getCheckSum();
}
} catch (NoAvailableSlaveException e1) {
out.println("200- " + fileName + "SFV: " +
Checksum.formatChecksum(checkSum.longValue()) +
" SLAVE: OFFLINE");
continue;
} catch (IOException ex) {
out.print("200- " + fileName + " SFV: " +
Checksum.formatChecksum(checkSum.longValue()) +
" SLAVE: IO error: " + ex.getMessage());
continue;
}
if (fileCheckSum == 0L) {
status = "FAILED - failed to checksum file";
} else if (checkSum.longValue() == fileCheckSum) {
status = "OK";
} else {
status = "FAILED - checksum mismatch";
}
out.println("200- " + fileName + " SFV: " +
Checksum.formatChecksum(checkSum.longValue()) + " SLAVE: " +
Checksum.formatChecksum(checkSum.longValue()) + " " + status);
continue;
}
return Reply.RESPONSE_200_COMMAND_OK;
}
private Reply doSITE_XDUPE(BaseFtpConnection conn) {
return Reply.RESPONSE_502_COMMAND_NOT_IMPLEMENTED;
// resetState();
//
// if (!request.hasArgument()) {
// if (this.xdupe == 0) {
// out.println("200 Extended dupe mode is disabled.");
// } else {
// out.println(
// "200 Extended dupe mode " + this.xdupe + " is enabled.");
// }
// return;
// }
//
// short myXdupe;
// try {
// myXdupe = Short.parseShort(request.getArgument());
// } catch (NumberFormatException ex) {
// out.print(FtpResponse.RESPONSE_501_SYNTAX_ERROR);
// return;
// }
//
// if (myXdupe > 0 || myXdupe < 4) {
// out.print(
// FtpResponse.RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM);
// return;
// }
// this.xdupe = myXdupe;
// out.println("200 Activated extended dupe mode " + myXdupe + ".");
}
/**
* <code>STRU <SP> <structure-code> <CRLF></code><br>
*
* The argument is a single Telnet character code specifying file structure.
*/
private Reply doSTRU(BaseFtpConnection conn) {
FtpRequest request = conn.getRequest();
// argument check
if (!request.hasArgument()) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
if (request.getArgument().equalsIgnoreCase("F")) {
return Reply.RESPONSE_200_COMMAND_OK;
}
return Reply.RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM;
}
/**
* <code>SYST <CRLF></code><br>
*
* This command is used to find out the type of operating system at the
* server.
*/
private Reply doSYST(BaseFtpConnection conn) {
/*
* String systemName = System.getProperty("os.name"); if(systemName ==
* null) { systemName = "UNKNOWN"; } else { systemName =
* systemName.toUpperCase(); systemName = systemName.replace(' ', '-'); }
* String args[] = {systemName};
*/
return Reply.RESPONSE_215_SYSTEM_TYPE;
//String args[] = { "UNIX" };
//out.write(ftpStatus.getResponse(215, request, user, args));
}
/**
* <code>TYPE <SP> <type-code> <CRLF></code><br>
*
* The argument specifies the representation type.
*/
private Reply doTYPE(BaseFtpConnection conn) {
FtpRequest request = conn.getRequest();
// get type from argument
if (!request.hasArgument()) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
// set it
if (setType(request.getArgument().charAt(0))) {
return Reply.RESPONSE_200_COMMAND_OK;
}
return Reply.RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM;
}
public Reply execute(BaseFtpConnection conn)
throws ReplyException {
String cmd = conn.getRequest().getCommand();
if ("MODE".equals(cmd)) {
return doMODE(conn);
}
if ("PASV".equals(cmd)) {
return doPASV(conn);
}
if ("PORT".equals(cmd)) {
return doPORT(conn);
}
if ("PRET".equals(cmd)) {
return doPRET(conn);
}
if ("REST".equals(cmd)) {
return doREST(conn);
}
if ("RETR".equals(cmd) || "STOR".equals(cmd) || "APPE".equals(cmd)) {
return transfer(conn);
}
if ("SITE RESCAN".equals(cmd)) {
return doSITE_RESCAN(conn);
}
if ("SITE XDUPE".equals(cmd)) {
return doSITE_XDUPE(conn);
}
if ("STRU".equals(cmd)) {
return doSTRU(conn);
}
if ("SYST".equals(cmd)) {
return doSYST(conn);
}
if ("TYPE".equals(cmd)) {
return doTYPE(conn);
}
if ("AUTH".equals(cmd)) {
return doAUTH(conn);
}
if ("PROT".equals(cmd)) {
return doPROT(conn);
}
if ("PBSZ".equals(cmd)) {
return doPBSZ(conn);
}
throw UnhandledCommandException.create(DataConnectionHandler.class,
conn.getRequest());
}
/**
* Get the data socket.
*
* Used by LIST and NLST and MLST.
*/
public Socket getDataSocket() throws IOException {
Socket dataSocket;
// get socket depending on the selection
if (isPort()) {
try {
dataSocket = getSocketFactory(_encryptedDataChannel)
.createSocket();
dataSocket.connect(_portAddress);
} catch (IOException ex) {
logger.warn("Error opening data socket", ex);
dataSocket = null;
throw ex;
}
} else if (isPasv()) {
try {
dataSocket = _serverSocket.accept();
} finally {
_serverSocket.close();
_serverSocket = null;
}
} else {
throw new IllegalStateException("Neither PASV nor PORT");
}
if (dataSocket instanceof SSLSocket) {
SSLSocket ssldatasocket = (SSLSocket) dataSocket;
ssldatasocket.setUseClientMode(false);
ssldatasocket.startHandshake();
}
dataSocket.setSoTimeout(15000); // 15 seconds timeout
return dataSocket;
}
public SocketFactory getSocketFactory(boolean dataChannel) {
if (dataChannel) {
if (_ctx == null) {
throw new IllegalStateException(
"cannot request a secure socket without being in secure mode");
}
return _ctx.getSocketFactory();
}
return SocketFactory.getDefault();
}
public ServerSocketFactory getServerSocketFactory(boolean dataChannel) {
if (dataChannel) {
if (_ctx == null) {
throw new IllegalStateException(
"cannot request a SecureSocketFactory without being in secure mode");
}
return _ctx.getServerSocketFactory();
}
return ServerSocketFactory.getDefault();
}
public String[] getFeatReplies() {
if (_ctx != null) {
return new String[] { "PRET", "AUTH SSL", "PBSZ" };
}
return new String[] { "PRET" };
}
public String getHelp(String cmd) {
ResourceBundle bundle = ResourceBundle.getBundle(DataConnectionHandler.class.getName());
if ("".equals(cmd))
return bundle.getString("help.general")+"\n";
else if("rescan".equals(cmd))
return bundle.getString("help.rescan")+"\n";
else
return "";
}
public RemoteSlave getTranferSlave() {
return _rslave;
}
public RemoteTransfer getTransfer() {
if (_transfer == null) {
throw new IllegalStateException();
}
return _transfer;
}
public LinkedRemoteFileInterface getTransferFile() {
return _transferFile;
}
/**
* Get the user data type.
*/
public char getType() {
return _type;
}
public CommandHandler initialize(BaseFtpConnection conn,
CommandManager initializer) {
try {
return (DataConnectionHandler) clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
public boolean isEncryptedDataChannel() {
return _encryptedDataChannel;
}
/**
* Guarantes pre transfer is set up correctly.
*/
public boolean isPasv() {
return _isPasv;
}
public boolean isPort() {
return _isPort;
}
public boolean isPreTransfer() {
return _preTransfer || isPasv();
}
public boolean isTransfering() {
return _transfer != null;
}
public void load(CommandManagerFactory initializer) {
}
protected void reset() {
_rslave = null;
_transfer = null;
_transferFile = null;
_preTransfer = false;
_preTransferRSlave = null;
if (_serverSocket != null) { //isPasv() && _preTransferRSlave == null
try {
_serverSocket.close();
} catch (IOException e) {
}
}
_isPasv = false;
_serverSocket = null;
_isPort = false;
_resumePosition = 0;
}
/**
* Set the data type. Supported types are A (ascii) and I (binary).
*
* @return true if success
*/
private boolean setType(char type) {
type = Character.toUpperCase(type);
if ((type != 'A') && (type != 'I')) {
return false;
}
_type = type;
return true;
}
/**
* <code>STOU <CRLF></code><br>
*
* This command behaves like STOR except that the resultant file is to be
* created in the current directory under a name unique to that directory.
* The 250 Transfer Started response must include the name generated.
*/
//TODO STOU
/*
* public void doSTOU(FtpRequest request, PrintWriter out) {
* // reset state variables resetState();
* // get filenames String fileName =
* user.getVirtualDirectory().getAbsoluteName("ftp.dat"); String
* physicalName = user.getVirtualDirectory().getPhysicalName(fileName); File
* requestedFile = new File(physicalName); requestedFile =
* IoUtils.getUniqueFile(requestedFile); fileName =
* user.getVirtualDirectory().getVirtualName(requestedFile.getAbsolutePath());
* String args[] = {fileName};
* // check permission
* if(!user.getVirtualDirectory().hasCreatePermission(fileName, false)) {
* out.write(ftpStatus.getResponse(550, request, user, null)); return; }
* // now transfer file data out.print(FtpResponse.RESPONSE_150_OK);
* InputStream is = null; OutputStream os = null; try { Socket dataSoc =
* mDataConnection.getDataSocket(); if (dataSoc == null) {
* out.write(ftpStatus.getResponse(550, request, user, args)); return; }
*
*
* is = dataSoc.getInputStream(); os = user.getOutputStream( new
* FileOutputStream(requestedFile) );
*
* StreamConnector msc = new StreamConnector(is, os);
* msc.setMaxTransferRate(user.getMaxUploadRate()); msc.setObserver(this);
* msc.connect();
*
* if(msc.hasException()) { out.write(ftpStatus.getResponse(451, request,
* user, null)); return; } else {
* mConfig.getStatistics().setUpload(requestedFile, user,
* msc.getTransferredSize()); }
*
* out.write(ftpStatus.getResponse(226, request, user, null));
* mDataConnection.reset(); out.write(ftpStatus.getResponse(250, request,
* user, args)); } catch(IOException ex) {
* out.write(ftpStatus.getResponse(425, request, user, null)); } finally {
* IoUtils.close(is); IoUtils.close(os); mDataConnection.reset(); } }
*/
/**
* <code>RETR <SP> <pathname> <CRLF></code><br>
*
* This command causes the server-DTP to transfer a copy of the file,
* specified in the pathname, to the server- or user-DTP at the other end of
* the data connection. The status and contents of the file at the server
* site shall be unaffected.
*
* RETR 125, 150 (110) 226, 250 425, 426, 451 450, 550 500, 501, 421, 530
* <p>
* <code>STOR <SP> <pathname> <CRLF></code><br>
*
* This command causes the server-DTP to accept the data transferred via the
* data connection and to store the data as a file at the server site. If
* the file specified in the pathname exists at the server site, then its
* contents shall be replaced by the data being transferred. A new file is
* created at the server site if the file specified in the pathname does not
* already exist.
*
* STOR 125, 150 (110) 226, 250 425, 426, 451, 551, 552 532, 450, 452, 553
* 500, 501, 421, 530
*
* ''zipscript?? renames bad uploads to .bad, how do we handle this with
* resumes?
*/
//TODO add APPE support
private Reply transfer(BaseFtpConnection conn)
throws ReplyException {
if (!_encryptedDataChannel &&
conn.getGlobalContext().getConfig().checkPermission("denydatauncrypted", conn.getUserNull())) {
return new Reply(530, "USE SECURE DATA CONNECTION");
}
try {
FtpRequest request = conn.getRequest();
char direction = conn.getDirection();
String cmd = conn.getRequest().getCommand();
boolean isStor = cmd.equals("STOR");
boolean isRetr = cmd.equals("RETR");
boolean isAppe = cmd.equals("APPE");
boolean isStou = cmd.equals("STOU");
String eventType = isRetr ? "RETR" : "STOR";
if (isAppe || isStou) {
throw UnhandledCommandException.create(DataConnectionHandler.class,
conn.getRequest());
}
// argument check
if (!request.hasArgument()) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
// get filenames
LinkedRemoteFileInterface targetDir;
String targetFileName;
if (isRetr) {
try {
_transferFile = conn.getCurrentDirectory().lookupFile(request.getArgument());
if (!_transferFile.isFile()) {
return new Reply(550, "Not a plain file");
}
targetDir = _transferFile.getParentFileNull();
targetFileName = _transferFile.getName();
} catch (FileNotFoundException ex) {
return new Reply(550, ex.getMessage());
}
} else if (isStor) {
LinkedRemoteFile.NonExistingFile ret = conn.getCurrentDirectory()
.lookupNonExistingFile(conn.getGlobalContext()
.getConfig()
.getFileName(request.getArgument()));
targetDir = ret.getFile();
targetFileName = ret.getPath();
if (ret.exists()) {
// target exists, this could be overwrite or resume
//TODO overwrite & resume files.
return new Reply(550,
"Requested action not taken. File exists.");
//_transferFile = targetDir;
//targetDir = _transferFile.getParent();
//if(_transfereFile.getOwner().equals(getUser().getUsername()))
// {
// // allow overwrite/resume
//}
//if(directory.isDirectory()) {
// return FtpReply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN;
//}
}
if (!ListUtils.isLegalFileName(targetFileName) ||
!conn.getGlobalContext().getConfig().checkPathPermission("privpath", conn.getUserNull(), targetDir, true)) {
return new Reply(553,
"Requested action not taken. File name not allowed.");
}
} else {
throw UnhandledCommandException.create(DataConnectionHandler.class,
request);
}
//check access
if (!conn.getGlobalContext().getConfig().checkPathPermission("privpath", conn.getUserNull(), targetDir, true)) {
return new Reply(550,
request.getArgument() + ": No such file");
}
switch (direction) {
case Transfer.TRANSFER_SENDING_DOWNLOAD:
if (!conn.getGlobalContext().getConfig().checkPathPermission("download", conn.getUserNull(), targetDir)) {
return Reply.RESPONSE_530_ACCESS_DENIED;
}
break;
case Transfer.TRANSFER_RECEIVING_UPLOAD:
if (!conn.getGlobalContext().getConfig().checkPathPermission("upload", conn.getUserNull(), targetDir)) {
return Reply.RESPONSE_530_ACCESS_DENIED;
}
break;
default:
throw UnhandledCommandException.create(DataConnectionHandler.class,
request);
}
//check credits
if (isRetr) {
if ((conn.getUserNull().getKeyedMap().getObjectFloat(UserManagement.RATIO) != 0) &&
(conn.getUserNull().getCredits() < _transferFile.length())) {
return new Reply(550, "Not enough credits.");
}
}
//setup _rslave
if (isPasv()) {
// isPasv() means we're setup correctly
// if (!_preTransfer || _preTransferRSlave == null)
// return FtpReply.RESPONSE_503_BAD_SEQUENCE_OF_COMMANDS;
//check pretransfer
if (isRetr &&
!_transferFile.getSlaves().contains(_preTransferRSlave)) {
return Reply.RESPONSE_503_BAD_SEQUENCE_OF_COMMANDS;
}
_rslave = _preTransferRSlave;
//_preTransferRSlave = null;
//_preTransfer = false;
//code above to be handled by reset()
} else {
try {
if (direction == Transfer.TRANSFER_SENDING_DOWNLOAD) {
_rslave = conn.getGlobalContext().getSlaveSelectionManager().getASlave(_transferFile.getAvailableSlaves(),
Transfer.TRANSFER_SENDING_DOWNLOAD, conn,
_transferFile);
} else if (direction == Transfer.TRANSFER_RECEIVING_UPLOAD) {
_rslave = conn.getGlobalContext().getSlaveSelectionManager().getASlave(conn.getGlobalContext()
.getSlaveManager()
.getAvailableSlaves(),
Transfer.TRANSFER_RECEIVING_UPLOAD, conn,
targetDir);
} else {
throw new RuntimeException();
}
} catch (NoAvailableSlaveException ex) {
//TODO Might not be good to 450 reply always
//from rfc: 450 Requested file action not taken. File unavailable (e.g., file busy).
throw new ReplySlaveUnavailableException(ex, 450);
}
}
if (isStor) {
//setup upload
if (_rslave == null) {
throw new NullPointerException();
}
List rslaves = Collections.singletonList(_rslave);
StaticRemoteFile uploadFile = new StaticRemoteFile(rslaves,
targetFileName, conn.getUserNull().getName(),
conn.getUserNull().getGroup(), 0L,
System.currentTimeMillis(), 0L);
_transferFile = targetDir.addFile(uploadFile);
}
// setup _transfer
if (isPort()) {
try {
String index = _rslave.issueConnectToSlave(_portAddress,
_encryptedDataChannel);
ConnectInfo ci = _rslave.fetchTransferResponseFromIndex(index);
_transfer = _rslave.getTransfer(ci.getTransferIndex());
} catch (Exception ex) {
logger.fatal("rslave=" + _rslave, ex);
reset();
return new Reply(450,
ex.getClass().getName() + " from slave: " +
ex.getMessage());
}
} else if (isPasv()) {
//_transfer is already set up by doPASV()
} else {
return Reply.RESPONSE_503_BAD_SEQUENCE_OF_COMMANDS;
}
if (_transfer == null) {
throw new NullPointerException();
}
{
PrintWriter out = conn.getControlWriter();
out.write(new Reply(150,
"File status okay; about to open data connection " +
(isRetr ? "from " : "to ") + _rslave.getName() + ".").toString());
out.flush();
}
TransferStatus status = null;
//transfer
try {
//TODO ABORtable transfers
if (isRetr) {
_transfer.sendFile(_transferFile.getPath(), getType(),
_resumePosition);
while (true) {
status = _transfer.getTransferStatus();
if (status.isFinished()) {
break;
}
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
}
}
} else if (isStor) {
_transfer.receiveFile(_transferFile.getPath(), getType(),
_resumePosition);
while (true) {
status = _transfer.getTransferStatus();
if (status.isFinished()) {
break;
}
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
}
}
} else {
throw new RuntimeException();
}
} catch (IOException ex) {
if (ex instanceof TransferFailedException) {
status = ((TransferFailedException) ex).getStatus();
conn.getGlobalContext()
.dispatchFtpEvent(new TransferEvent(conn, eventType,
_transferFile, conn.getClientAddress(), _rslave,
_transfer.getAddress().getAddress(), _type, false));
if (isRetr) {
conn.getUserNull().updateCredits(-status.getTransfered());
}
}
Reply reply = null;
if (isStor) {
_transferFile.delete();
logger.error("IOException during transfer, deleting file",
ex);
reply = new Reply(426, "Transfer failed, deleting file");
} else {
logger.error("IOException during transfer", ex);
reply = new Reply(426, ex.getMessage());
}
reply.addComment(ex.getLocalizedMessage());
reset();
return reply;
} catch (SlaveUnavailableException e) {
Reply reply = null;
if (isStor) {
_transferFile.delete();
logger.error("Slave went offline during transfer, deleting file",
e);
reply = new Reply(426,
"Slave went offline during transfer, deleting file");
} else {
logger.error("Slave went offline during transfer", e);
reply = new Reply(426,
"Slave went offline during transfer");
}
reply.addComment(e.getLocalizedMessage());
return reply;
}
// TransferThread transferThread = new TransferThread(rslave,
// transfer);
// System.err.println("Calling interruptibleSleepUntilFinished");
// try {
// transferThread.interruptibleSleepUntilFinished();
// } catch (Throwable e1) {
// e1.printStackTrace();
// }
// System.err.println("Finished");
ReplacerEnvironment env = new ReplacerEnvironment();
env.add("bytes", Bytes.formatBytes(status.getTransfered()));
env.add("speed", Bytes.formatBytes(status.getXferSpeed()) + "/s");
env.add("seconds", "" + ((float)status.getElapsed() / 1000F));
env.add("checksum", Checksum.formatChecksum(status.getChecksum()));
Reply response = new Reply(226,
conn.jprintf(DataConnectionHandler.class,
"transfer.complete", env));
if (isStor) {
if (_resumePosition == 0) {
_transferFile.setCheckSum(status.getChecksum());
} else {
// try {
// checksum = _transferFile.getCheckSumFromSlave();
// } catch (NoAvailableSlaveException e) {
// response.addComment(
// "No available slaves when getting checksum from slave: "
// + e.getMessage());
// logger.warn("", e);
// checksum = 0;
// } catch (IOException e) {
// response.addComment(
// "IO error getting checksum from slave: "
// + e.getMessage());
// logger.warn("", e);
// checksum = 0;
// }
}
_transferFile.setLastModified(System.currentTimeMillis());
_transferFile.setLength(status.getTransfered());
_transferFile.setXfertime(status.getElapsed());
}
boolean zipscript = zipscript(isRetr, isStor, status.getChecksum(),
response, targetFileName, targetDir);
if (zipscript) {
//transferstatistics
if (isRetr) {
float ratio = conn.getGlobalContext().getConfig()
.getCreditLossRatio(_transferFile,
conn.getUserNull());
if (ratio != 0) {
conn.getUserNull().updateCredits((long) (-status.getTransfered() * ratio));
}
conn.getUserNull().updateDownloadedBytes(status.getTransfered());
conn.getUserNull().updateDownloadedTime(status.getElapsed());
conn.getUserNull().updateDownloadedFiles(1);
} else {
conn.getUserNull().updateCredits((long) (status.getTransfered() * conn.getGlobalContext()
.getConfig()
.getCreditCheckRatio(_transferFile,
conn.getUserNull())));
conn.getUserNull().updateUploadedBytes(status.getTransfered());
conn.getUserNull().updateUploadedTime(status.getElapsed());
conn.getUserNull().updateUploadedFiles(1);
}
try {
conn.getUserNull().commit();
} catch (UserFileException e) {
logger.warn("", e);
}
}
//Dispatch for both STOR and RETR
conn.getGlobalContext().dispatchFtpEvent(new TransferEvent(
conn, eventType, _transferFile, conn.getClientAddress(),
_rslave, _transfer.getAddress().getAddress(), getType(),
zipscript));
return response;
} finally {
reset();
}
}
public void unload() {
}
/**
* @param isRetr
* @param isStor
* @param status
* @param response
* @param targetFileName
* @param targetDir
* Returns true if crc check was okay, i.e, if credits should be
* altered
*/
private boolean zipscript(boolean isRetr, boolean isStor, long checksum,
Reply response, String targetFileName,
LinkedRemoteFileInterface targetDir) {
//zipscript
logger.debug("Running zipscript on file " + targetFileName +
" with CRC of " + checksum);
if (isRetr) {
//compare checksum from transfer to cached checksum
logger.debug("checksum from transfer = " + checksum);
if (checksum != 0) {
response.addComment("Checksum from transfer: " +
Checksum.formatChecksum(checksum));
long cachedChecksum;
cachedChecksum = _transferFile.getCheckSumCached();
if (cachedChecksum == 0) {
_transferFile.setCheckSum(checksum);
} else if (cachedChecksum != checksum) {
response.addComment(
"WARNING: checksum from transfer didn't match cached checksum");
logger.info("checksum from transfer " +
Checksum.formatChecksum(checksum) +
"didn't match cached checksum" +
Checksum.formatChecksum(cachedChecksum) + " for " +
_transferFile.toString() + " from slave " +
_rslave.getName(), new Throwable());
}
//compare checksum from transfer to checksum from sfv
try {
long sfvChecksum = _transferFile.getParentFileNull()
.lookupSFVFile()
.getChecksum(_transferFile.getName());
if (sfvChecksum == checksum) {
response.addComment(
"checksum from transfer matched checksum in .sfv");
} else {
response.addComment(
"WARNING: checksum from transfer didn't match checksum in .sfv");
}
} catch (NoAvailableSlaveException e1) {
response.addComment(
"slave with .sfv offline, checksum not verified");
} catch (FileNotFoundException e1) {
//continue without verification
} catch (NoSFVEntryException e1) {
//file not found in .sfv, continue
} catch (IOException e1) {
logger.info("", e1);
response.addComment("IO Error reading sfv file: " +
e1.getMessage());
}
} else { // slave has disabled download crc
//response.addComment("Slave has disabled download checksum");
}
} else if (isStor) {
if (!targetFileName.toLowerCase().endsWith(".sfv")) {
try {
long sfvChecksum = targetDir.lookupSFVFile().getChecksum(targetFileName);
if (checksum == sfvChecksum) {
response.addComment("checksum match: SLAVE/SFV:" +
Long.toHexString(checksum));
} else if (checksum == 0) {
response.addComment(
"checksum match: SLAVE/SFV: DISABLED");
} else {
response.addComment("checksum mismatch: SLAVE: " +
Long.toHexString(checksum) + " SFV: " +
Long.toHexString(sfvChecksum));
response.addComment(" deleting file");
response.setMessage("Checksum mismatch, deleting file");
_transferFile.delete();
// getUser().updateCredits(
// - ((long) getUser().getRatio() * transferedBytes));
// getUser().updateUploadedBytes(-transferedBytes);
// response.addComment(conn.status());
return false; // don't modify credits
// String badtargetFilename = targetFilename + ".bad";
//
// try {
// LinkedRemoteFile badtargetFile =
// targetDir.getFile(badtargetFilename);
// badtargetFile.delete();
// response.addComment(
// "zipscript - removing "
// + badtargetFilename
// + " to be replaced with new file");
// } catch (FileNotFoundException e2) {
// //good, continue...
// response.addComment(
// "zipscript - checksum mismatch, renaming to "
// + badtargetFilename);
// }
// targetFile.renameTo(targetDir.getPath() +
// badtargetFilename);
}
} catch (NoAvailableSlaveException e) {
response.addComment(
"zipscript - SFV unavailable, slave(s) with .sfv file is offline");
} catch (NoSFVEntryException e) {
response.addComment("zipscript - no entry in sfv for file");
} catch (IOException e) {
response.addComment(
"zipscript - SFV unavailable, IO error: " +
e.getMessage());
}
}
}
return true; // modify credits, transfer was okay
}
- public void handshakeCompleted(HandshakeCompletedEvent arg0) {
+ public synchronized void handshakeCompleted(HandshakeCompletedEvent arg0) {
_handshakeCompleted = true;
+ notifyAll();
}
}
| false | false | null | null |
diff --git a/src/com/groupon/GridWrapper.java b/src/com/groupon/GridWrapper.java
index 17f152a..9d45a6b 100644
--- a/src/com/groupon/GridWrapper.java
+++ b/src/com/groupon/GridWrapper.java
@@ -1,91 +1,86 @@
/**
* Copyright (c) 2013, Groupon, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of GROUPON nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* Created with IntelliJ IDEA.
* User: Dima Kovalenko (@dimacus) && Darko Marinov
* Date: 5/10/13
* Time: 4:06 PM
*/
package com.groupon;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class GridWrapper {
public static String getCurrentJarPath() {
return RuntimeConfig.getWebdriverParentDir() + "/" + RuntimeConfig.getWebdriverVersion()
+ ".jar";
}
public static String getStartCommand(String role) {
return "java -jar " + getCurrentJarPath() + " " + getFormattedConfig(role);
}
public static String getGridConfigPortForRole(String role) {
Map<String, String> config = getGridConfig(role);
return config.get("-port");
}
public static Map<String, String> getGridConfig(String role) {
- Map grid = (HashMap<String, HashMap>) RuntimeConfig.config.get("grid");
+ Map grid = RuntimeConfig.getGridConfig();
Map config = (HashMap<String, String>) grid.get(role);
return config;
}
- public static String getDefaultRole(){
- Map grid = (HashMap<String, HashMap>) RuntimeConfig.config.get("grid");
+ public static String getDefaultRole() {
+ Map grid = RuntimeConfig.getGridConfig();
return grid.get("default_role").toString();
}
private static String getFormattedConfig(String role) {
Map<String, String> config = getGridConfig(role);
StringBuilder commandLineParam = new StringBuilder();
- Iterator it = config.entrySet().iterator();
- while (it.hasNext()) {
- Map.Entry pairs = (Map.Entry) it.next();
-
- commandLineParam.append(" " + pairs.getKey());
- commandLineParam.append(" " + pairs.getValue());
-
- it.remove();
+ for (Map.Entry<String, String> entry : config.entrySet()) {
+ commandLineParam.append(" " + entry.getKey());
+ commandLineParam.append(" " + entry.getValue());
}
return commandLineParam.toString();
}
}
| false | false | null | null |
diff --git a/lib/src/java/org/j2free/jpa/Controller.java b/lib/src/java/org/j2free/jpa/Controller.java
index 6d31fc8..2f1f462 100644
--- a/lib/src/java/org/j2free/jpa/Controller.java
+++ b/lib/src/java/org/j2free/jpa/Controller.java
@@ -1,1106 +1,1106 @@
/*
* Controller.java
*
* Created on March 28, 2008, 2:00 PM
*
*/
package org.j2free.jpa;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.OptimisticLockException;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.hibernate.CacheMode;
import org.hibernate.Criteria;
import org.hibernate.FlushMode;
import org.hibernate.PropertyValueException;
import org.hibernate.SQLQuery;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.StaleObjectStateException;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.NaturalIdentifier;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.ejb.EntityManagerImpl;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.Search;
import org.hibernate.validator.InvalidStateException;
import org.hibernate.validator.InvalidValue;
import org.j2free.util.Pair;
/**
*
* @author ryan
*/
public class Controller {
protected Log LOG = LogFactory.getLog(Controller.class);
public static final String ATTRIBUTE_KEY = "controller";
protected UserTransaction tx;
protected EntityManager em;
protected FullTextEntityManager fullTextEntityManager;
private boolean markedForRollback;
protected InvalidValue[] errors;
public Controller() throws NamingException {
markedForRollback = false;
InitialContext ctx = new InitialContext();
tx = (UserTransaction) ctx.lookup("UserTransaction");
em = (EntityManager) ctx.lookup("java:comp/env/" + getJndiName());
}
protected String getJndiName() {
return "persistence/EntityManager";
}
public UserTransaction getUserTransaction() {
return tx;
}
public EntityManager getEntityManager() {
return em;
}
public void setEntityManager(EntityManager em) {
this.em = em;
}
public void setUserTransaction(UserTransaction tx) {
this.tx = tx;
}
public void clear() {
em.clear();
}
public void flush() {
try {
em.flush();
} catch (OptimisticLockException ole) {
LOG.error("OptimisticLockException[" + ole.getEntity() + "]");
} catch (StaleObjectStateException sose) {
LOG.error("StaleObjectStateException[" + sose.getEntityName() + "=" + sose.getIdentifier() + "]");
} catch (InvalidStateException ise) {
this.errors = ise.getInvalidValues();
} catch (Exception e) {
this.errors = new InvalidValue[0];
LOG.error("Error flushing transaction",e);
}
}
public void flushAndClear() {
try {
em.flush();
em.clear();
} catch (OptimisticLockException ole) {
LOG.error("OptimisticLockException[" + ole.getEntity() + "]");
} catch (StaleObjectStateException sose) {
LOG.error("StaleObjectStateException[" + sose.getEntityName() + "=" + sose.getIdentifier() + "]");
} catch (InvalidStateException ise) {
this.errors = ise.getInvalidValues();
} catch (Exception e) {
this.errors = new InvalidValue[0];
LOG.error("Error flushing transaction",e);
}
}
public void markForRollback(boolean markForRollback) {
this.markedForRollback = markForRollback;
}
public void setMarkedForRollback(boolean markedForRollback) {
this.markedForRollback = markedForRollback;
}
public boolean isMarkedForRollback() {
return markedForRollback;
}
public FullTextEntityManager getFullTextEntityManager() {
if (fullTextEntityManager == null || !fullTextEntityManager.isOpen()) {
fullTextEntityManager = Search.createFullTextEntityManager(getEntityManager());
}
return fullTextEntityManager;
}
public void startTransaction() {
try {
tx.begin();
em.joinTransaction(); // make sure the entity manager knows the transaction has begun
markedForRollback = false; // make sure that a transaction always starts clean
} catch (Exception e) {
LOG.error("Error beginning transaction",e);
tx = null;
}
}
public void endTransaction() {
try {
if (markedForRollback)
tx.rollback();
else
tx.commit();
} catch (OptimisticLockException ole) {
LOG.error("OptimisticLockException[" + ole.getEntity() + "]");
} catch (StaleObjectStateException sose) {
LOG.error("StaleObjectStateException[" + sose.getEntityName() + "=" + sose.getIdentifier() + "]");
} catch (InvalidStateException ise) {
this.errors = ise.getInvalidValues();
} catch (Exception e) {
LOG.error("Error committing transaction",e);
}
}
public boolean isTransactionOpen() throws SystemException {
return (tx.getStatus() == Status.STATUS_ACTIVE);
}
public Session getSession() {
return ((EntityManagerImpl)em.getDelegate()).getSession();
}
public void setCacheMode(CacheMode mode) {
try {
if (!isTransactionOpen())
return;
getSession().setCacheMode(mode);
} catch (SystemException syse) {
LOG.error("Could not determine transaction status before setting CacheMode",syse);
} catch (Exception e) {
LOG.error("Error setting CacheMode for session",e);
}
}
public void evictCollection(String collectionName, Serializable primaryKey) {
try {
getSession().getSessionFactory().evictCollection(collectionName,primaryKey);
} catch (Exception e) {
LOG.error("Error evicting",e);
}
}
public void evict(Class clazz, Serializable primaryKey) {
try {
getSession().getSessionFactory().evict(clazz,primaryKey);
} catch (Exception e) {
LOG.error("Error evicting",e);
}
}
public void evictCollection(String collection) {
try {
getSession().getSessionFactory().evictCollection(collection);
} catch (Exception e) {
LOG.error("Error evicting",e);
}
}
public void evict(Class clazz) {
try {
getSession().getSessionFactory().evict(clazz);
} catch (Exception e) {
LOG.error("Error evicting",e);
}
}
public Query createQuery(String query) {
return em.createQuery(query);
}
public Query createNativeQuery(String query) {
return em.createNativeQuery(query);
}
public <T extends Object> T findPrimaryKey(Class<T> entityClass, Object entityId) {
try {
return (T)em.find(entityClass,entityId);
} catch (Exception e) {
LOG.error("Exception in Controller.find [entityId=" + entityId + "]",e);
}
return null;
}
public <T extends Object> List<T> list(Class<T> entityClass) {
return list(entityClass,-1,-1);
}
public <T extends Object> List<T> list(Class<T> entityClass, int start, int limit) {
try {
Query query = em.createQuery("SELECT e FROM " + entityClass.getSimpleName() + " e");
if (start > 0) query.setFirstResult(start);
if (limit > 0) query.setMaxResults(limit);
return (List<T>)query.getResultList();
} catch (Exception e) {
LOG.error("Exception in Controller.findAll",e);
}
return null;
}
public <T extends Object> int count(Class<T> entityClass) {
Object o = null;
try {
Query query = em.createQuery("SELECT COUNT(e) FROM " + entityClass.getSimpleName() + " e");
o = query.getSingleResult();
return o == null ? -1 : ((Long)o).intValue();
} catch (ClassCastException cce) {
return o == null ? -1 : ((java.math.BigInteger)o).intValue();
} catch (Exception e) {
LOG.error("Exception in Controller.count",e);
}
return -1;
}
public <T extends Object> int count(Query query, Pair<String,? extends Object>... parameters) {
int count = -1;
Object o = null;
if (parameters != null) {
for (Pair<String,? extends Object> parameter : parameters)
query.setParameter(parameter.getFirst(),parameter.getSecond());
}
try {
o = query.getSingleResult();
count = ((Long)o).intValue();
} catch (ClassCastException cce) {
count = ((java.math.BigInteger)o).intValue();
} catch (Exception e) {
LOG.error("Exception in Controller.count",e);
}
return count;
}
public int count(String queryString, Pair<String,? extends Object>... parameters) {
try {
return count(em.createQuery(queryString),parameters);
} catch (Exception e) {
LOG.error("Exception in Controller.count [query = \"" + queryString + "\"]",e);
}
return -1;
}
public <T extends Object> int namedCount(Class<T> entityClass, String namedQuery, Pair<String,? extends Object>... parameters) {
try {
return count(em.createNamedQuery(entityClass.getSimpleName() + "." + namedQuery),parameters);
} catch (Exception e) {
LOG.error("Exception in Controller.namedCount" + namedQuery,e);
}
return -1;
}
public <T extends Object> T proxy(Class<T> entityClass, Object entityId) {
try {
return (T)em.getReference(entityClass,entityId);
} catch (Exception e) {
LOG.error("Exception in Controller.proxy [entityId=" + entityId + "]",e);
}
return null;
}
public <T extends Object> T merge(T entity) {
try {
entity = (T)em.merge(entity);
} catch (Exception e) {
markForRollback(true);
LOG.error("Exception in Controller.merge",e);
}
return entity;
}
public <T extends Object> void refresh(T entity) {
try {
em.refresh(entity);
} catch (Exception e) {
markForRollback(true);
LOG.error("Exception in Controller.refresh",e);
}
}
public <T extends Object> boolean remove(Class<T> entityClass, Object entityId) {
boolean success = true;
try {
T entity = (T)proxy(entityClass,entityId);
if (entity != null)
em.remove(entity);
} catch (Exception e) {
markForRollback(true);
LOG.error("Exception in Controller.remove(entityClass,entityId)",e);
success = false;
}
return success;
}
public <T extends Object> boolean remove(T entity) {
boolean success = true;
try {
em.remove(entity);
} catch (Exception e) {
markForRollback(true);
LOG.error("Exception in Controller.remove",e);
success = false;
}
return success;
}
public <T extends Object> T persist(T entity) {
return persist(entity,false);
}
public <T extends Object> T persist(T entity, boolean flush) {
try {
em.persist(entity);
this.errors = null;
if (flush)
em.flush();
} catch (OptimisticLockException ole) {
LOG.error("OptimisticLockException[" + ole.getEntity() + "]");
} catch (StaleObjectStateException sose) {
LOG.error("StaleObjectStateException[" + sose.getEntityName() + "=" + sose.getIdentifier() + "]");
} catch (InvalidStateException ise) {
this.errors = ise.getInvalidValues();
for (InvalidValue error : ise.getInvalidValues()) {
LOG.warn("Invalid Value: " + error.getBeanClass() + "." + error.getPropertyName() + " = " + error.getValue() + " | " + error.getMessage());
}
markForRollback(true);
LOG.error("InvalidStateException in Controller.persist",ise);
} catch (ConstraintViolationException cve) {
this.errors = new InvalidValue[] {
new InvalidValue(cve.getMessage(), null, "", "", entity)
};
markForRollback(true);
LOG.error("ConstraintViolationException in Controller.persist",cve);
} catch (PersistenceException pe) {
this.errors = new InvalidValue[] {
new InvalidValue(pe.getMessage(), entity.getClass(), "", "", entity)
};
markForRollback(true);
LOG.error("PersistenceException in Controller.persist",pe);
} catch (PropertyValueException pve) {
this.errors = new InvalidValue[] {
new InvalidValue(pve.getMessage(), entity.getClass(), pve.getPropertyName(), "", entity)
};
markForRollback(true);
LOG.error("PropertyValueException in Controller.persist",pve);
} catch (Exception e) {
markForRollback(true);
LOG.error("Exception in Controller.persist",e);
}
return entity;
}
public boolean hasErrors() {
return this.errors != null;
}
public InvalidValue[] getErrors() {
return this.errors;
}
public void clearErrors() {
this.errors = null;
}
public String getErrorsAsString(String delimiter, boolean debug) {
StringBuilder errorStringBuilder = new StringBuilder();
boolean first = true;
for (InvalidValue error : this.errors) {
if (debug)
errorStringBuilder.append((first ? "" : delimiter) + "Invalid Value: " + error.getBeanClass() + "." + error.getPropertyName() + " = " + error.getValue() + ", message = " + error.getMessage());
else
errorStringBuilder.append((first ? "" : delimiter) + error.getMessage());
if (first) first = false;
}
return errorStringBuilder.toString();
}
/**
* Find all objects matching criteria
*
* Sample criteria include:
* Restrictions.eq("property", variable)
* Restrictions.eq("subclass.property", variable)
* Order.desc("property")
*
* See for more examples:
* http://www.hibernate.org/hib_docs/v3/api/org/hibernate/criterion/Restrictions.html
*
**/
public <T extends Object> List<T> listByCriterions(Class<T> entityClass, Object... criteria) {
return listByCriterions(entityClass,-1,-1,criteria);
}
/**
* Find numResults objects matching criteria
*
* Sample criteria include:
* Restrictions.eq("property", variable)
* Restrictions.eq("subclass.property", variable)
* Order.desc("property")
*
* See for more examples:
* http://www.hibernate.org/hib_docs/v3/api/org/hibernate/criterion/Restrictions.html
*
**/
public <T extends Object> List<T> listByCriterions(Class<T> entityClass, int numResults, Object... criteria) {
return listByCriterions(entityClass,0,numResults,criteria);
}
/**
* Find numResults objects matching criteria starting at firstResult
*
* Sample criteria include:
* Restrictions.eq("property", variable)
* Restrictions.eq("subclass.property", variable)
* Order.desc("property")
*
* See for more examples:
* http://www.hibernate.org/hib_docs/v3/api/org/hibernate/criterion/Restrictions.html
*
**/
public <T extends Object> List<T> listByCriterions(Class<T> entityClass, int firstResult, int numResults, Object... criteria) {
try {
Criteria search = getSession().createCriteria(entityClass);
for (Object c : criteria) {
if (c instanceof Criterion || c.getClass() == Criterion.class)
search.add((Criterion)c);
if (c instanceof Order || c.getClass() == Order.class)
search.addOrder((Order)c);
}
if (firstResult > 0)
search.setFirstResult(firstResult);
if (numResults > 0)
search.setMaxResults(numResults);
return (List<T>)search.list();
} catch (Exception e) {
LOG.error("Exception in Controller.findMultiple",e);
}
return null;
}
/**
* Find numResults objects matching criteria starting at firstResult
*
* See for more examples:
* http://www.hibernate.org/hib_docs/v3/api/org/hibernate/criterion/Restrictions.html
*
**/
public <T extends Object> List<T> listByCriterea(Class<T> entityClass, int firstResult, int numResults, Criteria criteria) {
if (firstResult > 0)
criteria.setFirstResult(firstResult);
if (numResults > 0)
criteria.setMaxResults(numResults);
return listByCriteria(entityClass,criteria);
}
/**
* Find numResults objects matching criteria starting at firstResult
*
* See for more examples:
* http://www.hibernate.org/hib_docs/v3/api/org/hibernate/criterion/Restrictions.html
*
**/
public <T extends Object> List<T> listByCriteria(Class<T> entityClass, Criteria criteria) {
try {
return (List<T>)criteria.list();
} catch (Exception e) {
LOG.error("Exception in Controller.findMultiple",e);
}
return null;
}
/**
* Find a single object matching criteria
*
* Sample criteria include:
* Restrictions.eq("property", variable)
* Restrictions.eq("subclass.property", variable)
* Order.desc("property")
*
* See for more examples:
* http://www.hibernate.org/hib_docs/v3/api/org/hibernate/criterion/Restrictions.html
*
**/
public <T extends Object> T findByCriterion(Class<T> entityClass, Object... criteria) {
try {
Criteria search = getSession().createCriteria(entityClass);
for (Object c : criteria) {
if (c instanceof Criterion || c.getClass() == Criterion.class)
search.add((Criterion)c);
if (c instanceof Order || c.getClass() == Order.class)
search.addOrder((Order)c);
}
return (T)search.setMaxResults(1).uniqueResult();
} catch (Exception e) {
LOG.error("Exception in Controller.find single",e);
}
return null;
}
/**
* Find a single object matching criteria using a naturalId lookup with the queryByFormula cache
*
* Sample criteria include:
* Restrictions.naturalId().set("email",request.getRemoteUser());
*
* See for more examples:
* http://www.hibernate.org/hib_docs/reference/en/html/querycriteria.html#queryByFormula-criteria-naturalid
*/
public <T extends Object> T findNaturalId(Class<T> entityClass, NaturalIdentifier naturalId) {
try {
return (T)(getSession().createCriteria(entityClass)
.add(naturalId)
.setCacheable(true)
.uniqueResult());
} catch (Exception e) {
LOG.error("Exception in Controller.find single",e);
}
return null;
}
/**
* Find the count of object matching the criteria
*
* Sample criteria include:
* Restrictions.eq("property", variable)
* Restrictions.eq("subclass.property", variable)
* Order.desc("property")
*
* See for more examples:
* http://www.hibernate.org/hib_docs/v3/api/org/hibernate/criterion/Restrictions.html
*
**/
public <T extends Object> int count(Class<T> entityClass, Object... criteria) {
try {
Criteria search = getSession().createCriteria(entityClass);
for (Object c : criteria) {
if (c instanceof Criterion || c.getClass() == Criterion.class)
search.add((Criterion)c);
}
search.setProjection(Projections.rowCount());
return ((Integer)search.list().get(0)).intValue();
} catch (Exception e) {
LOG.error("Exception in Controller.count criteria version",e);
}
return 0;
}
public <T extends Object> List<T> listByExample(T exampleInstance, String... excludeProperties) {
try {
Example example = Example.create(exampleInstance);
for (String prop : excludeProperties)
example.excludeProperty(prop);
return (List<T>)getSession().createCriteria(exampleInstance.getClass())
.add(example)
.list();
} catch (Exception e) {
LOG.error("Exception in Controller.findByExample",e);
}
return null;
}
public <T extends Object> List<T> listByExample(Class<T> entityClass, Example example) {
try {
return (List<T>)getSession().createCriteria(entityClass)
.add(example)
.list();
} catch (Exception e) {
LOG.error("Exception in Controller.findByExample",e);
}
return null;
}
public <T extends Object> T queryByFormula(QueryFormula formula) {
return (T)query(em.createQuery(formula.getQuery()), formula.getParametersAsPairArray());
}
public <T extends Object> T query(String queryString, Pair<String,? extends Object>... parameters) {
Query query = em.createQuery(queryString);
return (T)query(query,parameters);
}
public <T extends Object> T query(Query query, Pair<String,? extends Object>... parameters) {
if (parameters != null) {
for (Pair<String,? extends Object> parameter : parameters)
query.setParameter(parameter.getFirst(),parameter.getSecond());
}
try {
return (T)query.getSingleResult();
} catch (NoResultException nre) {
return null;
}
}
public <T extends Object> T query(Class<T> entityClass, String queryString, Pair<String,? extends Object>... parameters) {
try {
return (T)query(em.createQuery(queryString),parameters);
} catch (Exception e) {
LOG.error("Exception in Controller.getSingleResult [query = \"" + queryString + "\"]",e);
}
return null;
}
public <T extends Object> T namedQuery(Class<T> entityClass, String namedQuery, Pair<String,? extends Object>... parameters) {
try {
return (T)query(em.createNamedQuery(entityClass.getSimpleName() + "." + namedQuery),parameters);
} catch (Exception e) {
LOG.error("Exception in Controller.getNamedSingleResult$" + namedQuery,e);
}
return null;
}
public <T extends Object> T namedScaler(Class<T> returnClass, String namedQuery, Pair<String,? extends Object>... parameters) {
try {
return (T)query(em.createNamedQuery(namedQuery),parameters);
} catch (Exception e) {
LOG.error("Exception in Controller.getScalarValue [query = \"" + namedQuery + "\"]",e);
}
return null;
}
public <T extends Object> List<T> list(String queryString, Pair<String,? extends Object>... parameters) {
return (List<T>)list(queryString,0,-1,parameters);
}
public <T extends Object> List<T> list(String queryString, int start, int limit, Pair<String,? extends Object>... parameters) {
Query query = em.createQuery(queryString);
return (List<T>)list(query,start,limit,parameters);
}
public <T extends Object> List<T> list(Query query, Pair<String,? extends Object>... parameters) {
return (List<T>)list(query,0,-1,parameters);
}
public <T extends Object> List<T> list(Query query, int start, int limit, Pair<String,? extends Object>... parameters) {
if (parameters != null) {
for (Pair<String,? extends Object> parameter : parameters)
query.setParameter(parameter.getFirst(),parameter.getSecond());
}
if (start > 0) query.setFirstResult(start);
if (limit > 0) query.setMaxResults(limit);
try {
return (List<T>)query.getResultList();
} catch (NoResultException nre) {
return null;
}
}
public List<Object[]> namedList(String namedQuery, Pair<String, ? extends Object>... parameters) {
return namedList(namedQuery,-1,-1,parameters);
}
public List<Object[]> namedList(String namedQuery, int start, int limit, Pair<String,? extends Object>... parameters) {
Query query = em.createNamedQuery(namedQuery);
if (parameters != null) {
for (Pair<String,? extends Object> parameter : parameters)
query.setParameter(parameter.getFirst(),parameter.getSecond());
}
if (start > 0) query.setFirstResult(start);
if (limit > 0) query.setMaxResults(limit);
try {
return (List<Object[]>)query.getResultList();
} catch (NoResultException nre) {
return null;
}
}
public List<Object[]> namedNativeList(String namedQuery, Pair<String, ? extends Object>... parameters) {
return namedNativeList(namedQuery,-1,-1,parameters);
}
public List<Object[]> namedNativeList(String namedQuery, int start, int limit, Pair<String,? extends Object>... parameters) {
Query query = em.createNativeQuery(namedQuery);
if (parameters != null) {
for (Pair<String,? extends Object> parameter : parameters)
query.setParameter(parameter.getFirst(),parameter.getSecond());
}
if (start > 0) query.setFirstResult(start);
if (limit > 0) query.setMaxResults(limit);
try {
return (List<Object[]>)query.getResultList();
} catch (NoResultException nre) {
return null;
}
}
public <T extends Object> List<T> nativeList(Class<T> entityClass, String queryString, Pair<String,? extends Object>... parameters) {
Session session = getSession();
SQLQuery query = session.createSQLQuery(queryString).addEntity(entityClass);
if (parameters != null) {
for (Pair<String,? extends Object> parameter : parameters)
query.setParameter(parameter.getFirst(),parameter.getSecond());
}
try {
return (List<T>)query.list();
} catch (NoResultException nre) {
return null;
} catch (Exception e) {
LOG.error("Exception in Controller.nativeList [query:" + query + "]",e);
}
return null;
}
public <T extends Object> List<T> nativeScalerList(Class<T> scalarType, String queryString, Pair<String,? extends Object>... parameters) {
Query query = em.createNativeQuery(queryString);
if (parameters != null) {
for (Pair<String,? extends Object> parameter : parameters)
query.setParameter(parameter.getFirst(),parameter.getSecond());
}
try {
return (List<T>)query.getResultList();
} catch (NoResultException nre) {
return null;
} catch (Exception e) {
LOG.error("Exception in Controller.nativeList [query:" + query + "]",e);
}
return null;
}
public List<Object[]> nativeList(String queryString, Pair<String,? extends Object>... parameters) {
Query query = em.createNativeQuery(queryString);
if (parameters != null) {
for (Pair<String,? extends Object> parameter : parameters)
query.setParameter(parameter.getFirst(),parameter.getSecond());
}
try {
return (List<Object[]>)query.getResultList();
} catch (NoResultException nre) {
return null;
} catch (Exception e) {
LOG.error("Exception in Controller.nativeList [query:" + query + "]",e);
}
return null;
}
public Object nativeScalar(String queryString, Pair<String,? extends Object>... parameters) {
Query query = em.createNativeQuery(queryString);
if (parameters != null) {
for (Pair<String,? extends Object> parameter : parameters)
query.setParameter(parameter.getFirst(),parameter.getSecond());
}
try {
return query.getSingleResult();
} catch (NoResultException nre) {
return null;
} catch (Exception e) {
LOG.error("Exception in Controller.nativeScalar [query:" + queryString + "]",e);
}
return null;
}
public int nativeCount(String queryString, Pair<String,? extends Object>... parameters) {
Query query = em.createNativeQuery(queryString);
int count = 0;
Object o = null;
if (parameters != null) {
for (Pair<String,? extends Object> parameter : parameters)
query.setParameter(parameter.getFirst(),parameter.getSecond());
}
try {
o = query.getSingleResult();
count = ((Long)o).intValue();
} catch (NoResultException nre) {
} catch (ClassCastException cce) {
count = ((java.math.BigInteger)o).intValue();
} catch (Exception e) {
LOG.error("Exception in Controller.nativeScalar [query:" + queryString + "]",e);
}
return count;
}
public <T extends Object> List<T> list(Class<T> entityClass, String queryString, Pair<String,? extends Object>... parameters) {
return list(entityClass,queryString,-1,-1,parameters);
}
public <T extends Object> List<T> namedList(Class<T> entityClass, String namedQuery, Pair<String,? extends Object>... parameters) {
return namedList(entityClass,namedQuery,-1,-1,parameters);
}
public <T extends Object> List<T> list(Class<T> entityClass, String queryString, int start, int limit, Pair<String,? extends Object>... parameters) {
try {
return (List<T>)list(em.createQuery(queryString),start,limit,parameters);
} catch (Exception e) {
LOG.error("Exception in Controller.getResultList [query = \"" + queryString + "\"]",e);
}
return null;
}
public <T extends Object> List<T> namedList(Class<T> entityClass, String namedQuery, int start, int limit, Pair<String,? extends Object>... parameters) {
try {
return (List<T>)list(em.createNamedQuery(entityClass.getSimpleName() + "." + namedQuery),start,limit,parameters);
} catch (Exception e) {
LOG.error("Exception in Controller.getNamedResultList$" + namedQuery,e);
}
return null;
}
/**
* @deprecated
* will cause memory problems when mapping large numbers of entities, use the alternate version with batch sizes
**/
public <T extends Object> void hibernateSearchIndex(List<T> objects) {
this.getFullTextEntityManager();
for (T o : objects) {
fullTextEntityManager.index(o);
}
}
/**
* It is critical that batchSize matches the hibernate.search.worker.batch_size you set
**/
public <T extends Object> void hibernateSearchIndex(Class<T> entityClass, int batchSize) {
FullTextSession fullTextSession = org.hibernate.search.Search.getFullTextSession(getSession());
fullTextSession.setFlushMode(FlushMode.MANUAL);
fullTextSession.setCacheMode(CacheMode.IGNORE);
ScrollableResults results = fullTextSession.createCriteria( entityClass )
.setFetchSize(batchSize)
.scroll(ScrollMode.FORWARD_ONLY);
int index = 0;
while (results.next()) {
index++;
fullTextSession.index(results.get(0)); //index each element
//clear every batchSize since the queue is processed
if (index % batchSize == 0) {
fullTextSession.flushToIndexes();
fullTextSession.clear();
}
}
results.close();
}
/**
* It is critical that batchSize matches the hibernate.search.worker.batch_size you set
**/
public <T extends Object> void hibernateSearchClearAndIndex(Class<T> entityClass, int batchSize) {
FullTextSession fullTextSession = org.hibernate.search.Search.getFullTextSession(getSession());
fullTextSession.purgeAll(entityClass);
hibernateSearchIndex(entityClass, batchSize);
fullTextSession.getSearchFactory().optimize(entityClass);
}
public <T extends Object> void hibernateSearchRemove(Class<T> entityClass, int entityId) {
FullTextSession fullTextSession = org.hibernate.search.Search.getFullTextSession(getSession());
fullTextSession.purge(entityClass,entityId);
fullTextSession.flush(); //index are written at commit time
}
public <T extends Object> List<T> hibernateSearchResults(Class<T> entityClass, String query, String[] fields) {
return hibernateSearchResults(entityClass,query,-1,-1,fields);
}
public <T extends Object> List<T> hibernateSearchResults(Class<T> entityClass, String query, int limit, String[] fields) {
return hibernateSearchResults(entityClass,query,-1,limit,fields);
}
public <T extends Object> List<T> hibernateSearchResults(Class<T> entityClass, String query, int start, int limit, String[] fields) throws NullPointerException {
try {
MultiFieldQueryParser parser = new MultiFieldQueryParser( fields, new StandardAnalyzer());
//org.apache.lucene.search.Query luceneQuery = parser.parse(query.trim().replaceAll(" ","~ ").replaceAll(" [Aa][Nn][Dd]~ "," AND ").replaceAll(" [Oo][Rr]~ "," OR ") + "~");
//org.apache.lucene.search.Query luceneQuery = parser.parse(query.trim());
org.apache.lucene.search.Query luceneQuery;
query = filterLuceneQuery(query);
luceneQuery = parser.parse(query);
org.hibernate.search.jpa.FullTextQuery hibQuery = getFullTextEntityManager().createFullTextQuery( luceneQuery, entityClass );
if (start >= 0 && limit > 0) {
return hibQuery.setFirstResult(start).setMaxResults(limit).getResultList();
} else if (limit > 0) {
return hibQuery.setMaxResults(limit).getResultList();
} else if (start >= 0) {
return hibQuery.setFirstResult(start).getResultList();
} else {
return hibQuery.getResultList();
}
} catch (Exception ex) {
LOG.error("Error searching [entityClass=" + entityClass.getSimpleName() + ", query=" + query + "]",ex);
}
return null;
}
public <T extends Object> int hibernateSearchCount(Class<T> entityClass, String query, String[] fields) throws NullPointerException {
try {
MultiFieldQueryParser parser = new MultiFieldQueryParser( fields, new StandardAnalyzer());
//org.apache.lucene.search.Query luceneQuery = parser.parse(query.trim().replaceAll(" ","~ ").replaceAll(" [Aa][Nn][Dd]~ "," AND ").replaceAll(" [Oo][Rr]~ "," OR ") + "~");
//org.apache.lucene.search.Query luceneQuery = parser.parse(query.trim());
org.apache.lucene.search.Query luceneQuery;
query = filterLuceneQuery(query);
luceneQuery = parser.parse(query);
org.hibernate.search.jpa.FullTextQuery hibQuery = getFullTextEntityManager().createFullTextQuery( luceneQuery, entityClass );
return hibQuery.getResultSize();
} catch (Exception ex) {
LOG.error("Error counting [entityClass=" + entityClass.getSimpleName() + ", query=" + query + "]",ex);
}
return -1;
}
private String filterLuceneQuery(String queryOrig) {
String query = queryOrig;
query = query.trim()
.replaceAll("\\s+","* ")
.replaceAll(" [Aa][Nn][Dd]\\* "," AND ")
.replaceAll(" [Oo][Rr]\\* "," OR ")
.replaceAll("[-]\\* ","- ")
.replaceAll("[)]\\* ",") ")
.replaceAll("[(]\\* ","( ")
.replaceAll("[!]\\* ","! ")
.replaceAll("[?]\\* ","? ")
.replaceAll("[:]\\* ",": ")
.replaceAll("[+]\\* ","+ ");
query = query.replaceAll("[-]","\\\\-")
.replaceAll("[)]","\\\\)")
.replaceAll("[(]","\\\\(")
.replaceAll("[!]","\\\\!")
.replaceAll("[?]","\\\\?")
.replaceAll("[:]","\\\\:")
.replaceAll("[+]","\\\\+");
- if (query.matches("[\\w\\d]$")) {
+ if (query.matches(".*?[\\w\\d]$")) {
query += "*";
}
return query;
}
public <T extends Object> Criteria createCriteria(Class<T> entityClass) {
return getSession().createCriteria(entityClass);
}
public int update(String queryString, Pair<String,Object>... parameters) {
Query query = em.createQuery(queryString);
return update(query,parameters);
}
public int nativeUpdate(String queryString, Pair<String,Object>... parameters) {
Query query = em.createNativeQuery(queryString);
return update(query,parameters);
}
public int update(Query query, Pair<String,Object>... parameters) {
try {
if (parameters != null) {
for (Pair<String,Object> parameter : parameters)
query.setParameter(parameter.getFirst(),parameter.getSecond());
}
return query.executeUpdate();
} catch (Exception e) {
markForRollback(true);
LOG.error("Exception in Controller.update [query = \"" + query.toString() + "\"]",e);
}
return -1;
}
public <T extends Object> T filterSingle(Collection collection, String filterString) {
List<T> list = filter(collection,filterString,0,1);
return list.size() > 0 ? list.get(0) : null;
}
public <T extends Object> T filterSingle(Collection collection, String filterString, Pair<String,Object>... params) {
List<T> list = filter(collection,filterString,0,1,params);
return list.size() > 0 ? list.get(0) : null;
}
public <T extends Object> List<T> filter(Collection collection, String filterString) {
return filter(collection,filterString,0,-1);
}
public <T extends Object> List<T> filter(Collection collection, String filterString, int start, int limit) {
org.hibernate.Query query = getSession().createFilter(collection,filterString)
.setFirstResult(start);
if (limit > 0)
query.setMaxResults(limit);
return (List<T>)query.list();
}
public <T extends Object> List<T> filter(Collection collection, String filterString, Pair<String,Object>... params) {
return filter(collection,filterString,0,-1,params);
}
public <T extends Object> List<T> filter(Collection collection, String filterString, int start, int limit, Pair<String,Object>... params) {
org.hibernate.Query query = getSession().createFilter(collection,filterString)
.setFirstResult(start);
if (limit > 0)
query.setMaxResults(limit);
for (Pair<String,Object> param : params)
query.setParameter(param.getFirst(),param.getSecond());
return (List<T>)query.list();
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/src/main/java/org/apache/maven/plugin/nar/Compiler.java b/src/main/java/org/apache/maven/plugin/nar/Compiler.java
index 9d4cb090..03518088 100644
--- a/src/main/java/org/apache/maven/plugin/nar/Compiler.java
+++ b/src/main/java/org/apache/maven/plugin/nar/Compiler.java
@@ -1,613 +1,608 @@
package org.apache.maven.plugin.nar;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import net.sf.antcontrib.cpptasks.CUtil;
import net.sf.antcontrib.cpptasks.CompilerDef;
import net.sf.antcontrib.cpptasks.CompilerEnum;
import net.sf.antcontrib.cpptasks.OptimizationEnum;
import net.sf.antcontrib.cpptasks.types.CompilerArgument;
import net.sf.antcontrib.cpptasks.types.ConditionalFileSet;
import net.sf.antcontrib.cpptasks.types.DefineArgument;
import net.sf.antcontrib.cpptasks.types.DefineSet;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.StringUtils;
/**
* Abstract Compiler class
*
* @author Mark Donszelmann
*/
public abstract class Compiler
{
/**
* The name of the compiler Some choices are: "msvc", "g++", "gcc", "CC", "cc", "icc", "icpc", ... Default is
* Architecture-OS-Linker specific: FIXME: table missing
*
* @parameter expression=""
*/
private String name;
/**
* Source directory for native files
*
* @parameter expression="${basedir}/src/main"
* @required
*/
private File sourceDirectory;
/**
* Source directory for native test files
*
* @parameter expression="${basedir}/src/test"
* @required
*/
private File testSourceDirectory;
/**
* Include patterns for sources
*
* @parameter expression=""
* @required
*/
private Set includes = new HashSet();
/**
* Exclude patterns for sources
*
* @parameter expression=""
* @required
*/
private Set excludes = new HashSet();
/**
* Compile with debug information.
*
* @parameter expression="" default-value="false"
* @required
*/
private boolean debug = false;
/**
* Enables generation of exception handling code.
*
* @parameter expression="" default-value="true"
* @required
*/
private boolean exceptions = true;
/**
* Enables run-time type information.
*
* @parameter expression="" default-value="true"
* @required
*/
private boolean rtti = true;
/**
* Sets optimization. Possible choices are: "none", "size", "minimal", "speed", "full", "aggressive", "extreme",
* "unsafe".
*
* @parameter expression="" default-value="none"
* @required
*/
private String optimize = "none";
/**
* Enables or disables generation of multi-threaded code. Default value: false, except on Windows.
*
* @parameter expression="" default-value="false"
* @required
*/
private boolean multiThreaded = false;
/**
* Defines
*
* @parameter expression=""
*/
private List defines;
/**
* Defines for the compiler as a comma separated list of name[=value] pairs, where the value is optional. Will work
* in combination with <defines>.
*
* @parameter expression=""
*/
private String defineSet;
/**
* Clears default defines
*
* @parameter expression="" default-value="false"
* @required
*/
private boolean clearDefaultDefines;
/**
* Undefines
*
* @parameter expression=""
*/
private List undefines;
/**
* Undefines for the compiler as a comma separated list of name[=value] pairs where the value is optional. Will work
* in combination with <undefines>.
*
* @parameter expression=""
*/
private String undefineSet;
/**
* Clears default undefines
*
* @parameter expression="" default-value="false"
* @required
*/
private boolean clearDefaultUndefines;
/**
* Include Paths. Defaults to "${sourceDirectory}/include"
*
* @parameter expression=""
*/
private List includePaths;
/**
* Test Include Paths. Defaults to "${testSourceDirectory}/include"
*
* @parameter expression=""
*/
private List testIncludePaths;
/**
* System Include Paths, which are added at the end of all include paths
*
* @parameter expression=""
*/
private List systemIncludePaths;
/**
* Additional options for the C++ compiler Defaults to Architecture-OS-Linker specific values. FIXME table missing
*
* @parameter expression=""
*/
private List options;
/**
* Options for the compiler as a whitespace separated list. Will work in combination with <options>.
*
* @parameter expression=""
*/
private String optionSet;
/**
* Clears default options
*
* @parameter expression="" default-value="false"
* @required
*/
private boolean clearDefaultOptions;
private AbstractCompileMojo mojo;
protected Compiler()
{
}
public void setAbstractCompileMojo( AbstractCompileMojo mojo )
{
this.mojo = mojo;
}
public List/* <File> */getSourceDirectories()
{
return getSourceDirectories( "dummy" );
}
private List/* <File> */getSourceDirectories( String type )
{
List sourceDirectories = new ArrayList();
File baseDir = mojo.getMavenProject().getBasedir();
if ( type.equals( "test" ) )
{
if ( testSourceDirectory == null )
testSourceDirectory = new File( baseDir, "/src/test" );
if ( testSourceDirectory.exists() )
sourceDirectories.add( testSourceDirectory );
for ( Iterator i = mojo.getMavenProject().getTestCompileSourceRoots().iterator(); i.hasNext(); )
{
File extraTestSourceDirectory = new File( (String) i.next() );
if ( extraTestSourceDirectory.exists() )
sourceDirectories.add( extraTestSourceDirectory );
}
}
else
{
if ( sourceDirectory == null )
sourceDirectory = new File( baseDir, "src/main" );
if ( sourceDirectory.exists() )
sourceDirectories.add( sourceDirectory );
for ( Iterator i = mojo.getMavenProject().getCompileSourceRoots().iterator(); i.hasNext(); )
{
File extraSourceDirectory = new File( (String) i.next() );
if ( extraSourceDirectory.exists() )
sourceDirectories.add( extraSourceDirectory );
}
}
- // FIXME, see NAR-69
- File swigDir = new File( baseDir, "target/swig" );
- if ( swigDir.exists() )
- sourceDirectories.add( swigDir );
-
if (mojo.getLog().isDebugEnabled()) {
for ( Iterator i = sourceDirectories.iterator(); i.hasNext(); )
mojo.getLog().debug( "Added to sourceDirectory: " + ((File)i.next()).getPath() );
}
return sourceDirectories;
}
protected List/* <String> */getIncludePaths( String type )
{
return createIncludePaths( type, type.equals( "test" ) ? testIncludePaths : includePaths );
}
private List/* <String> */createIncludePaths( String type, List paths )
{
if ( paths == null || ( paths.size() == 0 ) )
{
paths = new ArrayList();
for ( Iterator i = getSourceDirectories( type ).iterator(); i.hasNext(); )
{
paths.add( new File( (File) i.next(), "include" ).getPath() );
}
}
return paths;
}
public Set getIncludes()
throws MojoFailureException
{
return getIncludes( "main" );
}
protected Set getIncludes( String type )
throws MojoFailureException
{
Set result = new HashSet();
if ( !type.equals( "test" ) && !includes.isEmpty() )
{
result.addAll( includes );
}
else
{
String defaultIncludes = NarUtil.getDefaults().getProperty( getPrefix() + "includes" );
if ( defaultIncludes == null )
{
throw new MojoFailureException(
"NAR: Please specify <Includes> as part of <Cpp>, <C> or <Fortran> for "
+ getPrefix() );
}
String[] include = defaultIncludes.split( " " );
for ( int i = 0; i < include.length; i++ )
{
result.add( include[i].trim() );
}
}
return result;
}
protected Set getExcludes()
throws MojoFailureException
{
Set result = new HashSet();
// add all excludes
if ( excludes.isEmpty() )
{
String defaultExcludes = NarUtil.getDefaults().getProperty( getPrefix() + "excludes" );
if ( defaultExcludes != null )
{
String[] exclude = defaultExcludes.split( " " );
for ( int i = 0; i < exclude.length; i++ )
{
result.add( exclude[i].trim() );
}
}
}
else
{
result.addAll( excludes );
}
return result;
}
protected String getPrefix()
throws MojoFailureException
{
return mojo.getAOL().getKey() + "." + getName() + ".";
}
public CompilerDef getCompiler( String type, String output )
throws MojoFailureException
{
// adjust default values
if ( name == null )
name = NarUtil.getDefaults().getProperty( getPrefix() + "compiler" );
if ( name == null )
{
throw new MojoFailureException( "NAR: Please specify <Name> as part of <Cpp>, <C> or <Fortran> for "
+ getPrefix() );
}
CompilerDef compiler = new CompilerDef();
compiler.setProject( mojo.getAntProject() );
CompilerEnum compilerName = new CompilerEnum();
compilerName.setValue( name );
compiler.setName( compilerName );
// debug, exceptions, rtti, multiThreaded
compiler.setDebug( debug );
compiler.setExceptions( exceptions );
compiler.setRtti( rtti );
compiler.setMultithreaded( mojo.getOS().equals( "Windows" ) ? true : multiThreaded );
// optimize
OptimizationEnum optimization = new OptimizationEnum();
optimization.setValue( optimize );
compiler.setOptimize( optimization );
// add options
if ( options != null )
{
for ( Iterator i = options.iterator(); i.hasNext(); )
{
CompilerArgument arg = new CompilerArgument();
arg.setValue( (String) i.next() );
compiler.addConfiguredCompilerArg( arg );
}
}
if ( optionSet != null )
{
String[] opts = optionSet.split( "\\s" );
for ( int i = 0; i < opts.length; i++ )
{
CompilerArgument arg = new CompilerArgument();
arg.setValue( opts[i] );
compiler.addConfiguredCompilerArg( arg );
}
}
if ( !clearDefaultOptions )
{
String optionsProperty = NarUtil.getDefaults().getProperty( getPrefix() + "options" );
if ( optionsProperty != null )
{
String[] option = optionsProperty.split( " " );
for ( int i = 0; i < option.length; i++ )
{
CompilerArgument arg = new CompilerArgument();
arg.setValue( option[i] );
compiler.addConfiguredCompilerArg( arg );
}
}
}
// add defines
if ( defines != null )
{
DefineSet defineSet = new DefineSet();
for ( Iterator i = defines.iterator(); i.hasNext(); )
{
DefineArgument define = new DefineArgument();
String[] pair = ( (String) i.next() ).split( "=", 2 );
define.setName( pair[0] );
define.setValue( pair.length > 1 ? pair[1] : null );
defineSet.addDefine( define );
}
compiler.addConfiguredDefineset( defineSet );
}
if ( defineSet != null )
{
String[] defList = defineSet.split( "," );
DefineSet defSet = new DefineSet();
for ( int i = 0; i < defList.length; i++ )
{
String[] pair = defList[i].trim().split( "=", 2 );
DefineArgument def = new DefineArgument();
def.setName( pair[0] );
def.setValue( pair.length > 1 ? pair[1] : null );
defSet.addDefine( def );
}
compiler.addConfiguredDefineset( defSet );
}
if ( !clearDefaultDefines )
{
DefineSet defineSet = new DefineSet();
String defaultDefines = NarUtil.getDefaults().getProperty( getPrefix() + "defines" );
if ( defaultDefines != null )
{
defineSet.setDefine( new CUtil.StringArrayBuilder( defaultDefines ) );
}
compiler.addConfiguredDefineset( defineSet );
}
// add undefines
if ( undefines != null )
{
DefineSet undefineSet = new DefineSet();
for ( Iterator i = undefines.iterator(); i.hasNext(); )
{
DefineArgument undefine = new DefineArgument();
String[] pair = ( (String) i.next() ).split( "=", 2 );
undefine.setName( pair[0] );
undefine.setValue( pair.length > 1 ? pair[1] : null );
undefineSet.addUndefine( undefine );
}
compiler.addConfiguredDefineset( undefineSet );
}
if ( undefineSet != null )
{
String[] undefList = undefineSet.split( "," );
DefineSet undefSet = new DefineSet();
for ( int i = 0; i < undefList.length; i++ )
{
String[] pair = undefList[i].trim().split( "=", 2 );
DefineArgument undef = new DefineArgument();
undef.setName( pair[0] );
undef.setValue( pair.length > 1 ? pair[1] : null );
undefSet.addUndefine( undef );
}
compiler.addConfiguredDefineset( undefSet );
}
if ( !clearDefaultUndefines )
{
DefineSet undefineSet = new DefineSet();
String defaultUndefines = NarUtil.getDefaults().getProperty( getPrefix() + "undefines" );
if ( defaultUndefines != null )
{
undefineSet.setUndefine( new CUtil.StringArrayBuilder( defaultUndefines ) );
}
compiler.addConfiguredDefineset( undefineSet );
}
// add include path
for ( Iterator i = getIncludePaths( type ).iterator(); i.hasNext(); )
{
String path = (String) i.next();
compiler.createIncludePath().setPath( path );
}
// add system include path (at the end)
if ( systemIncludePaths != null )
{
for ( Iterator i = systemIncludePaths.iterator(); i.hasNext(); )
{
String path = (String) i.next();
compiler.createSysIncludePath().setPath( path );
}
}
// Add default fileset (if exists)
List srcDirs = getSourceDirectories( type );
Set includes = getIncludes();
Set excludes = getExcludes();
// now add all but the current test to the excludes
for ( Iterator i = mojo.getTests().iterator(); i.hasNext(); )
{
Test test = (Test) i.next();
if ( !test.getName().equals( output ) )
{
excludes.add( "**/" + test.getName() + ".*" );
}
}
for ( Iterator i = srcDirs.iterator(); i.hasNext(); )
{
File srcDir = (File) i.next();
mojo.getLog().debug( "Checking for existence of " + getName() + " source directory: " + srcDir );
if ( srcDir.exists() )
{
ConditionalFileSet fileSet = new ConditionalFileSet();
fileSet.setProject( mojo.getAntProject() );
fileSet.setIncludes( StringUtils.join( includes.iterator(), "," ) );
fileSet.setExcludes( StringUtils.join( excludes.iterator(), "," ) );
fileSet.setDir( srcDir );
compiler.addFileset( fileSet );
}
}
// add other sources, FIXME seems
if ( !type.equals( "test" ) )
{
for ( Iterator i = mojo.getMavenProject().getCompileSourceRoots().iterator(); i.hasNext(); )
{
File dir = new File( (String) i.next() );
mojo.getLog().debug( "Checking for existence of " + getName() + " sourceCompileRoot: " + dir );
if ( dir.exists() )
{
ConditionalFileSet otherFileSet = new ConditionalFileSet();
otherFileSet.setProject( mojo.getAntProject() );
otherFileSet.setIncludes( StringUtils.join( includes.iterator(), "," ) );
otherFileSet.setExcludes( StringUtils.join( excludes.iterator(), "," ) );
otherFileSet.setDir( dir );
compiler.addFileset( otherFileSet );
}
}
}
return compiler;
}
protected abstract String getName();
public void copyIncludeFiles( MavenProject mavenProject, File targetDirectory )
throws IOException
{
for ( Iterator i = getIncludePaths( "dummy" ).iterator(); i.hasNext(); )
{
File path = new File( (String) i.next() );
if ( path.exists() )
{
NarUtil.copyDirectoryStructure( path, targetDirectory, null, NarUtil.DEFAULT_EXCLUDES );
}
}
}
}
| true | false | null | null |
diff --git a/src/com/android/mms/ui/RecipientsAdapter.java b/src/com/android/mms/ui/RecipientsAdapter.java
index ca5efa5..deaa8a3 100644
--- a/src/com/android/mms/ui/RecipientsAdapter.java
+++ b/src/com/android/mms/ui/RecipientsAdapter.java
@@ -1,235 +1,245 @@
/*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.ui;
import com.android.common.ArrayListCursor;
import com.android.mms.R;
import com.android.mms.data.Contact;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.database.MergeCursor;
import android.net.Uri;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.telephony.PhoneNumberUtils;
import android.text.Annotation;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.View;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* This adapter is used to filter contacts on both name and number.
*/
public class RecipientsAdapter extends ResourceCursorAdapter {
public static final int CONTACT_ID_INDEX = 1;
public static final int TYPE_INDEX = 2;
public static final int NUMBER_INDEX = 3;
public static final int LABEL_INDEX = 4;
public static final int NAME_INDEX = 5;
private static final String[] PROJECTION_PHONE = {
Phone._ID, // 0
Phone.CONTACT_ID, // 1
Phone.TYPE, // 2
Phone.NUMBER, // 3
Phone.LABEL, // 4
Phone.DISPLAY_NAME, // 5
};
private static final String SORT_ORDER = Contacts.TIMES_CONTACTED + " DESC,"
+ Contacts.DISPLAY_NAME + "," + Phone.TYPE;
private final Context mContext;
private final ContentResolver mContentResolver;
public RecipientsAdapter(Context context) {
// Note that the RecipientsAdapter doesn't support auto-requeries. If we
// want to respond to changes in the contacts we're displaying in the drop-down,
// code using this adapter would have to add a line such as:
// mRecipientsAdapter.setOnDataSetChangedListener(mDataSetChangedListener);
// See ComposeMessageActivity for an example.
super(context, R.layout.recipient_filter_item, null, false /* no auto-requery */);
mContext = context;
mContentResolver = context.getContentResolver();
}
@Override
public final CharSequence convertToString(Cursor cursor) {
String number = cursor.getString(RecipientsAdapter.NUMBER_INDEX);
if (number == null) {
return "";
}
number = number.trim();
String name = cursor.getString(RecipientsAdapter.NAME_INDEX);
int type = cursor.getInt(RecipientsAdapter.TYPE_INDEX);
String label = cursor.getString(RecipientsAdapter.LABEL_INDEX);
CharSequence displayLabel = Phone.getDisplayLabel(mContext, type, label);
if (name == null) {
name = "";
} else {
// Names with commas are the bane of the recipient editor's existence.
// We've worked around them by using spans, but there are edge cases
// where the spans get deleted. Furthermore, having commas in names
// can be confusing to the user since commas are used as separators
// between recipients. The best solution is to simply remove commas
// from names.
name = name.replace(", ", " ")
.replace(",", " "); // Make sure we leave a space between parts of names.
}
String nameAndNumber = Contact.formatNameAndNumber(name, number);
SpannableString out = new SpannableString(nameAndNumber);
int len = out.length();
if (!TextUtils.isEmpty(name)) {
out.setSpan(new Annotation("name", name), 0, len,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} else {
out.setSpan(new Annotation("name", number), 0, len,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
String person_id = cursor.getString(RecipientsAdapter.CONTACT_ID_INDEX);
out.setSpan(new Annotation("person_id", person_id), 0, len,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
out.setSpan(new Annotation("label", displayLabel.toString()), 0, len,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
out.setSpan(new Annotation("number", number), 0, len,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return out;
}
@Override
public final void bindView(View view, Context context, Cursor cursor) {
TextView name = (TextView) view.findViewById(R.id.name);
name.setText(cursor.getString(NAME_INDEX));
TextView label = (TextView) view.findViewById(R.id.label);
int type = cursor.getInt(TYPE_INDEX);
- label.setText(Phone.getDisplayLabel(mContext, type, cursor.getString(LABEL_INDEX)));
+ CharSequence labelText = Phone.getDisplayLabel(mContext, type,
+ cursor.getString(LABEL_INDEX));
+ // When there's no label, getDisplayLabel() returns a CharSequence of length==1 containing
+ // a unicode non-breaking space. Need to check for that and consider that as "no label".
+ if (labelText.length() == 0 ||
+ (labelText.length() == 1 && labelText.charAt(0) == '\u00A0')) {
+ label.setVisibility(View.GONE);
+ } else {
+ label.setText(labelText);
+ label.setVisibility(View.VISIBLE);
+ }
TextView number = (TextView) view.findViewById(R.id.number);
- number.setText("(" + cursor.getString(NUMBER_INDEX) + ")");
+ number.setText(cursor.getString(NUMBER_INDEX));
}
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
String phone = "";
String cons = null;
if (constraint != null) {
cons = constraint.toString();
if (usefulAsDigits(cons)) {
phone = PhoneNumberUtils.convertKeypadLettersToDigits(cons);
if (phone.equals(cons)) {
phone = "";
} else {
phone = phone.trim();
}
}
}
Uri uri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(cons));
/*
* if we decide to filter based on phone types use a selection
* like this.
String selection = String.format("%s=%s OR %s=%s OR %s=%s",
Phone.TYPE,
Phone.TYPE_MOBILE,
Phone.TYPE,
Phone.TYPE_WORK_MOBILE,
Phone.TYPE,
Phone.TYPE_MMS);
*/
Cursor phoneCursor =
mContentResolver.query(uri,
PROJECTION_PHONE,
null, //selection,
null,
SORT_ORDER);
if (phone.length() > 0) {
ArrayList result = new ArrayList();
result.add(Integer.valueOf(-1)); // ID
result.add(Long.valueOf(-1)); // CONTACT_ID
result.add(Integer.valueOf(Phone.TYPE_CUSTOM)); // TYPE
result.add(phone); // NUMBER
/*
* The "\u00A0" keeps Phone.getDisplayLabel() from deciding
* to display the default label ("Home") next to the transformation
* of the letters into numbers.
*/
result.add("\u00A0"); // LABEL
result.add(cons); // NAME
ArrayList<ArrayList> wrap = new ArrayList<ArrayList>();
wrap.add(result);
ArrayListCursor translated = new ArrayListCursor(PROJECTION_PHONE, wrap);
return new MergeCursor(new Cursor[] { translated, phoneCursor });
} else {
return phoneCursor;
}
}
/**
* Returns true if all the characters are meaningful as digits
* in a phone number -- letters, digits, and a few punctuation marks.
*/
private boolean usefulAsDigits(CharSequence cons) {
int len = cons.length();
for (int i = 0; i < len; i++) {
char c = cons.charAt(i);
if ((c >= '0') && (c <= '9')) {
continue;
}
if ((c == ' ') || (c == '-') || (c == '(') || (c == ')') || (c == '.') || (c == '+')
|| (c == '#') || (c == '*')) {
continue;
}
if ((c >= 'A') && (c <= 'Z')) {
continue;
}
if ((c >= 'a') && (c <= 'z')) {
continue;
}
return false;
}
return true;
}
}
| false | false | null | null |
diff --git a/lucene/spatial/src/test/org/apache/lucene/spatial/prefix/TestRecursivePrefixTreeStrategy.java b/lucene/spatial/src/test/org/apache/lucene/spatial/prefix/TestRecursivePrefixTreeStrategy.java
index d5c575f28..995fb96a8 100644
--- a/lucene/spatial/src/test/org/apache/lucene/spatial/prefix/TestRecursivePrefixTreeStrategy.java
+++ b/lucene/spatial/src/test/org/apache/lucene/spatial/prefix/TestRecursivePrefixTreeStrategy.java
@@ -1,216 +1,216 @@
package org.apache.lucene.spatial.prefix;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.distance.DistanceUtils;
import com.spatial4j.core.io.GeohashUtils;
import com.spatial4j.core.shape.Point;
import com.spatial4j.core.shape.Rectangle;
import com.spatial4j.core.shape.Shape;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.spatial.SpatialMatchConcern;
import org.apache.lucene.spatial.StrategyTestCase;
import org.apache.lucene.spatial.prefix.tree.GeohashPrefixTree;
import org.apache.lucene.spatial.query.SpatialArgs;
import org.apache.lucene.spatial.query.SpatialOperation;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TestRecursivePrefixTreeStrategy extends StrategyTestCase {
private int maxLength;
//Tests should call this first.
private void init(int maxLength) {
this.maxLength = maxLength;
this.ctx = SpatialContext.GEO;
GeohashPrefixTree grid = new GeohashPrefixTree(ctx, maxLength);
this.strategy = new RecursivePrefixTreeStrategy(grid, getClass().getSimpleName());
}
@Test
public void testFilterWithVariableScanLevel() throws IOException {
init(GeohashPrefixTree.getMaxLevelsPossible());
getAddAndVerifyIndexedDocuments(DATA_WORLD_CITIES_POINTS);
//execute queries for each prefix grid scan level
for(int i = 0; i <= maxLength; i++) {
((RecursivePrefixTreeStrategy)strategy).setPrefixGridScanLevel(i);
executeQueries(SpatialMatchConcern.FILTER, QTEST_Cities_IsWithin_BBox);
}
}
@Test
public void testOneMeterPrecision() {
init(GeohashPrefixTree.getMaxLevelsPossible());
GeohashPrefixTree grid = (GeohashPrefixTree) ((RecursivePrefixTreeStrategy) strategy).getGrid();
//DWS: I know this to be true. 11 is needed for one meter
double degrees = DistanceUtils.dist2Degrees(0.001, DistanceUtils.EARTH_MEAN_RADIUS_KM);
assertEquals(11, grid.getLevelForDistance(degrees));
}
@Test
public void testPrecision() throws IOException{
init(GeohashPrefixTree.getMaxLevelsPossible());
Point iPt = ctx.makePoint(2.8028712999999925, 48.3708044);//lon, lat
addDocument(newDoc("iPt", iPt));
commit();
Point qPt = ctx.makePoint(2.4632387000000335, 48.6003516);
final double KM2DEG = DistanceUtils.dist2Degrees(1, DistanceUtils.EARTH_MEAN_RADIUS_KM);
final double DEG2KM = 1 / KM2DEG;
final double DIST = 35.75;//35.7499...
assertEquals(DIST, ctx.getDistCalc().distance(iPt, qPt) * DEG2KM, 0.001);
//distErrPct will affect the query shape precision. The indexed precision
// was set to nearly zilch via init(GeohashPrefixTree.getMaxLevelsPossible());
final double distErrPct = 0.025; //the suggested default, by the way
final double distMult = 1+distErrPct;
assertTrue(35.74*distMult >= DIST);
checkHits(q(qPt, 35.74 * KM2DEG, distErrPct), 1, null);
assertTrue(30*distMult < DIST);
checkHits(q(qPt, 30 * KM2DEG, distErrPct), 0, null);
assertTrue(33*distMult < DIST);
checkHits(q(qPt, 33 * KM2DEG, distErrPct), 0, null);
assertTrue(34*distMult < DIST);
checkHits(q(qPt, 34 * KM2DEG, distErrPct), 0, null);
}
@Test
public void geohashRecursiveRandom() throws IOException {
init(12);
//1. Iterate test with the cluster at some worldly point of interest
Point[] clusterCenters = new Point[]{ctx.makePoint(-180,0), ctx.makePoint(0,90), ctx.makePoint(0,-90)};
for (Point clusterCenter : clusterCenters) {
//2. Iterate on size of cluster (a really small one and a large one)
String hashCenter = GeohashUtils.encodeLatLon(clusterCenter.getY(), clusterCenter.getX(), maxLength);
//calculate the number of degrees in the smallest grid box size (use for both lat & lon)
String smallBox = hashCenter.substring(0,hashCenter.length()-1);//chop off leaf precision
Rectangle clusterDims = GeohashUtils.decodeBoundary(smallBox,ctx);
double smallRadius = Math.max(clusterDims.getMaxX()-clusterDims.getMinX(),clusterDims.getMaxY()-clusterDims.getMinY());
assert smallRadius < 1;
double largeRadius = 20d;//good large size; don't use >=45 for this test code to work
double[] radiusDegs = {largeRadius,smallRadius};
for (double radiusDeg : radiusDegs) {
//3. Index random points in this cluster circle
deleteAll();
List<Point> points = new ArrayList<Point>();
for(int i = 0; i < 20; i++) {
//Note that this will not result in randomly distributed points in the
// circle, they will be concentrated towards the center a little. But
// it's good enough.
Point pt = ctx.getDistCalc().pointOnBearing(clusterCenter,
random().nextDouble() * radiusDeg, random().nextInt() * 360, ctx, null);
pt = alignGeohash(pt);
points.add(pt);
addDocument(newDoc("" + i, pt));
}
commit();
//3. Use some query centers. Each is twice the cluster's radius away.
for(int ri = 0; ri < 4; ri++) {
Point queryCenter = ctx.getDistCalc().pointOnBearing(clusterCenter,
radiusDeg*2, random().nextInt(360), ctx, null);
queryCenter = alignGeohash(queryCenter);
//4.1 Query a small box getting nothing
checkHits(q(queryCenter, radiusDeg - smallRadius/2), 0, null);
//4.2 Query a large box enclosing the cluster, getting everything
- checkHits(q(queryCenter, radiusDeg*3*1.01), points.size(), null);
+ checkHits(q(queryCenter, radiusDeg*3 + smallRadius/2), points.size(), null);
//4.3 Query a medium box getting some (calculate the correct solution and verify)
double queryDist = radiusDeg * 2;
//Find matching points. Put into int[] of doc ids which is the same thing as the index into points list.
int[] ids = new int[points.size()];
int ids_sz = 0;
for (int i = 0; i < points.size(); i++) {
Point point = points.get(i);
if (ctx.getDistCalc().distance(queryCenter, point) <= queryDist)
ids[ids_sz++] = i;
}
ids = Arrays.copyOf(ids, ids_sz);
//assert ids_sz > 0 (can't because randomness keeps us from being able to)
checkHits(q(queryCenter, queryDist), ids.length, ids);
}
}//for radiusDeg
}//for clusterCenter
}//randomTest()
/** Query point-distance (in degrees) with zero error percent. */
private SpatialArgs q(Point pt, double distDEG) {
return q(pt, distDEG, 0.0);
}
private SpatialArgs q(Point pt, double distDEG, double distErrPct) {
Shape shape = ctx.makeCircle(pt, distDEG);
SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects,shape);
args.setDistErrPct(distErrPct);
return args;
}
private void checkHits(SpatialArgs args, int assertNumFound, int[] assertIds) {
SearchResults got = executeQuery(strategy.makeQuery(args), 100);
assertEquals("" + args, assertNumFound, got.numFound);
if (assertIds != null) {
Set<Integer> gotIds = new HashSet<Integer>();
for (SearchResult result : got.results) {
gotIds.add(Integer.valueOf(result.document.get("id")));
}
for (int assertId : assertIds) {
assertTrue("has "+assertId,gotIds.contains(assertId));
}
}
}
private Document newDoc(String id, Shape shape) {
Document doc = new Document();
doc.add(new StringField("id", id, Field.Store.YES));
for (Field f : strategy.createIndexableFields(shape)) {
doc.add(f);
}
if (storeShape)
doc.add(new StoredField(strategy.getFieldName(), ctx.toString(shape)));
return doc;
}
/** NGeohash round-trip for given precision. */
private Point alignGeohash(Point p) {
return GeohashUtils.decode(GeohashUtils.encodeLatLon(p.getY(), p.getX(), maxLength), ctx);
}
}
| true | true | public void geohashRecursiveRandom() throws IOException {
init(12);
//1. Iterate test with the cluster at some worldly point of interest
Point[] clusterCenters = new Point[]{ctx.makePoint(-180,0), ctx.makePoint(0,90), ctx.makePoint(0,-90)};
for (Point clusterCenter : clusterCenters) {
//2. Iterate on size of cluster (a really small one and a large one)
String hashCenter = GeohashUtils.encodeLatLon(clusterCenter.getY(), clusterCenter.getX(), maxLength);
//calculate the number of degrees in the smallest grid box size (use for both lat & lon)
String smallBox = hashCenter.substring(0,hashCenter.length()-1);//chop off leaf precision
Rectangle clusterDims = GeohashUtils.decodeBoundary(smallBox,ctx);
double smallRadius = Math.max(clusterDims.getMaxX()-clusterDims.getMinX(),clusterDims.getMaxY()-clusterDims.getMinY());
assert smallRadius < 1;
double largeRadius = 20d;//good large size; don't use >=45 for this test code to work
double[] radiusDegs = {largeRadius,smallRadius};
for (double radiusDeg : radiusDegs) {
//3. Index random points in this cluster circle
deleteAll();
List<Point> points = new ArrayList<Point>();
for(int i = 0; i < 20; i++) {
//Note that this will not result in randomly distributed points in the
// circle, they will be concentrated towards the center a little. But
// it's good enough.
Point pt = ctx.getDistCalc().pointOnBearing(clusterCenter,
random().nextDouble() * radiusDeg, random().nextInt() * 360, ctx, null);
pt = alignGeohash(pt);
points.add(pt);
addDocument(newDoc("" + i, pt));
}
commit();
//3. Use some query centers. Each is twice the cluster's radius away.
for(int ri = 0; ri < 4; ri++) {
Point queryCenter = ctx.getDistCalc().pointOnBearing(clusterCenter,
radiusDeg*2, random().nextInt(360), ctx, null);
queryCenter = alignGeohash(queryCenter);
//4.1 Query a small box getting nothing
checkHits(q(queryCenter, radiusDeg - smallRadius/2), 0, null);
//4.2 Query a large box enclosing the cluster, getting everything
checkHits(q(queryCenter, radiusDeg*3*1.01), points.size(), null);
//4.3 Query a medium box getting some (calculate the correct solution and verify)
double queryDist = radiusDeg * 2;
//Find matching points. Put into int[] of doc ids which is the same thing as the index into points list.
int[] ids = new int[points.size()];
int ids_sz = 0;
for (int i = 0; i < points.size(); i++) {
Point point = points.get(i);
if (ctx.getDistCalc().distance(queryCenter, point) <= queryDist)
ids[ids_sz++] = i;
}
ids = Arrays.copyOf(ids, ids_sz);
//assert ids_sz > 0 (can't because randomness keeps us from being able to)
checkHits(q(queryCenter, queryDist), ids.length, ids);
}
}//for radiusDeg
}//for clusterCenter
}//randomTest()
| public void geohashRecursiveRandom() throws IOException {
init(12);
//1. Iterate test with the cluster at some worldly point of interest
Point[] clusterCenters = new Point[]{ctx.makePoint(-180,0), ctx.makePoint(0,90), ctx.makePoint(0,-90)};
for (Point clusterCenter : clusterCenters) {
//2. Iterate on size of cluster (a really small one and a large one)
String hashCenter = GeohashUtils.encodeLatLon(clusterCenter.getY(), clusterCenter.getX(), maxLength);
//calculate the number of degrees in the smallest grid box size (use for both lat & lon)
String smallBox = hashCenter.substring(0,hashCenter.length()-1);//chop off leaf precision
Rectangle clusterDims = GeohashUtils.decodeBoundary(smallBox,ctx);
double smallRadius = Math.max(clusterDims.getMaxX()-clusterDims.getMinX(),clusterDims.getMaxY()-clusterDims.getMinY());
assert smallRadius < 1;
double largeRadius = 20d;//good large size; don't use >=45 for this test code to work
double[] radiusDegs = {largeRadius,smallRadius};
for (double radiusDeg : radiusDegs) {
//3. Index random points in this cluster circle
deleteAll();
List<Point> points = new ArrayList<Point>();
for(int i = 0; i < 20; i++) {
//Note that this will not result in randomly distributed points in the
// circle, they will be concentrated towards the center a little. But
// it's good enough.
Point pt = ctx.getDistCalc().pointOnBearing(clusterCenter,
random().nextDouble() * radiusDeg, random().nextInt() * 360, ctx, null);
pt = alignGeohash(pt);
points.add(pt);
addDocument(newDoc("" + i, pt));
}
commit();
//3. Use some query centers. Each is twice the cluster's radius away.
for(int ri = 0; ri < 4; ri++) {
Point queryCenter = ctx.getDistCalc().pointOnBearing(clusterCenter,
radiusDeg*2, random().nextInt(360), ctx, null);
queryCenter = alignGeohash(queryCenter);
//4.1 Query a small box getting nothing
checkHits(q(queryCenter, radiusDeg - smallRadius/2), 0, null);
//4.2 Query a large box enclosing the cluster, getting everything
checkHits(q(queryCenter, radiusDeg*3 + smallRadius/2), points.size(), null);
//4.3 Query a medium box getting some (calculate the correct solution and verify)
double queryDist = radiusDeg * 2;
//Find matching points. Put into int[] of doc ids which is the same thing as the index into points list.
int[] ids = new int[points.size()];
int ids_sz = 0;
for (int i = 0; i < points.size(); i++) {
Point point = points.get(i);
if (ctx.getDistCalc().distance(queryCenter, point) <= queryDist)
ids[ids_sz++] = i;
}
ids = Arrays.copyOf(ids, ids_sz);
//assert ids_sz > 0 (can't because randomness keeps us from being able to)
checkHits(q(queryCenter, queryDist), ids.length, ids);
}
}//for radiusDeg
}//for clusterCenter
}//randomTest()
|
diff --git a/src/drbd/configs/DistResource_redhat_5.java b/src/drbd/configs/DistResource_redhat_5.java
index a1495b31..7c7fee00 100644
--- a/src/drbd/configs/DistResource_redhat_5.java
+++ b/src/drbd/configs/DistResource_redhat_5.java
@@ -1,105 +1,118 @@
/*
* This file is part of DRBD Management Console by LINBIT HA-Solutions GmbH
* written by Rasto Levrinc.
*
* Copyright (C) 2009, LINBIT HA-Solutions GmbH.
*
* DRBD Management Console is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* DRBD Management Console is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with drbd; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package drbd.configs;
import java.util.Arrays;
/**
* Here are commands for centos verson 5.
*/
public class DistResource_redhat_5 extends
java.util.ListResourceBundle {
/** Get contents. */
protected final Object[][] getContents() {
return Arrays.copyOf(contents, contents.length);
}
/** Contents. */
private static Object[][] contents = {
/* Kernel versions and their counterpart in @KERNELVERSION@ variable in
* the donwload url. Must begin with "kernel:" keyword. deprecated */
/* distribution name that is used in the download url */
{"distributiondir", "rhel5"},
{"arch:i686", "i686"},
/* support */
{"Support", "redhat-5"},
/* Corosync/Openais/Pacemaker clusterlabs */
{"PmInst.install.text.1",
"clusterlabs repo: 1.0.x/1.1.x" },
{"PmInst.install.1",
"wget -N -nd -P /etc/yum.repos.d/"
+ " http://www.clusterlabs.org/rpm/epel-5/clusterlabs.repo && "
+ " rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/i386"
+ "/epel-release-5-3.noarch.rpm && "
+ "(yum -y -x resource-agents-3.* -x openais-1* -x openais-0.9*"
- + " -x heartbeat-2.1* install pacemaker corosync"
+ + " -x heartbeat-2.1* install pacemaker.@ARCH@ corosync.@ARCH@"
+ " && if [ -e /etc/corosync/corosync.conf ]; then"
+ " mv /etc/corosync/corosync.conf /etc/corosync/corosync.conf.orig;"
+ " fi)"
+ " && (/sbin/chkconfig --del heartbeat;"
+ " /sbin/chkconfig --level 2345 corosync on"
+ " && /sbin/chkconfig --level 016 corosync off)"},
/* Corosync/Openais/Pacemaker Opensuse */
{"PmInst.install.text.2",
"opensuse:ha-clustering repo: 1.0.x/0.80.x" },
{"PmInst.install.2",
"wget -N -nd -P /etc/yum.repos.d/ http://download.opensuse.org/repositories/server:/ha-clustering/CentOS_5/server:ha-clustering.repo && "
+ "yum -y install OpenIPMI-libs lm_sensors "
+ "&& yum -y -x openais-0.80.6 install openais pacemaker resource-agents"
+ " && (/sbin/chkconfig --add corosync"
+ " || /sbin/chkconfig --add openais)"
+ " && if [ -e /etc/ais/openais.conf ];then"
+ " mv /etc/ais/openais.conf /etc/ais/openais.conf.orig; fi"
+ " && if [ -e /etc/corosync/corosync.conf ];then"
+ " mv /etc/corosync/corosync.conf /etc/corosync/corosync.conf.orig; fi"},
- /* Heartbeat/Pacemaker Opensuse */
+ /* Heartbeat/Pacemaker clusterlabs */
{"HbPmInst.install.text.1",
- "opensuse:ha-clustering repo: 1.0.x/2.99.x" },
+ "clusterlabs repo: 1.0.x/3.0.x" },
{"HbPmInst.install.1",
+ "wget -N -nd -P /etc/yum.repos.d/"
+ + " http://www.clusterlabs.org/rpm/epel-5/clusterlabs.repo && "
+ + " rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/i386"
+ + "/epel-release-5-3.noarch.rpm && "
+ + "yum -y -x resource-agents-3.* -x openais-1* -x openais-0.9*"
+ + " -x heartbeat-2.1* install pacemaker.@ARCH@ heartbeat.@ARCH@"
+ + " && /sbin/chkconfig --add heartbeat"},
+
+ /* Heartbeat/Pacemaker Opensuse */
+ {"HbPmInst.install.text.2",
+ "opensuse:ha-clustering repo: 1.0.x/2.99.x" },
+
+ {"HbPmInst.install.2",
"wget -N -nd -P /etc/yum.repos.d/ http://download.opensuse.org/repositories/server:/ha-clustering/CentOS_5/server:ha-clustering.repo && "
+ "yum -y -x resource-agents-3.* -x openais-1* -x openais-0.9*"
+ " -x heartbeat-2.1* "
+ " install heartbeat pacemaker resource-agents "
+ "&& /sbin/chkconfig --add heartbeat"},
- {"HbPmInst.install.text.2", "the centos way: HB 2.1.3 (obsolete)" },
+ {"HbPmInst.install.text.3", "the centos way: HB 2.1.3 (obsolete)" },
- {"HbPmInst.install.2",
+ {"HbPmInst.install.3",
"/usr/sbin/useradd hacluster 2>/dev/null; "
+ "/usr/bin/yum -y install heartbeat "
+ "&& /sbin/chkconfig --add heartbeat"},
{"Openais.startOpenais.i686",
"/etc/init.d/openais start"},
{"Openais.reloadOpenais.i686",
"/etc/init.d/openais reload"},
};
}
| false | false | null | null |
diff --git a/bindings/java/src/org/hyperic/sigar/test/TestTcpStat.java b/bindings/java/src/org/hyperic/sigar/test/TestTcpStat.java
index 29e52ff0..3a20d6e7 100644
--- a/bindings/java/src/org/hyperic/sigar/test/TestTcpStat.java
+++ b/bindings/java/src/org/hyperic/sigar/test/TestTcpStat.java
@@ -1,52 +1,54 @@
/*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of SIGAR.
*
* SIGAR is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package org.hyperic.sigar.test;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarNotImplementedException;
import org.hyperic.sigar.TcpStat;
public class TestTcpStat extends SigarTestCase {
public TestTcpStat(String name) {
super(name);
}
public void testCreate() throws Exception {
Sigar sigar = getSigar();
TcpStat tcp;
try {
tcp = sigar.getTcpStat();
} catch (SigarNotImplementedException e) {
return;
}
traceln("");
- assertGtZeroTrace("MaxConn", tcp.getMaxConn());
+ //assertGtZeroTrace("MaxConn", tcp.getMaxConn()); //XXX -1 on linux
+ traceln("MaxConn=" + tcp.getMaxConn());
assertGtEqZeroTrace("ActiveOpens", tcp.getActiveOpens());
assertGtEqZeroTrace("PassiveOpens", tcp.getPassiveOpens());
assertGtEqZeroTrace("AttemptFails", tcp.getAttemptFails());
+ assertGtEqZeroTrace("EstabResets", tcp.getEstabResets());
assertGtEqZeroTrace("CurrEstab", tcp.getCurrEstab());
assertGtEqZeroTrace("InSegs", tcp.getInSegs());
assertGtEqZeroTrace("OutSegs", tcp.getOutSegs());
assertGtEqZeroTrace("RetransSegs", tcp.getRetransSegs());
assertGtEqZeroTrace("OutRsts", tcp.getOutRsts());
}
}
| false | true | public void testCreate() throws Exception {
Sigar sigar = getSigar();
TcpStat tcp;
try {
tcp = sigar.getTcpStat();
} catch (SigarNotImplementedException e) {
return;
}
traceln("");
assertGtZeroTrace("MaxConn", tcp.getMaxConn());
assertGtEqZeroTrace("ActiveOpens", tcp.getActiveOpens());
assertGtEqZeroTrace("PassiveOpens", tcp.getPassiveOpens());
assertGtEqZeroTrace("AttemptFails", tcp.getAttemptFails());
assertGtEqZeroTrace("CurrEstab", tcp.getCurrEstab());
assertGtEqZeroTrace("InSegs", tcp.getInSegs());
assertGtEqZeroTrace("OutSegs", tcp.getOutSegs());
assertGtEqZeroTrace("RetransSegs", tcp.getRetransSegs());
assertGtEqZeroTrace("OutRsts", tcp.getOutRsts());
}
| public void testCreate() throws Exception {
Sigar sigar = getSigar();
TcpStat tcp;
try {
tcp = sigar.getTcpStat();
} catch (SigarNotImplementedException e) {
return;
}
traceln("");
//assertGtZeroTrace("MaxConn", tcp.getMaxConn()); //XXX -1 on linux
traceln("MaxConn=" + tcp.getMaxConn());
assertGtEqZeroTrace("ActiveOpens", tcp.getActiveOpens());
assertGtEqZeroTrace("PassiveOpens", tcp.getPassiveOpens());
assertGtEqZeroTrace("AttemptFails", tcp.getAttemptFails());
assertGtEqZeroTrace("EstabResets", tcp.getEstabResets());
assertGtEqZeroTrace("CurrEstab", tcp.getCurrEstab());
assertGtEqZeroTrace("InSegs", tcp.getInSegs());
assertGtEqZeroTrace("OutSegs", tcp.getOutSegs());
assertGtEqZeroTrace("RetransSegs", tcp.getRetransSegs());
assertGtEqZeroTrace("OutRsts", tcp.getOutRsts());
}
|
diff --git a/src/main/java/de/kumpelblase2/remoteentities/api/thinking/goals/DesireWanderAroundArea.java b/src/main/java/de/kumpelblase2/remoteentities/api/thinking/goals/DesireWanderAroundArea.java
index 8ea2230..573f1d8 100644
--- a/src/main/java/de/kumpelblase2/remoteentities/api/thinking/goals/DesireWanderAroundArea.java
+++ b/src/main/java/de/kumpelblase2/remoteentities/api/thinking/goals/DesireWanderAroundArea.java
@@ -1,60 +1,57 @@
package de.kumpelblase2.remoteentities.api.thinking.goals;
import net.minecraft.server.v1_5_R3.Vec3D;
import org.bukkit.Location;
import org.bukkit.entity.LivingEntity;
import de.kumpelblase2.remoteentities.api.RemoteEntity;
import de.kumpelblase2.remoteentities.nms.RandomPositionGenerator;
import de.kumpelblase2.remoteentities.persistence.ParameterData;
import de.kumpelblase2.remoteentities.persistence.SerializeAs;
import de.kumpelblase2.remoteentities.utilities.ReflectionUtil;
import de.kumpelblase2.remoteentities.utilities.WorldUtilities;
public class DesireWanderAroundArea extends DesireWanderAround
{
@SerializeAs(pos = 1)
protected int m_Radius;
@SerializeAs(pos = 2)
protected Location m_midSpot;
public DesireWanderAroundArea(RemoteEntity inEntity, int inRadius, Location inMidPoint)
{
super(inEntity);
this.m_Radius = inRadius;
this.m_midSpot = inMidPoint;
}
@Override
public boolean shouldExecute()
{
LivingEntity handle = this.getRemoteEntity().getBukkitEntity();
if(!WorldUtilities.isInCircle(this.m_midSpot.getX(), this.m_midSpot.getZ(), handle.getLocation().getX(), handle.getLocation().getZ(), this.m_Radius) || super.shouldExecute())
{
int tries = 0;
while(!WorldUtilities.isInCircle(this.m_midSpot.getX(), this.m_midSpot.getZ(), this.m_xPos, this.m_zPos, this.m_Radius) && tries <= 10)
{
Vec3D vector = RandomPositionGenerator.a(this.getEntityHandle(), 10, 7);
if(vector != null)
{
this.m_xPos = vector.c;
this.m_yPos = vector.d;
this.m_zPos = vector.e;
Vec3D.a.release(vector);
- return true;
}
tries++;
}
- return false;
+ return tries <= 10;
}
else
- {
return false;
- }
}
@Override
public ParameterData[] getSerializeableData()
{
return ReflectionUtil.getParameterDataForClass(this).toArray(new ParameterData[0]);
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/gui/GameTreeViewer.java b/src/gui/GameTreeViewer.java
index 5b4523f5..86f582ac 100644
--- a/src/gui/GameTreeViewer.java
+++ b/src/gui/GameTreeViewer.java
@@ -1,354 +1,355 @@
//-----------------------------------------------------------------------------
// $Id$
// $Source$
//-----------------------------------------------------------------------------
package gui;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import game.*;
import go.*;
//-----------------------------------------------------------------------------
class GameNode
extends JComponent
implements MouseListener
{
public GameNode(Node node, int moveNumber, int width, int height,
GameTreeViewer.Listener listener)
{
m_node = node;
m_moveNumber = moveNumber;
m_width = width;
m_height = height;
m_listener = listener;
addMouseListener(this);
}
public Dimension getPreferredSize()
{
return new Dimension(m_width, m_height);
}
public void mouseClicked(MouseEvent event)
{
if (m_listener != null)
m_listener.gotoNode(m_node);
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void paintComponent(Graphics graphics)
{
Graphics2D graphics2D = (Graphics2D)graphics;
if (graphics2D != null)
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setColor(java.awt.Color.lightGray);
graphics.fillRect(0, 0, m_width, m_width);
Move move = m_node.getMove();
int halfSize = m_width / 2;
if (m_node.getNumberAddBlack() + m_node.getNumberAddWhite() > 0)
{
graphics.setColor(java.awt.Color.black);
graphics.fillOval(0, 0, halfSize, halfSize);
graphics.fillOval(halfSize, halfSize, halfSize, halfSize);
graphics.setColor(java.awt.Color.white);
graphics.fillOval(halfSize, 0, halfSize, halfSize);
graphics.fillOval(0, halfSize, halfSize, halfSize);
}
else if (move == null)
{
graphics.setColor(java.awt.Color.darkGray);
int[] xPoints = { halfSize, m_width, halfSize, 0 };
int[] yPoints = { 0, halfSize, m_width, halfSize };
graphics.fillPolygon(xPoints, yPoints, 4);
}
else
{
if (move.getColor() == go.Color.BLACK)
graphics.setColor(java.awt.Color.black);
else
graphics.setColor(java.awt.Color.white);
graphics.fillOval(0, 0, m_width, m_width);
String text = Integer.toString(m_moveNumber);
int textWidth = graphics.getFontMetrics().stringWidth(text);
int textHeight = graphics.getFont().getSize();
int xText = (m_width - textWidth) / 2;
int yText = textHeight + (m_width - textHeight) / 2;
if (move.getColor() == go.Color.BLACK)
graphics.setColor(java.awt.Color.white);
else
graphics.setColor(java.awt.Color.black);
graphics.drawString(text, xText, yText);
}
if (m_node.getComment() != null
&& ! m_node.getComment().trim().equals(""))
{
graphics.setColor(java.awt.Color.black);
graphics.drawLine(3, m_width + 2, m_width - 3, m_width + 2);
graphics.drawLine(3, m_width + 4, m_width - 3, m_width + 4);
graphics.drawLine(3, m_width + 6, m_width - 3, m_width + 6);
}
if (m_isCurrent)
{
graphics.setColor(java.awt.Color.red);
int d = m_width / 6;
int w = m_width;
graphics.drawLine(d, d, 2 * d, d);
graphics.drawLine(d, d, d, 2 * d);
graphics.drawLine(d, w - 2 * d - 1, d, w - d - 1);
graphics.drawLine(d, w - d - 1, 2 * d, w - d - 1);
graphics.drawLine(w - 2 * d - 1, d, w - d - 1, d);
graphics.drawLine(w - d - 1, d, w - d - 1, 2 * d);
graphics.drawLine(w - d - 1, w - d - 1, w - d - 1, w - 2 * d - 1);
graphics.drawLine(w - d - 1, w - d - 1, w - 2 * d - 1, w - d - 1);
}
}
public void setCurrentNode(boolean isCurrent)
{
m_isCurrent = isCurrent;
}
private boolean m_isCurrent;
private int m_moveNumber;
public int m_width;
public int m_height;
private GameTreeViewer.Listener m_listener;
private Node m_node;
}
//-----------------------------------------------------------------------------
class GameTreePanel
extends JPanel
implements Scrollable
{
public GameTreePanel(GameTreeViewer.Listener listener)
{
super(new SpringLayout());
setBackground(java.awt.Color.lightGray);
m_nodeSize = 25;
m_nodeDist = 35;
Font font = UIManager.getFont("Label.font");
if (font != null)
{
m_nodeSize = font.getSize() * 2;
if (m_nodeSize % 2 == 0)
++m_nodeSize;
m_nodeDist = font.getSize() * 3;
if (m_nodeDist % 2 == 0)
++m_nodeDist;
}
setOpaque(false);
m_listener = listener;
}
public Dimension getPreferredScrollableViewportSize()
{
return new Dimension(m_nodeDist * 10, m_nodeDist * 3);
}
public int getScrollableBlockIncrement(Rectangle visibleRect,
int orientation, int direction)
{
return m_nodeDist * 10;
}
public boolean getScrollableTracksViewportHeight()
{
return false;
}
public boolean getScrollableTracksViewportWidth()
{
return false;
}
public int getScrollableUnitIncrement(Rectangle visibleRect,
int orientation, int direction)
{
return m_nodeDist;
}
public void paintComponent(Graphics graphics)
{
if (m_gameTree == null)
return;
drawGrid(graphics, m_gameTree.getRoot(),
m_margin + m_nodeSize / 2, m_margin + m_nodeSize / 2);
super.paintComponent(graphics);
}
public void update(GameTree gameTree, Node currentNode)
{
assert(currentNode != null);
m_gameTree = gameTree;
m_currentNode = currentNode;
removeAll();
m_map.clear();
m_maxX = 0;
m_maxY = 0;
createNodes(this, m_gameTree.getRoot(), 0, 0, m_margin, m_margin, 0);
GameNode gameNode = getGameNode(currentNode);
gameNode.setCurrentNode(true);
SpringLayout layout = (SpringLayout)getLayout();
setPreferredSize(new Dimension(m_maxX + m_nodeDist + m_margin,
m_maxY + m_nodeDist + m_margin));
revalidate();
- scrollRectToVisible(new Rectangle(m_currentNodeX, m_currentNodeY,
- m_nodeSize, m_nodeSize));
+ scrollRectToVisible(new Rectangle(m_currentNodeX - 2 * m_nodeSize,
+ m_currentNodeY,
+ 5 * m_nodeSize, m_nodeSize));
}
private int m_currentNodeX;
private int m_currentNodeY;
private int m_nodeSize;
private static final int m_margin = 15;
private int m_maxX;
private int m_maxY;
private int m_nodeDist;
private Font m_font;
private GameTree m_gameTree;
private GameTreeViewer.Listener m_listener;
private Node m_currentNode;
private HashMap m_map = new HashMap();
private int createNodes(Component father, Node node, int x, int y,
int dx, int dy, int moveNumber)
{
m_maxX = Math.max(x, m_maxX);
m_maxY = Math.max(y, m_maxY);
if (node.getMove() != null)
++moveNumber;
GameNode gameNode = new GameNode(node, moveNumber,
m_nodeSize, m_nodeDist, m_listener);
m_map.put(node, gameNode);
add(gameNode);
SpringLayout layout = (SpringLayout)getLayout();
layout.putConstraint(SpringLayout.WEST, gameNode, dx,
SpringLayout.WEST, father);
layout.putConstraint(SpringLayout.NORTH, gameNode, dy,
SpringLayout.NORTH, father);
int numberChildren = node.getNumberChildren();
dx = m_nodeDist;
dy = 0;
for (int i = 0; i < numberChildren; ++i)
{
dy += createNodes(gameNode, node.getChild(i),
x + dx, y + dy, dx, dy, moveNumber);
if (i < numberChildren - 1)
dy += m_nodeDist;
}
if (node == m_currentNode)
{
m_currentNodeX = x;
m_currentNodeY = y;
}
return dy;
}
private int drawGrid(Graphics graphics, Node node, int x, int y)
{
int numberChildren = node.getNumberChildren();
int offset = m_nodeSize / 2;
int xChild = x + m_nodeDist;
int yChild = y;
for (int i = 0; i < numberChildren; ++i)
{
graphics.setColor(java.awt.Color.DARK_GRAY);
graphics.drawLine(x, y, x, yChild);
graphics.drawLine(x, yChild, xChild, yChild);
yChild = drawGrid(graphics, node.getChild(i), xChild, yChild);
if (i < numberChildren - 1)
yChild += m_nodeDist;
}
return yChild;
}
private GameNode getGameNode(Node node)
{
return (GameNode)m_map.get(node);
}
}
//-----------------------------------------------------------------------------
public class GameTreeViewer
extends JDialog
{
public interface Listener
{
public abstract void gotoNode(Node node);
}
public GameTreeViewer(Frame owner, Listener listener)
{
super(owner, "GoGui: Game Tree");
Container contentPane = getContentPane();
m_panel = new GameTreePanel(listener);
m_scrollPane =
new JScrollPane(m_panel,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
m_scrollPane.getViewport().setBackground(java.awt.Color.lightGray);
contentPane.add(m_scrollPane, BorderLayout.CENTER);
pack();
m_listener = listener;
}
public void toTop()
{
setVisible(true);
toFront();
}
public void update(GameTree gameTree, Node currentNode)
{
m_panel.update(gameTree, currentNode);
repaint();
}
private GameTreePanel m_panel;
private JScrollPane m_scrollPane;
private Listener m_listener;
}
//-----------------------------------------------------------------------------
| true | false | null | null |
diff --git a/xftl-fixtures/src/de/xftl/fixture/Fixture.java b/xftl-fixtures/src/de/xftl/fixture/Fixture.java
index 0621797..7dc0948 100644
--- a/xftl-fixtures/src/de/xftl/fixture/Fixture.java
+++ b/xftl-fixtures/src/de/xftl/fixture/Fixture.java
@@ -1,94 +1,97 @@
package de.xftl.fixture;
import java.util.ArrayList;
import java.util.List;
import de.xftl.model.ships.BasicDeck;
import de.xftl.model.ships.BasicRoom;
import de.xftl.model.ships.BasicShip;
import de.xftl.model.ships.BasicTile;
+import de.xftl.model.util.TileConnector;
import de.xftl.spec.game.Game;
import de.xftl.spec.model.Point;
import de.xftl.spec.model.ships.Deck;
import de.xftl.spec.model.ships.DeckNumber;
import de.xftl.spec.model.ships.Room;
import de.xftl.spec.model.ships.Ship;
import de.xftl.spec.model.ships.Tile;
import de.xftl.spec.model.ships.TileUnit;
public class Fixture {
public static Game buildGame() {
Game game = new FixtureGame();
return game;
}
public static Ship buildShip() {
BasicShip ship = new BasicShip();
ship.addDeck(buildDeck(1));
return ship;
}
private static Deck buildDeck(int number) {
BasicDeck deck = new BasicDeck(new DeckNumber(number));
deck.addRoom(buildRoom(2, 2, 0, 1));
deck.addRoom(buildRoom(2, 2, 2, 1));
deck.addRoom(buildRoom(2, 1, 1, 0));
deck.addRoom(buildRoom(2, 1, 1, 3));
deck.addRoom(buildRoom(2, 2, 4, 1));
deck.addRoom(buildRoom(1, 2, 5, 1));
return deck;
}
private static Room buildRoom(int width, int height, int x, int y) {
- BasicRoom room = new BasicRoom(buildTiles(width, height, x, y));
+ List<BasicTile> tiles = buildTiles(width, height, x, y);
+ new TileConnector(tiles).connectTiles();
+ BasicRoom room = new BasicRoom(new ArrayList<Tile>(tiles));
return room;
}
- private static List<Tile> buildTiles(int width, int height, int pX, int pY) {
- List<Tile> tiles = new ArrayList<>(width * height);
+ private static List<BasicTile> buildTiles(int width, int height, int pX, int pY) {
+ List<BasicTile> tiles = new ArrayList<>(width * height);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
TileUnit tux = new TileUnit(x + pX);
TileUnit tuy = new TileUnit(y + pY);
BasicTile tile = new BasicTile(new Point<TileUnit>(tux, tuy));
tiles.add(tile);
}
}
return tiles;
}
public static void main(String[] args) {
Ship ship = buildShip();
final int MATRIX_X = 10;
final int MATRIX_Y = 10;
Tile[][] matrix = new Tile[MATRIX_X][MATRIX_Y];
for (Room room : ship.getDecks().get(0).getRooms()) {
for (Tile tile : room.getTiles()) {
Point<TileUnit> pos = tile.getLeftUpperCornerPos();
int x = pos.getX().getValue();
int y = pos.getY().getValue();
matrix[y][x] = tile;
}
}
for (int y = 0; y < MATRIX_Y; y++) {
for (int x = 0; x < MATRIX_X; x++) {
System.out.print(matrix[y][x] == null ? ' ' : 'X');
}
System.out.println("");
}
}
}
diff --git a/xftl-model/src/main/java/de/xftl/model/ships/BasicRoom.java b/xftl-model/src/main/java/de/xftl/model/ships/BasicRoom.java
index f255f5f..b5c6bab 100644
--- a/xftl-model/src/main/java/de/xftl/model/ships/BasicRoom.java
+++ b/xftl-model/src/main/java/de/xftl/model/ships/BasicRoom.java
@@ -1,93 +1,91 @@
package de.xftl.model.ships;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
-import de.xftl.model.util.TileConnector;
import de.xftl.spec.model.Point;
import de.xftl.spec.model.crew.CrewMember;
import de.xftl.spec.model.ships.OxygenLevel;
import de.xftl.spec.model.ships.Room;
import de.xftl.spec.model.ships.RoomConnector;
import de.xftl.spec.model.ships.Tile;
import de.xftl.spec.model.ships.TileUnit;
import de.xftl.spec.model.ships.TileUnitPositioned;
public class BasicRoom implements Room {
private Point<TileUnit> _leftUpperCornerPos;
private System _system;
private List<Tile> _tiles;
private OxygenLevel _oxygenLevel;
public BasicRoom(List<Tile> tiles) {
super();
_tiles = tiles;
- new TileConnector(_tiles).connectTiles();
determineLeftUpperCornerPos();
}
private void determineLeftUpperCornerPos() {
List<Tile> tiles = new ArrayList<>(_tiles);
Collections.sort(tiles);
_leftUpperCornerPos = tiles.get(0).getLeftUpperCornerPos();
}
@Override
public void update(float elapsedTime) {
// TODO Auto-generated method stub
}
@Override
public Point<TileUnit> getLeftUpperCornerPos() {
return _leftUpperCornerPos;
}
@Override
public System getSystem() {
return _system;
}
@Override
public List<Tile> getTiles() {
return _tiles;
}
@Override
public List<CrewMember> getCrewMembers() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<RoomConnector> getRoomConnectors() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Room> getAdjacentRooms() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Room> getAdjacentRooms(Room origin) {
// TODO Auto-generated method stub
return null;
}
@Override
public OxygenLevel getOxygenLevel() {
return _oxygenLevel;
}
@Override
public int compareTo(TileUnitPositioned o) {
return _leftUpperCornerPos.compareTo(o.getLeftUpperCornerPos());
}
}
| false | false | null | null |
diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/local/FileClientHelper.java b/modules/com.noelios.restlet/src/com/noelios/restlet/local/FileClientHelper.java
index 260e816c6..7bb432617 100644
--- a/modules/com.noelios.restlet/src/com/noelios/restlet/local/FileClientHelper.java
+++ b/modules/com.noelios.restlet/src/com/noelios/restlet/local/FileClientHelper.java
@@ -1,722 +1,720 @@
/*
* Copyright 2005-2008 Noelios Consulting.
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License"). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the license at
* http://www.opensource.org/licenses/cddl1.txt See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at http://www.opensource.org/licenses/cddl1.txt If
* applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*/
package com.noelios.restlet.local;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import org.restlet.Client;
import org.restlet.data.Encoding;
import org.restlet.data.Language;
import org.restlet.data.LocalReference;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Preference;
import org.restlet.data.Protocol;
import org.restlet.data.Reference;
import org.restlet.data.ReferenceList;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.resource.FileRepresentation;
import org.restlet.resource.Representation;
import org.restlet.resource.Variant;
import org.restlet.service.MetadataService;
import org.restlet.util.ByteUtils;
/**
* Connector to the file resources accessible
*
* @author Jerome Louvel ([email protected])
* @author Thierry Boileau
*/
public class FileClientHelper extends LocalClientHelper {
/**
* Constructor.
*
* @param client
* The client to help.
*/
public FileClientHelper(Client client) {
super(client);
getProtocols().add(Protocol.FILE);
}
/**
* Check that all extensions of the file correspond to a known metadata
*
* @param file
* @param metadataService
* @param representation
* @return
*/
private boolean checkExtensionsConsistency(File file,
MetadataService metadataService) {
boolean knownExtension = true;
final Set<String> set = getExtensions(file, metadataService);
final Iterator<String> iterator = set.iterator();
while (iterator.hasNext() && knownExtension) {
knownExtension = metadataService.getMetadata(iterator.next()) != null;
}
return knownExtension;
}
/**
* Checks that the URI and the representation are compatible. The whole set
* of metadata of the representation must be included in the set of those of
* the URI
*
* @param fileName
* The name of the resource
* @param metadataService
* metadata helper
* @param representation
* the provided representation
* @return true if the metadata of the representation are compatible with
* the metadata extracted from the filename
*/
private boolean checkMetadataConsistency(String fileName,
MetadataService metadataService, Representation representation) {
boolean result = true;
if (representation != null) {
final Variant var = new Variant();
updateMetadata(metadataService, fileName, var);
// "var" contains the theorical correct metadata
if (!representation.getLanguages().isEmpty()
&& !var.getLanguages().containsAll(
representation.getLanguages())) {
result = false;
}
if ((representation.getMediaType() != null)
&& !((var.getMediaType() != null) && var.getMediaType()
.includes(representation.getMediaType()))) {
result = false;
}
if (!representation.getEncodings().isEmpty()
&& !var.getEncodings().containsAll(
representation.getEncodings())) {
result = false;
}
}
return result;
}
/**
* Returns the base name as the longest part of the name without known
* extensions (beginning from the left)
*
* @param file
* @param metadataService
* @return the base name of the file
*/
private String getBaseName(File file, MetadataService metadataService) {
final String[] result = file.getName().split("\\.");
final StringBuilder baseName = new StringBuilder().append(result[0]);
boolean extensionFound = false;
for (int i = 1; (i < result.length) && !extensionFound; i++) {
extensionFound = metadataService.getMetadata(result[i]) != null;
if (!extensionFound) {
baseName.append(".").append(result[i]);
}
}
return baseName.toString();
}
/**
* Returns the Set of extensions of a file
*
* @param file
* @param metadataService
* @return
*/
private Set<String> getExtensions(File file, MetadataService metadataService) {
final Set<String> result = new TreeSet<String>();
final String[] tokens = file.getName().split("\\.");
boolean extensionFound = false;
int i;
for (i = 1; (i < tokens.length) && !extensionFound; i++) {
extensionFound = metadataService.getMetadata(tokens[i]) != null;
}
if (extensionFound) {
for (--i; (i < tokens.length); i++) {
result.add(tokens[i]);
}
}
return result;
}
/**
* Percent-encodes the given percent-decoded variant name of a resource
* whose percent-encoded name is given. Tries to match the longest common
* part of both encoded file name and decoded variant name.
*
* @param encodedFileName
* the percent-encoded name of the initial resource
* @param decodedVariantFileName
* the percent-decoded file name of a variant of the initial
* resource.
* @return the variant percent-encoded file name.
*/
private String getReencodedVariantFileName(String encodedFileName,
String decodedVariantFileName) {
int i = 0;
int j = 0;
boolean stop = false;
for (i = 0; (i < decodedVariantFileName.length())
&& (j < encodedFileName.length()) && !stop; i++) {
final String decodedChar = decodedVariantFileName.substring(i,
i + 1);
if (decodedChar.equals(encodedFileName.substring(j, j + 1))) {
j++;
} else {
if (encodedFileName.substring(j, j + 1).equals("%")) {
if (decodedChar.equals(Reference.decode(encodedFileName
.substring(j, j + 3)))) {
j += 3;
} else {
stop = true;
}
} else {
if (decodedChar.equals(Reference.decode(encodedFileName
.substring(j, j + 1)))) {
j++;
} else {
stop = true;
}
}
}
}
if (stop) {
return encodedFileName.substring(0, j)
+ decodedVariantFileName.substring(i - 1);
}
if (j == encodedFileName.length()) {
return encodedFileName.substring(0, j)
+ decodedVariantFileName.substring(i);
}
return encodedFileName.substring(0, j);
}
/**
* Handles a call.
*
* @param request
* The request to handle.
* @param response
* The response to update.
*/
@Override
public void handle(Request request, Response response) {
final String scheme = request.getResourceRef().getScheme();
// Ensure that all ".." and "." are normalized into the path
// to preven unauthorized access to user directories.
request.getResourceRef().normalize();
if (scheme.equalsIgnoreCase("file")) {
handleFile(request, response, request.getResourceRef().getPath());
} else {
throw new IllegalArgumentException(
"Protocol \""
+ scheme
+ "\" not supported by the connector. Only FILE is supported.");
}
}
/**
* Handles a call for the FILE protocol.
*
* @param request
* The request to handle.
* @param response
* The response to update.
* @param path
* The file or directory path.
*/
protected void handleFile(Request request, Response response, String path) {
// As the path may be percent-encoded, it has to be percent-decoded.
// Then, all generated uris must be encoded.
final String decodedPath = LocalReference.localizePath(Reference
.decode(path));
File file = new File(decodedPath);
final MetadataService metadataService = getMetadataService(request);
if (request.getMethod().equals(Method.GET)
|| request.getMethod().equals(Method.HEAD)) {
Representation output = null;
// Get variants for a resource
boolean found = false;
final Iterator<Preference<MediaType>> iterator = request
.getClientInfo().getAcceptedMediaTypes().iterator();
while (iterator.hasNext() && !found) {
final Preference<MediaType> pref = iterator.next();
found = pref.getMetadata().equals(MediaType.TEXT_URI_LIST);
}
if (found) {
// Try to list all variants of this resource
// 1- set up base name as the longest part of the name without
// known extensions (beginning from the left)
final String baseName = getBaseName(file, metadataService);
// 2- looking for resources with the same base name
if (file.getParentFile() != null) {
final File[] files = file.getParentFile().listFiles();
if (files != null) {
final ReferenceList rl = new ReferenceList(files.length);
final String encodedParentDirectoryURI = path
.substring(0, path.lastIndexOf("/"));
final String encodedFileName = path.substring(path
.lastIndexOf("/") + 1);
for (final File entry : files) {
if (baseName.equals(getBaseName(entry,
metadataService))) {
rl
.add(LocalReference
.createFileReference(encodedParentDirectoryURI
+ "/"
+ getReencodedVariantFileName(
encodedFileName,
entry.getName())));
}
}
output = rl.getTextRepresentation();
}
}
} else {
if (file.exists()) {
if (file.isDirectory()) {
// Return the directory listing
final File[] files = file.listFiles();
final ReferenceList rl = new ReferenceList(files.length);
String directoryUri = request.getResourceRef()
.toString();
// Ensures that the directory URI ends with a slash
if (!directoryUri.endsWith("/")) {
directoryUri += "/";
}
for (final File entry : files) {
rl.add(directoryUri
+ Reference.encode(entry.getName()));
}
output = rl.getTextRepresentation();
} else {
// Return the file content
output = new FileRepresentation(file, metadataService
.getDefaultMediaType(), getTimeToLive());
updateMetadata(metadataService, file.getName(), output);
}
} else {
// We look for the possible variant which has the same
// extensions in a distinct order.
// 1- set up base name as the longest part of the name
// without known extensions (beginning from the left)
final String baseName = getBaseName(file, metadataService);
final Set<String> extensions = getExtensions(file,
metadataService);
// 2- loooking for resources with the same base name
final File[] files = file.getParentFile().listFiles();
File uniqueVariant = null;
if (files != null) {
for (final File entry : files) {
if (baseName.equals(getBaseName(entry,
metadataService))) {
final Set<String> entryExtensions = getExtensions(
entry, metadataService);
if (entryExtensions.containsAll(extensions)
&& extensions
.containsAll(entryExtensions)) {
// The right representation has been found.
uniqueVariant = entry;
break;
}
}
}
}
if (uniqueVariant != null) {
// Return the file content
output = new FileRepresentation(uniqueVariant,
metadataService.getDefaultMediaType(),
getTimeToLive());
updateMetadata(metadataService, file.getName(), output);
}
}
}
if (output == null) {
response.setStatus(Status.CLIENT_ERROR_NOT_FOUND);
} else {
output.setIdentifier(request.getResourceRef());
response.setEntity(output);
response.setStatus(Status.SUCCESS_OK);
}
} else if (request.getMethod().equals(Method.PUT)) {
// Deals with directory
boolean isDirectory = false;
if (file.exists()) {
if (file.isDirectory()) {
isDirectory = true;
response.setStatus(new Status(
Status.CLIENT_ERROR_FORBIDDEN,
"Can't put a new representation of a directory"));
}
} else {
// No existing file or directory found
if (path.endsWith("/")) {
isDirectory = true;
// Create a new directory and its necessary parents
if (file.mkdirs()) {
response.setStatus(Status.SUCCESS_NO_CONTENT);
} else {
getLogger().log(Level.WARNING,
"Unable to create the new directory");
response.setStatus(new Status(
Status.SERVER_ERROR_INTERNAL,
"Unable to create the new directory"));
}
}
}
if (!isDirectory) {
// Several checks : first the consistency of the metadata and
- // the
- // filename
+ // the filename
if (!checkMetadataConsistency(file.getName(), metadataService,
request.getEntity())) {
// ask the client to reiterate properly its request
response.setStatus(new Status(Status.REDIRECTION_SEE_OTHER,
"The metadata are not consistent with the URI"));
} else {
-
// We look for the possible variants
// 1- set up base name as the longest part of the name
// without known extensions (beginning from the left)
final String baseName = getBaseName(file, metadataService);
final Set<String> extensions = getExtensions(file,
metadataService);
// 2- loooking for resources with the same base name
final File[] files = file.getParentFile().listFiles();
File uniqueVariant = null;
final List<File> variantsList = new ArrayList<File>();
if (files != null) {
for (final File entry : files) {
if (baseName.equals(getBaseName(entry,
metadataService))) {
final Set<String> entryExtensions = getExtensions(
entry, metadataService);
if (entryExtensions.containsAll(extensions)) {
variantsList.add(entry);
if (extensions.containsAll(entryExtensions)) {
// The right representation has been
// found.
uniqueVariant = entry;
}
}
}
}
}
if (uniqueVariant != null) {
file = uniqueVariant;
} else {
if (!variantsList.isEmpty()) {
// Negociated resource (several variants, but not
// the right one).
// Check if the request could be completed or not.
// The request could be more precise
response
.setStatus(new Status(
Status.CLIENT_ERROR_NOT_ACCEPTABLE,
"Unable to process properly the request. Several variants exist but none of them suits precisely."));
} else {
// This resource does not exist, yet.
// Complete it with the default metadata
updateMetadata(metadataService, file.getName(),
request.getEntity());
if (request.getEntity().getLanguages().isEmpty()) {
if (metadataService.getDefaultLanguage() != null) {
request.getEntity().getLanguages().add(
metadataService
.getDefaultLanguage());
}
}
if (request.getEntity().getMediaType() == null) {
request.getEntity().setMediaType(
metadataService.getDefaultMediaType());
}
if (request.getEntity().getEncodings().isEmpty()) {
if ((metadataService.getDefaultEncoding() != null)
&& !metadataService
.getDefaultEncoding().equals(
Encoding.IDENTITY)) {
request.getEntity().getEncodings().add(
metadataService
.getDefaultEncoding());
}
}
// Update the URI
final StringBuilder fileName = new StringBuilder(
baseName);
if (metadataService.getExtension(request
.getEntity().getMediaType()) != null) {
fileName.append("."
+ metadataService.getExtension(request
.getEntity().getMediaType()));
}
for (final Language language : request.getEntity()
.getLanguages()) {
if (metadataService.getExtension(language) != null) {
fileName.append("."
+ metadataService
.getExtension(language));
}
}
for (final Encoding encoding : request.getEntity()
.getEncodings()) {
if (metadataService.getExtension(encoding) != null) {
fileName.append("."
+ metadataService
.getExtension(encoding));
}
}
file = new File(file.getParentFile(), fileName
.toString());
}
}
// Before putting the file representation, we check that all
// the extensions are known
if (!checkExtensionsConsistency(file, metadataService)) {
response
.setStatus(new Status(
Status.SERVER_ERROR_INTERNAL,
"Unable to process properly the URI. At least one extension is not known by the server."));
} else {
File tmp = null;
if (file.exists()) {
FileOutputStream fos = null;
// Replace the content of the file
// First, create a temporary file
try {
tmp = File.createTempFile("restlet-upload",
"bin");
if (request.isEntityAvailable()) {
fos = new FileOutputStream(tmp);
ByteUtils.write(request.getEntity()
.getStream(), fos);
}
} catch (final IOException ioe) {
getLogger().log(Level.WARNING,
"Unable to create the temporary file",
ioe);
response.setStatus(new Status(
Status.SERVER_ERROR_INTERNAL,
"Unable to create a temporary file"));
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (final IOException ioe) {
getLogger()
.log(
Level.WARNING,
"Unable to close the temporary file",
ioe);
response.setStatus(
Status.SERVER_ERROR_INTERNAL, ioe);
}
}
// Then delete the existing file
if (file.delete()) {
// Finally move the temporary file to the
// existing file location
boolean renameSuccessfull = false;
if ((tmp != null) && tmp.renameTo(file)) {
if (request.getEntity() == null) {
response
.setStatus(Status.SUCCESS_NO_CONTENT);
} else {
response.setStatus(Status.SUCCESS_OK);
}
renameSuccessfull = true;
} else {
// Many aspects of the behavior of the
// method "renameTo" are inherently
// platform-dependent: The rename operation
// might not be able to move a file from one
// filesystem to another.
if ((tmp != null) && tmp.exists()) {
try {
final BufferedReader br = new BufferedReader(
new FileReader(tmp));
final BufferedWriter wr = new BufferedWriter(
new FileWriter(file));
String s;
while ((s = br.readLine()) != null) {
wr.append(s);
}
br.close();
wr.flush();
wr.close();
renameSuccessfull = true;
tmp.delete();
} catch (final Exception e) {
renameSuccessfull = false;
}
}
if (!renameSuccessfull) {
getLogger()
.log(Level.WARNING,
"Unable to move the temporary file to replace the existing file");
response
.setStatus(new Status(
Status.SERVER_ERROR_INTERNAL,
"Unable to move the temporary file to replace the existing file"));
}
}
} else {
getLogger().log(Level.WARNING,
"Unable to delete the existing file");
response.setStatus(new Status(
Status.SERVER_ERROR_INTERNAL,
"Unable to delete the existing file"));
}
} else {
final File parent = file.getParentFile();
if ((parent != null) && !parent.exists()) {
// Create the parent directories then the new
// file
if (!parent.mkdirs()) {
getLogger()
.log(Level.WARNING,
"Unable to create the parent directory");
response
.setStatus(new Status(
Status.SERVER_ERROR_INTERNAL,
"Unable to create the parent directory"));
}
}
FileOutputStream fos = null;
// Create the new file
try {
if (file.createNewFile()) {
if (request.getEntity() == null) {
response
.setStatus(Status.SUCCESS_NO_CONTENT);
} else {
fos = new FileOutputStream(file);
ByteUtils.write(request.getEntity()
.getStream(), fos);
response
.setStatus(Status.SUCCESS_CREATED);
}
} else {
getLogger().log(Level.WARNING,
"Unable to create the new file");
response.setStatus(new Status(
Status.SERVER_ERROR_INTERNAL,
"Unable to create the new file"));
}
} catch (final FileNotFoundException fnfe) {
getLogger().log(Level.WARNING,
"Unable to create the new file", fnfe);
response.setStatus(
Status.SERVER_ERROR_INTERNAL, fnfe);
} catch (final IOException ioe) {
getLogger().log(Level.WARNING,
"Unable to create the new file", ioe);
response.setStatus(
Status.SERVER_ERROR_INTERNAL, ioe);
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (final IOException ioe) {
getLogger()
.log(
Level.WARNING,
"Unable to close the temporary file",
ioe);
response.setStatus(
Status.SERVER_ERROR_INTERNAL, ioe);
}
}
}
}
}
}
} else if (request.getMethod().equals(Method.DELETE)) {
if (file.isDirectory()) {
if (file.listFiles().length == 0) {
if (file.delete()) {
response.setStatus(Status.SUCCESS_NO_CONTENT);
} else {
response.setStatus(Status.SERVER_ERROR_INTERNAL,
"Couldn't delete the directory");
}
} else {
response.setStatus(Status.CLIENT_ERROR_FORBIDDEN,
"Couldn't delete the non-empty directory");
}
} else {
if (file.delete()) {
response.setStatus(Status.SUCCESS_NO_CONTENT);
} else {
response.setStatus(Status.SERVER_ERROR_INTERNAL,
"Couldn't delete the file");
}
}
} else {
response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
response.getAllowedMethods().add(Method.GET);
response.getAllowedMethods().add(Method.HEAD);
response.getAllowedMethods().add(Method.PUT);
response.getAllowedMethods().add(Method.DELETE);
}
}
}
| false | false | null | null |
diff --git a/src/main/java/com/euroit/militaryshop/service/impl/ItemServiceImpl.java b/src/main/java/com/euroit/militaryshop/service/impl/ItemServiceImpl.java
index d379ae6..48dd979 100644
--- a/src/main/java/com/euroit/militaryshop/service/impl/ItemServiceImpl.java
+++ b/src/main/java/com/euroit/militaryshop/service/impl/ItemServiceImpl.java
@@ -1,151 +1,154 @@
package com.euroit.militaryshop.service.impl;
import com.euroit.eshop.dto.BaseTrolleyItemDto;
import com.euroit.eshop.exception.ItemAlreadyExistsException;
import com.euroit.militaryshop.dto.DictionaryEntryDto;
import com.euroit.militaryshop.dto.ItemInTrolleyDto;
import com.euroit.militaryshop.dto.MilitaryShopItemDto;
import com.euroit.militaryshop.persistence.dao.ItemDao;
import com.euroit.militaryshop.persistence.entity.MilitaryShopItem;
import com.euroit.militaryshop.service.DictionaryEntryService;
import com.euroit.militaryshop.service.ItemService;
import com.google.appengine.api.datastore.Key;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @author Roman Tuchin
*/
@Service
public class ItemServiceImpl implements ItemService {
Logger log = LoggerFactory.getLogger(ItemServiceImpl.class);
private ItemDao itemDao;
private DictionaryEntryService dictionaryEntryService;
@Autowired
public void setItemDao(ItemDao itemDao) {
this.itemDao = itemDao;
}
@Autowired
public void setDictionaryEntryService(
DictionaryEntryService dictionaryEntryService) {
this.dictionaryEntryService = dictionaryEntryService;
}
@Override
@Transactional
public void createOrSaveItem(MilitaryShopItemDto militaryShopItemDto) {
itemDao.createOrSave(militaryShopItemDto);
}
@Override
@Transactional
public void checkItemWithProperties(MilitaryShopItemDto militaryShopItemDto) throws ItemAlreadyExistsException {
Assert.state(militaryShopItemDto.getProductId() > 0);
List<MilitaryShopItem> items = itemDao.getProductItemsByProperties(militaryShopItemDto.getProductId(),
militaryShopItemDto.getColorId(), militaryShopItemDto.getMaterialId(), militaryShopItemDto.getSizeId());
if (items.size() > 0) {
throw new ItemAlreadyExistsException();
}
}
@Override
public List<ItemInTrolleyDto> getItemsForTrolleyList(Map<BaseTrolleyItemDto, Integer> itemsMap) {
List<ItemInTrolleyDto> retList = new ArrayList<ItemInTrolleyDto>();
if (itemsMap == null || itemsMap.isEmpty()) {
return retList;
}
Map<BaseTrolleyItemDto, MilitaryShopItemDto> fullItemsMap = getItemsByIds(itemsMap);
for (Map.Entry<BaseTrolleyItemDto, MilitaryShopItemDto> itemEntry : fullItemsMap.entrySet()) {
ItemInTrolleyDto itemDto = new ItemInTrolleyDto();
itemDto.setShortName(itemEntry.getValue().getShortName());
itemDto.setQuantity(itemsMap.get(itemEntry.getKey()));
long colorId = itemEntry.getValue().getColorId();
itemDto.setColorId(colorId);
DictionaryEntryDto dictDto = fetchValueFromDictionary(colorId);
itemDto.setColor(dictDto != null ? dictDto.getValue() : "");
long materialId = itemEntry.getValue().getMaterialId();
itemDto.setMaterialId(materialId);
dictDto = fetchValueFromDictionary(materialId);
itemDto.setMaterial(dictDto != null ? dictDto.getValue() : "");
long sizeId = itemEntry.getValue().getSizeId();
itemDto.setSizeId(sizeId);
dictDto = fetchValueFromDictionary(sizeId);
itemDto.setSize(dictDto != null ? dictDto.getValue() : "");
itemDto.setPrice(itemEntry.getKey().getPrice());
retList.add(itemDto);
}
return retList;
}
//TODO try to avoid using it
private Map<BaseTrolleyItemDto, MilitaryShopItemDto> getItemsByIds(
Map<BaseTrolleyItemDto, Integer> itemsMap) {
Map<BaseTrolleyItemDto, MilitaryShopItemDto> retMap =
new LinkedHashMap<BaseTrolleyItemDto, MilitaryShopItemDto>();
Map<BaseTrolleyItemDto, MilitaryShopItem> fullItemsMap = itemDao.getItemsByIds(itemsMap.keySet());
for (Map.Entry<BaseTrolleyItemDto, MilitaryShopItem> entry : fullItemsMap.entrySet()) {
MilitaryShopItemDto dto = new MilitaryShopItemDto();
dto.setId(entry.getValue().getKey().getId());
final Key colorKey = entry.getValue().getColorKey();
if (colorKey != null) {
dto.setColorId(colorKey.getId());
}
final Key materialKey = entry.getValue().getMaterialKey();
if (materialKey != null) {
dto.setMaterialId(materialKey.getId());
}
final Key sizeKey = entry.getValue().getSizeKey();
if (sizeKey != null) {
dto.setSizeId(sizeKey.getId());
}
dto.setProductId(entry.getValue().getProductKey().getId());
dto.setShortName(entry.getValue().getShortName());
retMap.put(entry.getKey(), dto);
}
return retMap;
}
private DictionaryEntryDto fetchValueFromDictionary(
long dictId) {
- DictionaryEntryDto dictDto;
- dictDto = dictionaryEntryService.findDictionaryEntryById(dictId);
- if (dictDto == null) {
- log.warn("Dictionary entry for id={} wasn't found", dictId);
- }
+ DictionaryEntryDto dictDto = null;
+ if (dictId != 0) {
+ dictDto = dictionaryEntryService.findDictionaryEntryById(dictId);
+ }
+ if (dictDto == null) {
+ log.warn("Dictionary entry for id={} wasn't found", dictId);
+ }
+
return dictDto;
}
}
| true | false | null | null |
diff --git a/src/main/java/me/limebyte/battlenight/api/battle/Battle.java b/src/main/java/me/limebyte/battlenight/api/battle/Battle.java
index 1eb8e32..82ddd99 100644
--- a/src/main/java/me/limebyte/battlenight/api/battle/Battle.java
+++ b/src/main/java/me/limebyte/battlenight/api/battle/Battle.java
@@ -1,434 +1,435 @@
package me.limebyte.battlenight.api.battle;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.logging.Level;
import me.limebyte.battlenight.api.BattleNightAPI;
import me.limebyte.battlenight.api.event.BattleDeathEvent;
import me.limebyte.battlenight.api.util.PlayerData;
import me.limebyte.battlenight.core.listeners.SignListener;
import me.limebyte.battlenight.core.util.Messenger;
import me.limebyte.battlenight.core.util.Messenger.Message;
import me.limebyte.battlenight.core.util.Metadata;
import me.limebyte.battlenight.core.util.SafeTeleporter;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.Player;
public abstract class Battle {
public BattleNightAPI api;
public static final int INFINITE_LIVES = -1;
private Arena arena;
private boolean inProgress = false;
private int minPlayers = 2;
private int maxPlayers = Integer.MAX_VALUE;
private int lives = INFINITE_LIVES;
private Set<String> players = new HashSet<String>();
private Set<String> spectators = new HashSet<String>();
Battle() {
}
/* --------------- */
/* General Methods */
/* --------------- */
public boolean start() {
if (isInProgress()) return false;
if (getPlayers().size() < getMinPlayers()) return false;
if (getPlayers().size() > getMaxPlayers()) return false;
if (getArena() == null || !getArena().isSetup(1) || !getArena().isEnabled()) return false;
if (!onStart()) return false;
Iterator<String> it = getPlayers().iterator();
while (it.hasNext()) {
Player player = toPlayer(it.next());
if (player == null) {
it.remove();
continue;
}
Metadata.remove(player, "ready");
Metadata.set(player, "lives", getLives());
Metadata.set(player, "kills", 0);
Metadata.set(player, "deaths", 0);
}
teleportAllToSpawn();
SignListener.cleanSigns();
inProgress = true;
return true;
}
public boolean stop() {
if (!onStop()) return false;
Iterator<String> pIt = getPlayers().iterator();
while (pIt.hasNext()) {
Player player = toPlayer(pIt.next());
if (player == null) {
pIt.remove();
continue;
}
PlayerData.reset(player);
PlayerData.restore(player, true, false);
api.setPlayerClass(player, null);
Metadata.remove(player, "lives");
Metadata.remove(player, "kills");
Metadata.remove(player, "deaths");
pIt.remove();
}
Iterator<String> sIt = getSpectators().iterator();
while (sIt.hasNext()) {
Player player = toPlayer(sIt.next());
if (player == null) {
sIt.remove();
continue;
}
PlayerData.reset(player);
PlayerData.restore(player, true, false);
api.setPlayerClass(player, null);
Metadata.remove(player, "lives");
Metadata.remove(player, "kills");
Metadata.remove(player, "deaths");
sIt.remove();
}
arena = null;
inProgress = false;
return true;
}
/**
* Adds the specified {@link Player} to the battle. This will return false
* if it is unsuccessful.
*
* @param player the Player to add
* @return true if successful
*/
public boolean addPlayer(Player player) {
if (isInProgress()) return false;
if (getArena() == null) {
if (api.getArenas().isEmpty()) {
Messenger.tell(player, "No Arenas.");
return false;
}
setArena(api.getRandomArena());
}
if (!getArena().isSetup(1)) {
Messenger.tell(player, "No Spawn Points.");
return false;
}
if (!api.getLoungeWaypoint().isSet()) {
Messenger.tell(player, Message.WAYPOINTS_UNSET);
return false;
}
PlayerData.store(player);
PlayerData.reset(player);
getPlayers().add(player.getName());
SafeTeleporter.tp(player, api.getLoungeWaypoint().getLocation());
return true;
}
/**
* Removes the specified {@link Player} to the battle. This will return
* false if it is unsuccessful.
*
* @param player the Player to remove
* @return true if successful
*/
public boolean removePlayer(Player player) {
if (!containsPlayer(player)) return false;
PlayerData.reset(player);
PlayerData.restore(player, true, false);
api.setPlayerClass(player, null);
getPlayers().remove(player.getName());
Metadata.remove(player, "ready");
Metadata.remove(player, "lives");
Metadata.remove(player, "kills");
Metadata.remove(player, "deaths");
if (shouldEnd()) stop();
return true;
}
public boolean addSpectator(Player player) {
PlayerData.store(player);
PlayerData.reset(player);
getSpectators().add(player.getName());
player.setGameMode(GameMode.ADVENTURE);
player.setAllowFlight(true);
for (String n : getPlayers()) {
if (Bukkit.getPlayerExact(n) != null) {
Bukkit.getPlayerExact(n).hidePlayer(player);
}
}
SafeTeleporter.tp(player, Bukkit.getPlayerExact((String) getPlayers().toArray()[0]).getLocation());
return true;
}
public boolean removeSpectator(Player player) {
+ if (!containsSpectator(player)) return false;
PlayerData.reset(player);
PlayerData.restore(player, true, false);
getSpectators().remove(player.getName());
return true;
}
public void respawn(Player player) {
if (!containsPlayer(player)) return;
Messenger.debug(Level.INFO, "Respawning " + player.getName() + "...");
PlayerData.reset(player);
api.getPlayerClass(player).equip(player);
SafeTeleporter.tp(player, getArena().getRandomSpawnPoint().getLocation());
}
public abstract Location toSpectator(Player player, boolean death);
/* --------------- */
/* Utility Methods */
/* --------------- */
private Player toPlayer(String name) {
Player player = Bukkit.getPlayerExact(name);
return player;
}
protected void teleportAllToSpawn() {
List<Waypoint> waypoints = getArena().getSpawnPoints();
List<Waypoint> free = waypoints;
Random random = new Random();
for (String name : getPlayers()) {
Player player = Bukkit.getPlayerExact(name);
if (player == null || !player.isOnline()) continue;
if (free.size() <= 0) free = waypoints;
int id = random.nextInt(free.size());
SafeTeleporter.tp(player, free.get(id).getLocation());
free.remove(id);
}
}
public boolean shouldEnd() {
return isInProgress() && getPlayers().size() < getMinPlayers();
}
/* ------------------- */
/* Getters and Setters */
/* ------------------- */
/**
* Returns the {@link Arena} that is set for this battle.
*
* @return the arena
* @see Arena
*/
public Arena getArena() {
return arena;
}
/**
* Sets the {@link Arena} that will be used for this battle. The arena will
* not be set if this battle is in progress.
*
* @param arena the arena to set
* @see Arena
*/
public void setArena(Arena arena) {
if (isInProgress()) return;
this.arena = arena;
}
/**
* Returns the minimum amount of players the battle requires before it can
* be started.
*
* @return the minPlayers
*/
public int getMinPlayers() {
return minPlayers;
}
/**
* Sets the minimum amount of players the battle requires before it can be
* started. This cannot be set below one.
*
* @param minPlayers the minPlayers to set
*/
public void setMinPlayers(int minPlayers) {
if (getMinPlayers() < 1) return;
this.minPlayers = minPlayers;
}
/**
* Returns the maximum amount of players the battle can have. By default
* this is set to {@link Integer.MAX_VALUE}.
*
* @return the maxPlayers
*/
public int getMaxPlayers() {
return maxPlayers;
}
/**
* Sets the maximum amount of players the battle can have. Setting this
* value will prevent players from joining if the battle is full. This
* cannot be set to a value that is less than the minimum.
*
* @param maxPlayers the maxPlayers to set
*/
public void setMaxPlayers(int maxPlayers) {
if (maxPlayers < getMinPlayers()) return;
this.maxPlayers = maxPlayers;
}
/**
* @return the lives
*/
public int getLives() {
return lives;
}
/**
* @param lives the lives to set
*/
public void setLives(int lives) {
this.lives = lives;
}
/**
* @return the inProgress
*/
public boolean isInProgress() {
return inProgress;
}
/**
* @return the players
*/
public Set<String> getPlayers() {
return players;
}
public boolean containsPlayer(Player player) {
return getPlayers().contains(player.getName());
}
public List<String> getLeadingPlayers() {
if (getPlayers().size() == 0) return null;
List<String> leading = new ArrayList<String>();
Iterator<String> it = getPlayers().iterator();
while (it.hasNext()) {
String name = it.next();
Player player = toPlayer(name);
if (player == null) {
it.remove();
continue;
}
if (leading.isEmpty()) {
leading.add(name);
continue;
}
int kills = Metadata.getInt(player, "kills");
int leadingKills = Metadata.getInt(toPlayer(leading.get(0)), "kills");
if (leadingKills == kills) {
leading.add(name);
continue;
}
if (leadingKills < kills) {
leading.clear();
leading.add(name);
continue;
}
}
return leading;
}
public String getWinMessage() {
String message;
List<String> leading = getLeadingPlayers();
if (leading.isEmpty() || leading.size() == players.size()) {
message = "Draw!";
} else if (leading.size() == 1) {
message = leading.get(0) + " won the battle!";
} else {
message = leading.toString().replaceAll("\\[|\\]", "").replaceAll("[,]([^,]*)$", " and$1") + " won the battle!";
}
return message;
}
/**
* @return the spectators
*/
public Set<String> getSpectators() {
return spectators;
}
public boolean containsSpectator(Player player) {
return getSpectators().contains(player.getName());
}
/* ------ */
/* Events */
/* ------ */
public abstract boolean onStart();
public abstract boolean onStop();
public void onPlayerDeath(BattleDeathEvent event) {
Player player = event.getPlayer();
Player killer = player.getKiller();
if (killer != null) {
Metadata.set(player, "kills", Metadata.getInt(killer, "kills") + 1);
Messenger.tell(player, "You were killed by " + ChatColor.RED + killer.getName() + ChatColor.RESET + "!");
} else {
Messenger.tell(player, "You were killed!");
}
int deaths = Metadata.getInt(player, "deaths");
int lives = Metadata.getInt(player, "lives");
Metadata.set(player, "deaths", ++deaths);
Metadata.set(player, "lives", --lives);
if (lives > 0) {
if (lives == 1) {
Messenger.tell(player, ChatColor.RED + "Last life!");
} else {
Messenger.tell(player, "You have " + lives + " lives remaining.");
}
event.setCancelled(true);
}
}
}
diff --git a/src/main/java/me/limebyte/battlenight/api/util/PlayerData.java b/src/main/java/me/limebyte/battlenight/api/util/PlayerData.java
index b62ea38..624b021 100644
--- a/src/main/java/me/limebyte/battlenight/api/util/PlayerData.java
+++ b/src/main/java/me/limebyte/battlenight/api/util/PlayerData.java
@@ -1,233 +1,234 @@
package me.limebyte.battlenight.api.util;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import me.limebyte.battlenight.api.BattleNightAPI;
import me.limebyte.battlenight.core.hooks.Nameplates;
import me.limebyte.battlenight.core.util.Messenger;
import me.limebyte.battlenight.core.util.SafeTeleporter;
import me.limebyte.battlenight.core.util.config.ConfigManager;
import me.limebyte.battlenight.core.util.config.ConfigManager.Config;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.util.Vector;
public class PlayerData {
public static BattleNightAPI api;
private static Map<String, PlayerData> storage = new HashMap<String, PlayerData>();
private Set<String> vanishedPlayers = new HashSet<String>();
private Collection<PotionEffect> potionEffects;
private boolean allowFlight;
private Location bedSpawnLocation;
private Location compassTarget;
private String displayName;
private ItemStack[] enderItems;
private float exaustion;
private float exp;
private float fallDistance;
private int fireTicks;
private float flySpeed;
private int foodLevel;
private int gameMode;
private int health;
private ItemStack[] invItems;
private ItemStack[] invArmour;
private int level;
private Location location;
private String playerListName;
private long playerTimeOffset;
private int remainingAir;
private float saturation;
private int ticksLived;
private Vector velocity;
private float walkSpeed;
private boolean flying;
private boolean playerTimeRelative;
private boolean sleepingIgnored;
private boolean sneaking;
private boolean sprinting;
private PlayerData() {
}
public static void store(Player player) {
PlayerData data = new PlayerData();
for (Player p : Bukkit.getServer().getOnlinePlayers()) {
if (!player.canSee(p)) {
data.vanishedPlayers.add(p.getName());
}
}
data.potionEffects = player.getActivePotionEffects();
data.allowFlight = player.getAllowFlight();
data.bedSpawnLocation = player.getBedSpawnLocation();
data.compassTarget = player.getCompassTarget();
data.displayName = player.getDisplayName();
data.enderItems = player.getEnderChest().getContents();
data.exaustion = player.getExhaustion();
data.exp = player.getExp();
data.fallDistance = player.getFallDistance();
data.fireTicks = player.getFireTicks();
data.flySpeed = player.getFlySpeed();
data.foodLevel = player.getFoodLevel();
data.gameMode = player.getGameMode().getValue();
data.health = player.getHealth();
data.invItems = player.getInventory().getContents();
data.invArmour = player.getInventory().getArmorContents();
data.level = player.getLevel();
data.location = player.getLocation().clone();
data.playerListName = player.getPlayerListName();
data.playerTimeOffset = player.getPlayerTimeOffset();
data.remainingAir = player.getRemainingAir();
data.saturation = player.getSaturation();
data.ticksLived = player.getTicksLived();
data.velocity = player.getVelocity();
data.walkSpeed = player.getWalkSpeed();
data.flying = player.isFlying();
data.playerTimeRelative = player.isPlayerTimeRelative();
data.sleepingIgnored = player.isSleepingIgnored();
data.sneaking = player.isSneaking();
data.sprinting = player.isSprinting();
storage.put(player.getName(), data);
}
public static boolean restore(Player player, boolean teleport, boolean keepInMemory) {
String name = player.getName();
if (!storage.containsKey(name)) {
Messenger.debug(Level.SEVERE, "Failed to restore " + name + "!");
return false;
}
PlayerData data = storage.get(name);
+ boolean exit = ConfigManager.get(Config.MAIN).getBoolean("ExitWaypoint", false);
if (teleport) {
- if (ConfigManager.get(Config.MAIN).getBoolean("ExitWaypoint", false) && api.getExitWaypoint().isSet()) {
+ if (exit && api.getExitWaypoint().isSet()) {
SafeTeleporter.tp(player, api.getExitWaypoint().getLocation());
} else {
SafeTeleporter.tp(player, data.location);
}
}
for (Player p : Bukkit.getServer().getOnlinePlayers()) {
if (data.vanishedPlayers.contains(p.getName())) {
player.hidePlayer(p);
} else {
player.showPlayer(p);
}
}
for (PotionEffect effect : player.getActivePotionEffects()) {
player.addPotionEffect(new PotionEffect(effect.getType(), 0, 0), true);
}
player.addPotionEffects(data.potionEffects);
player.setAllowFlight(data.allowFlight);
if (data.bedSpawnLocation != null) {
player.setBedSpawnLocation(data.bedSpawnLocation);
} else {
player.setBedSpawnLocation(player.getWorld().getSpawnLocation(), true);
}
player.setCompassTarget(data.compassTarget);
player.setDisplayName(data.displayName);
player.getEnderChest().setContents(data.enderItems);
player.setExhaustion(data.exaustion);
player.setExp(data.exp);
player.setFallDistance(data.fallDistance);
player.setFireTicks(data.fireTicks);
player.setFlySpeed(data.flySpeed);
player.setFoodLevel(data.foodLevel);
player.setGameMode(GameMode.getByValue(data.gameMode));
player.setHealth(data.health);
player.getInventory().setContents(data.invItems);
player.getInventory().setArmorContents(data.invArmour);
player.setLevel(data.level);
player.setPlayerListName(data.playerListName);
if (!data.playerTimeRelative) {
player.setPlayerTime(data.playerTimeOffset, true);
} else {
player.resetPlayerTime();
}
player.setRemainingAir(data.remainingAir);
player.setSaturation(data.saturation);
player.setTicksLived(data.ticksLived);
player.setVelocity(data.velocity);
player.setWalkSpeed(data.walkSpeed);
player.setFlying(data.flying);
player.setSleepingIgnored(data.sleepingIgnored);
player.setSneaking(data.sneaking);
player.setSprinting(data.sprinting);
Nameplates.refresh(player);
if (!keepInMemory) {
storage.remove(name);
}
return true;
}
public static void reset(Player player) {
for (Player p : Bukkit.getServer().getOnlinePlayers()) {
if (!player.canSee(p)) {
player.showPlayer(p);
}
}
for (PotionEffect effect : player.getActivePotionEffects()) {
player.addPotionEffect(new PotionEffect(effect.getType(), 0, 0), true);
}
player.setFlying(false);
player.setAllowFlight(false);
player.getEnderChest().clear();
player.setExhaustion(0);
player.setExp(0);
player.setFallDistance(0);
player.setFireTicks(0);
player.setFoodLevel(20);
player.setGameMode(GameMode.SURVIVAL);
player.setHealth(player.getMaxHealth());
player.getInventory().clear();
player.getInventory().setArmorContents(new ItemStack[player.getInventory().getArmorContents().length]);
player.setLevel(0);
String pListName = ChatColor.GRAY + "[BN] " + player.getName();
player.setPlayerListName(pListName.length() < 16 ? pListName : pListName.substring(0, 16));
player.resetPlayerTime();
player.setRemainingAir(player.getMaximumAir());
player.setSaturation(20);
player.setTicksLived(1);
player.setVelocity(new Vector());
player.setWalkSpeed(0.2F);
player.setSleepingIgnored(true);
player.setSneaking(false);
player.setSprinting(false);
Nameplates.refresh(player);
}
public static Location getSavedLocation(Player player) {
String name = player.getName();
if (!storage.containsKey(name)) return null;
return storage.get(name).location;
}
public static boolean storageContains(Player player) {
return storage.containsKey(player.getName());
}
}
| false | false | null | null |
diff --git a/mbt/src/org/tigris/mbt/generators/ShortestPathGenerator.java b/mbt/src/org/tigris/mbt/generators/ShortestPathGenerator.java
index c11f05b..846881a 100644
--- a/mbt/src/org/tigris/mbt/generators/ShortestPathGenerator.java
+++ b/mbt/src/org/tigris/mbt/generators/ShortestPathGenerator.java
@@ -1,205 +1,206 @@
package org.tigris.mbt.generators;
import java.util.Comparator;
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.Stack;
import java.util.Vector;
import org.apache.log4j.Logger;
import org.tigris.mbt.FiniteStateMachine;
import org.tigris.mbt.Util;
import org.tigris.mbt.exceptions.FoundNoEdgeException;
import org.tigris.mbt.generators.PathGenerator;
import edu.uci.ics.jung.graph.impl.DirectedSparseEdge;
import edu.uci.ics.jung.graph.impl.DirectedSparseVertex;
public class ShortestPathGenerator extends PathGenerator {
static Logger logger = Util.setupLogger(ShortestPathGenerator.class);
private Stack preCalculatedPath = null;
private DirectedSparseVertex lastState;
public void setMachine(FiniteStateMachine machine) {
super.setMachine(machine);
}
public String[] getNext() {
Util.AbortIf(!hasNext(), "No more lines available");
if(lastState == null || lastState != getMachine().getCurrentState() || preCalculatedPath == null || preCalculatedPath.size() == 0)
{
boolean oldCalculatingPathValue = getMachine().isCalculatingPath();
getMachine().setCalculatingPath(true);
preCalculatedPath = a_star();
getMachine().setCalculatingPath(oldCalculatingPathValue);
if(preCalculatedPath == null)
{
throw new RuntimeException( "No path found to " + this.getStopCondition() );
}
// reverse path
Stack temp = new Stack();
while( preCalculatedPath.size() > 0 )
{
temp.push(preCalculatedPath.pop());
}
preCalculatedPath = temp;
}
DirectedSparseEdge edge = (DirectedSparseEdge) preCalculatedPath.pop();
getMachine().walkEdge(edge);
lastState = getMachine().getCurrentState();
String[] retur = {getMachine().getEdgeName(edge), getMachine().getCurrentStateName()};
return retur;
}
private Stack a_star()
{
Vector closed = new Vector();
PriorityQueue q = new PriorityQueue(10, new Comparator(){
public int compare(Object arg0, Object arg1) {
if(arg0 instanceof weightedPath && arg1 instanceof weightedPath)
{
int retur = Double.compare(((weightedPath)arg0).getWeight(), ((weightedPath)arg1).getWeight());
if(retur == 0)
retur = ((weightedPath)arg0).getPath().size() - ((weightedPath)arg1).getPath().size();
return retur;
}
throw new RuntimeException("Could not compare '"+arg0.getClass().getName()+"' with '"+arg1.getClass().getName()+"' as they are not both instances of 'weightedPath'");
}
});
Set availableOutEdges;
try {
availableOutEdges = getMachine().getCurrentOutEdges();
} catch (FoundNoEdgeException e) {
throw new RuntimeException("No available edges found at "+ getMachine().getCurrentStateName(), e );
}
for(Iterator i=availableOutEdges.iterator(); i.hasNext();)
{
DirectedSparseEdge y = (DirectedSparseEdge) i.next();
Stack s = new Stack();
s.push(y);
q.add(getWeightedPath(s));
}
-
+ double maxWeight = 0;
while(q.size() > 0)
{
weightedPath p = (weightedPath) q.poll();
+ if(p.getWeight() > maxWeight) maxWeight = p.getWeight();
if( p.getWeight() > 0.99999) // are we done yet?
return p.getPath();
DirectedSparseEdge x = (DirectedSparseEdge) p.getPath().peek();
// have we been here before?
- if(closed.contains(Util.getCompleteName(x)+p.getSubState()))
+ if(closed.contains(Util.getCompleteName(x)+p.getSubState()+p.getWeight()))
continue; // ignore this and move on
// We don't want to use this edge again as this path is
// the fastest, and if we come here again we have used more
// steps to get here than we used this time.
- closed.add(Util.getCompleteName(x)+p.getSubState());
+ closed.add(Util.getCompleteName(x)+p.getSubState()+p.getWeight());
availableOutEdges = getPathOutEdges(p.getPath());
if(availableOutEdges != null && availableOutEdges.size()>0)
{
for(Iterator i=availableOutEdges.iterator(); i.hasNext();)
{
DirectedSparseEdge y = (DirectedSparseEdge) i.next();
Stack newStack = (Stack)p.getPath().clone();
newStack.push(y);
q.add(getWeightedPath(newStack));
}
}
}
- throw new RuntimeException("No path found to satisfy stop condition "+getStopCondition());
+ throw new RuntimeException("No path found to satisfy stop condition "+getStopCondition() +", best path satified only "+ (int)(maxWeight*100) +"% of condition.");
}
private weightedPath getWeightedPath(Stack path)
{
double weight = 0;
String subState = "";
getMachine().storeState();
getMachine().walkEdge(path);
weight = getConditionFulfillment();
String currentState = getMachine().getCurrentStateName();
if(currentState.contains("/"))
{
subState = currentState.split("/",2)[1];
}
getMachine().restoreState();
return new weightedPath(path, weight, subState);
}
private Set getPathOutEdges(Stack path)
{
Set retur = null;
getMachine().storeState();
getMachine().walkEdge(path);
try {
retur = getMachine().getCurrentOutEdges();
} catch (FoundNoEdgeException e) {
// no edges found? degrade gracefully and return the default value of null.
}
getMachine().restoreState();
return retur;
}
/**
* Will reset the generator to its initial state.
*/
public void reset()
{
preCalculatedPath = null;
}
public String toString() {
return "SHORTEST{"+ super.toString() +"}";
}
private class weightedPath{
private double weight;
private Stack path;
private String subState;
public String getSubState() {
return subState;
}
public void setSubState(String subState) {
this.subState = subState;
}
public Stack getPath() {
return path;
}
public void setPath(Stack path) {
this.path = path;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public weightedPath(Stack path, double weight, String subState) {
setPath(path);
setWeight(weight);
setSubState(subState);
}
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/main/java/net/dandielo/citizens/traders_v3/bukkit/commands/TraderCommands.java b/src/main/java/net/dandielo/citizens/traders_v3/bukkit/commands/TraderCommands.java
index b5d5b69..d0135bb 100644
--- a/src/main/java/net/dandielo/citizens/traders_v3/bukkit/commands/TraderCommands.java
+++ b/src/main/java/net/dandielo/citizens/traders_v3/bukkit/commands/TraderCommands.java
@@ -1,687 +1,688 @@
package net.dandielo.citizens.traders_v3.bukkit.commands;
import java.util.Map;
import org.bukkit.ChatColor;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.api.trait.trait.MobType;
import net.dandielo.citizens.traders_v3.tNpcManager;
import net.dandielo.citizens.traders_v3.tNpcStatus;
import net.dandielo.citizens.traders_v3.bukkit.DtlTraders;
import net.dandielo.citizens.traders_v3.core.commands.Command;
import net.dandielo.citizens.traders_v3.core.events.trader.TraderCreateEvent;
import net.dandielo.citizens.traders_v3.core.exceptions.InvalidTraderTypeException;
import net.dandielo.citizens.traders_v3.core.exceptions.TraderTypeNotFoundException;
import net.dandielo.citizens.traders_v3.core.locale.LocaleManager;
import net.dandielo.citizens.traders_v3.traders.Trader;
import net.dandielo.citizens.traders_v3.traders.setting.Settings;
import net.dandielo.citizens.traders_v3.traders.setting.TGlobalSettings;
import net.dandielo.citizens.traders_v3.traders.stock.StockItem;
import net.dandielo.citizens.traders_v3.traits.TraderTrait;
import net.dandielo.citizens.traders_v3.traits.WalletTrait;
import net.dandielo.citizens.traders_v3.utils.items.attributes.Price;
/**
* Holds all Trader specific commands as methods
* @author dandielo
*
*/
public class TraderCommands {
private static LocaleManager locale = LocaleManager.locale;
/**
* Creates a new trader on the senders position. For creating the trader this command needs to have specified his name. The name should be parsed as a entry in the args Map, under the "free" key.
* @param plugin
* This plugin
* @param sender
* The command sender
* @param trader
* that took part when the command was executed
* @param args
* additional arguments, like name, type and entity type
* @throws TraderTypeNotFoundException
* @throws InvalidTraderTypeException
*/
@Command(
name = "trader",
syntax = "create {args}",
perm = "dtl.trader.commands.create",
desc = "creates a new trader with the given arguments | 'e:', 't:'",
usage = "- /trader create Wool trader e:sheep t:server",
npc = false)
public void traderCreate(DtlTraders plugin, Player sender, Trader trader, Map<String, String> args) throws TraderTypeNotFoundException, InvalidTraderTypeException
{
//get the traders name
String name = args.get("free");
//get the entity
EntityType entity = EntityType.fromName(args.get("e") == null ? "player" : args.get("e"));
//the the type
String type = args.get("t") == null ? "server" : args.get("t");
if ( name == null )
{
locale.sendMessage(sender, "error-argument-missing", "argument", "#name");
return;
}
//if entity is still null set it to player
if(entity == null) entity = EntityType.PLAYER;
//Create the npc
NPC npc = CitizensAPI.getNPCRegistry().createNPC(entity, name);
//add Traits
npc.addTrait(TraderTrait.class);
npc.addTrait(WalletTrait.class);
//set the walet trait
WalletTrait wallet = npc.getTrait(WalletTrait.class);
wallet.setType(TGlobalSettings.getDefaultWallet());
wallet.setMoney(TGlobalSettings.getWalletStartBalance());
//set the mob type
npc.addTrait(MobType.class);
npc.getTrait(MobType.class).setType(entity);
//spawn and the location of the sender
npc.spawn(sender.getLocation());
//create a test Trader Npc
Trader nTrader = (Trader) tNpcManager.create_tNpc(npc, type, sender, TraderTrait.class);
nTrader.getSettings().setType(type);
//start with the unlocked status, to allow fast stock setting
nTrader.parseStatus(tNpcStatus.MANAGE_SELL);
nTrader.parseStatus(tNpcStatus.MANAGE_UNLOCKED);
//register the relation
tNpcManager.instance().registerRelation(sender, nTrader);
//send messages
locale.sendMessage(sender, "trader-created", "player", sender.getName(), "trader", name);
locale.sendMessage(sender, "trader-managermode-enabled", "npc", npc.getName());
locale.sendMessage(sender, "trader-managermode-toggled", "mode", "#stock-sell");
//send the Trader Create event
new TraderCreateEvent(nTrader, sender).callEvent();
}
/**
* Allows to change the stock name for a specified trader
* @param plugin
* This plugin
* @param sender
* The command sender
* @param trader
* that took part when the command was executed
* @param args
* additional arguments, like name, type and entity type
* @throws TraderTypeNotFoundException
* @throws InvalidTraderTypeException
*/
@Command(
name = "trader",
syntax = "stockname <action> {args}",
perm = "dtl.trader.commands.stockname",
desc = "Shows/resets or changes the stock name",
usage = "- /trader stockname set Santas Stock",
npc = true)
public void settingStockName(DtlTraders plugin, Player sender, Trader trader, Map<String, String> args)
{
String action = args.get("action");
//if we should set the setting
if ( action.equals("set") )
{
//check the argument
if ( args.get("free") == null )
{
locale.sendMessage(sender, "error-argument-missing", "argument", "{args}");
return;
}
//set the new stock name
trader.getSettings().setStockFormat(args.get("free"));
//send a message
locale.sendMessage(sender, "key-change",
"key", "#stock-name",
"value", trader.getSettings().getStockFormat());
}
else
//reset the setting to the global default
if ( action.equals("reset") )
{
//set to default
trader.getSettings().setStockFormat(Settings.getGlobalStockNameFormat());
//send a message
locale.sendMessage(sender, "key-change",
"key", "#stock-name",
"value", trader.getSettings().getStockFormat());
}
else
//show the setting
if ( action.equals("show") )
{
//send the current setting
locale.sendMessage(sender, "key-value",
"key", "#stock-name",
"value", trader.getSettings().getStockFormat());
}
//send a error message
else
{
locale.sendMessage(sender, "error-argument-invalid", "argument", "<action>");
}
}
/**
* Allows to change the stock size for a specified trader
* @param plugin
* This plugin
* @param sender
* The command sender
* @param trader
* that took part when the command was executed
* @param args
* additional arguments, like name, type and entity type
* @throws TraderTypeNotFoundException
* @throws InvalidTraderTypeException
*/
@Command(
name = "trader",
syntax = "stocksize <action> (size)",
perm = "dtl.trader.commands.stocksize",
desc = "Shows/resets or changes the stock size",
usage = "- /trader stocksize set 5",
npc = true)
public void settingStockSize(DtlTraders plugin, Player sender, Trader trader, Map<String, String> args)
{
String action = args.get("action");
//if we should set the setting
if ( action.equals("set") )
{
//check the argument
if ( args.get("size") == null )
{
locale.sendMessage(sender, "error-argument-missing", "argument", "(size)");
return;
}
//is the size valid?
int size = Integer.parseInt(args.get("size"));
if ( size < 0 || size > 6 )
{
locale.sendMessage(sender, "error-argument-invalid", "argument", "(size)");
return;
}
//set the new stock name
trader.getSettings().setStockSize( size );
//send a message
locale.sendMessage(sender, "key-change",
"key", "#stock-size",
"value", String.valueOf(trader.getSettings().getStockSize()));
}
else
//reset the setting to the global default
if ( action.equals("reset") )
{
//set to default
trader.getSettings().setStockSize( Settings.getGlobalStockSize() );
//send a message
locale.sendMessage(sender, "key-change",
"key", "#stock-size",
"value", String.valueOf(trader.getSettings().getStockSize()));
}
else
//show the setting
if ( action.equals("show") )
{
//send the current setting
locale.sendMessage(sender, "key-value",
"key", "#stock-size",
"value", String.valueOf(trader.getSettings().getStockSize()));
}
//send a error message
else
{
locale.sendMessage(sender, "error-argument-invalid", "argument", "<action>");
}
}
/**
* Allows to change the starting stock for the specified trader
* @param plugin
* This plugin
* @param sender
* The command sender
* @param trader
* that took part when the command was executed
* @param args
* additional arguments, like name, type and entity type
* @throws TraderTypeNotFoundException
* @throws InvalidTraderTypeException
*/
@Command(
name = "trader",
syntax = "startstock <action> (stock)",
perm = "dtl.trader.commands.startstock",
desc = "Shows/resets or changes the starting stock (buy|sell)",
usage = "- /trader startstock set buy",
npc = true)
public void settingStockStart(DtlTraders plugin, Player sender, Trader trader, Map<String, String> args)
{
String action = args.get("action");
//if we should set the setting
if ( action.equals("set") )
{
//check the argument
if ( args.get("stock") == null )
{
locale.sendMessage(sender, "error-argument-missing", "argument", "(stock)");
return;
}
//set the new stock name
trader.getSettings().setStockStart( args.get("stock") );
//send a message
locale.sendMessage(sender, "key-change",
"key", "#stock-start",
"value", trader.getSettings().getStockStart());
}
else
//reset the setting to the global default
if ( action.equals("reset") )
{
//set to default
trader.getSettings().setStockStart( Settings.getGlobalStockStart() );
//send a message
locale.sendMessage(sender, "key-change",
"key", "#stock-start",
"value", trader.getSettings().getStockStart());
}
else
//show the setting
if ( action.equals("show") )
{
//send the current setting
locale.sendMessage(sender, "key-value",
"key", "#stock-start",
"value", trader.getSettings().getStockStart());
}
//send a error message
else
{
locale.sendMessage(sender, "error-argument-invalid", "argument", "<action>");
}
}
/**
* Allows to change the traders wallet and it's settings
* @param plugin
* This plugin
* @param sender
* The command sender
* @param trader
* that took part when the command was executed
* @param args
* additional arguments, like name, type and entity type
* @throws TraderTypeNotFoundException
* @throws InvalidTraderTypeException
*/
@Command(
name = "trader",
syntax = "wallet <option> <action> (value)",
perm = "dtl.trader.commands.wallet",
desc = "Shows/sets the wallet type or its settings (infinite|private|owner|player)",
usage = "- /trader wallet set type player",
npc = true)
public void settingWallet(DtlTraders plugin, Player sender, Trader trader, Map<String, String> args)
{
String option = args.get("option");
String action = args.get("action");
if ( action.equals("set") )
{
//get the value
String value = args.get("value");
//throw an error if the value is null
if ( value == null )
{
locale.sendMessage(sender, "error-argument-missing", "argument", "(value)");
return;
}
//depending on the option set the new value
WalletTrait wallet = trader.getNPC().getTrait(WalletTrait.class);
if ( option.equals("type") )
{
//set the new wallet type
wallet.setType(value);
//send a message
locale.sendMessage(sender, "key-change",
"key", "#wallet-type",
"value", wallet.getType());
}
else
if ( option.equals("player") )
{
wallet.setPlayer(value);
//send a message
locale.sendMessage(sender, "key-change",
"key", "#wallet-player",
"value", wallet.getPlayer());
}
else
if ( option.equals("amount") )
{
try
{
wallet.setMoney(Double.parseDouble(value));
//send a message
locale.sendMessage(sender, "key-change",
"key", "#wallet-balance",
"value", String.valueOf(wallet.getBalance()) );
}
catch(NumberFormatException e)
{
locale.sendMessage(sender, "error-argument-invalid", "argument", "(value)");
}
}
else
{
locale.sendMessage(sender, "error-argument-invalid", "argument", "<option>");
}
}
else
if ( action.equals("show") )
{
//depending on the option show the value
WalletTrait wallet = trader.getNPC().getTrait(WalletTrait.class);
if ( option.equals("type") )
{
//send a message
locale.sendMessage(sender, "key-value",
"key", "#wallet-type",
"value", wallet.getType());
}
else
if ( option.equals("player") )
{
//send a message
locale.sendMessage(sender, "key-value",
"key", "#wallet-player",
"value", wallet.getPlayer());
}
else
if ( option.equals("amount") )
{
//send a message
locale.sendMessage(sender, "key-value",
"key", "#wallet-balance",
"value", String.valueOf(wallet.getBalance()) );
}
else
{
locale.sendMessage(sender, "error-argument-invalid", "argument", "<option>");
}
}
else
{
locale.sendMessage(sender, "error-argument-invalid", "argument", "<action>");
}
}
/**
* Allows to change the starting stock for the specified trader
* @param plugin
* This plugin
* @param sender
* The command sender
* @param trader
* that took part when the command was executed
* @param args
* additional arguments, like name, type and entity type
* @throws TraderTypeNotFoundException
* @throws InvalidTraderTypeException
*/
@Command(
name = "trader",
syntax = "sellprice {args}",
perm = "dtl.trader.commands.sellprice",
desc = "Sets price to an item that matches the string",
usage = "- /trader sellprice 33 p:12.11",
npc = true)
public void sellprice(DtlTraders plugin, Player sender, Trader trader, Map<String, String> args)
{
String itemString = args.get("free");
+
+ int items = 0;
+ StockItem price = new StockItem(itemString);
for ( StockItem item : trader.getStock().getStock("sell") )
{
- StockItem price = new StockItem(itemString);
- int items = 0;
if ( item.priorityMatch(price) >= 0 )
{
++items;
if ( item.hasAttr(Price.class) )
item.getPriceAttr().setPrice(price.getPrice());
else
item.addAttr("p", price.getPriceFormated());
}
-
- //send message
- locale.sendMessage(sender, "trader-stock-price-set", "items", String.valueOf(items));
}
+ //send message
+ locale.sendMessage(sender, "trader-stock-price-set", "items", String.valueOf(items));
}
@Command(
name = "trader",
syntax = "buyprice {args}",
perm = "dtl.trader.commands.buyprice",
desc = "Sets price to an item that matches the string",
usage = "- /trader buyprice 33 p:12.11",
npc = true)
public void buyprice(DtlTraders plugin, Player sender, Trader trader, Map<String, String> args)
{
String itemString = args.get("free");
int items = 0;
+
+ StockItem price = new StockItem(itemString);
for ( StockItem item : trader.getStock().getStock("buy") )
{
- StockItem price = new StockItem(itemString);
if ( price.priorityMatch(item) >= 0 )
{
++items;
if ( item.hasAttr(Price.class) )
item.getPriceAttr().setPrice(price.getPrice());
else
item.addAttr("p", price.getPriceFormated());
}
}
//send message
locale.sendMessage(sender, "trader-stock-price-set", "items", String.valueOf(items));
}
@Command(
name = "trader",
syntax = "reset <option>",
perm = "dtl.trader.commands.reset",
npc = true)
public void resetSettings(DtlTraders plugin, Player sender, Trader trader, Map<String, String> args)
{
if ( args.get("option").equals("prices") )
{
//remove all prices attributes
for ( StockItem item : trader.getStock().getStock("sell") )
item.removeAttr(Price.class);
//send a message
locale.sendMessage(sender, "trader-stock-price-reset");
}
else
{
//error action arg invalid
locale.sendMessage(sender, "error-argument-invalid", "argument", "<action>");
}
}
@Command(
name = "trader",
syntax = "pattern <action> (pattern)",
perm = "dtl.trader.commands.pattern",
desc = "Allows to manage patterns for a trader",
usage = "- /trader pattern set pattern_na,e",
npc = true)
//Action set/remove/add/clear/reload/show/
public void setPattern(DtlTraders plugin, Player sender, Trader trader, Map<String, String> args)
{
//show all patterns
if ( args.get("action").equals("show") )
{
String result = "";
for ( String pat : trader.getSettings().getPatterns() )
result += ChatColor.DARK_AQUA + pat + ", " + ChatColor.RESET;
//send the message
locale.sendMessage(sender, "key-value", "key", "#pattern-list", "value", result);
}
else
//add a pattern
if ( args.get("action").equals("add") )
{
if ( !args.containsKey("pattern") )
{
locale.sendMessage(sender, "error-argument-missing", "argument", "(pattern)");
return;
}
//add the new pattern
trader.getSettings().getPatterns().add(args.get("pattern"));
//added message
locale.sendMessage(sender, "key-change", "key", "#pattern-add", "value", args.get("pattern"));
}
else
//remove a pattern
if ( args.get("action").equals("remove") )
{
if ( !args.containsKey("pattern") )
{
locale.sendMessage(sender, "error-argument-missing", "argument", "(pattern)");
return;
}
//remove the pattern
trader.getSettings().getPatterns().remove(args.get("pattern"));
//added message
locale.sendMessage(sender, "key-change", "key", "#pattern-remove", "value", args.get("pattern"));
}
else
//remove all patterns
if ( args.get("action").equals("removeall") )
{
//pattern list
String result = "";
for ( String pat : trader.getSettings().getPatterns() )
result += ChatColor.DARK_AQUA + pat + ", " + ChatColor.RESET;
//clear the pattern list
trader.getSettings().getPatterns().clear();
//added message
locale.sendMessage(sender, "key-change", "key","#pattern-remove-all", "value", result);
}
else
//set back to default
if ( args.get("action").equals("default") )
{
//set defaults
trader.getSettings().getPatterns().clear();
trader.getSettings().getPatterns().addAll(Settings.defaultPatterns());
//pattern list
String result = "";
for ( String pat : trader.getSettings().getPatterns() )
result += ChatColor.DARK_AQUA + pat + ", " + ChatColor.RESET;
//added message
locale.sendMessage(sender, "key-change", "key","#pattern-default", "value", result);
}
else
{
//error action arg invalid
locale.sendMessage(sender, "error-argument-invalid", "argument", "<action>");
}
}
/*
@SerializableAs("dice")
static class Dice implements ConfigurationSerializable
{
int x = 2;
int y = 3;
public Dice(int x, int y)
{
}
public Dice(Map<String, Object> m)
{
x = (Integer) m.get("x");
y = (Integer) m.get("y");
}
@Override
public Map<String, Object> serialize()
{
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("x", x);
map.put("y", y);
return map;
}
public Dice deserialize(Map<String, Object> m)
{
return new Dice(m);
}
public Dice valueOf(Map<String, Object> m)
{
return new Dice(m);
}
}
public static void main(String[] a)
{
YamlConfiguration yaml = new YamlConfiguration();
ConfigurationSerialization.registerClass(Dice.class, "dice");
yaml.set("test", new Dice(2, 3));
System.out.print(yaml.saveToString());
}*/
}
diff --git a/src/main/java/net/dandielo/citizens/traders_v3/tNpcListener.java b/src/main/java/net/dandielo/citizens/traders_v3/tNpcListener.java
index 1a3ae48..7b32f61 100644
--- a/src/main/java/net/dandielo/citizens/traders_v3/tNpcListener.java
+++ b/src/main/java/net/dandielo/citizens/traders_v3/tNpcListener.java
@@ -1,477 +1,474 @@
package net.dandielo.citizens.traders_v3;
-import java.util.Timer;
-import java.util.TimerTask;
-
import net.citizensnpcs.api.event.NPCLeftClickEvent;
import net.citizensnpcs.api.event.NPCRightClickEvent;
import net.dandielo.api.traders.tNpcAPI;
import net.dandielo.citizens.traders_v3.bankers.Banker;
import net.dandielo.citizens.traders_v3.bukkit.DtlTraders;
import net.dandielo.citizens.traders_v3.bukkit.Perms;
import net.dandielo.citizens.traders_v3.core.PluginSettings;
import net.dandielo.citizens.traders_v3.core.dB;
import net.dandielo.citizens.traders_v3.core.dB.DebugLevel;
import net.dandielo.citizens.traders_v3.core.exceptions.InvalidTraderTypeException;
import net.dandielo.citizens.traders_v3.core.exceptions.TraderTypeNotFoundException;
import net.dandielo.citizens.traders_v3.core.locale.LocaleManager;
import net.dandielo.citizens.traders_v3.traders.Trader;
import net.dandielo.citizens.traders_v3.traits.BankerTrait;
import net.dandielo.citizens.traders_v3.traits.TraderTrait;
import net.dandielo.citizens.traders_v3.utils.NBTUtils;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;
public class tNpcListener implements Listener {
/**
* Permissions manager instance
*/
Perms perms = Perms.perms;
/**
* Locale manager instance
*/
LocaleManager locale = LocaleManager.locale;
// InventoryCleaner cleaner = new InventoryCleaner();
private static tNpcListener instance = new tNpcListener();
public static tNpcListener instance()
{
return instance;
}
//class definition
tNpcManager manager = tNpcManager.instance();
public tNpcListener()
{
// cleaner.start();
}
//general events
@EventHandler
public void inventoryClickEvent(InventoryClickEvent e)
{
tNpc trader = manager.getRelation(e.getWhoClicked().getName(), tNpc.class);
if ( trader != null )
{
if ( trader.getStatus().inManagementMode() )
trader.onManageInventoryClick(e);
else
trader.onInventoryClick(e);
}
}
@EventHandler
public void onLogoutRemoving(PlayerQuitEvent e)
{
int i = 0;
for ( ItemStack item : e.getPlayer().getInventory().getContents() )
{
if ( item != null )
{
if ( NBTUtils.isMarked(item) )
{
//send specific debug messages
dB.spec(DebugLevel.S1_ADONDRIEL, "Marked item found on player quit event");
dB.spec(DebugLevel.S1_ADONDRIEL, "Item: ", item);
//remove the item
e.getPlayer().getInventory().setItem(i, null);
}
}
++i;
}
}
@EventHandler
public void onLoginRemoving(PlayerJoinEvent e)
{
int i = 0;
for ( ItemStack item : e.getPlayer().getInventory().getContents() )
{
if ( item != null )
{
if ( NBTUtils.hasTraderLore(item) )
{
//send specific debug messages
dB.spec(DebugLevel.S1_ADONDRIEL, "Item with trader price lore found on player join event");
dB.spec(DebugLevel.S1_ADONDRIEL, "Item: ", item);
//remove the item
e.getPlayer().getInventory().setItem(i, null);
}
}
++i;
}
}
//remove marked items on inventory click events
@EventHandler
public void markedItemRemoval(InventoryClickEvent e)
{
int i = 0;
for ( ItemStack item : e.getWhoClicked().getInventory().getContents() )
{
if ( item != null )
{
if ( NBTUtils.isMarked(item) ||
( !tNpcAPI.isTNpcInventory((Player) e.getWhoClicked()) && NBTUtils.hasTraderLore(item) ) )
{
//send specific debug messages
dB.spec(DebugLevel.S1_ADONDRIEL, "Marked item found on player inventory click");
dB.spec(DebugLevel.S1_ADONDRIEL, "Marked: ", NBTUtils.isMarked(item));
dB.spec(DebugLevel.S1_ADONDRIEL, "Lore: ", NBTUtils.hasTraderLore(item));
dB.spec(DebugLevel.S1_ADONDRIEL, "Item: ", item);
//remove the item
e.getWhoClicked().getInventory().setItem(i, null);
}
}
++i;
}
}
//remove marked items on inventory open events
@EventHandler
public void inventoryOpenEvent(InventoryOpenEvent e)
{
}
@EventHandler(priority = EventPriority.LOW)
public void inventoryCloseEvent(InventoryCloseEvent e)
{
tNpc npc = manager.getRelation(e.getPlayer().getName(), tNpc.class);
if ( npc != null )
{
//unregister the inventory as a traderInventory
manager.removeOpenedInventory((Player) e.getPlayer());
//if the trader is not in mm, remove the relation too
if ( !npc.getStatus().inManagementMode() )
{
//check accounts for unlocked stock
if ( npc.getStatus().equals(tNpcStatus.ACCOUNT_UNLOCKED) )
{
//lock and save the content first
npc.lockAndSave();
}
//remove the relation
manager.removeRelation((Player) e.getPlayer());
//send specific debug info
dB.spec(DebugLevel.S1_ADONDRIEL, "Adding player inventory to the cleaning querry");
//clean his inventory
//cleaner.addPlayer((Player) e.getPlayer());
new InventoryCleaner((Player) e.getPlayer());
}
//in the mode is MANAGE_UNLOCKED, lock it and save items
else
{
if ( npc.getStatus().equals(tNpcStatus.MANAGE_UNLOCKED) )
{
//lock and save the inventory
npc.lockAndSave();
}
if ( npc.getStatus().equals(tNpcStatus.MANAGE_PRICE) )
{
//remove all special block lores
((Trader)npc).setSpecialBlockPrices();
}
}
}
}
//npc events for traders
@EventHandler(priority=EventPriority.HIGHEST)
public void npcLeftClickEvent(NPCLeftClickEvent e)
{
//check trait
if ( !e.getNPC().hasTrait(TraderTrait.class) ) return;
//check permission
if ( !perms.has(e.getClicker(), "dtl.trader.use") )
{
locale.sendMessage(e.getClicker(), "error-nopermission");
return;
}
//dont allow creative to open traders
if ( e.getClicker().getGameMode().equals(GameMode.CREATIVE)
&& !perms.has(e.getClicker(), "dtl.trader.bypass.creative") )
{
locale.sendMessage(e.getClicker(), "error-nopermission-creative");
return;
}
TraderTrait traderTrait = e.getNPC().getTrait(TraderTrait.class);
Trader trader;
try
{
if ( !manager.inRelation(e.getClicker()) )
{
trader = (Trader) tNpcManager.create_tNpc(e.getNPC(), traderTrait.getType(), e.getClicker(), TraderTrait.class);
manager.registerRelation(e.getClicker(), trader);
}
else
{
trader = manager.getTraderRelation(e.getClicker());
if ( !trader.equals(e.getNPC()) )
{
manager.removeRelation(e.getClicker());
trader = (Trader) tNpcManager.create_tNpc(e.getNPC(), traderTrait.getType(), e.getClicker(), TraderTrait.class);
manager.registerRelation(e.getClicker(), trader);
}
}
trader.onLeftClick(e.getClicker().getItemInHand());
if ( !trader.getStatus().inManagementMode() )
manager.removeRelation(e.getClicker());
}
catch (TraderTypeNotFoundException e1)
{
//debug critical
dB.critical("Trader type was not found, type: ", traderTrait.getType());
dB.critical("Did you changed the save file?");
}
catch (InvalidTraderTypeException e1)
{
//debug critical
dB.critical("Trader type is invalid, type: ", traderTrait.getType());
dB.critical("Contact the dev to fix this!");
}
}
@EventHandler(priority=EventPriority.HIGHEST)
public void npcRightClickEvent(NPCRightClickEvent e)
{
//check trait
if ( !e.getNPC().hasTrait(TraderTrait.class) ) return;
//check permission
if ( !perms.has(e.getClicker(), "dtl.trader.use") )
{
locale.sendMessage(e.getClicker(), "error-nopermission");
return;
}
//dont allow creative to open traders
if ( e.getClicker().getGameMode().equals(GameMode.CREATIVE)
&& !perms.has(e.getClicker(), "dtl.trader.bypass.creative") )
{
locale.sendMessage(e.getClicker(), "error-nopermission-creative");
return;
}
TraderTrait traderTrait = e.getNPC().getTrait(TraderTrait.class);
Trader trader;
try
{
if ( !manager.inRelation(e.getClicker()) )
{
trader = (Trader) tNpcManager.create_tNpc(e.getNPC(), traderTrait.getType(), e.getClicker(), TraderTrait.class);
manager.registerRelation(e.getClicker(), trader);
}
else
{
trader = manager.getTraderRelation(e.getClicker());
//check if its the same NPC if not then close the old manager mode and open the next NPC i normal mode
if ( !trader.equals(e.getNPC()) )
{
manager.removeRelation(e.getClicker());
trader = (Trader) tNpcManager.create_tNpc(e.getNPC(), traderTrait.getType(), e.getClicker(), TraderTrait.class);
manager.registerRelation(e.getClicker(), trader);
}
}
if ( !trader.onRightClick(e.getClicker().getItemInHand()) )
//check the mode
if ( !trader.getStatus().inManagementMode() )
manager.removeRelation(e.getClicker());
}
catch (TraderTypeNotFoundException e1)
{
//debug critical
dB.critical("Trader type was not found, type: ", traderTrait.getType());
dB.critical("Did you changed the save file?");
}
catch (InvalidTraderTypeException e1)
{
//debug critical
dB.critical("Trader type is invalid, type: ", traderTrait.getType());
dB.critical("Contact the dev to fix this!");
}
}
//npc events for bankers
@EventHandler(priority=EventPriority.HIGHEST)
public void bankerLeftClickEvent(NPCLeftClickEvent e)
{
//check trait
if ( !e.getNPC().hasTrait(BankerTrait.class) ) return;
//check permission
if ( !perms.has(e.getClicker(), "dtl.banker.use") )
{
locale.sendMessage(e.getClicker(), "error-nopermission");
return;
}
//dont allow creative to open traders
if ( e.getClicker().getGameMode().equals(GameMode.CREATIVE)
&& !perms.has(e.getClicker(), "dtl.banker.bypass.creative") )
{
locale.sendMessage(e.getClicker(), "error-nopermission-creative");
return;
}
BankerTrait bankerTrait = e.getNPC().getTrait(BankerTrait.class);
Banker banker;
try
{
banker = (Banker) tNpcManager.create_tNpc(e.getNPC(), bankerTrait.getType(), e.getClicker(), BankerTrait.class);
manager.registerRelation(e.getClicker(), banker);
banker.onLeftClick(e.getClicker().getItemInHand());
}
catch (TraderTypeNotFoundException e1)
{
//debug critical
dB.critical("Banker type was not found, type: ", bankerTrait.getType());
dB.critical("Did you changed the save file?");
}
catch (InvalidTraderTypeException e1)
{
//debug critical
dB.critical("TBanker type is invalid, type: ", bankerTrait.getType());
dB.critical("Contact the dev to fix this!");
}
}
@EventHandler(priority=EventPriority.HIGHEST)
public void bankerightClickEvent(NPCRightClickEvent e)
{
//check trait
if ( !e.getNPC().hasTrait(BankerTrait.class) ) return;
//check permission
if ( !perms.has(e.getClicker(), "dtl.banker.use") )
{
locale.sendMessage(e.getClicker(), "error-nopermission");
return;
}
//dont allow creative to open traders
if ( e.getClicker().getGameMode().equals(GameMode.CREATIVE)
&& !perms.has(e.getClicker(), "dtl.banker.bypass.creative") )
{
locale.sendMessage(e.getClicker(), "error-nopermission-creative");
return;
}
BankerTrait bankerTrait = e.getNPC().getTrait(BankerTrait.class);
Banker banker;
try
{
banker = (Banker) tNpcManager.create_tNpc(e.getNPC(), bankerTrait.getType(), e.getClicker(), BankerTrait.class);
manager.registerRelation(e.getClicker(), banker);
banker.onRightClick(e.getClicker().getItemInHand());
}
catch (TraderTypeNotFoundException e1)
{
//debug critical
dB.critical("Banker type was not found, type: ", bankerTrait.getType());
dB.critical("Did you changed the save file?");
}
catch (InvalidTraderTypeException e1)
{
//debug critical
dB.critical("TBanker type is invalid, type: ", bankerTrait.getType());
dB.critical("Contact the dev to fix this!");
}
}
/**
* Cleans the players inventory from any "dtltrader" lore that is applied to ease the way of using traders.
* @author dandielo
*/
static class InventoryCleaner implements Runnable
{
private final Player player;
public InventoryCleaner(final Player player)
{
//set the player
this.player = player;
//set the task for schedule
Bukkit.getScheduler().scheduleSyncDelayedTask(DtlTraders.getInstance(), this, PluginSettings.cleaningTimeout());
}
@Override
public void run()
{
//clean the player
clean(player);
//specific debug info
dB.spec(DebugLevel.S1_ADONDRIEL, "Removed from the cleaning querry");
}
public static void clean(Player thisPlayer)
{
int i = 0;
//search for items
for ( ItemStack item : thisPlayer.getInventory().getContents() )
{
if ( item != null )
{
if ( NBTUtils.isMarked(item) )
{
//specific debug info
dB.spec(DebugLevel.S1_ADONDRIEL, "Marked item found, remove it");
dB.spec(DebugLevel.S1_ADONDRIEL, "Item: ", item);
//remove item
thisPlayer.getInventory().setItem(i, null);
}
else
{
dB.spec(DebugLevel.S1_ADONDRIEL, "Item: ", item);
dB.spec(DebugLevel.S1_ADONDRIEL, "Has trader lore: ", NBTUtils.hasTraderLore(item));
dB.spec(DebugLevel.S1_ADONDRIEL, "Cleaned Item: ", NBTUtils.cleanItem(item));
//clean transaction lores
ItemStack it = NBTUtils.cleanItem(item);
it.setAmount(1);
thisPlayer.getInventory().setItem(i, it);
}
}
++i;
}
}
}
}
diff --git a/src/main/java/net/dandielo/citizens/traders_v3/traders/setting/Settings.java b/src/main/java/net/dandielo/citizens/traders_v3/traders/setting/Settings.java
index ef0275b..d668194 100644
--- a/src/main/java/net/dandielo/citizens/traders_v3/traders/setting/Settings.java
+++ b/src/main/java/net/dandielo/citizens/traders_v3/traders/setting/Settings.java
@@ -1,161 +1,162 @@
package net.dandielo.citizens.traders_v3.traders.setting;
import java.util.ArrayList;
import java.util.List;
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.api.trait.trait.Owner;
import net.citizensnpcs.api.util.DataKey;
import net.dandielo.citizens.traders_v3.core.dB;
public class Settings extends TGlobalSettings {
//the Npc associated with these settings
private final NPC npc;
private String owner = "no owner";
private String type = "server"; //needs to be here when some1 will apply it with the /trait command
//npc related settings
private int stockSize = TGlobalSettings.stockSize;
private String stockNameFormat = TGlobalSettings.stockNameFormat;
private String stockStart = TGlobalSettings.stockStart;
//pattern settings
private List<String> patterns = new ArrayList<String>();
public Settings(NPC npc) {
this.npc = npc;
}
public NPC getNPC()
{
return npc;
}
//trader type
public String getType()
{
return type;
}
/**
* Should be used only when creating a new NPC and setting default values.
* Sets the traders type
*/
public void setType(String type)
{
this.type = type;
}
//trader owner
public String getOwner()
{
return owner;
}
public void setOwner(String owner)
{
this.owner = owner;
}
//npc owner
public String getNpcOwner()
{
return npc.getTrait(Owner.class).getOwner();
}
//stock size
public int getStockSize() {
return stockSize;
}
public void setStockSize(int size)
{
stockSize = size;
}
//stock name format
public String getStockName() {
//get the npc name and change all abstract color codes into real ones
//#request 3 on PiratePad
return stockNameFormat.replace("{npc}", npc.getName()).replace('&', '§').replace('^', '§');
}
public String getStockFormat() {
return stockNameFormat;
}
public void setStockFormat(String format)
{
stockNameFormat = format;
}
//start stock
public String getStockStart()
{
return stockStart;
}
public void setStockStart(String stock)
{
stockStart = stock;
}
//other
public String getManagerStockStart()
{
return mmStockStart;
}
//loading and saving
@SuppressWarnings("unchecked")
public void load(DataKey data)
{
//debug info
dB.info("Loading trader settings for: ", this.npc.getName());
//load trader settings
type = data.getString("type");
owner = data.getString("owner", "no owner");
/* compatibility start */
if ( type.equals("trader") )
type = data.getString("trader");
/* compatibility end */
//load stock settings
stockSize = data.getInt("stock.size", TGlobalSettings.stockSize);
stockNameFormat = data.getString("stock.format", TGlobalSettings.stockNameFormat);
stockStart = data.getString("stock.default", TGlobalSettings.stockStart);
//load pattern settings
- patterns.addAll((List<String>)data.getRaw("patterns"));
+ if ( data.getRaw("patterns") != null )
+ patterns.addAll((List<String>)data.getRaw("patterns"));
}
public void save(DataKey data)
{
//debug info
dB.info("Saving trader settings for:", this.npc.getName());
//save trader settings
data.setString("type", type);
data.setString("owner", owner);
data.setRaw("stock", null);
//save patterns
data.setRaw("patterns", patterns);
//save stock settings
if ( stockSize != TGlobalSettings.stockSize )
data.setInt("stock.size", stockSize);
if ( !stockNameFormat.equals(TGlobalSettings.stockNameFormat) )
data.setString("stock.format", stockNameFormat);
if ( !stockStart.equals(TGlobalSettings.stockStart) )
data.setString("stock.default", stockStart);
}
public List<String> getPatterns()
{
return patterns;
}
}
| false | false | null | null |
diff --git a/otp-core/src/main/java/org/opentripplanner/routing/edgetype/TimetableResolver.java b/otp-core/src/main/java/org/opentripplanner/routing/edgetype/TimetableResolver.java
index c5bac16b7..37ca5019a 100644
--- a/otp-core/src/main/java/org/opentripplanner/routing/edgetype/TimetableResolver.java
+++ b/otp-core/src/main/java/org/opentripplanner/routing/edgetype/TimetableResolver.java
@@ -1,184 +1,186 @@
/* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.routing.edgetype;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.Iterator;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.onebusaway.gtfs.model.calendar.ServiceDate;
import org.opentripplanner.routing.trippattern.TripUpdate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// this is only currently in edgetype because that's where Trippattern is. move these classes elsewhere.
/**
* Part of concurrency control for stoptime updates.
*
* All updates should be performed on a snapshot before it is handed off to any searches.
* A single snapshot should be used for an entire search, and should remain unchanged
* for that duration to provide a consistent view not only of trips that have been boarded,
* but of relative arrival and departure times of other trips that have not necessarily been boarded.
*
* At this point, only one writing thread at a time is supported.
*/
public class TimetableResolver {
protected static class SortedTimetableComparator implements Comparator<Timetable> {
@Override
public int compare(Timetable t1, Timetable t2) {
return t1.getServiceDate().compareTo(t2.getServiceDate());
}
}
private static final Logger LOG = LoggerFactory.getLogger(TimetableResolver.class);
// Use HashMap not Map so we can clone.
// if this turns out to be slow/spacious we can use an array with integer pattern indexes
// The SortedSet members are copy-on-write
private HashMap<TableTripPattern, SortedSet<Timetable>> timetables = new HashMap<TableTripPattern, SortedSet<Timetable>>();
/** A set of all timetables which have been modified and are waiting to be indexed. */
private Set<Timetable> dirty = new HashSet<Timetable>();
/**
* Returns an updated timetable for the specified pattern if one is available in this snapshot,
* or the originally scheduled timetable if there are no updates in this snapshot.
*/
public Timetable resolve(TableTripPattern pattern, ServiceDate serviceDate) {
SortedSet<Timetable> sortedTimetables = timetables.get(pattern);
if(sortedTimetables != null && serviceDate != null) {
for(Timetable timetable : sortedTimetables) {
if (timetable != null && timetable.isValidFor(serviceDate)) {
LOG.trace("returning modified timetable");
return timetable;
}
}
}
return pattern.scheduledTimetable;
}
/**
* @return whether or not the update was actually applied
*/
public boolean update(TableTripPattern pattern, TripUpdate tripUpdate) {
// synchronization prevents commits/snapshots while update is in progress
synchronized(this) {
if (dirty == null)
throw new ConcurrentModificationException("This TimetableResolver is read-only.");
Timetable tt = resolve(pattern, tripUpdate.getServiceDate());
// we need to perform the copy of Timetable here rather than in Timetable.update()
// to avoid repeatedly copying in case several updates are applied to the same timetable
if ( ! dirty.contains(tt)) {
Timetable old = tt;
tt = tt.copy(tripUpdate.getServiceDate());
SortedSet<Timetable> sortedTimetables = timetables.get(pattern);
if(sortedTimetables == null) {
sortedTimetables = new TreeSet<Timetable>(new SortedTimetableComparator());
} else {
SortedSet<Timetable> temp = new TreeSet<Timetable>(new SortedTimetableComparator());
temp.addAll(sortedTimetables);
sortedTimetables = temp;
}
if(old.getServiceDate() != null)
sortedTimetables.remove(old);
sortedTimetables.add(tt);
timetables.put(pattern, sortedTimetables);
dirty.add(tt);
}
return tt.update(tripUpdate);
}
}
/**
* This produces a small delay of typically around 50ms, which is almost entirely due to
* the indexing step. Cloning the map is much faster (2ms).
* It is perhaps better to index timetables as they are changed to avoid experiencing all
* this lag at once, but we want to avoid re-indexing when receiving multiple updates for
* the same timetable in rapid succession. This compromise is expressed by the
* maxSnapshotFrequency property of StoptimeUpdater. The indexing could be made much more
* efficient as well.
* @return an immutable copy of this TimetableResolver with all updates applied
*/
public TimetableResolver commit() {
return commit(false);
}
@SuppressWarnings("unchecked")
public TimetableResolver commit(boolean force) {
TimetableResolver ret = new TimetableResolver();
// synchronization prevents updates while commit/snapshot in progress
synchronized(this) {
if (dirty == null)
throw new ConcurrentModificationException("This TimetableResolver is read-only.");
if (!force && !this.isDirty())
return null;
for (Timetable tt : dirty)
tt.finish(); // summarize, index, etc. the new timetables
ret.timetables = (HashMap<TableTripPattern, SortedSet<Timetable>>) this.timetables.clone();
this.dirty.clear();
}
ret.dirty = null; // mark the snapshot as henceforth immutable
return ret;
}
/**
* Removes all Timetables which are valid for a ServiceDate on-or-before the one supplied.
*/
public boolean purgeExpiredData(ServiceDate serviceDate) {
synchronized(this) {
if (dirty == null)
throw new ConcurrentModificationException("This TimetableResolver is read-only.");
boolean modified = false;
- for(TableTripPattern pattern : timetables.keySet()) {
+ for (Iterator<TableTripPattern> it = timetables.keySet().iterator(); it.hasNext();){
+ TableTripPattern pattern = it.next();
SortedSet<Timetable> sortedTimetables = timetables.get(pattern);
SortedSet<Timetable> toKeepTimetables = new TreeSet<Timetable>(new SortedTimetableComparator());
for(Timetable timetable : sortedTimetables) {
if(serviceDate.compareTo(timetable.getServiceDate()) < 0) {
toKeepTimetables.add(timetable);
} else {
modified = true;
}
}
if(toKeepTimetables.isEmpty()) {
- timetables.remove(pattern);
+ it.remove();
} else {
timetables.put(pattern, toKeepTimetables);
}
}
return modified;
}
}
public boolean isDirty() {
if (dirty == null)
return false;
return dirty.size() > 0;
}
public String toString() {
String d = dirty == null ? "committed" : String.format("%d dirty", dirty.size());
return String.format("Timetable snapshot: %d timetables (%s)", timetables.size(), d);
}
}
| false | false | null | null |
diff --git a/src/ljdp/minechem/common/tileentity/TileEntityFusion.java b/src/ljdp/minechem/common/tileentity/TileEntityFusion.java
index 1ac5a79..845430b 100644
--- a/src/ljdp/minechem/common/tileentity/TileEntityFusion.java
+++ b/src/ljdp/minechem/common/tileentity/TileEntityFusion.java
@@ -1,354 +1,354 @@
package ljdp.minechem.common.tileentity;
import ljdp.minechem.api.core.EnumElement;
import ljdp.minechem.api.util.Constants;
import ljdp.minechem.common.MinechemItems;
import ljdp.minechem.common.blueprint.BlueprintFusion;
import ljdp.minechem.common.inventory.BoundedInventory;
import ljdp.minechem.common.inventory.Transactor;
import ljdp.minechem.common.items.ItemElement;
import ljdp.minechem.common.utils.MinechemHelper;
import ljdp.minechem.computercraft.IMinechemMachinePeripheral;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.common.ForgeDirection;
import buildcraft.api.core.SafeTimeTracker;
public class TileEntityFusion extends TileEntityMultiBlock implements IMinechemMachinePeripheral {
public static int[] kFusionStar = { 0 };
public static int[] kInput = { 1, 2 };
public static int[] kOutput = { 3 };
private final BoundedInventory inputInventory;
private final BoundedInventory outputInventory;
private final BoundedInventory starInventory;
private Transactor inputTransactor;
private Transactor outputTransactor;
private Transactor starTransactor;
public static int kStartFusionStar = 0;
public static int kStartInput1 = 1;
public static int kStartInput2 = 2;
public static int kStartOutput = 3;
public static int kSizeInput = 2;
public static int kSizeOutput = 1;
public static int kSizeFusionStar = 1;
int energyStored = 0;
int maxEnergy = 9;
int targetEnergy = 0;
boolean isRecharging = false;
SafeTimeTracker energyUpdateTracker = new SafeTimeTracker();
boolean shouldSendUpdatePacket;
public TileEntityFusion() {
inventory = new ItemStack[getSizeInventory()];
inputInventory = new BoundedInventory(this, kInput);
outputInventory = new BoundedInventory(this, kOutput);
starInventory = new BoundedInventory(this, kFusionStar);
inputTransactor = new Transactor(inputInventory);
outputTransactor = new Transactor(outputInventory);
starTransactor = new Transactor(starInventory, 1);
this.inventory = new ItemStack[this.getSizeInventory()];
setBlueprint(new BlueprintFusion());
}
@Override
public void updateEntity() {
super.updateEntity();
if(!completeStructure)
return;
shouldSendUpdatePacket = false;
if(!worldObj.isRemote && inventory[kStartFusionStar] != null
&& energyUpdateTracker.markTimeIfDelay(worldObj, Constants.TICKS_PER_SECOND * 2))
{
if(!isRecharging)
targetEnergy = takeEnergyFromStar(inventory[kStartFusionStar], true);
if(targetEnergy > 0)
isRecharging = true;
if(isRecharging) {
recharge();
} else {
ItemStack fusionResult = getFusionOutput();
while(fusionResult != null && canFuse(fusionResult)) {
if(!worldObj.isRemote) {
addToOutput(fusionResult);
removeInputs();
}
energyStored -= getEnergyCost(fusionResult);
fusionResult = getFusionOutput();
shouldSendUpdatePacket = true;
}
}
}
if(shouldSendUpdatePacket && !worldObj.isRemote)
sendUpdatePacket();
}
private void addToOutput(ItemStack fusionResult) {
if (inventory[kOutput[0]] == null) {
ItemStack output = fusionResult.copy();
inventory[kOutput[0]] = output;
} else {
inventory[kOutput[0]].stackSize++;
}
}
private void removeInputs() {
decrStackSize(kInput[0], 1);
decrStackSize(kInput[1], 1);
}
private boolean canFuse(ItemStack fusionResult) {
ItemStack itemInOutput = inventory[kOutput[0]];
if (itemInOutput != null)
return itemInOutput.stackSize < getInventoryStackLimit() && itemInOutput.isItemEqual(fusionResult) && energyStored >= getEnergyCost(fusionResult);
else
return energyStored >= getEnergyCost(fusionResult);
}
private ItemStack getFusionOutput() {
if (hasInputs()) {
int mass1 = inventory[kInput[0]].getItemDamage() + 1;
int mass2 = inventory[kInput[1]].getItemDamage() + 1;
int massSum = mass1 + mass2;
if (massSum <= EnumElement.heaviestMass) {
return new ItemStack(MinechemItems.element, 1, massSum - 1);
} else {
return null;
}
} else {
return null;
}
}
private int getEnergyCost(ItemStack itemstack) {
int mass = itemstack.getItemDamage();
int cost = (int) MinechemHelper.translateValue(mass + 1, 1, EnumElement.heaviestMass, 1, this.maxEnergy);
return cost;
}
private boolean hasInputs() {
return inventory[kInput[0]] != null && inventory[kInput[1]] != null;
}
private void recharge() {
if (energyStored < targetEnergy) {
energyStored++;
shouldSendUpdatePacket = true;
} else {
isRecharging = false;
targetEnergy = 0;
}
}
private int takeEnergyFromStar(ItemStack fusionStar, boolean doTake) {
int energyCapacityAvailable = maxEnergy - energyStored;
int fusionStarDamage = fusionStar.getItemDamage();
int energyInStar = fusionStar.getMaxDamage() - fusionStarDamage;
if (energyCapacityAvailable == 0) {
return 0;
} else if (energyInStar > energyCapacityAvailable) {
if (doTake) {
fusionStarDamage += energyCapacityAvailable;
fusionStar.setItemDamage(fusionStarDamage);
}
return maxEnergy;
} else {
if (doTake) {
destroyFusionStar(fusionStar);
}
return energyStored + energyInStar;
}
}
private void destroyFusionStar(ItemStack fusionStar) {
this.inventory[kFusionStar[0]] = null;
}
@Override
public int getSizeInventory() {
return 4;
}
@Override
public void setInventorySlotContents(int slot, ItemStack itemstack) {
if (slot==0&&itemstack != null && itemstack.itemID == Item.netherStar.itemID) {
System.out.println("Turning nether star into fusion star");
this.inventory[slot] = new ItemStack(MinechemItems.fusionStar);
} else {
this.inventory[slot] = itemstack;
}
}
@Override
public String getInvName() {
return "container.minechemFusion";
}
@Override
public boolean isUseableByPlayer(EntityPlayer entityPlayer) {
if (!completeStructure)
return false;
return true;
}
@Override
public void writeToNBT(NBTTagCompound nbtTagCompound) {
super.writeToNBT(nbtTagCompound);
- nbtTagCompound.setInteger("energyStored", energyStored);
+ nbtTagCompound.setInteger("fusionenergyStored", energyStored);
nbtTagCompound.setInteger("targetEnergy", targetEnergy);
nbtTagCompound.setBoolean("isRecharging", isRecharging);
NBTTagList inventoryTagList = MinechemHelper.writeItemStackArrayToTagList(inventory);
nbtTagCompound.setTag("inventory", inventoryTagList);
}
@Override
public void readFromNBT(NBTTagCompound nbtTagCompound) {
super.readFromNBT(nbtTagCompound);
- energyStored = nbtTagCompound.getInteger("energyStored");
+ energyStored = nbtTagCompound.getInteger("fusionenergyStored");
targetEnergy = nbtTagCompound.getInteger("targetEnergy");
isRecharging = nbtTagCompound.getBoolean("isRecharging");
inventory = new ItemStack[getSizeInventory()];
MinechemHelper.readTagListToItemStackArray(nbtTagCompound.getTagList("inventory"), inventory);
}
public void setEnergyStored(int amount) {
this.energyStored = amount;
}
public int getMaxEnergy() {
return this.maxEnergy;
}
@Override
public ItemStack takeEmptyTestTube() {
return null;
}
@Override
public int putEmptyTestTube(ItemStack testTube) {
return 0;
}
@Override
public ItemStack takeOutput() {
return outputTransactor.removeItem(true);
}
@Override
public int putOutput(ItemStack output) {
return outputTransactor.add(output, true);
}
@Override
public ItemStack takeInput() {
return inputTransactor.removeItem(true);
}
@Override
public int putInput(ItemStack input) {
return inputTransactor.add(input, true);
}
@Override
public ItemStack takeFusionStar() {
return starTransactor.removeItem(true);
}
@Override
public int putFusionStar(ItemStack fusionStar) {
return starTransactor.add(fusionStar, true);
}
@Override
public ItemStack takeJournal() {
return null;
}
@Override
public int putJournal(ItemStack journal) {
return 0;
}
@Override
public String getMachineState() {
if (starInventory.getStackInSlot(0) == null) {
return "needfusionstar";
} else if (isRecharging) {
return "recharging";
} else {
return "powered";
}
}
@Override
public boolean isInvNameLocalized() {
return false;
}
@Override
public boolean isItemValidForSlot(int i, ItemStack itemstack) {
if (i == kFusionStar[0]){
if (itemstack.itemID == Item.netherStar.itemID || itemstack.itemID == MinechemItems.fusionStar.itemID){
return true;
}
}
for (int slot : kInput) {
if(i==slot&&itemstack.getItem() instanceof ItemElement){
return true;
}
}
return false;
}
public int[] getSizeInventorySide(int side) {
switch (side) {
case 0:
case 1:
return kInput;
default:
return kOutput;
}
}
@Override
public boolean canConnect(ForgeDirection direction) {
return false;
}
@Override
void sendUpdatePacket() {
// TODO Auto-generated method stub
}
@Override
public float getProvide(ForgeDirection direction) {
// TODO Auto-generated method stub
return 0;
}
@Override
public float getMaxEnergyStored() {
// TODO Auto-generated method stub
return 0;
}
public int getFusionEnergyStored() {
if(this.inventory[0]!=null){
return this.inventory[0].getMaxDamage()-this.inventory[0].getItemDamage();
}
return 0;
}
}
| false | false | null | null |
diff --git a/src/com/shj00007/activity/MainActivity.java b/src/com/shj00007/activity/MainActivity.java
index 73248b2..7302603 100644
--- a/src/com/shj00007/activity/MainActivity.java
+++ b/src/com/shj00007/activity/MainActivity.java
@@ -1,526 +1,526 @@
package com.shj00007.activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import com.shj00007.R;
import com.shj00007.activity.base.BaseActivity;
import com.shj00007.adapter.ExpandableAdapter;
import com.shj00007.adapter.MidListViewAdapter;
import com.shj00007.business.BusinessRss;
import com.shj00007.cache.AsyncImageGetter;
import com.shj00007.cache.ImageCache;
import com.shj00007.touch.ctrl.GestureListenerImpl;
import com.shj00007.utility.DownFile;
public class MainActivity extends BaseActivity implements OnTouchListener {
AsyncImageGetter mAsyncImageGetter = null;
private LinearLayout layout = null;
private GestureDetector gestureDetector = null;
private BusinessRss mBusinessRss = null;
private ExpandableListView mExpandableListView = null;
private ExpandableAdapter mExpandableAdapter = null;
private SimpleCursorAdapter mSimpleCursorAdapter = null;
private ListView mMidListView = null;
private ImageView mMidUnreadImage = null;
private ImageView mRightUnreadImage = null;
private TextView tvrighttext = null;
private ScrollView svrightscroll = null;
private ListView mMid_starr_listview = null;
private ImageView mSetAllRead = null;
private ImageView mUnread = null;
private ImageView mAddFeed = null;
private ImageView mViewStarr = null;
private ImageView mSetStarr = null;
private ImageView mUpdateRss = null;
DisplayMetrics dm = null;
private Cursor _Cursor = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initTools();
setListener();
bindData();
if(mExpandableAdapter.getGroupCount()==0){
addNorRss();
}
}
public void initTools() {
mBusinessRss = new BusinessRss(this);
mAsyncImageGetter = new AsyncImageGetter();
dm = getResources().getDisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
gestureDetector = new GestureDetector(this, new GestureListenerImpl(
this, layout, dm));
}
public void initView() {
layout = (LinearLayout) findViewById(R.id.homelayout);
mExpandableListView = (ExpandableListView) findViewById(R.id.expandableListleft);
mMidListView = (ListView) findViewById(R.id.mid_listview);
tvrighttext = (TextView) findViewById(R.id.tvright_text_up);
svrightscroll = (ScrollView) findViewById(R.id.svrightscrool);
mMidUnreadImage = (ImageView) findViewById(R.id.ivmidunreadimage);
mRightUnreadImage = (ImageView) findViewById(R.id.ivrightunreadimage);
mSetAllRead = (ImageView) findViewById(R.id.ivsetallread);
mUnread = (ImageView) findViewById(R.id.ivonlyunread);
mAddFeed = (ImageView) findViewById(R.id.ivaddfeed);
mViewStarr = (ImageView) findViewById(R.id.ivviewstarred);
mSetStarr = (ImageView) findViewById(R.id.ivsetstarr);
mMid_starr_listview = (ListView) findViewById(R.id.mid_starr_listview);
mUpdateRss = (ImageView) findViewById(R.id.ivupdate);
}
public void setListener() {
mExpandableListView.setOnTouchListener(this);
mMidListView.setOnTouchListener(this);
mMidListView.setOverscrollHeader(getResources().getDrawable(
R.drawable.choose_background));
tvrighttext.setOnTouchListener(this);
svrightscroll.setOnTouchListener(this);
mMid_starr_listview.setOnTouchListener(this);
mSetStarr.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showToast("请选中Item");
}
});
mExpandableListView.setOnChildClickListener(new OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
mMid_starr_listview.setVisibility(View.GONE);
return false;
}
});
mAddFeed.setOnClickListener(new OnClickListener() {
private EditText etaddfeedname = null;
private AutoCompleteTextView etaddcategoryname = null;
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
View _v = getLayoutInflater().inflate(R.layout.addfeeddialog,
null);
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_dropdown_item_1line,
getResources().getStringArray(R.array.category));
etaddfeedname = (EditText) _v.findViewById(R.id.etaddfeedname);
etaddcategoryname = (AutoCompleteTextView) _v
.findViewById(R.id.etaddcategory);
etaddcategoryname.setAdapter(adapter);
new AlertDialog.Builder(MainActivity.this)
.setTitle("请输入")
.setView(_v)
.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method
// stub
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
final String link = etaddfeedname
.getText().toString();
if (etaddfeedname.getText().toString()
.equals("")) {
showToast("请输入地址");
return;
}
if (etaddcategoryname.getText()
.toString().equals("")) {
showToast("请输入类别");
return;
}
final String category = etaddcategoryname
.getText().toString();
if (mBusinessRss.isRssFeedExist(link)) {
showToast("rss已存在");
return;
}
imm.hideSoftInputFromWindow(
etaddcategoryname
.getWindowToken(), 0);
showProgressDialog("正在加载rss", "loading");
new Thread(new Runnable() {
@Override
public void run() {
if (mBusinessRss
.downloadRSS(link)) {
mBusinessRss.addRssFeed(
category, link);
mBusinessRss.updateRss();
Handler myhandler = new Handler(
Looper.getMainLooper()) {
@Override
public void handleMessage(
Message msg) {
bindData();
dismissProgressDialog();
}
};
myhandler.removeMessages(0);
myhandler
.sendEmptyMessage(0);
} else {
Handler handler = new Handler(
Looper.getMainLooper()) {
@Override
public void handleMessage(
Message msg) {
dismissProgressDialog();
showToast("网络异常,请检查你的feed地址是否正确");
}
};
handler.removeMessages(0);
handler.sendEmptyMessage(0);
}
}
}).start();
}
}).setNegativeButton("取消", null).show();
}
});
mSetAllRead.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String _RssName = "";
try {
_RssName = ((MidListViewAdapter) mMidListView.getAdapter())
.getRssName();
} catch (Exception e) {
_RssName = null;
}
if (_RssName != null) {
showToast("将rss所有条目设置为已阅读");
mBusinessRss.setRssIsread(_RssName);
mExpandableAdapter.notifyDataSetChanged();
((MidListViewAdapter) mMidListView.getAdapter())
.notifyDataSetChanged();
} else {
showToast("请先选中rss");
}
}
});
mUnread.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mMidListView.getAdapter() == null) {
showToast("请选择rss");
return;
}
mMid_starr_listview.setVisibility(View.GONE);
mMidListView.setVisibility(View.VISIBLE);
MidListViewAdapter _Adapter = (MidListViewAdapter) mMidListView
.getAdapter();
if (_Adapter.getOnlyViewUnRead()) {
_Adapter.setOnlyViewUnRead(false);
showToast("显示所有条目");
} else {
_Adapter.setOnlyViewUnRead(true);
showToast("只显示未读条目");
}
_Adapter.notifyDataSetChanged();
}
});
mViewStarr.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showToast("显示所有星标条目");
_Cursor = mBusinessRss.getStarredCursor();
mSimpleCursorAdapter = new SimpleCursorAdapter(
MainActivity.this,
R.layout.mid_listview,
_Cursor,
new String[] { "rssname", "title", "pubdate" },
new int[] { R.id.midname, R.id.midtitle, R.id.middate },
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
mMid_starr_listview.setAdapter(mSimpleCursorAdapter);
mMidUnreadImage.setVisibility(View.GONE);
mMidListView.setVisibility(View.GONE);
mMid_starr_listview.setVisibility(View.VISIBLE);
}
});
mMid_starr_listview
.setOnItemClickListener(new OnItemClickListenerImpl());
mMidListView.setOnItemClickListener(new OnItemClickListenerImpl());
mUpdateRss.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showProgressDialog("正在更新rss", "loading");
svrightscroll.scrollTo(0, 0);
new Thread(new Runnable() {
@Override
public void run() {
try {
mBusinessRss.updateAllRss();
} catch (Exception e) {
e.printStackTrace();
Handler myhandler = new Handler(Looper
.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
showToast("网络异常");
}
};
myhandler.removeMessages(0);
myhandler.sendEmptyMessage(0);
}
Handler myhandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
bindData();
dismissProgressDialog();
}
};
myhandler.removeMessages(0);
myhandler.sendEmptyMessage(0);
}
}).start();
}
});
}
private class OnItemClickListenerImpl implements OnItemClickListener {
String _RssName = "";
String _ItemTitle = "";
String _Pubdate = "";
String _Description = null;
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
_RssName = ((TextView) arg1.findViewById(R.id.midname)).getText()
.toString();
_ItemTitle = ((TextView) arg1.findViewById(R.id.midtitle))
.getText().toString();
_Pubdate = ((TextView) arg1.findViewById(R.id.middate)).getText()
.toString();
_Description = "<h1>" + _ItemTitle + "</h1>\n\n<hr />"
+ mBusinessRss.getDescription(_RssName, _ItemTitle);
tvrighttext.setText(Html.fromHtml(_Description, new DownFile(
tvrighttext), null));
mRightUnreadImage.setVisibility(View.GONE);
svrightscroll.setVisibility(View.VISIBLE);
if (!mBusinessRss.isRead(_RssName, _ItemTitle)) {
mBusinessRss.setHasRead(_RssName, _ItemTitle);
mExpandableAdapter.notifyDataSetChanged();
((MidListViewAdapter) mMidListView.getAdapter())
.notifyDataSetChanged();
}
mSetStarr.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mBusinessRss.isItemStarred(_ItemTitle)) {
mBusinessRss.setItemUnstarr(_ItemTitle);
showToast("set unstarr");
} else {
mBusinessRss.setItemStarr(_RssName, _ItemTitle,
_Pubdate);
showToast("set starr");
}
}
});
}
}
public void bindData() {
mExpandableAdapter = new ExpandableAdapter(this, mBusinessRss,
mMidListView, mMidUnreadImage);
mExpandableListView.setAdapter(mExpandableAdapter);
}
public void addNorRss(){
new AlertDialog.Builder(MainActivity.this)
.setTitle("rss为空,是否自动加入rss测试")
.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
showProgressDialog("正在加载rss", "loading");
new Thread(new Runnable() {
@Override
public void run() {
String testlinks[]=getResources().getStringArray(R.array.testlinks);
Log.i("test", "count="+testlinks.length);
String category="";
for (int i = 0; i < testlinks.length; i++) {
if(i<3){
category="资讯1";
}else{
category="资讯2";
}
Log.i("test", testlinks[i]);
Log.i("test", category);
if (mBusinessRss
.downloadRSS(testlinks[i])) {
mBusinessRss.addRssFeed(
category, testlinks[i]);
mBusinessRss.updateRss();
} else {
Handler handler = new Handler(
Looper.getMainLooper()) {
@Override
public void handleMessage(
Message msg) {
dismissProgressDialog();
- showToast("网络错误,添加失败,请自输地址");
+ showToast("网络错误,添加失败,请链接网络");
}
};
handler.removeMessages(0);
handler.sendEmptyMessage(0);
}
}
Handler myhandler = new Handler(
Looper.getMainLooper()) {
@Override
public void handleMessage(
Message msg) {
bindData();
dismissProgressDialog();
}
};
myhandler.removeMessages(0);
myhandler
.sendEmptyMessage(0);
}
}).start();
}
}).setNegativeButton("取消", null).show();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
return gestureDetector.onTouchEvent(event);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return gestureDetector.onTouchEvent(event);
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
if (_Cursor != null) {
_Cursor.close();
}
ImageCache.getInstance().clearCache();
mBusinessRss.closeDatabase();
super.onDestroy();
}
}
| true | false | null | null |
diff --git a/src/main/java/xelitez/frostcraft/world/WorldGenFrostWingTower.java b/src/main/java/xelitez/frostcraft/world/WorldGenFrostWingTower.java
index da20b05..bfd78c3 100644
--- a/src/main/java/xelitez/frostcraft/world/WorldGenFrostWingTower.java
+++ b/src/main/java/xelitez/frostcraft/world/WorldGenFrostWingTower.java
@@ -1,659 +1,659 @@
package xelitez.frostcraft.world;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import net.minecraft.block.material.Material;
import net.minecraft.init.Blocks;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.ChatComponentText;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraftforge.common.util.ForgeDirection;
import xelitez.frostcraft.SaveHandler;
import xelitez.frostcraft.registry.IdMap;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.IWorldGenerator;
public class WorldGenFrostWingTower implements IWorldGenerator
{
public List<BiomeGenBase> biomeList = new ArrayList<BiomeGenBase>();
private static WorldGenFrostWingTower instance = new WorldGenFrostWingTower();
public static WorldGenFrostWingTower getInstance()
{
return instance;
}
public WorldGenFrostWingTower()
{
biomeList.add(BiomeGenBase.iceMountains);
biomeList.add(BiomeGenBase.icePlains);
- biomeList.add(BiomeGenBase.taiga);
- biomeList.add(BiomeGenBase.taigaHills);
+ biomeList.add(BiomeGenBase.coldTaiga);
+ biomeList.add(BiomeGenBase.coldTaigaHills);
}
public static List<Integer> getPossibleYPos(World world, int x, int z)
{
List<Integer> list = new ArrayList<Integer>();
for(int i = 50;i < world.getActualHeight() - 50;i++)
{
if(world.getBlock(x, i - 1, z) != null && (world.getBlock(x, i - 1, z).isSideSolid(world, x, i - 1, z, ForgeDirection.UP)) && world.getBlock(x, i, z).getMaterial() == Material.air)
{
list.add(i);
}
}
return list;
}
private static void sendChatMsg(String Msg)
{
FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager().sendChatMsg(new ChatComponentText("<Frostcraft Generator> " + Msg));
}
@Override
public void generate(Random random, int chunkX, int chunkZ, World world,
IChunkProvider chunkGenerator, IChunkProvider chunkProvider)
{
int centerX = chunkX * 16 + random.nextInt(16);
int centerZ = chunkZ * 16 + random.nextInt(16);
if(!biomeList.contains(world.getBiomeGenForCoords(centerX, centerZ)))
{
return;
}
NBTTagCompound nbt = SaveHandler.getTagCompound(world, false);
NBTTagList list = null;
if(nbt.hasKey("Castles"))
{
- list = nbt.getTagList("Castles", 0);
+ list = nbt.getTagList("Castles", 10);
}
if(list == null)
{
list = new NBTTagList();
}
List<Integer[]> intlist = new ArrayList<Integer[]>();
if(list != null)
{
for(int var0 = 0;var0 < list.tagCount();var0++)
{
NBTTagCompound nbt1 = (NBTTagCompound)list.getCompoundTagAt(var0);
Integer[] coords = new Integer[] {nbt1.getInteger("xCoord"), nbt1.getInteger("yCoord"), nbt1.getInteger("zCoord")};
intlist.add(coords);
}
}
int centerY = 0;
for(Integer int1 : getPossibleYPos(world, centerX, centerZ))
{
if(int1 > 50 && random.nextInt(6) == 2)
{
centerY = int1;
}
}
if(centerY != 0)
{
boolean canGenerate = true;
for(Integer[] ints : intlist)
{
int dx = ints[0] - centerX;
int dy = ints[1] - centerY;
int dz = ints[2] - centerZ;
if(Math.sqrt(dx * dx + dy * dy + dz * dz) < 750)
{
canGenerate = false;
}
}
if(canGenerate)
{
generateSimple(random, centerX, centerY, centerZ, world);
NBTTagCompound nbt2 = new NBTTagCompound();
nbt2.setInteger("xCoord", centerX);
nbt2.setInteger("yCoord", centerY);
nbt2.setInteger("zCoord", centerZ);
list.appendTag(nbt2);
nbt.setTag("Castles", list);
}
}
}
private void generateSimple(Random random, int xCoord, int yCoord, int zCoord, World world)
{
for(int x = -7;x < 8;x++)
{
for(int z = -7;z < 8;z++)
{
for(int y = -1;y <= 20;y++)
{
if(Math.floor(Math.sqrt(x * x + z * z)) <= 7.0D)
{
world.setBlockToAir(xCoord + x, yCoord + y, zCoord + z);
if(y == -1)
{
this.generateFloor(world, xCoord + x, yCoord + y - 1, zCoord + z);
}
}
if(Math.floor(Math.sqrt(x * x + z * z)) == 7.0D)
{
if(!(Math.abs(x) < 2 && z < 0 && y < 3 && y >= 0) && !(x == 0 && y == 3 && z < 0) && y <= 18)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 2, 2);
}
if(y == 18)
{
if(Math.abs(x) == 1 || Math.abs(z) == 1 || Math.abs(x) == 3 || Math.abs(z) == 3)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrostSingleSlabSet, 2, 2);
}
if(Math.abs(x) == 5 && Math.abs(z) == 5)
{
world.setBlockToAir(xCoord + x, yCoord + y, zCoord + z);
}
}
}
if(y == -1)
{
if(Math.floor(Math.sqrt(x * x + z * z)) <= 6.0D)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 2, 2);
if(Math.floor(Math.sqrt(x * x + z * z)) == 6.0D)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 0, 2);
}
if(Math.floor(Math.sqrt(x * x + z * z)) == 2.0D)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 0, 2);
}
if(Math.abs(x) > 1 && z == 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 0, 2);
}
if(Math.abs(z) > 1 && x == 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 0, 2);
}
}
}
if(y == 17)
{
if(Math.floor(Math.sqrt(x * x + z * z)) > 2.0D)
{
if(Math.floor(Math.sqrt(x * x + z * z)) <= 6.0D)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 2, 2);
if(Math.floor(Math.sqrt(x * x + z * z)) == 6.0D)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 0, 2);
}
if(Math.abs(x) > 1 && z == 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 0, 2);
}
if(Math.abs(z) > 1 && x == 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 0, 2);
}
}
}
}
if(x == 0 && z == 0 && y <= 17)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 0, 2);
}
if(Math.floor(Math.sqrt(x * x + z * z)) <= 2.0D && y >= 0 && y <= 17)
{
if(y % 4 == 0)
{
if(x < 0 && z > 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 2, 2);
}
if(z == 0 && x < 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrostStairBrick, 2, 2);
}
if(z > 0 && x == 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrostStairBrick, 5, 2);
}
}
if(y % 4 == 1)
{
if(x > 0 && z > 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 2, 2);
}
if(z > 0 && x == 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrostStairBrick, 0, 2);
}
if(z == 0 && x > 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrostStairBrick, 6, 2);
}
if(y == 17 && Math.floor(Math.sqrt(x * x + z * z)) == 2.0D)
{
if(z > 0 && x > 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 0, 2);
}
if(z == 0 && x > 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrostStairBrick, 6, 2);
}
}
}
if(y % 4 == 2)
{
if(x > 0 && z < 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 2, 2);
}
if(z == 0 && x > 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrostStairBrick, 3, 2);
}
if(z < 0 && x == 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrostStairBrick, 4, 2);
}
}
if(y % 4 == 3)
{
if(x < 0 && z < 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 2, 2);
}
if(z < 0 && x == 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrostStairBrick, 1, 2);
}
if(z == 0 && x < 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrostStairBrick, 7, 2);
}
}
}
}
}
}
this.generateCandle(world, xCoord + 6, yCoord, zCoord, 2);
this.generateCandle(world, xCoord, yCoord, zCoord + 6, 1);
this.generateCandle(world, xCoord - 6, yCoord, zCoord, 2);
this.generateCandle(world, xCoord - 2, yCoord, zCoord - 6, 0);
this.generateCandle(world, xCoord + 2, yCoord, zCoord - 6, 0);
this.generateCandle(world, xCoord, yCoord + 18, zCoord, 0);
this.generateCandle(world, xCoord + 6, yCoord + 18, zCoord, 0);
this.generateCandle(world, xCoord, yCoord + 18, zCoord + 6, 0);
this.generateCandle(world, xCoord - 6, yCoord + 18, zCoord, 0);
world.setBlock(xCoord, yCoord + 18, zCoord - 6, IdMap.blockStatue, 2, 2);
world.setBlock(xCoord, yCoord + 19, zCoord - 6, IdMap.blockStatue, 4, 2);
world.setBlock(xCoord, yCoord + 20, zCoord - 6, IdMap.blockStatue, 5, 2);
}
private void generateFloor(World world, int x, int yStart, int z)
{
for(int y = yStart; y > 0; y--)
{
if(world.getBlock(x, y, z).getMaterial() == Material.air || world.getBlock(x, y, z).isReplaceable(world, x, y, z))
{
world.setBlock(x, y, z, Blocks.dirt, 0, 2);
}
else
{
break;
}
}
}
private void generateCandle(World world, int x, int y, int z, int type)
{
switch(type)
{
case 0:
world.setBlock(x, y, z, IdMap.blockBlackFrostFenceSet, 1, 2);
world.setBlock(x, y + 1, z, Blocks.torch, 5, 2);
break;
case 1:
world.setBlock(x, y, z, IdMap.blockBlackFrostFenceSet, 1, 2);
world.setBlock(x, y + 1, z, IdMap.blockBlackFrostFenceSet, 1, 2);
world.setBlock(x + 1, y + 1, z , IdMap.blockBlackFrostFenceSet, 1, 2);
world.setBlock(x - 1, y + 1, z, IdMap.blockBlackFrostFenceSet, 1, 2);
world.setBlock(x + 1, y + 2, z, Blocks.torch, 5, 2);
world.setBlock(x - 1, y + 2, z, Blocks.torch, 5, 2);
break;
case 2:
world.setBlock(x, y, z, IdMap.blockBlackFrostFenceSet, 1, 2);
world.setBlock(x, y + 1, z, IdMap.blockBlackFrostFenceSet, 1, 2);
world.setBlock(x, y + 1, z + 1, IdMap.blockBlackFrostFenceSet, 1, 2);
world.setBlock(x, y + 1, z - 1, IdMap.blockBlackFrostFenceSet, 1, 2);
world.setBlock(x, y + 2, z + 1, Blocks.torch, 5, 2);
world.setBlock(x, y + 2, z - 1, Blocks.torch, 5, 2);
break;
}
}
public static void generateAt(Random random, int i, int j, int k, World world1)
{
final World world = world1;
final int xCoord = i;
final int yCoord = j;
final int zCoord = k;
new Thread()
{
public void run()
{
for(int x = -7;x < 8;x++)
{
for(int z = -7;z < 8;z++)
{
for(int y = -1;y <= 20;y++)
{
if(Math.floor(Math.sqrt(x * x + z * z)) <= 7.0D)
{
world.setBlockToAir(xCoord + x, yCoord + y, zCoord + z);
if(y == -1)
{
this.generateFloor(world, xCoord + x, yCoord + y - 1, zCoord + z);
}
}
if(Math.floor(Math.sqrt(x * x + z * z)) == 7.0D)
{
if(!(Math.abs(x) < 2 && z < 0 && y < 3 && y >= 0) && !(x == 0 && y == 3 && z < 0) && y <= 18)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 2, 2);
}
if(y == 18)
{
if(Math.abs(x) == 1 || Math.abs(z) == 1 || Math.abs(x) == 3 || Math.abs(z) == 3)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrostSingleSlabSet, 2, 2);
}
if(Math.abs(x) == 5 && Math.abs(z) == 5)
{
world.setBlockToAir(xCoord + x, yCoord + y, zCoord + z);
}
}
}
if(y == -1)
{
if(Math.floor(Math.sqrt(x * x + z * z)) <= 6.0D)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 2, 2);
if(Math.floor(Math.sqrt(x * x + z * z)) == 6.0D)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 0, 2);
}
if(Math.floor(Math.sqrt(x * x + z * z)) == 2.0D)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 0, 2);
}
if(Math.abs(x) > 1 && z == 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 0, 2);
}
if(Math.abs(z) > 1 && x == 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 0, 2);
}
}
}
if(y == 17)
{
if(Math.floor(Math.sqrt(x * x + z * z)) > 2.0D)
{
if(Math.floor(Math.sqrt(x * x + z * z)) <= 6.0D)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 2, 2);
if(Math.floor(Math.sqrt(x * x + z * z)) == 6.0D)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 0, 2);
}
if(Math.abs(x) > 1 && z == 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 0, 2);
}
if(Math.abs(z) > 1 && x == 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 0, 2);
}
}
}
}
if(x == 0 && z == 0 && y <= 17)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 0, 2);
}
if(Math.floor(Math.sqrt(x * x + z * z)) <= 2.0D && y >= 0 && y <= 17)
{
if(y % 4 == 0)
{
if(x < 0 && z > 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 2, 2);
}
if(z == 0 && x < 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrostStairBrick, 2, 2);
}
if(z > 0 && x == 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrostStairBrick, 5, 2);
}
}
if(y % 4 == 1)
{
if(x > 0 && z > 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 2, 2);
}
if(z > 0 && x == 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrostStairBrick, 0, 2);
}
if(z == 0 && x > 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrostStairBrick, 6, 2);
}
if(y == 17 && Math.floor(Math.sqrt(x * x + z * z)) == 2.0D)
{
if(z > 0 && x > 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 0, 2);
}
if(z == 0 && x > 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrostStairBrick, 6, 2);
}
}
}
if(y % 4 == 2)
{
if(x > 0 && z < 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 2, 2);
}
if(z == 0 && x > 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrostStairBrick, 3, 2);
}
if(z < 0 && x == 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrostStairBrick, 4, 2);
}
}
if(y % 4 == 3)
{
if(x < 0 && z < 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 2, 2);
}
if(z < 0 && x == 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrostStairBrick, 1, 2);
}
if(z == 0 && x < 0)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrostStairBrick, 7, 2);
}
}
}
}
}
}
this.generateCandle(world, xCoord + 6, yCoord, zCoord, 2);
this.generateCandle(world, xCoord, yCoord, zCoord + 6, 1);
this.generateCandle(world, xCoord - 6, yCoord, zCoord, 2);
this.generateCandle(world, xCoord - 2, yCoord, zCoord - 6, 0);
this.generateCandle(world, xCoord + 2, yCoord, zCoord - 6, 0);
this.generateCandle(world, xCoord, yCoord + 18, zCoord, 0);
this.generateCandle(world, xCoord + 6, yCoord + 18, zCoord, 0);
this.generateCandle(world, xCoord, yCoord + 18, zCoord + 6, 0);
this.generateCandle(world, xCoord - 6, yCoord + 18, zCoord, 0);
world.setBlock(xCoord, yCoord + 18, zCoord - 6, IdMap.blockStatue, 2, 2);
world.setBlock(xCoord, yCoord + 19, zCoord - 6, IdMap.blockStatue, 4, 2);
world.setBlock(xCoord, yCoord + 20, zCoord - 6, IdMap.blockStatue, 5, 2);
}
private void generateFloor(World world, int x, int yStart, int z)
{
for(int y = yStart; y > 0; y--)
{
if(world.getBlock(x, y, z).getMaterial() == Material.air || world.getBlock(x, y, z).isReplaceable(world, x, y, z))
{
world.setBlock(x, y, z, Blocks.dirt, 0, 2);
}
else
{
break;
}
}
}
private void generateCandle(World world, int x, int y, int z, int type)
{
switch(type)
{
case 0:
world.setBlock(x, y, z, IdMap.blockBlackFrostFenceSet, 1, 2);
world.setBlock(x, y + 1, z, Blocks.torch, 5, 2);
break;
case 1:
world.setBlock(x, y, z, IdMap.blockBlackFrostFenceSet, 1, 2);
world.setBlock(x, y + 1, z, IdMap.blockBlackFrostFenceSet, 1, 2);
world.setBlock(x + 1, y + 1, z , IdMap.blockBlackFrostFenceSet, 1, 2);
world.setBlock(x - 1, y + 1, z, IdMap.blockBlackFrostFenceSet, 1, 2);
world.setBlock(x + 1, y + 2, z, Blocks.torch, 5, 2);
world.setBlock(x - 1, y + 2, z, Blocks.torch, 5, 2);
break;
case 2:
world.setBlock(x, y, z, IdMap.blockBlackFrostFenceSet, 1, 2);
world.setBlock(x, y + 1, z, IdMap.blockBlackFrostFenceSet, 1, 2);
world.setBlock(x, y + 1, z + 1, IdMap.blockBlackFrostFenceSet, 1, 2);
world.setBlock(x, y + 1, z - 1, IdMap.blockBlackFrostFenceSet, 1, 2);
world.setBlock(x, y + 2, z + 1, Blocks.torch, 5, 2);
world.setBlock(x, y + 2, z - 1, Blocks.torch, 5, 2);
break;
}
}
}.start();
}
public static void generateFrostWingCylinder(World world, int xCoord, int zCoord)
{
sendChatMsg("Generating Arena... 0%");
int yCoord = world.getActualHeight() - 27;
for(int x = -25;x <= 25;x++)
{
for(int z = -25;z <= 25;z++)
{
for(int y = 0;y <= 25;y++)
{
if(x == -15 && y == 5 && z == -15)
{
sendChatMsg("Generating Arena... 20%");
}
if(x == -5 && y == 10 && z == -5)
{
sendChatMsg("Generating Arena... 40%");
}
if(x == 5 && y == 15 && z == 5)
{
sendChatMsg("Generating Arena... 60%");
}
if(x == 15 && y == 20 && z == 15)
{
sendChatMsg("Generating Arena... 80%");
}
if(x == 25 && y == 25 && z == 25)
{
sendChatMsg("Generating Arena... 100%");
}
if(y == 0 && Math.floor(Math.sqrt(x * x + z * z)) < 25.0D)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, Blocks.snow, 0, 2);
}
if(Math.floor(Math.sqrt(x * x + z * z)) == 25.0D)
{
world.setBlock(xCoord + x, yCoord + y, zCoord + z, IdMap.blockBlackFrost, 0, 2);
}
}
}
}
sendChatMsg("Generation complete!");
}
public static void removeCylinder(World world, int xCoord, int zCoord)
{
if(!world.isRemote)
{
sendChatMsg("Removing Arena... 0%");
int yCoord = world.getActualHeight() - 27;
for(int x = -25;x <= 25;x++)
{
for(int z = -25;z <= 25;z++)
{
for(int y = 0;y <= 25;y++)
{
if(x == -15 && y == 5 && z == -15)
{
sendChatMsg("Removing Arena... 20%");
}
if(x == -5 && y == 10 && z == -5)
{
sendChatMsg("Removing Arena... 40%");
}
if(x == 5 && y == 15 && z == 5)
{
sendChatMsg("Removing Arena... 60%");
}
if(x == 15 && y == 20 && z == 15)
{
sendChatMsg("Removing Arena... 80%");
}
if(x == 25 && y == 25 && z == 25)
{
sendChatMsg("Removing Arena... 100%");
}
if(y == 0 && Math.floor(Math.sqrt(x * x + z * z)) < 25.0D)
{
world.setBlockToAir(xCoord + x, yCoord + y, zCoord + z);
}
if(Math.floor(Math.sqrt(x * x + z * z)) == 25.0D)
{
world.setBlockToAir(xCoord + x, yCoord + y, zCoord + z);
}
}
}
}
sendChatMsg("Removal complete!");
}
}
}
| false | false | null | null |
diff --git a/core/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java b/core/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
index d3032d86..1c02455b 100644
--- a/core/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
+++ b/core/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
@@ -1,6073 +1,6073 @@
/**
: * Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.hypervisor.xen.resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import com.cloud.agent.IAgentControl;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.AttachIsoCommand;
import com.cloud.agent.api.AttachVolumeAnswer;
import com.cloud.agent.api.AttachVolumeCommand;
import com.cloud.agent.api.BackupSnapshotAnswer;
import com.cloud.agent.api.BackupSnapshotCommand;
import com.cloud.agent.api.CheckHealthAnswer;
import com.cloud.agent.api.CheckHealthCommand;
import com.cloud.agent.api.CheckOnHostAnswer;
import com.cloud.agent.api.CheckOnHostCommand;
import com.cloud.agent.api.CheckVirtualMachineAnswer;
import com.cloud.agent.api.CheckVirtualMachineCommand;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand;
import com.cloud.agent.api.CreateVolumeFromSnapshotAnswer;
import com.cloud.agent.api.CreateVolumeFromSnapshotCommand;
import com.cloud.agent.api.CreateZoneVlanAnswer;
import com.cloud.agent.api.CreateZoneVlanCommand;
import com.cloud.agent.api.DeleteSnapshotBackupAnswer;
import com.cloud.agent.api.DeleteSnapshotBackupCommand;
import com.cloud.agent.api.DeleteSnapshotsDirCommand;
import com.cloud.agent.api.DeleteStoragePoolCommand;
import com.cloud.agent.api.GetHostStatsAnswer;
import com.cloud.agent.api.GetHostStatsCommand;
import com.cloud.agent.api.GetStorageStatsAnswer;
import com.cloud.agent.api.GetStorageStatsCommand;
import com.cloud.agent.api.GetVmStatsAnswer;
import com.cloud.agent.api.GetVmStatsCommand;
import com.cloud.agent.api.GetVncPortAnswer;
import com.cloud.agent.api.GetVncPortCommand;
import com.cloud.agent.api.HostStatsEntry;
import com.cloud.agent.api.MaintainAnswer;
import com.cloud.agent.api.MaintainCommand;
import com.cloud.agent.api.ManageSnapshotAnswer;
import com.cloud.agent.api.ManageSnapshotCommand;
import com.cloud.agent.api.MigrateAnswer;
import com.cloud.agent.api.MigrateCommand;
import com.cloud.agent.api.ModifySshKeysCommand;
import com.cloud.agent.api.ModifyStoragePoolAnswer;
import com.cloud.agent.api.ModifyStoragePoolCommand;
import com.cloud.agent.api.NetworkIngressRuleAnswer;
import com.cloud.agent.api.NetworkIngressRulesCmd;
import com.cloud.agent.api.PingCommand;
import com.cloud.agent.api.PingRoutingCommand;
import com.cloud.agent.api.PingRoutingWithNwGroupsCommand;
import com.cloud.agent.api.PingTestCommand;
import com.cloud.agent.api.PoolEjectCommand;
import com.cloud.agent.api.PrepareForMigrationAnswer;
import com.cloud.agent.api.PrepareForMigrationCommand;
import com.cloud.agent.api.ReadyAnswer;
import com.cloud.agent.api.ReadyCommand;
import com.cloud.agent.api.RebootAnswer;
import com.cloud.agent.api.RebootCommand;
import com.cloud.agent.api.RebootRouterCommand;
import com.cloud.agent.api.SetupAnswer;
import com.cloud.agent.api.SetupCommand;
import com.cloud.agent.api.StartAnswer;
import com.cloud.agent.api.StartCommand;
import com.cloud.agent.api.StartConsoleProxyAnswer;
import com.cloud.agent.api.StartConsoleProxyCommand;
import com.cloud.agent.api.StartRouterAnswer;
import com.cloud.agent.api.StartRouterCommand;
import com.cloud.agent.api.StartSecStorageVmAnswer;
import com.cloud.agent.api.StartSecStorageVmCommand;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupRoutingCommand;
import com.cloud.agent.api.StartupStorageCommand;
import com.cloud.agent.api.StopAnswer;
import com.cloud.agent.api.StopCommand;
import com.cloud.agent.api.StoragePoolInfo;
import com.cloud.agent.api.ValidateSnapshotAnswer;
import com.cloud.agent.api.ValidateSnapshotCommand;
import com.cloud.agent.api.VmStatsEntry;
import com.cloud.agent.api.WatchNetworkAnswer;
import com.cloud.agent.api.WatchNetworkCommand;
import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
import com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer;
import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
import com.cloud.agent.api.routing.DhcpEntryCommand;
import com.cloud.agent.api.routing.IPAssocCommand;
import com.cloud.agent.api.routing.LoadBalancerCfgCommand;
import com.cloud.agent.api.routing.SavePasswordCommand;
import com.cloud.agent.api.routing.SetFirewallRuleCommand;
import com.cloud.agent.api.routing.VmDataCommand;
import com.cloud.agent.api.storage.CopyVolumeAnswer;
import com.cloud.agent.api.storage.CopyVolumeCommand;
import com.cloud.agent.api.storage.CreateAnswer;
import com.cloud.agent.api.storage.CreateCommand;
import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer;
import com.cloud.agent.api.storage.CreatePrivateTemplateCommand;
import com.cloud.agent.api.storage.DestroyCommand;
import com.cloud.agent.api.storage.DownloadAnswer;
import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
import com.cloud.agent.api.storage.ShareAnswer;
import com.cloud.agent.api.storage.ShareCommand;
import com.cloud.agent.api.to.DiskCharacteristicsTO;
import com.cloud.agent.api.to.StoragePoolTO;
import com.cloud.agent.api.to.VolumeTO;
import com.cloud.exception.InternalErrorException;
import com.cloud.host.Host.Type;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.resource.ServerResource;
import com.cloud.storage.StorageLayer;
import com.cloud.storage.StoragePoolVO;
import com.cloud.storage.VolumeVO;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.Storage.StoragePoolType;
import com.cloud.storage.Volume.StorageResourceType;
import com.cloud.storage.Volume.VolumeType;
import com.cloud.storage.resource.StoragePoolResource;
import com.cloud.storage.template.TemplateInfo;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.Ternary;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.utils.script.Script;
import com.cloud.vm.ConsoleProxyVO;
import com.cloud.vm.DomainRouter;
import com.cloud.vm.SecondaryStorageVmVO;
import com.cloud.vm.State;
import com.cloud.vm.VirtualMachineName;
import com.trilead.ssh2.SCPClient;
import com.xensource.xenapi.APIVersion;
import com.xensource.xenapi.Bond;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Console;
import com.xensource.xenapi.Host;
import com.xensource.xenapi.HostCpu;
import com.xensource.xenapi.HostMetrics;
import com.xensource.xenapi.Network;
import com.xensource.xenapi.PBD;
import com.xensource.xenapi.PIF;
import com.xensource.xenapi.Pool;
import com.xensource.xenapi.SR;
import com.xensource.xenapi.Session;
import com.xensource.xenapi.Types;
import com.xensource.xenapi.VBD;
import com.xensource.xenapi.VDI;
import com.xensource.xenapi.VIF;
import com.xensource.xenapi.VLAN;
import com.xensource.xenapi.VM;
import com.xensource.xenapi.VMGuestMetrics;
import com.xensource.xenapi.XenAPIObject;
import com.xensource.xenapi.Types.BadServerResponse;
import com.xensource.xenapi.Types.IpConfigurationMode;
import com.xensource.xenapi.Types.VmPowerState;
import com.xensource.xenapi.Types.XenAPIException;
/**
* Encapsulates the interface to the XenServer API.
*
*/
@Local(value = ServerResource.class)
public abstract class CitrixResourceBase implements StoragePoolResource, ServerResource {
private static final Logger s_logger = Logger.getLogger(CitrixResourceBase.class);
protected static final XenServerConnectionPool _connPool = XenServerConnectionPool.getInstance();
protected static final String SR_MOUNT_BASE = "/var/run/sr-mount/";
protected static final int MB = 1024 * 1024;
protected String _name;
protected String _username;
protected String _password;
protected String _scriptsDir = "scripts/vm/storage/xenserver";
protected final int _retry = 24;
protected final int _sleep = 10000;
protected long _dcId;
protected String _pod;
protected String _cluster;
protected HashMap<String, State> _vms = new HashMap<String, State>(71);
protected String _patchPath;
protected String _privateNetworkName;
protected String _linkLocalPrivateNetworkName;
protected String _publicNetworkName;
protected String _storageNetworkName1;
protected String _storageNetworkName2;
protected String _guestNetworkName;
protected int _wait;
protected IAgentControl _agentControl;
protected Map<String, String> _domrIPMap = new ConcurrentHashMap<String, String>();
protected final XenServerHost _host = new XenServerHost();
// Guest and Host Performance Statistics
protected boolean _collectHostStats = false;
protected String _consolidationFunction = "AVERAGE";
protected int _pollingIntervalInSeconds = 60;
protected StorageLayer _storage;
protected boolean _canBridgeFirewall = false;
protected HashMap<StoragePoolType, StoragePoolResource> _pools = new HashMap<StoragePoolType, StoragePoolResource>(5);
public enum SRType {
NFS, LVM, ISCSI, ISO, LVMOISCSI;
@Override
public String toString() {
return super.toString().toLowerCase();
}
public boolean equals(String type) {
return super.toString().equalsIgnoreCase(type);
}
}
protected static HashMap<Types.VmPowerState, State> s_statesTable;
protected String _localGateway;
static {
s_statesTable = new HashMap<Types.VmPowerState, State>();
s_statesTable.put(Types.VmPowerState.HALTED, State.Stopped);
s_statesTable.put(Types.VmPowerState.PAUSED, State.Running);
s_statesTable.put(Types.VmPowerState.RUNNING, State.Running);
s_statesTable.put(Types.VmPowerState.SUSPENDED, State.Running);
s_statesTable.put(Types.VmPowerState.UNKNOWN, State.Unknown);
s_statesTable.put(Types.VmPowerState.UNRECOGNIZED, State.Unknown);
}
protected boolean isRefNull(XenAPIObject object) {
return (object == null || object.toWireString().equals("OpaqueRef:NULL"));
}
@Override
public void disconnected() {
s_logger.debug("Logging out of " + _host.uuid);
if (_host.pool != null) {
_connPool.disconnect(_host.uuid, _host.pool);
}
}
protected VDI cloudVDIcopy(VDI vdi, SR sr) throws BadServerResponse, XenAPIException, XmlRpcException{
Connection conn = getConnection();
return vdi.copy(conn, sr);
}
protected void destroyStoppedVm() {
Map<VM, VM.Record> vmentries = null;
Connection conn = getConnection();
for (int i = 0; i < 2; i++) {
try {
vmentries = VM.getAllRecords(conn);
break;
} catch (final Throwable e) {
s_logger.warn("Unable to get vms", e);
}
try {
Thread.sleep(1000);
} catch (final InterruptedException ex) {
}
}
if (vmentries == null) {
return;
}
for (Map.Entry<VM, VM.Record> vmentry : vmentries.entrySet()) {
VM.Record record = vmentry.getValue();
if (record.isControlDomain || record.isASnapshot || record.isATemplate) {
continue; // Skip DOM0
}
if (record.powerState != Types.VmPowerState.HALTED) {
continue;
}
try {
if (isRefNull(record.affinity) || !record.affinity.getUuid(conn).equals(_host.uuid)) {
continue;
}
vmentry.getKey().destroy(conn);
} catch (Exception e) {
String msg = "VM destroy failed for " + record.nameLabel + " due to " + e.getMessage();
s_logger.warn(msg, e);
}
}
}
protected void cleanupDiskMounts() {
Connection conn = getConnection();
Map<SR, SR.Record> srs;
try {
srs = SR.getAllRecords(conn);
} catch (XenAPIException e) {
s_logger.warn("Unable to get the SRs " + e.toString(), e);
throw new CloudRuntimeException("Unable to get SRs " + e.toString(), e);
} catch (XmlRpcException e) {
throw new CloudRuntimeException("Unable to get SRs " + e.getMessage());
}
for (Map.Entry<SR, SR.Record> sr : srs.entrySet()) {
SR.Record rec = sr.getValue();
if (SRType.NFS.equals(rec.type) || (SRType.ISO.equals(rec.type) && rec.nameLabel.endsWith("iso"))) {
if (rec.PBDs == null || rec.PBDs.size() == 0) {
cleanSR(sr.getKey(), rec);
continue;
}
for (PBD pbd : rec.PBDs) {
if (isRefNull(pbd)) {
continue;
}
PBD.Record pbdr = null;
try {
pbdr = pbd.getRecord(conn);
} catch (XenAPIException e) {
s_logger.warn("Unable to get pbd record " + e.toString());
} catch (XmlRpcException e) {
s_logger.warn("Unable to get pbd record " + e.getMessage());
}
if (pbdr == null) {
continue;
}
try {
if (pbdr.host.getUuid(conn).equals(_host.uuid)) {
if (!currentlyAttached(sr.getKey(), rec, pbd, pbdr)) {
pbd.unplug(conn);
pbd.destroy(conn);
cleanSR(sr.getKey(), rec);
} else if (!pbdr.currentlyAttached) {
pbd.plug(conn);
}
}
} catch (XenAPIException e) {
s_logger.warn("Catch XenAPIException due to" + e.toString(), e);
} catch (XmlRpcException e) {
s_logger.warn("Catch XmlRpcException due to" + e.getMessage(), e);
}
}
}
}
}
protected Pair<VM, VM.Record> getVmByNameLabel(Connection conn, Host host, String nameLabel, boolean getRecord) throws XmlRpcException, XenAPIException {
Set<VM> vms = host.getResidentVMs(conn);
for (VM vm : vms) {
VM.Record rec = null;
String name = null;
if (getRecord) {
rec = vm.getRecord(conn);
name = rec.nameLabel;
} else {
name = vm.getNameLabel(conn);
}
if (name.equals(nameLabel)) {
return new Pair<VM, VM.Record>(vm, rec);
}
}
return null;
}
protected boolean currentlyAttached(SR sr, SR.Record rec, PBD pbd, PBD.Record pbdr) {
String status = null;
if (SRType.NFS.equals(rec.type)) {
status = callHostPlugin("checkMount", "mount", rec.uuid);
} else if (SRType.LVMOISCSI.equals(rec.type) ) {
String scsiid = pbdr.deviceConfig.get("SCSIid");
if (scsiid.isEmpty()) {
return false;
}
status = callHostPlugin("checkIscsi", "scsiid", scsiid);
} else {
return true;
}
if (status != null && status.equalsIgnoreCase("1")) {
s_logger.debug("currently attached " + pbdr.uuid);
return true;
} else {
s_logger.debug("currently not attached " + pbdr.uuid);
return false;
}
}
protected boolean pingdomr(String host, String port) {
String status;
status = callHostPlugin("pingdomr", "host", host, "port", port);
if (status == null || status.isEmpty()) {
return false;
}
return true;
}
protected boolean pingxenserver() {
Session slaveSession = null;
Connection slaveConn = null;
try {
URL slaveUrl = null;
slaveUrl = new URL("http://" + _host.ip);
slaveConn = new Connection(slaveUrl, 100);
slaveSession = Session.slaveLocalLoginWithPassword(slaveConn, _username, _password);
return true;
} catch (Exception e) {
return false;
} finally {
if( slaveSession != null ){
try{
Session.localLogout(slaveConn);
} catch (Exception e) {
}
slaveConn.dispose();
}
}
}
protected String logX(XenAPIObject obj, String msg) {
return new StringBuilder("Host ").append(_host.ip).append(" ").append(obj.toWireString()).append(": ").append(msg).toString();
}
protected void cleanSR(SR sr, SR.Record rec) {
Connection conn = getConnection();
if (rec.VDIs != null) {
for (VDI vdi : rec.VDIs) {
VDI.Record vdir;
try {
vdir = vdi.getRecord(conn);
} catch (XenAPIException e) {
s_logger.debug("Unable to get VDI: " + e.toString());
continue;
} catch (XmlRpcException e) {
s_logger.debug("Unable to get VDI: " + e.getMessage());
continue;
}
if (vdir.VBDs == null)
continue;
for (VBD vbd : vdir.VBDs) {
try {
VBD.Record vbdr = vbd.getRecord(conn);
VM.Record vmr = vbdr.VM.getRecord(conn);
if ((!isRefNull(vmr.residentOn) && vmr.residentOn.getUuid(conn).equals(_host.uuid))
|| (isRefNull(vmr.residentOn) && !isRefNull(vmr.affinity) && vmr.affinity.getUuid(conn).equals(_host.uuid))) {
if (vmr.powerState != VmPowerState.HALTED && vmr.powerState != VmPowerState.UNKNOWN && vmr.powerState != VmPowerState.UNRECOGNIZED) {
try {
vbdr.VM.hardShutdown(conn);
} catch (XenAPIException e) {
s_logger.debug("Shutdown hit error " + vmr.nameLabel + ": " + e.toString());
}
}
try {
vbdr.VM.destroy(conn);
} catch (XenAPIException e) {
s_logger.debug("Destroy hit error " + vmr.nameLabel + ": " + e.toString());
} catch (XmlRpcException e) {
s_logger.debug("Destroy hit error " + vmr.nameLabel + ": " + e.getMessage());
}
vbd.destroy(conn);
break;
}
} catch (XenAPIException e) {
s_logger.debug("Unable to get VBD: " + e.toString());
continue;
} catch (XmlRpcException e) {
s_logger.debug("Uanbel to get VBD: " + e.getMessage());
continue;
}
}
}
}
for (PBD pbd : rec.PBDs) {
PBD.Record pbdr = null;
try {
pbdr = pbd.getRecord(conn);
pbd.unplug(conn);
pbd.destroy(conn);
} catch (XenAPIException e) {
s_logger.warn("PBD " + ((pbdr != null) ? "(uuid:" + pbdr.uuid + ")" : "") + "destroy failed due to " + e.toString());
} catch (XmlRpcException e) {
s_logger.warn("PBD " + ((pbdr != null) ? "(uuid:" + pbdr.uuid + ")" : "") + "destroy failed due to " + e.getMessage());
}
}
try {
rec = sr.getRecord(conn);
if (rec.PBDs == null || rec.PBDs.size() == 0) {
sr.forget(conn);
return;
}
} catch (XenAPIException e) {
s_logger.warn("Unable to retrieve sr again: " + e.toString(), e);
} catch (XmlRpcException e) {
s_logger.warn("Unable to retrieve sr again: " + e.getMessage(), e);
}
}
@Override
public Answer executeRequest(Command cmd) {
if (cmd instanceof CreateCommand) {
return execute((CreateCommand) cmd);
} else if (cmd instanceof SetFirewallRuleCommand) {
return execute((SetFirewallRuleCommand) cmd);
} else if (cmd instanceof LoadBalancerCfgCommand) {
return execute((LoadBalancerCfgCommand) cmd);
} else if (cmd instanceof IPAssocCommand) {
return execute((IPAssocCommand) cmd);
} else if (cmd instanceof CheckConsoleProxyLoadCommand) {
return execute((CheckConsoleProxyLoadCommand) cmd);
} else if (cmd instanceof WatchConsoleProxyLoadCommand) {
return execute((WatchConsoleProxyLoadCommand) cmd);
} else if (cmd instanceof SavePasswordCommand) {
return execute((SavePasswordCommand) cmd);
} else if (cmd instanceof DhcpEntryCommand) {
return execute((DhcpEntryCommand) cmd);
} else if (cmd instanceof VmDataCommand) {
return execute((VmDataCommand) cmd);
} else if (cmd instanceof StartCommand) {
return execute((StartCommand) cmd);
} else if (cmd instanceof StartRouterCommand) {
return execute((StartRouterCommand) cmd);
} else if (cmd instanceof ReadyCommand) {
return execute((ReadyCommand) cmd);
} else if (cmd instanceof GetHostStatsCommand) {
return execute((GetHostStatsCommand) cmd);
} else if (cmd instanceof GetVmStatsCommand) {
return execute((GetVmStatsCommand) cmd);
} else if (cmd instanceof WatchNetworkCommand) {
return execute((WatchNetworkCommand) cmd);
} else if (cmd instanceof CheckHealthCommand) {
return execute((CheckHealthCommand) cmd);
} else if (cmd instanceof StopCommand) {
return execute((StopCommand) cmd);
} else if (cmd instanceof RebootRouterCommand) {
return execute((RebootRouterCommand) cmd);
} else if (cmd instanceof RebootCommand) {
return execute((RebootCommand) cmd);
} else if (cmd instanceof CheckVirtualMachineCommand) {
return execute((CheckVirtualMachineCommand) cmd);
} else if (cmd instanceof PrepareForMigrationCommand) {
return execute((PrepareForMigrationCommand) cmd);
} else if (cmd instanceof MigrateCommand) {
return execute((MigrateCommand) cmd);
} else if (cmd instanceof DestroyCommand) {
return execute((DestroyCommand) cmd);
} else if (cmd instanceof ShareCommand) {
return execute((ShareCommand) cmd);
} else if (cmd instanceof ModifyStoragePoolCommand) {
return execute((ModifyStoragePoolCommand) cmd);
} else if (cmd instanceof DeleteStoragePoolCommand) {
return execute((DeleteStoragePoolCommand) cmd);
} else if (cmd instanceof CopyVolumeCommand) {
return execute((CopyVolumeCommand) cmd);
} else if (cmd instanceof AttachVolumeCommand) {
return execute((AttachVolumeCommand) cmd);
} else if (cmd instanceof AttachIsoCommand) {
return execute((AttachIsoCommand) cmd);
} else if (cmd instanceof ValidateSnapshotCommand) {
return execute((ValidateSnapshotCommand) cmd);
} else if (cmd instanceof ManageSnapshotCommand) {
return execute((ManageSnapshotCommand) cmd);
} else if (cmd instanceof BackupSnapshotCommand) {
return execute((BackupSnapshotCommand) cmd);
} else if (cmd instanceof DeleteSnapshotBackupCommand) {
return execute((DeleteSnapshotBackupCommand) cmd);
} else if (cmd instanceof CreateVolumeFromSnapshotCommand) {
return execute((CreateVolumeFromSnapshotCommand) cmd);
} else if (cmd instanceof DeleteSnapshotsDirCommand) {
return execute((DeleteSnapshotsDirCommand) cmd);
} else if (cmd instanceof CreatePrivateTemplateCommand) {
return execute((CreatePrivateTemplateCommand) cmd);
} else if (cmd instanceof CreatePrivateTemplateFromSnapshotCommand) {
return execute((CreatePrivateTemplateFromSnapshotCommand) cmd);
} else if (cmd instanceof GetStorageStatsCommand) {
return execute((GetStorageStatsCommand) cmd);
} else if (cmd instanceof PrimaryStorageDownloadCommand) {
return execute((PrimaryStorageDownloadCommand) cmd);
} else if (cmd instanceof StartConsoleProxyCommand) {
return execute((StartConsoleProxyCommand) cmd);
} else if (cmd instanceof StartSecStorageVmCommand) {
return execute((StartSecStorageVmCommand) cmd);
} else if (cmd instanceof GetVncPortCommand) {
return execute((GetVncPortCommand) cmd);
} else if (cmd instanceof SetupCommand) {
return execute((SetupCommand) cmd);
} else if (cmd instanceof CreateZoneVlanCommand) {
return execute((CreateZoneVlanCommand) cmd);
} else if (cmd instanceof MaintainCommand) {
return execute((MaintainCommand) cmd);
} else if (cmd instanceof PingTestCommand) {
return execute((PingTestCommand) cmd);
} else if (cmd instanceof CheckOnHostCommand) {
return execute((CheckOnHostCommand) cmd);
} else if (cmd instanceof ModifySshKeysCommand) {
return execute((ModifySshKeysCommand) cmd);
} else if (cmd instanceof NetworkIngressRulesCmd) {
return execute((NetworkIngressRulesCmd) cmd);
} else if (cmd instanceof PoolEjectCommand) {
return execute((PoolEjectCommand) cmd);
} else {
return Answer.createUnsupportedCommandAnswer(cmd);
}
}
protected Answer execute(ModifySshKeysCommand cmd) {
String publickey = cmd.getPubKey();
String privatekey = cmd.getPrvKey();
com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(_host.ip, 22);
try {
sshConnection.connect(null, 60000, 60000);
if (!sshConnection.authenticateWithPassword(_username, _password)) {
throw new Exception("Unable to authenticate");
}
SCPClient scp = new SCPClient(sshConnection);
scp.put(publickey.getBytes(), "id_rsa.pub", "/opt/xensource/bin", "0600");
scp.put(privatekey.getBytes(), "id_rsa", "/opt/xensource/bin", "0600");
scp.put(privatekey.getBytes(), "id_rsa.cloud", "/root/.ssh", "0600");
return new Answer(cmd);
} catch (Exception e) {
String msg = " scp ssh key failed due to " + e.toString() + " - " + e.getMessage();
s_logger.warn(msg);
} finally {
sshConnection.close();
}
return new Answer(cmd, false, "modifySshkeys failed");
}
private boolean doPingTest(final String computingHostIp) {
String args = "-h " + computingHostIp;
String result = callHostPlugin("pingtest", "args", args);
if (result == null || result.isEmpty())
return false;
return true;
}
protected CheckOnHostAnswer execute(CheckOnHostCommand cmd) {
return new CheckOnHostAnswer(cmd, null, "Not Implmeneted");
}
private boolean doPingTest(final String domRIp, final String vmIp) {
String args = "-i " + domRIp + " -p " + vmIp;
String result = callHostPlugin("pingtest", "args", args);
if (result == null || result.isEmpty())
return false;
return true;
}
private Answer execute(PingTestCommand cmd) {
boolean result = false;
final String computingHostIp = cmd.getComputingHostIp(); // TODO, split the command into 2 types
if (computingHostIp != null) {
result = doPingTest(computingHostIp);
} else {
result = doPingTest(cmd.getRouterIp(), cmd.getPrivateIp());
}
if (!result) {
return new Answer(cmd, false, "PingTestCommand failed");
}
return new Answer(cmd);
}
protected MaintainAnswer execute(MaintainCommand cmd) {
Connection conn = getConnection();
try {
Pool pool = Pool.getByUuid(conn, _host.pool);
Pool.Record poolr = pool.getRecord(conn);
Host.Record hostr = poolr.master.getRecord(conn);
if (!_host.uuid.equals(hostr.uuid)) {
s_logger.debug("Not the master node so just return ok: " + _host.ip);
return new MaintainAnswer(cmd);
}
Map<Host, Host.Record> hostMap = Host.getAllRecords(conn);
if (hostMap.size() == 1) {
s_logger.debug("There's no one to take over as master");
return new MaintainAnswer(cmd, "Only master in the pool");
}
Host newMaster = null;
Host.Record newMasterRecord = null;
for (Map.Entry<Host, Host.Record> entry : hostMap.entrySet()) {
if (!_host.uuid.equals(entry.getValue().uuid)) {
newMaster = entry.getKey();
newMasterRecord = entry.getValue();
s_logger.debug("New master for the XenPool is " + newMasterRecord.uuid + " : " + newMasterRecord.address);
try {
_connPool.switchMaster(_host.ip, _host.pool, conn, newMaster, _username, _password, _wait);
return new MaintainAnswer(cmd, "New Master is " + newMasterRecord.address);
} catch (XenAPIException e) {
s_logger.warn("Unable to switch the new master to " + newMasterRecord.uuid + ": " + newMasterRecord.address + " Trying again...");
} catch (XmlRpcException e) {
s_logger.warn("Unable to switch the new master to " + newMasterRecord.uuid + ": " + newMasterRecord.address + " Trying again...");
}
}
}
return new MaintainAnswer(cmd, false, "Unable to find an appropriate host to set as the new master");
} catch (XenAPIException e) {
s_logger.warn("Unable to put server in maintainence mode", e);
return new MaintainAnswer(cmd, false, e.getMessage());
} catch (XmlRpcException e) {
s_logger.warn("Unable to put server in maintainence mode", e);
return new MaintainAnswer(cmd, false, e.getMessage());
}
}
protected SetupAnswer execute(SetupCommand cmd) {
return new SetupAnswer(cmd);
}
protected Answer execute(StartSecStorageVmCommand cmd) {
final String vmName = cmd.getVmName();
SecondaryStorageVmVO storage = cmd.getSecondaryStorageVmVO();
try {
Connection conn = getConnection();
Network network = Network.getByUuid(conn, _host.privateNetwork);
String bootArgs = cmd.getBootArgs();
bootArgs += " zone=" + _dcId;
bootArgs += " pod=" + _pod;
bootArgs += " localgw=" + _localGateway;
String result = startSystemVM(vmName, storage.getVlanId(), network, cmd.getVolumes(), bootArgs, storage.getGuestMacAddress(), storage.getGuestIpAddress(), storage
.getPrivateMacAddress(), storage.getPublicMacAddress(), cmd.getProxyCmdPort(), storage.getRamSize(), storage.getGuestOSId(), cmd.getNetworkRateMbps());
if (result == null) {
return new StartSecStorageVmAnswer(cmd);
}
return new StartSecStorageVmAnswer(cmd, result);
} catch (Exception e) {
String msg = "Exception caught while starting router vm " + vmName + " due to " + e.getMessage();
s_logger.warn(msg, e);
return new StartSecStorageVmAnswer(cmd, msg);
}
}
protected Answer execute(final SetFirewallRuleCommand cmd) {
String args;
if (cmd.isEnable()) {
args = "-A";
} else {
args = "-D";
}
args += " -P " + cmd.getProtocol().toLowerCase();
args += " -l " + cmd.getPublicIpAddress();
args += " -p " + cmd.getPublicPort();
args += " -n " + cmd.getRouterName();
args += " -i " + cmd.getRouterIpAddress();
args += " -r " + cmd.getPrivateIpAddress();
args += " -d " + cmd.getPrivatePort();
args += " -N " + cmd.getVlanNetmask();
String oldPrivateIP = cmd.getOldPrivateIP();
String oldPrivatePort = cmd.getOldPrivatePort();
if (oldPrivateIP != null) {
args += " -w " + oldPrivateIP;
}
if (oldPrivatePort != null) {
args += " -x " + oldPrivatePort;
}
String result = callHostPlugin("setFirewallRule", "args", args);
if (result == null || result.isEmpty()) {
return new Answer(cmd, false, "SetFirewallRule failed");
}
return new Answer(cmd);
}
protected Answer execute(final LoadBalancerCfgCommand cmd) {
String routerIp = cmd.getRouterIp();
if (routerIp == null) {
return new Answer(cmd);
}
String tmpCfgFilePath = "/tmp/" + cmd.getRouterIp().replace('.', '_') + ".cfg";
String tmpCfgFileContents = "";
for (int i = 0; i < cmd.getConfig().length; i++) {
tmpCfgFileContents += cmd.getConfig()[i];
tmpCfgFileContents += "\n";
}
String result = callHostPlugin("createFile", "filepath", tmpCfgFilePath, "filecontents", tmpCfgFileContents);
if (result == null || result.isEmpty()) {
return new Answer(cmd, false, "LoadBalancerCfgCommand failed to create HA proxy cfg file.");
}
String[] addRules = cmd.getAddFwRules();
String[] removeRules = cmd.getRemoveFwRules();
String args = "";
args += "-i " + routerIp;
args += " -f " + tmpCfgFilePath;
StringBuilder sb = new StringBuilder();
if (addRules.length > 0) {
for (int i = 0; i < addRules.length; i++) {
sb.append(addRules[i]).append(',');
}
args += " -a " + sb.toString();
}
sb = new StringBuilder();
if (removeRules.length > 0) {
for (int i = 0; i < removeRules.length; i++) {
sb.append(removeRules[i]).append(',');
}
args += " -d " + sb.toString();
}
result = callHostPlugin("setLoadBalancerRule", "args", args);
if (result == null || result.isEmpty()) {
return new Answer(cmd, false, "LoadBalancerCfgCommand failed");
}
callHostPlugin("deleteFile", "filepath", tmpCfgFilePath);
return new Answer(cmd);
}
protected synchronized Answer execute(final DhcpEntryCommand cmd) {
String args = "-r " + cmd.getRouterPrivateIpAddress();
args += " -v " + cmd.getVmIpAddress();
args += " -m " + cmd.getVmMac();
args += " -n " + cmd.getVmName();
String result = callHostPlugin("saveDhcpEntry", "args", args);
if (result == null || result.isEmpty()) {
return new Answer(cmd, false, "DhcpEntry failed");
}
return new Answer(cmd);
}
protected Answer execute(final VmDataCommand cmd) {
String routerPrivateIpAddress = cmd.getRouterPrivateIpAddress();
String vmIpAddress = cmd.getVmIpAddress();
List<String[]> vmData = cmd.getVmData();
String[] vmDataArgs = new String[vmData.size() * 2 + 4];
vmDataArgs[0] = "routerIP";
vmDataArgs[1] = routerPrivateIpAddress;
vmDataArgs[2] = "vmIP";
vmDataArgs[3] = vmIpAddress;
int i = 4;
for (String[] vmDataEntry : vmData) {
String folder = vmDataEntry[0];
String file = vmDataEntry[1];
String contents = (vmDataEntry[2] != null) ? vmDataEntry[2] : "none";
vmDataArgs[i] = folder + "," + file;
vmDataArgs[i + 1] = contents;
i += 2;
}
String result = callHostPlugin("vm_data", vmDataArgs);
if (result == null || result.isEmpty()) {
return new Answer(cmd, false, "vm_data failed");
} else {
return new Answer(cmd);
}
}
protected Answer execute(final SavePasswordCommand cmd) {
final String password = cmd.getPassword();
final String routerPrivateIPAddress = cmd.getRouterPrivateIpAddress();
final String vmName = cmd.getVmName();
final String vmIpAddress = cmd.getVmIpAddress();
final String local = vmName;
// Run save_password_to_domr.sh
String args = "-r " + routerPrivateIPAddress;
args += " -v " + vmIpAddress;
args += " -p " + password;
args += " " + local;
String result = callHostPlugin("savePassword", "args", args);
if (result == null || result.isEmpty()) {
return new Answer(cmd, false, "savePassword failed");
}
return new Answer(cmd);
}
protected void assignPublicIpAddress(final String vmName, final String privateIpAddress, final String publicIpAddress, final boolean add, final boolean firstIP,
final boolean sourceNat, final String vlanId, final String vlanGateway, final String vlanNetmask, final String vifMacAddress) throws InternalErrorException {
try {
Connection conn = getConnection();
VM router = getVM(conn, vmName);
// Determine the correct VIF on DomR to associate/disassociate the
// IP address with
VIF correctVif = getCorrectVif(router, vlanId);
// If we are associating an IP address and DomR doesn't have a VIF
// for the specified vlan ID, we need to add a VIF
// If we are disassociating the last IP address in the VLAN, we need
// to remove a VIF
boolean addVif = false;
boolean removeVif = false;
if (add && correctVif == null) {
addVif = true;
} else if (!add && firstIP) {
removeVif = true;
}
if (addVif) {
// Add a new VIF to DomR
String vifDeviceNum = getLowestAvailableVIFDeviceNum(router);
if (vifDeviceNum == null) {
throw new InternalErrorException("There were no more available slots for a new VIF on router: " + router.getNameLabel(conn));
}
correctVif = createVIF(conn, router, vifMacAddress, vlanId, 0, vifDeviceNum, true);
correctVif.plug(conn);
// Add iptables rule for network usage
networkUsage(privateIpAddress, "addVif", "eth" + correctVif.getDevice(conn));
}
if (correctVif == null) {
throw new InternalErrorException("Failed to find DomR VIF to associate/disassociate IP with.");
}
String args;
if (add) {
args = "-A";
} else {
args = "-D";
}
if (sourceNat) {
args += " -f";
}
args += " -i ";
args += privateIpAddress;
args += " -l ";
args += publicIpAddress;
args += " -c ";
args += "eth" + correctVif.getDevice(conn);
args += " -g ";
args += vlanGateway;
String result = callHostPlugin("ipassoc", "args", args);
if (result == null || result.isEmpty()) {
throw new InternalErrorException("Xen plugin \"ipassoc\" failed.");
}
if (removeVif) {
Network network = correctVif.getNetwork(conn);
// Mark this vif to be removed from network usage
networkUsage(privateIpAddress, "deleteVif", "eth" + correctVif.getDevice(conn));
// Remove the VIF from DomR
correctVif.unplug(conn);
correctVif.destroy(conn);
// Disable the VLAN network if necessary
disableVlanNetwork(network);
}
} catch (XenAPIException e) {
String msg = "Unable to assign public IP address due to " + e.toString();
s_logger.warn(msg, e);
throw new InternalErrorException(msg);
} catch (final XmlRpcException e) {
String msg = "Unable to assign public IP address due to " + e.getMessage();
s_logger.warn(msg, e);
throw new InternalErrorException(msg);
}
}
protected String networkUsage(final String privateIpAddress, final String option, final String vif) {
String args = null;
if (option.equals("get")) {
args = "-g";
} else if (option.equals("create")) {
args = "-c";
} else if (option.equals("reset")) {
args = "-r";
} else if (option.equals("addVif")) {
args = "-a";
args += vif;
} else if (option.equals("deleteVif")) {
args = "-d";
args += vif;
}
args += " -i ";
args += privateIpAddress;
return callHostPlugin("networkUsage", "args", args);
}
protected Answer execute(final IPAssocCommand cmd) {
try {
assignPublicIpAddress(cmd.getRouterName(), cmd.getRouterIp(), cmd.getPublicIp(), cmd.isAdd(), cmd.isFirstIP(), cmd.isSourceNat(), cmd.getVlanId(),
cmd.getVlanGateway(), cmd.getVlanNetmask(), cmd.getVifMacAddress());
} catch (InternalErrorException e) {
return new Answer(cmd, false, e.getMessage());
}
return new Answer(cmd);
}
protected GetVncPortAnswer execute(GetVncPortCommand cmd) {
Connection conn = getConnection();
try {
Set<VM> vms = VM.getByNameLabel(conn, cmd.getName());
return new GetVncPortAnswer(cmd, getVncPort(vms.iterator().next()));
} catch (XenAPIException e) {
s_logger.warn("Unable to get vnc port " + e.toString(), e);
return new GetVncPortAnswer(cmd, e.toString());
} catch (Exception e) {
s_logger.warn("Unable to get vnc port ", e);
return new GetVncPortAnswer(cmd, e.getMessage());
}
}
protected StorageResourceType getStorageResourceType() {
return StorageResourceType.STORAGE_POOL;
}
protected CheckHealthAnswer execute(CheckHealthCommand cmd) {
boolean result = pingxenserver();
return new CheckHealthAnswer(cmd, result);
}
protected WatchNetworkAnswer execute(WatchNetworkCommand cmd) {
WatchNetworkAnswer answer = new WatchNetworkAnswer(cmd);
for (String domr : _domrIPMap.keySet()) {
long[] stats = getNetworkStats(domr);
answer.addStats(domr, stats[0], stats[1]);
}
return answer;
}
protected long[] getNetworkStats(String domr) {
String result = networkUsage(_domrIPMap.get(domr), "get", null);
long[] stats = new long[2];
if (result != null) {
String[] splitResult = result.split(":");
int i = 0;
while (i < splitResult.length - 1) {
stats[0] += (new Long(splitResult[i++])).longValue();
stats[1] += (new Long(splitResult[i++])).longValue();
}
}
return stats;
}
/**
* This is the method called for getting the HOST stats
*
* @param cmd
* @return
*/
protected GetHostStatsAnswer execute(GetHostStatsCommand cmd) {
// Connection conn = getConnection();
try {
HostStatsEntry hostStats = getHostStats(cmd, cmd.getHostGuid(), cmd.getHostId());
return new GetHostStatsAnswer(cmd, hostStats);
} catch (Exception e) {
String msg = "Unable to get Host stats" + e.toString();
s_logger.warn(msg, e);
return new GetHostStatsAnswer(cmd, null);
}
}
protected HostStatsEntry getHostStats(GetHostStatsCommand cmd, String hostGuid, long hostId) {
HostStatsEntry hostStats = new HostStatsEntry(hostId, 0, 0, 0, 0, "host", 0, 0, 0, 0);
Object[] rrdData = getRRDData(1); // call rrd method with 1 for host
if (rrdData == null) {
return null;
}
Integer numRows = (Integer) rrdData[0];
Integer numColumns = (Integer) rrdData[1];
Node legend = (Node) rrdData[2];
Node dataNode = (Node) rrdData[3];
NodeList legendChildren = legend.getChildNodes();
for (int col = 0; col < numColumns; col++) {
if (legendChildren == null || legendChildren.item(col) == null) {
continue;
}
String columnMetadata = getXMLNodeValue(legendChildren.item(col));
if (columnMetadata == null) {
continue;
}
String[] columnMetadataList = columnMetadata.split(":");
if (columnMetadataList.length != 4) {
continue;
}
String type = columnMetadataList[1];
String param = columnMetadataList[3];
if (type.equalsIgnoreCase("host")) {
if (param.contains("pif_eth0_rx")) {
hostStats.setNetworkReadKBs(getDataAverage(dataNode, col, numRows));
}
if (param.contains("pif_eth0_tx")) {
hostStats.setNetworkWriteKBs(getDataAverage(dataNode, col, numRows));
}
if (param.contains("memory_total_kib")) {
hostStats.setTotalMemoryKBs(getDataAverage(dataNode, col, numRows));
}
if (param.contains("memory_free_kib")) {
hostStats.setFreeMemoryKBs(getDataAverage(dataNode, col, numRows));
}
if (param.contains("cpu")) {
hostStats.setNumCpus(hostStats.getNumCpus() + 1);
hostStats.setCpuUtilization(hostStats.getCpuUtilization() + getDataAverage(dataNode, col, numRows));
}
if (param.contains("loadavg")) {
hostStats.setAverageLoad((hostStats.getAverageLoad() + getDataAverage(dataNode, col, numRows)));
}
}
}
// add the host cpu utilization
if (hostStats.getNumCpus() != 0) {
hostStats.setCpuUtilization(hostStats.getCpuUtilization() / hostStats.getNumCpus());
s_logger.debug("Host cpu utilization " + hostStats.getCpuUtilization());
}
return hostStats;
}
protected GetVmStatsAnswer execute(GetVmStatsCommand cmd) {
List<String> vmNames = cmd.getVmNames();
HashMap<String, VmStatsEntry> vmStatsNameMap = new HashMap<String, VmStatsEntry>();
if( vmNames.size() == 0 ) {
return new GetVmStatsAnswer(cmd, vmStatsNameMap);
}
Connection conn = getConnection();
try {
// Determine the UUIDs of the requested VMs
List<String> vmUUIDs = new ArrayList<String>();
for (String vmName : vmNames) {
VM vm = getVM(conn, vmName);
vmUUIDs.add(vm.getUuid(conn));
}
HashMap<String, VmStatsEntry> vmStatsUUIDMap = getVmStats(cmd, vmUUIDs, cmd.getHostGuid());
if( vmStatsUUIDMap == null )
return new GetVmStatsAnswer(cmd, vmStatsNameMap);
for (String vmUUID : vmStatsUUIDMap.keySet()) {
vmStatsNameMap.put(vmNames.get(vmUUIDs.indexOf(vmUUID)), vmStatsUUIDMap.get(vmUUID));
}
return new GetVmStatsAnswer(cmd, vmStatsNameMap);
} catch (XenAPIException e) {
String msg = "Unable to get VM stats" + e.toString();
s_logger.warn(msg, e);
return new GetVmStatsAnswer(cmd, vmStatsNameMap);
} catch (XmlRpcException e) {
String msg = "Unable to get VM stats" + e.getMessage();
s_logger.warn(msg, e);
return new GetVmStatsAnswer(cmd, vmStatsNameMap);
}
}
protected HashMap<String, VmStatsEntry> getVmStats(GetVmStatsCommand cmd, List<String> vmUUIDs, String hostGuid) {
HashMap<String, VmStatsEntry> vmResponseMap = new HashMap<String, VmStatsEntry>();
for (String vmUUID : vmUUIDs) {
vmResponseMap.put(vmUUID, new VmStatsEntry(0, 0, 0, 0, "vm"));
}
Object[] rrdData = getRRDData(2); // call rrddata with 2 for vm
if (rrdData == null) {
return null;
}
Integer numRows = (Integer) rrdData[0];
Integer numColumns = (Integer) rrdData[1];
Node legend = (Node) rrdData[2];
Node dataNode = (Node) rrdData[3];
NodeList legendChildren = legend.getChildNodes();
for (int col = 0; col < numColumns; col++) {
if (legendChildren == null || legendChildren.item(col) == null) {
continue;
}
String columnMetadata = getXMLNodeValue(legendChildren.item(col));
if (columnMetadata == null) {
continue;
}
String[] columnMetadataList = columnMetadata.split(":");
if (columnMetadataList.length != 4) {
continue;
}
String type = columnMetadataList[1];
String uuid = columnMetadataList[2];
String param = columnMetadataList[3];
if (type.equals("vm") && vmResponseMap.keySet().contains(uuid)) {
VmStatsEntry vmStatsAnswer = vmResponseMap.get(uuid);
vmStatsAnswer.setEntityType("vm");
if (param.contains("cpu")) {
vmStatsAnswer.setNumCPUs(vmStatsAnswer.getNumCPUs() + 1);
vmStatsAnswer.setCPUUtilization(vmStatsAnswer.getCPUUtilization() + getDataAverage(dataNode, col, numRows));
} else if (param.equals("vif_0_rx")) {
- vmStatsAnswer.setNetworkReadKBs(getDataAverage(dataNode, col, numRows));
+ vmStatsAnswer.setNetworkReadKBs(getDataAverage(dataNode, col, numRows)/(8*2));
} else if (param.equals("vif_0_tx")) {
- vmStatsAnswer.setNetworkWriteKBs(getDataAverage(dataNode, col, numRows));
+ vmStatsAnswer.setNetworkWriteKBs(getDataAverage(dataNode, col, numRows)/(8*2));
}
}
}
for (String vmUUID : vmResponseMap.keySet()) {
VmStatsEntry vmStatsAnswer = vmResponseMap.get(vmUUID);
if (vmStatsAnswer.getNumCPUs() != 0) {
vmStatsAnswer.setCPUUtilization(vmStatsAnswer.getCPUUtilization() / vmStatsAnswer.getNumCPUs());
s_logger.debug("Vm cpu utilization " + vmStatsAnswer.getCPUUtilization());
}
}
return vmResponseMap;
}
protected Object[] getRRDData(int flag) {
/*
* Note: 1 => called from host, hence host stats 2 => called from vm, hence vm stats
*/
String stats = "";
try {
if (flag == 1)
stats = getHostStatsRawXML();
if (flag == 2)
stats = getVmStatsRawXML();
} catch (Exception e1) {
s_logger.warn("Error whilst collecting raw stats from plugin:" + e1);
return null;
}
// s_logger.debug("The raw xml stream is:"+stats);
// s_logger.debug("Length of raw xml is:"+stats.length());
//stats are null when the host plugin call fails (host down state)
if(stats == null)
return null;
StringReader statsReader = new StringReader(stats);
InputSource statsSource = new InputSource(statsReader);
Document doc = null;
try {
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(statsSource);
} catch (Exception e) {
}
NodeList firstLevelChildren = doc.getChildNodes();
NodeList secondLevelChildren = (firstLevelChildren.item(0)).getChildNodes();
Node metaNode = secondLevelChildren.item(0);
Node dataNode = secondLevelChildren.item(1);
Integer numRows = 0;
Integer numColumns = 0;
Node legend = null;
NodeList metaNodeChildren = metaNode.getChildNodes();
for (int i = 0; i < metaNodeChildren.getLength(); i++) {
Node n = metaNodeChildren.item(i);
if (n.getNodeName().equals("rows")) {
numRows = Integer.valueOf(getXMLNodeValue(n));
} else if (n.getNodeName().equals("columns")) {
numColumns = Integer.valueOf(getXMLNodeValue(n));
} else if (n.getNodeName().equals("legend")) {
legend = n;
}
}
return new Object[] { numRows, numColumns, legend, dataNode };
}
protected String getXMLNodeValue(Node n) {
return n.getChildNodes().item(0).getNodeValue();
}
protected double getDataAverage(Node dataNode, int col, int numRows) {
double value = 0;
double dummy = 0;
int numRowsUsed = 0;
for (int row = 0; row < numRows; row++) {
Node data = dataNode.getChildNodes().item(numRows - 1 - row).getChildNodes().item(col + 1);
Double currentDataAsDouble = Double.valueOf(getXMLNodeValue(data));
if (!currentDataAsDouble.equals(Double.NaN)) {
numRowsUsed += 1;
value += currentDataAsDouble;
}
}
if(numRowsUsed == 0)
{
if((!Double.isInfinite(value))&&(!Double.isNaN(value)))
{
return value;
}
else
{
s_logger.warn("Found an invalid value (infinity/NaN) in getDataAverage(), numRows=0");
return dummy;
}
}
else
{
if((!Double.isInfinite(value/numRowsUsed))&&(!Double.isNaN(value/numRowsUsed)))
{
return (value/numRowsUsed);
}
else
{
s_logger.warn("Found an invalid value (infinity/NaN) in getDataAverage(), numRows>0");
return dummy;
}
}
}
protected String getHostStatsRawXML() {
Date currentDate = new Date();
String startTime = String.valueOf(currentDate.getTime() / 1000 - 1000);
return callHostPlugin("gethostvmstats", "collectHostStats", String.valueOf("true"), "consolidationFunction", _consolidationFunction, "interval", String
.valueOf(_pollingIntervalInSeconds), "startTime", startTime);
}
protected String getVmStatsRawXML() {
Date currentDate = new Date();
String startTime = String.valueOf(currentDate.getTime() / 1000 - 1000);
return callHostPlugin("gethostvmstats", "collectHostStats", String.valueOf("false"), "consolidationFunction", _consolidationFunction, "interval", String
.valueOf(_pollingIntervalInSeconds), "startTime", startTime);
}
protected void recordWarning(final VM vm, final String message, final Throwable e) {
Connection conn = getConnection();
final StringBuilder msg = new StringBuilder();
try {
final Long domId = vm.getDomid(conn);
msg.append("[").append(domId != null ? domId : -1l).append("] ");
} catch (final BadServerResponse e1) {
} catch (final XmlRpcException e1) {
} catch (XenAPIException e1) {
}
msg.append(message);
}
protected State convertToState(Types.VmPowerState ps) {
final State state = s_statesTable.get(ps);
return state == null ? State.Unknown : state;
}
protected HashMap<String, State> getAllVms() {
final HashMap<String, State> vmStates = new HashMap<String, State>();
Connection conn = getConnection();
Set<VM> vms = null;
for (int i = 0; i < 2; i++) {
try {
Host host = Host.getByUuid(conn, _host.uuid);
vms = host.getResidentVMs(conn);
break;
} catch (final Throwable e) {
s_logger.warn("Unable to get vms", e);
}
try {
Thread.sleep(1000);
} catch (final InterruptedException ex) {
}
}
if (vms == null) {
return null;
}
for (VM vm : vms) {
VM.Record record = null;
for (int i = 0; i < 2; i++) {
try {
record = vm.getRecord(conn);
break;
} catch (XenAPIException e1) {
s_logger.debug("VM.getRecord failed on host:" + _host.uuid + " due to " + e1.toString());
} catch (XmlRpcException e1) {
s_logger.debug("VM.getRecord failed on host:" + _host.uuid + " due to " + e1.getMessage());
}
try {
Thread.sleep(1000);
} catch (final InterruptedException ex) {
}
}
if (record == null) {
continue;
}
if (record.isControlDomain || record.isASnapshot || record.isATemplate) {
continue; // Skip DOM0
}
VmPowerState ps = record.powerState;
final State state = convertToState(ps);
if (s_logger.isTraceEnabled()) {
s_logger.trace("VM " + record.nameLabel + ": powerstate = " + ps + "; vm state=" + state.toString());
}
vmStates.put(record.nameLabel, state);
}
return vmStates;
}
protected State getVmState(final String vmName) {
Connection conn = getConnection();
int retry = 3;
while (retry-- > 0) {
try {
Set<VM> vms = VM.getByNameLabel(conn, vmName);
for (final VM vm : vms) {
return convertToState(vm.getPowerState(conn));
}
} catch (final BadServerResponse e) {
// There is a race condition within xen such that if a vm is
// deleted and we
// happen to ask for it, it throws this stupid response. So
// if this happens,
// we take a nap and try again which then avoids the race
// condition because
// the vm's information is now cleaned up by xen. The error
// is as follows
// com.xensource.xenapi.Types$BadServerResponse
// [HANDLE_INVALID, VM,
// 3dde93f9-c1df-55a7-2cde-55e1dce431ab]
s_logger.info("Unable to get a vm PowerState due to " + e.toString() + ". We are retrying. Count: " + retry);
try {
Thread.sleep(3000);
} catch (final InterruptedException ex) {
}
} catch (XenAPIException e) {
String msg = "Unable to get a vm PowerState due to " + e.toString();
s_logger.warn(msg, e);
break;
} catch (final XmlRpcException e) {
String msg = "Unable to get a vm PowerState due to " + e.getMessage();
s_logger.warn(msg, e);
break;
}
}
return State.Stopped;
}
protected CheckVirtualMachineAnswer execute(final CheckVirtualMachineCommand cmd) {
final String vmName = cmd.getVmName();
final State state = getVmState(vmName);
Integer vncPort = null;
if (state == State.Running) {
synchronized (_vms) {
_vms.put(vmName, State.Running);
}
}
return new CheckVirtualMachineAnswer(cmd, state, vncPort);
}
protected PrepareForMigrationAnswer execute(final PrepareForMigrationCommand cmd) {
/*
*
* String result = null;
*
* List<VolumeVO> vols = cmd.getVolumes(); result = mountwithoutvdi(vols, cmd.getMappings()); if (result !=
* null) { return new PrepareForMigrationAnswer(cmd, false, result); }
*/
final String vmName = cmd.getVmName();
try {
Connection conn = getConnection();
Set<Host> hosts = Host.getAll(conn);
// workaround before implementing xenserver pool
// no migration
if (hosts.size() <= 1) {
return new PrepareForMigrationAnswer(cmd, false, "not in a same xenserver pool");
}
// if the vm have CD
// 1. make iosSR shared
// 2. create pbd in target xenserver
SR sr = getISOSRbyVmName(cmd.getVmName());
if (sr != null) {
Set<PBD> pbds = sr.getPBDs(conn);
boolean found = false;
for (PBD pbd : pbds) {
if (Host.getByUuid(conn, _host.uuid).equals(pbd.getHost(conn))) {
found = true;
break;
}
}
if (!found) {
sr.setShared(conn, true);
PBD pbd = pbds.iterator().next();
PBD.Record pbdr = new PBD.Record();
pbdr.deviceConfig = pbd.getDeviceConfig(conn);
pbdr.host = Host.getByUuid(conn, _host.uuid);
pbdr.SR = sr;
PBD newpbd = PBD.create(conn, pbdr);
newpbd.plug(conn);
}
}
Set<VM> vms = VM.getByNameLabel(conn, vmName);
if (vms.size() != 1) {
String msg = "There are " + vms.size() + " " + vmName;
s_logger.warn(msg);
return new PrepareForMigrationAnswer(cmd, false, msg);
}
VM vm = vms.iterator().next();
// check network
Set<VIF> vifs = vm.getVIFs(conn);
for (VIF vif : vifs) {
Network network = vif.getNetwork(conn);
Set<PIF> pifs = network.getPIFs(conn);
Long vlan = null;
PIF npif = null;
for (PIF pif : pifs) {
try {
vlan = pif.getVLAN(conn);
if (vlan != null) {
VLAN vland = pif.getVLANMasterOf(conn);
npif = vland.getTaggedPIF(conn);
break;
}
}catch (Exception e) {
vlan = null;
continue;
}
}
if (vlan == null) {
continue;
}
network = npif.getNetwork(conn);
String nwuuid = network.getUuid(conn);
String pifuuid = null;
if(nwuuid.equalsIgnoreCase(_host.guestNetwork)) {
pifuuid = _host.guestPif;
} else if(nwuuid.equalsIgnoreCase(_host.publicNetwork)) {
pifuuid = _host.publicPif;
} else if(nwuuid.equalsIgnoreCase(_host.privateNetwork)) {
pifuuid = _host.privatePif;
} else {
continue;
}
Network vlanNetwork = enableVlanNetwork(vlan, pifuuid);
if (vlanNetwork == null) {
throw new InternalErrorException("Failed to enable VLAN network with tag: " + vlan);
}
}
synchronized (_vms) {
_vms.put(cmd.getVmName(), State.Migrating);
}
return new PrepareForMigrationAnswer(cmd, true, null);
} catch (Exception e) {
String msg = "catch exception " + e.getMessage();
s_logger.warn(msg, e);
return new PrepareForMigrationAnswer(cmd, false, msg);
}
}
public DownloadAnswer execute(final PrimaryStorageDownloadCommand cmd) {
SR tmpltsr = null;
String tmplturl = cmd.getUrl();
int index = tmplturl.lastIndexOf("/");
String mountpoint = tmplturl.substring(0, index);
String tmpltname = null;
if (index < tmplturl.length() - 1)
tmpltname = tmplturl.substring(index + 1).replace(".vhd", "");
try {
Connection conn = getConnection();
String pUuid = cmd.getPoolUuid();
SR poolsr = null;
Set<SR> srs = SR.getByNameLabel(conn, pUuid);
if (srs.size() != 1) {
String msg = "There are " + srs.size() + " SRs with same name: " + pUuid;
s_logger.warn(msg);
return new DownloadAnswer(null, 0, msg, com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR, "", "", 0);
} else {
poolsr = srs.iterator().next();
}
/* Does the template exist in primary storage pool? If yes, no copy */
VDI vmtmpltvdi = null;
VDI snapshotvdi = null;
Set<VDI> vdis = VDI.getByNameLabel(conn, "Template " + cmd.getName());
for (VDI vdi : vdis) {
VDI.Record vdir = vdi.getRecord(conn);
if (vdir.SR.equals(poolsr)) {
vmtmpltvdi = vdi;
break;
}
}
String uuid;
if (vmtmpltvdi == null) {
tmpltsr = createNfsSRbyURI(new URI(mountpoint), false);
tmpltsr.scan(conn);
VDI tmpltvdi = null;
if (tmpltname != null) {
tmpltvdi = getVDIbyUuid(tmpltname);
}
if (tmpltvdi == null) {
vdis = tmpltsr.getVDIs(conn);
for (VDI vdi : vdis) {
tmpltvdi = vdi;
break;
}
}
if (tmpltvdi == null) {
String msg = "Unable to find template vdi on secondary storage" + "host:" + _host.uuid + "pool: " + tmplturl;
s_logger.warn(msg);
return new DownloadAnswer(null, 0, msg, com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR, "", "", 0);
}
vmtmpltvdi = cloudVDIcopy(tmpltvdi, poolsr);
snapshotvdi = vmtmpltvdi.snapshot(conn, new HashMap<String, String>());
vmtmpltvdi.destroy(conn);
snapshotvdi.setNameLabel(conn, "Template " + cmd.getName());
// vmtmpltvdi.setNameDescription(conn, cmd.getDescription());
uuid = snapshotvdi.getUuid(conn);
vmtmpltvdi = snapshotvdi;
} else
uuid = vmtmpltvdi.getUuid(conn);
// Determine the size of the template
long phySize = vmtmpltvdi.getPhysicalUtilisation(conn);
DownloadAnswer answer = new DownloadAnswer(null, 100, cmd, com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOADED, uuid, uuid);
answer.setTemplateSize(phySize);
return answer;
} catch (XenAPIException e) {
String msg = "XenAPIException:" + e.toString() + "host:" + _host.uuid + "pool: " + tmplturl;
s_logger.warn(msg, e);
return new DownloadAnswer(null, 0, msg, com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR, "", "", 0);
} catch (Exception e) {
String msg = "XenAPIException:" + e.getMessage() + "host:" + _host.uuid + "pool: " + tmplturl;
s_logger.warn(msg, e);
return new DownloadAnswer(null, 0, msg, com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR, "", "", 0);
} finally {
removeSR(tmpltsr);
}
}
protected String removeSRSync(SR sr) {
if (sr == null) {
return null;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug(logX(sr, "Removing SR"));
}
Connection conn = getConnection();
long waittime = 0;
try {
Set<VDI> vdis = sr.getVDIs(conn);
for (VDI vdi : vdis) {
Map<java.lang.String, Types.VdiOperations> currentOperation = vdi.getCurrentOperations(conn);
if (currentOperation == null || currentOperation.size() == 0) {
continue;
}
if (waittime >= 1800000) {
String msg = "This template is being used, try late time";
s_logger.warn(msg);
return msg;
}
waittime += 30000;
try {
Thread.sleep(30000);
} catch (final InterruptedException ex) {
}
}
removeSR(sr);
return null;
} catch (XenAPIException e) {
s_logger.warn(logX(sr, "Unable to get current opertions " + e.toString()), e);
} catch (XmlRpcException e) {
s_logger.warn(logX(sr, "Unable to get current opertions " + e.getMessage()), e);
}
String msg = "Remove SR failed";
s_logger.warn(msg);
return msg;
}
protected void removeSR(SR sr) {
if (sr == null) {
return;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug(logX(sr, "Removing SR"));
}
for (int i = 0; i < 2; i++) {
Connection conn = getConnection();
try {
Set<VDI> vdis = sr.getVDIs(conn);
for (VDI vdi : vdis) {
vdi.forget(conn);
}
Set<PBD> pbds = sr.getPBDs(conn);
for (PBD pbd : pbds) {
if (s_logger.isDebugEnabled()) {
s_logger.debug(logX(pbd, "Unplugging pbd"));
}
if (pbd.getCurrentlyAttached(conn)) {
pbd.unplug(conn);
}
pbd.destroy(conn);
}
pbds = sr.getPBDs(conn);
if (pbds.size() == 0) {
if (s_logger.isDebugEnabled()) {
s_logger.debug(logX(sr, "Forgetting"));
}
sr.forget(conn);
return;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug(logX(sr, "There are still pbd attached"));
if (s_logger.isTraceEnabled()) {
for (PBD pbd : pbds) {
s_logger.trace(logX(pbd, " Still attached"));
}
}
}
} catch (XenAPIException e) {
s_logger.debug(logX(sr, "Catch XenAPIException: " + e.toString()));
} catch (XmlRpcException e) {
s_logger.debug(logX(sr, "Catch Exception: " + e.getMessage()));
}
}
s_logger.warn(logX(sr, "Unable to remove SR"));
}
protected MigrateAnswer execute(final MigrateCommand cmd) {
final String vmName = cmd.getVmName();
State state = null;
synchronized (_vms) {
state = _vms.get(vmName);
_vms.put(vmName, State.Stopping);
}
try {
Connection conn = getConnection();
Set<VM> vms = VM.getByNameLabel(conn, vmName);
String ipaddr = cmd.getDestinationIp();
Set<Host> hosts = Host.getAll(conn);
Host dsthost = null;
for (Host host : hosts) {
if (host.getAddress(conn).equals(ipaddr)) {
dsthost = host;
break;
}
}
// if it is windows, we will not fake it is migrateable,
// windows requires PV driver to migrate
for (VM vm : vms) {
if (!cmd.isWindows()) {
String uuid = vm.getUuid(conn);
String result = callHostPlugin("preparemigration", "uuid", uuid);
if (result == null || result.isEmpty()) {
return new MigrateAnswer(cmd, false, "migration failed", null);
}
// check if pv version is successfully set up
int i = 0;
for (; i < 20; i++) {
try {
Thread.sleep(1000);
} catch (final InterruptedException ex) {
}
VMGuestMetrics vmmetric = vm.getGuestMetrics(conn);
if (isRefNull(vmmetric))
continue;
Map<String, String> PVversion = vmmetric.getPVDriversVersion(conn);
if (PVversion != null && PVversion.containsKey("major")) {
break;
}
}
if (i >= 20) {
String msg = "migration failed due to can not fake PV driver for " + vmName;
s_logger.warn(msg);
return new MigrateAnswer(cmd, false, msg, null);
}
}
final Map<String, String> options = new HashMap<String, String>();
vm.poolMigrate(conn, dsthost, options);
state = State.Stopping;
}
return new MigrateAnswer(cmd, true, "migration succeeded", null);
} catch (XenAPIException e) {
String msg = "migration failed due to " + e.toString();
s_logger.warn(msg, e);
return new MigrateAnswer(cmd, false, msg, null);
} catch (XmlRpcException e) {
String msg = "migration failed due to " + e.getMessage();
s_logger.warn(msg, e);
return new MigrateAnswer(cmd, false, msg, null);
} finally {
synchronized (_vms) {
_vms.put(vmName, state);
}
}
}
protected State getRealPowerState(String label) {
Connection conn = getConnection();
int i = 0;
s_logger.trace("Checking on the HALTED State");
for (; i < 20; i++) {
try {
Set<VM> vms = VM.getByNameLabel(conn, label);
if (vms == null || vms.size() == 0) {
continue;
}
VM vm = vms.iterator().next();
VmPowerState vps = vm.getPowerState(conn);
if (vps != null && vps != VmPowerState.HALTED && vps != VmPowerState.UNKNOWN && vps != VmPowerState.UNRECOGNIZED) {
return convertToState(vps);
}
} catch (XenAPIException e) {
String msg = "Unable to get real power state due to " + e.toString();
s_logger.warn(msg, e);
} catch (XmlRpcException e) {
String msg = "Unable to get real power state due to " + e.getMessage();
s_logger.warn(msg, e);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
return State.Stopped;
}
protected Pair<VM, VM.Record> getControlDomain(Connection conn) throws XenAPIException, XmlRpcException {
Host host = Host.getByUuid(conn, _host.uuid);
Set<VM> vms = null;
vms = host.getResidentVMs(conn);
for (VM vm : vms) {
if (vm.getIsControlDomain(conn)) {
return new Pair<VM, VM.Record>(vm, vm.getRecord(conn));
}
}
throw new CloudRuntimeException("Com'on no control domain? What the crap?!#@!##$@");
}
protected HashMap<String, State> sync() {
HashMap<String, State> newStates;
HashMap<String, State> oldStates = null;
final HashMap<String, State> changes = new HashMap<String, State>();
synchronized (_vms) {
newStates = getAllVms();
if (newStates == null) {
s_logger.debug("Unable to get the vm states so no state sync at this point.");
return null;
}
oldStates = new HashMap<String, State>(_vms.size());
oldStates.putAll(_vms);
for (final Map.Entry<String, State> entry : newStates.entrySet()) {
final String vm = entry.getKey();
State newState = entry.getValue();
final State oldState = oldStates.remove(vm);
if (newState == State.Stopped && oldState != State.Stopping && oldState != null && oldState != State.Stopped) {
newState = getRealPowerState(vm);
}
if (s_logger.isTraceEnabled()) {
s_logger.trace("VM " + vm + ": xen has state " + newState + " and we have state " + (oldState != null ? oldState.toString() : "null"));
}
if (vm.startsWith("migrating")) {
s_logger.debug("Migrating from xen detected. Skipping");
continue;
}
if (oldState == null) {
_vms.put(vm, newState);
s_logger.debug("Detecting a new state but couldn't find a old state so adding it to the changes: " + vm);
changes.put(vm, newState);
} else if (oldState == State.Starting) {
if (newState == State.Running) {
_vms.put(vm, newState);
} else if (newState == State.Stopped) {
s_logger.debug("Ignoring vm " + vm + " because of a lag in starting the vm.");
}
} else if (oldState == State.Migrating) {
if (newState == State.Running) {
s_logger.debug("Detected that an migrating VM is now running: " + vm);
_vms.put(vm, newState);
}
} else if (oldState == State.Stopping) {
if (newState == State.Stopped) {
_vms.put(vm, newState);
} else if (newState == State.Running) {
s_logger.debug("Ignoring vm " + vm + " because of a lag in stopping the vm. ");
}
} else if (oldState != newState) {
_vms.put(vm, newState);
if (newState == State.Stopped) {
/*
* if (_vmsKilled.remove(vm)) { s_logger.debug("VM " + vm + " has been killed for storage. ");
* newState = State.Error; }
*/
}
changes.put(vm, newState);
}
}
for (final Map.Entry<String, State> entry : oldStates.entrySet()) {
final String vm = entry.getKey();
final State oldState = entry.getValue();
if (s_logger.isTraceEnabled()) {
s_logger.trace("VM " + vm + " is now missing from xen so reporting stopped");
}
if (oldState == State.Stopping) {
s_logger.debug("Ignoring VM " + vm + " in transition state stopping.");
_vms.remove(vm);
} else if (oldState == State.Starting) {
s_logger.debug("Ignoring VM " + vm + " in transition state starting.");
} else if (oldState == State.Stopped) {
_vms.remove(vm);
} else if (oldState == State.Migrating) {
s_logger.debug("Ignoring VM " + vm + " in migrating state.");
} else {
State state = State.Stopped;
/*
* if (_vmsKilled.remove(entry.getKey())) { s_logger.debug("VM " + vm +
* " has been killed by storage monitor"); state = State.Error; }
*/
changes.put(entry.getKey(), state);
}
}
}
return changes;
}
protected ReadyAnswer execute(ReadyCommand cmd) {
Long dcId = cmd.getDataCenterId();
// Ignore the result of the callHostPlugin. Even if unmounting the
// snapshots dir fails, let Ready command
// succeed.
callHostPlugin("unmountSnapshotsDir", "dcId", dcId.toString());
return new ReadyAnswer(cmd);
}
//
// using synchronized on VM name in the caller does not prevent multiple
// commands being sent against
// the same VM, there will be a race condition here in finally clause and
// the main block if
// there are multiple requests going on
//
// Therefore, a lazy solution is to add a synchronized guard here
protected int getVncPort(VM vm) {
Connection conn = getConnection();
VM.Record record;
try {
record = vm.getRecord(conn);
} catch (XenAPIException e) {
String msg = "Unable to get vnc-port due to " + e.toString();
s_logger.warn(msg, e);
return -1;
} catch (XmlRpcException e) {
String msg = "Unable to get vnc-port due to " + e.getMessage();
s_logger.warn(msg, e);
return -1;
}
String hvm = "true";
if (record.HVMBootPolicy.isEmpty()) {
hvm = "false";
}
String vncport = callHostPlugin("getvncport", "domID", record.domid.toString(), "hvm", hvm);
if (vncport == null || vncport.isEmpty()) {
return -1;
}
vncport = vncport.replace("\n", "");
return NumbersUtil.parseInt(vncport, -1);
}
protected Answer execute(final RebootCommand cmd) {
synchronized (_vms) {
_vms.put(cmd.getVmName(), State.Starting);
}
try {
Connection conn = getConnection();
Set<VM> vms = null;
try {
vms = VM.getByNameLabel(conn, cmd.getVmName());
} catch (XenAPIException e0) {
s_logger.debug("getByNameLabel failed " + e0.toString());
return new RebootAnswer(cmd, "getByNameLabel failed " + e0.toString());
} catch (Exception e0) {
s_logger.debug("getByNameLabel failed " + e0.getMessage());
return new RebootAnswer(cmd, "getByNameLabel failed");
}
for (VM vm : vms) {
try {
vm.cleanReboot(conn);
} catch (XenAPIException e) {
s_logger.debug("Do Not support Clean Reboot, fall back to hard Reboot: " + e.toString());
try {
vm.hardReboot(conn);
} catch (XenAPIException e1) {
s_logger.debug("Caught exception on hard Reboot " + e1.toString());
return new RebootAnswer(cmd, "reboot failed: " + e1.toString());
} catch (XmlRpcException e1) {
s_logger.debug("Caught exception on hard Reboot " + e1.getMessage());
return new RebootAnswer(cmd, "reboot failed");
}
} catch (XmlRpcException e) {
String msg = "Clean Reboot failed due to " + e.getMessage();
s_logger.warn(msg, e);
return new RebootAnswer(cmd, msg);
}
}
return new RebootAnswer(cmd, "reboot succeeded", null, null);
} finally {
synchronized (_vms) {
_vms.put(cmd.getVmName(), State.Running);
}
}
}
protected Answer execute(RebootRouterCommand cmd) {
Long bytesSent = 0L;
Long bytesRcvd = 0L;
if (VirtualMachineName.isValidRouterName(cmd.getVmName())) {
long[] stats = getNetworkStats(cmd.getVmName());
bytesSent = stats[0];
bytesRcvd = stats[1];
}
RebootAnswer answer = (RebootAnswer) execute((RebootCommand) cmd);
answer.setBytesSent(bytesSent);
answer.setBytesReceived(bytesRcvd);
if (answer.getResult()) {
String cnct = connect(cmd.getVmName(), cmd.getPrivateIpAddress());
networkUsage(cmd.getPrivateIpAddress(), "create", null);
if (cnct == null) {
_domrIPMap.put(cmd.getVmName(), cmd.getPrivateIpAddress());
return answer;
} else {
return new Answer(cmd, false, cnct);
}
}
return answer;
}
protected VM createVmFromTemplate(Connection conn, StartCommand cmd) throws XenAPIException, XmlRpcException {
Set<VM> templates;
VM vm = null;
String guestOsTypeName = cmd.getGuestOSDescription();
templates = VM.getByNameLabel(conn, guestOsTypeName);
assert templates.size() == 1 : "Should only have 1 template but found " + templates.size();
VM template = templates.iterator().next();
vm = template.createClone(conn, cmd.getVmName());
vm.removeFromOtherConfig(conn, "disks");
if (!(guestOsTypeName.startsWith("Windows") || guestOsTypeName.startsWith("Citrix") || guestOsTypeName.startsWith("Other"))) {
if (cmd.getBootFromISO())
vm.setPVBootloader(conn, "eliloader");
else
vm.setPVBootloader(conn, "pygrub");
vm.addToOtherConfig(conn, "install-repository", "cdrom");
}
return vm;
}
public boolean joinPool(String masterIp, String username, String password) {
Connection slaveConn = null;
Connection poolConn = null;
Session slaveSession = null;
URL slaveUrl = null;
try {
// Connect and find out about the new connection to the new pool.
poolConn = _connPool.masterConnect(masterIp, username, password);
//check if this host is already in pool
Set<Host> hosts = Host.getAll(poolConn);
for( Host host : hosts ) {
if(host.getAddress(poolConn).equals(_host.ip)) {
return true;
}
}
slaveUrl = new URL("http://" + _host.ip);
slaveConn = new Connection(slaveUrl, 100);
slaveSession = Session.slaveLocalLoginWithPassword(slaveConn, _username, _password);
// Now join it.
Pool.join(slaveConn, masterIp, username, password);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Joined the pool at " + masterIp);
}
try {
// slave will restart xapi in 10 sec
Thread.sleep(10000);
} catch (InterruptedException e) {
}
// check if the master of this host is set correctly.
Connection c = new Connection(slaveUrl, 100);
for (int i = 0; i < 15; i++) {
try {
Session.loginWithPassword(c, _username, _password, APIVersion.latest().toString());
s_logger.debug("Still waiting for the conversion to the master");
Session.logout(c);
c.dispose();
} catch (Types.HostIsSlave e) {
try {
Session.logout(c);
c.dispose();
} catch (XmlRpcException e1) {
s_logger.debug("Unable to logout of test connection due to " + e1.getMessage());
} catch (XenAPIException e1) {
s_logger.debug("Unable to logout of test connection due to " + e1.getMessage());
}
break;
} catch (XmlRpcException e) {
s_logger.debug("XmlRpcException: Still waiting for the conversion to the master");
} catch (Exception e) {
s_logger.debug("Exception: Still waiting for the conversion to the master");
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
}
return true;
} catch (MalformedURLException e) {
throw new CloudRuntimeException("Problem with url " + _host.ip);
} catch (XenAPIException e) {
String msg = "Unable to allow host " + _host.uuid
+ " to join pool " + masterIp + " due to " + e.toString();
s_logger.warn(msg, e);
throw new RuntimeException(msg);
} catch (XmlRpcException e) {
String msg = "Unable to allow host " + _host.uuid
+ " to join pool " + masterIp + " due to " + e.getMessage();
s_logger.warn(msg, e);
throw new RuntimeException(msg);
} finally {
if (poolConn != null) {
try {
Session.logout(poolConn);
} catch (Exception e) {
}
poolConn.dispose();
}
if(slaveSession != null) {
try {
Session.localLogout(slaveConn);
} catch (Exception e) {
}
}
}
}
protected void startvmfailhandle(VM vm, List<Ternary<SR, VDI, VolumeVO>> mounts) {
Connection conn = getConnection();
if (vm != null) {
try {
if (vm.getPowerState(conn) == VmPowerState.RUNNING) {
try {
vm.hardShutdown(conn);
} catch (Exception e) {
String msg = "VM hardshutdown failed due to " + e.toString();
s_logger.warn(msg);
}
}
if (vm.getPowerState(conn) == VmPowerState.HALTED) {
try {
vm.destroy(conn);
} catch (Exception e) {
String msg = "VM destroy failed due to " + e.toString();
s_logger.warn(msg);
}
}
} catch (Exception e) {
String msg = "VM getPowerState failed due to " + e.toString();
s_logger.warn(msg);
}
}
if (mounts != null) {
for (Ternary<SR, VDI, VolumeVO> mount : mounts) {
VDI vdi = mount.second();
Set<VBD> vbds = null;
try {
vbds = vdi.getVBDs(conn);
} catch (Exception e) {
String msg = "VDI getVBDS failed due to " + e.toString();
s_logger.warn(msg);
continue;
}
for (VBD vbd : vbds) {
try {
vbd.unplug(conn);
vbd.destroy(conn);
} catch (Exception e) {
String msg = "VBD destroy failed due to " + e.toString();
s_logger.warn(msg);
}
}
}
}
}
protected void setMemory(Connection conn, VM vm, long memsize) throws XmlRpcException, XenAPIException {
vm.setMemoryStaticMin(conn, memsize);
vm.setMemoryDynamicMin(conn, memsize);
vm.setMemoryDynamicMax(conn, memsize);
vm.setMemoryStaticMax(conn, memsize);
}
protected StartAnswer execute(StartCommand cmd) {
State state = State.Stopped;
Connection conn = getConnection();
VM vm = null;
SR isosr = null;
List<Ternary<SR, VDI, VolumeVO>> mounts = null;
for (int retry = 0; retry < 2; retry++) {
try {
synchronized (_vms) {
_vms.put(cmd.getVmName(), State.Starting);
}
List<VolumeVO> vols = cmd.getVolumes();
mounts = mount(vols);
if (retry == 1) {
// at the second time, try hvm
cmd.setGuestOSDescription("Other install media");
}
vm = createVmFromTemplate(conn, cmd);
long memsize = cmd.getRamSize() * 1024L * 1024L;
setMemory(conn, vm, memsize);
vm.setIsATemplate(conn, false);
vm.setVCPUsMax(conn, (long) cmd.getCpu());
vm.setVCPUsAtStartup(conn, (long) cmd.getCpu());
Host host = Host.getByUuid(conn, _host.uuid);
vm.setAffinity(conn, host);
Map<String, String> vcpuparam = new HashMap<String, String>();
vcpuparam.put("weight", Integer.toString(cmd.getCpuWeight()));
vcpuparam.put("cap", Integer.toString(cmd.getUtilization()));
vm.setVCPUsParams(conn, vcpuparam);
boolean bootFromISO = cmd.getBootFromISO();
/* create root VBD */
VBD.Record vbdr = new VBD.Record();
Ternary<SR, VDI, VolumeVO> mount = mounts.get(0);
vbdr.VM = vm;
vbdr.VDI = mount.second();
vbdr.bootable = !bootFromISO;
vbdr.userdevice = "0";
vbdr.mode = Types.VbdMode.RW;
vbdr.type = Types.VbdType.DISK;
VBD.create(conn, vbdr);
/* determine available slots to attach data volumes to */
List<String> availableSlots = new ArrayList<String>();
availableSlots.add("1");
availableSlots.add("2");
availableSlots.add("4");
availableSlots.add("5");
availableSlots.add("6");
availableSlots.add("7");
/* create data VBDs */
for (int i = 1; i < mounts.size(); i++) {
mount = mounts.get(i);
// vdi.setNameLabel(conn, cmd.getVmName() + "-DATA");
vbdr.VM = vm;
vbdr.VDI = mount.second();
vbdr.bootable = false;
vbdr.userdevice = Long.toString(mount.third().getDeviceId());
vbdr.mode = Types.VbdMode.RW;
vbdr.type = Types.VbdType.DISK;
vbdr.unpluggable = true;
VBD.create(conn, vbdr);
}
/* create CD-ROM VBD */
VBD.Record cdromVBDR = new VBD.Record();
cdromVBDR.VM = vm;
cdromVBDR.empty = true;
cdromVBDR.bootable = bootFromISO;
cdromVBDR.userdevice = "3";
cdromVBDR.mode = Types.VbdMode.RO;
cdromVBDR.type = Types.VbdType.CD;
VBD cdromVBD = VBD.create(conn, cdromVBDR);
/* insert the ISO VDI if isoPath is not null */
String isopath = cmd.getISOPath();
if (isopath != null) {
int index = isopath.lastIndexOf("/");
String mountpoint = isopath.substring(0, index);
URI uri = new URI(mountpoint);
isosr = createIsoSRbyURI(uri, cmd.getVmName(), false);
String isoname = isopath.substring(index + 1);
VDI isovdi = getVDIbyLocationandSR(isoname, isosr);
if (isovdi == null) {
String msg = " can not find ISO " + cmd.getISOPath();
s_logger.warn(msg);
return new StartAnswer(cmd, msg);
} else {
cdromVBD.insert(conn, isovdi);
}
}
createVIF(conn, vm, cmd.getGuestMacAddress(), cmd.getGuestNetworkId(), cmd.getNetworkRateMbps(), "0", false);
if (cmd.getExternalMacAddress() != null && cmd.getExternalVlan() != null) {
createVIF(conn, vm, cmd.getExternalMacAddress(), cmd.getExternalVlan(), 0, "1", true);
}
/* set action after crash as destroy */
vm.setActionsAfterCrash(conn, Types.OnCrashBehaviour.DESTROY);
vm.start(conn, false, true);
if (_canBridgeFirewall) {
String result = callHostPlugin("default_network_rules",
"vmName", cmd.getVmName(),
"vmIP", cmd.getGuestIpAddress(),
"vmMAC", cmd.getGuestMacAddress(),
"vmID", Long.toString(cmd.getId()));
if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
s_logger.warn("Failed to program default network rules for vm " + cmd.getVmName());
} else {
s_logger.info("Programmed default network rules for vm " + cmd.getVmName());
}
}
state = State.Running;
return new StartAnswer(cmd);
} catch (XenAPIException e) {
String errormsg = e.toString();
String msg = "Exception caught while starting VM due to message:" + errormsg + " (" + e.getClass().getName() + ")";
if (!errormsg.contains("Unable to find partition containing kernel") && !errormsg.contains("Unable to access a required file in the specified repository")) {
s_logger.warn(msg, e);
startvmfailhandle(vm, mounts);
removeSR(isosr);
} else {
startvmfailhandle(vm, mounts);
removeSR(isosr);
continue;
}
state = State.Stopped;
return new StartAnswer(cmd, msg);
} catch (Exception e) {
String msg = "Exception caught while starting VM due to message:" + e.getMessage();
s_logger.warn(msg, e);
startvmfailhandle(vm, mounts);
removeSR(isosr);
state = State.Stopped;
return new StartAnswer(cmd, msg);
} finally {
synchronized (_vms) {
_vms.put(cmd.getVmName(), state);
}
}
}
String msg = "Start VM failed";
return new StartAnswer(cmd, msg);
}
protected VIF createVIF(Connection conn, VM vm, String mac, int rate, String devNum, Network network) throws XenAPIException, XmlRpcException,
InternalErrorException {
VIF.Record vifr = new VIF.Record();
vifr.VM = vm;
vifr.device = devNum;
vifr.MAC = mac;
vifr.network = network;
if ( rate == 0 ) rate = 200;
vifr.qosAlgorithmType = "ratelimit";
vifr.qosAlgorithmParams = new HashMap<String, String>();
// convert mbs to kilobyte per second
vifr.qosAlgorithmParams.put("kbps", Integer.toString(rate * 128));
return VIF.create(conn, vifr);
}
protected VIF createVIF(Connection conn, VM vm, String mac, String vlanTag, int rate, String devNum, boolean isPub) throws XenAPIException, XmlRpcException,
InternalErrorException {
String nwUuid = (isPub ? _host.publicNetwork : _host.guestNetwork);
String pifUuid = (isPub ? _host.publicPif : _host.guestPif);
Network vlanNetwork = null;
if ("untagged".equalsIgnoreCase(vlanTag)) {
vlanNetwork = Network.getByUuid(conn, nwUuid);
} else {
vlanNetwork = enableVlanNetwork(Long.valueOf(vlanTag), pifUuid);
}
if (vlanNetwork == null) {
throw new InternalErrorException("Failed to enable VLAN network with tag: " + vlanTag);
}
return createVIF(conn, vm, mac, rate, devNum, vlanNetwork);
}
protected StopAnswer execute(final StopCommand cmd) {
String vmName = cmd.getVmName();
try {
Connection conn = getConnection();
Set<VM> vms = VM.getByNameLabel(conn, vmName);
// stop vm which is running on this host or is in halted state
for (VM vm : vms) {
VM.Record vmr = vm.getRecord(conn);
if (vmr.powerState != VmPowerState.RUNNING)
continue;
if (isRefNull(vmr.residentOn))
continue;
if (vmr.residentOn.getUuid(conn).equals(_host.uuid))
continue;
vms.remove(vm);
}
if (vms.size() == 0) {
s_logger.warn("VM does not exist on XenServer" + _host.uuid);
synchronized (_vms) {
_vms.remove(vmName);
}
return new StopAnswer(cmd, "VM does not exist", 0, 0L, 0L);
}
Long bytesSent = 0L;
Long bytesRcvd = 0L;
for (VM vm : vms) {
VM.Record vmr = vm.getRecord(conn);
if (vmr.isControlDomain) {
String msg = "Tring to Shutdown control domain";
s_logger.warn(msg);
return new StopAnswer(cmd, msg);
}
if (vmr.powerState == VmPowerState.RUNNING && !isRefNull(vmr.residentOn) && !vmr.residentOn.getUuid(conn).equals(_host.uuid)) {
String msg = "Stop Vm " + vmName + " failed due to this vm is not running on this host: " + _host.uuid + " but host:" + vmr.residentOn.getUuid(conn);
s_logger.warn(msg);
return new StopAnswer(cmd, msg);
}
State state = null;
synchronized (_vms) {
state = _vms.get(vmName);
_vms.put(vmName, State.Stopping);
}
try {
if (vmr.powerState == VmPowerState.RUNNING) {
/* when stop a vm, set affinity to current xenserver */
vm.setAffinity(conn, vm.getResidentOn(conn));
try {
if (VirtualMachineName.isValidRouterName(vmName)) {
long[] stats = getNetworkStats(vmName);
bytesSent = stats[0];
bytesRcvd = stats[1];
}
if (_canBridgeFirewall) {
String result = callHostPlugin("destroy_network_rules_for_vm", "vmName", cmd.getVmName());
if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
s_logger.warn("Failed to remove network rules for vm " + cmd.getVmName());
} else {
s_logger.info("Removed network rules for vm " + cmd.getVmName());
}
}
vm.cleanShutdown(conn);
} catch (XenAPIException e) {
s_logger.debug("Do Not support Clean Shutdown, fall back to hard Shutdown: " + e.toString());
try {
vm.hardShutdown(conn);
} catch (XenAPIException e1) {
String msg = "Hard Shutdown failed due to " + e1.toString();
s_logger.warn(msg, e1);
return new StopAnswer(cmd, msg);
} catch (XmlRpcException e1) {
String msg = "Hard Shutdown failed due to " + e1.getMessage();
s_logger.warn(msg, e1);
return new StopAnswer(cmd, msg);
}
} catch (XmlRpcException e) {
String msg = "Clean Shutdown failed due to " + e.getMessage();
s_logger.warn(msg, e);
return new StopAnswer(cmd, msg);
}
}
} catch (Exception e) {
String msg = "Catch exception " + e.getClass().toString() + " when stop VM:" + cmd.getVmName();
s_logger.debug(msg);
return new StopAnswer(cmd, msg);
} finally {
try {
if (vm.getPowerState(conn) == VmPowerState.HALTED) {
Set<VIF> vifs = vm.getVIFs(conn);
List<Network> networks = new ArrayList<Network>();
for (VIF vif : vifs) {
networks.add(vif.getNetwork(conn));
}
List<VDI> vdis = getVdis(vm);
vm.destroy(conn);
for( VDI vdi : vdis ){
umount(vdi);
}
state = State.Stopped;
SR sr = getISOSRbyVmName(cmd.getVmName());
removeSR(sr);
if (VirtualMachineName.isValidRouterName(vmName)) {
_domrIPMap.remove(vmName);
}
// Disable any VLAN networks that aren't used
// anymore
for (Network network : networks) {
if (network.getNameLabel(conn).startsWith("VLAN")) {
disableVlanNetwork(network);
}
}
}
} catch (XenAPIException e) {
String msg = "VM destroy failed in Stop " + vmName + " Command due to " + e.toString();
s_logger.warn(msg, e);
} catch (Exception e) {
String msg = "VM destroy failed in Stop " + vmName + " Command due to " + e.getMessage();
s_logger.warn(msg, e);
} finally {
synchronized (_vms) {
_vms.put(vmName, state);
}
}
}
}
return new StopAnswer(cmd, "Stop VM " + vmName + " Succeed", 0, bytesSent, bytesRcvd);
} catch (XenAPIException e) {
String msg = "Stop Vm " + vmName + " fail due to " + e.toString();
s_logger.warn(msg, e);
return new StopAnswer(cmd, msg);
} catch (XmlRpcException e) {
String msg = "Stop Vm " + vmName + " fail due to " + e.getMessage();
s_logger.warn(msg, e);
return new StopAnswer(cmd, msg);
}
}
private List<VDI> getVdis(VM vm) {
List<VDI> vdis = new ArrayList<VDI>();
try {
Connection conn = getConnection();
Set<VBD> vbds =vm.getVBDs(conn);
for( VBD vbd : vbds ) {
vdis.add(vbd.getVDI(conn));
}
} catch (XenAPIException e) {
String msg = "getVdis can not get VPD due to " + e.toString();
s_logger.warn(msg, e);
} catch (XmlRpcException e) {
String msg = "getVdis can not get VPD due to " + e.getMessage();
s_logger.warn(msg, e);
}
return vdis;
}
protected String connect(final String vmName, final String ipAddress, final int port) {
for (int i = 0; i <= _retry; i++) {
try {
Connection conn = getConnection();
Set<VM> vms = VM.getByNameLabel(conn, vmName);
if (vms.size() < 1) {
String msg = "VM " + vmName + " is not running";
s_logger.warn(msg);
return msg;
}
} catch (Exception e) {
String msg = "VM.getByNameLabel " + vmName + " failed due to " + e.toString();
s_logger.warn(msg, e);
return msg;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Trying to connect to " + ipAddress);
}
if (pingdomr(ipAddress, Integer.toString(port)))
return null;
try {
Thread.sleep(_sleep);
} catch (final InterruptedException e) {
}
}
String msg = "Timeout, Unable to logon to " + ipAddress;
s_logger.debug(msg);
return msg;
}
protected String connect(final String vmname, final String ipAddress) {
return connect(vmname, ipAddress, 3922);
}
protected StartRouterAnswer execute(StartRouterCommand cmd) {
final String vmName = cmd.getVmName();
final DomainRouter router = cmd.getRouter();
try {
String tag = router.getVnet();
Network network = null;
if ("untagged".equalsIgnoreCase(tag)) {
Connection conn = getConnection();
network = Network.getByUuid(conn, _host.guestNetwork);
} else {
network = enableVlanNetwork(Long.parseLong(tag), _host.guestPif);
}
if (network == null) {
throw new InternalErrorException("Failed to enable VLAN network with tag: " + tag);
}
String bootArgs = cmd.getBootArgs();
String result = startSystemVM(vmName, router.getVlanId(), network, cmd.getVolumes(), bootArgs, router.getGuestMacAddress(), router.getPrivateIpAddress(), router
.getPrivateMacAddress(), router.getPublicMacAddress(), 3922, router.getRamSize(), router.getGuestOSId(), cmd.getNetworkRateMbps());
if (result == null) {
networkUsage(router.getPrivateIpAddress(), "create", null);
_domrIPMap.put(cmd.getVmName(), router.getPrivateIpAddress());
return new StartRouterAnswer(cmd);
}
return new StartRouterAnswer(cmd, result);
} catch (Exception e) {
String msg = "Exception caught while starting router vm " + vmName + " due to " + e.getMessage();
s_logger.warn(msg, e);
return new StartRouterAnswer(cmd, msg);
}
}
protected String startSystemVM(String vmName, String vlanId, Network nw0, List<VolumeVO> vols, String bootArgs, String guestMacAddr, String privateIp, String privateMacAddr,
String publicMacAddr, int cmdPort, long ramSize, long guestOsId, int networkRateMbps) {
VM vm = null;
List<Ternary<SR, VDI, VolumeVO>> mounts = null;
Connection conn = getConnection();
State state = State.Stopped;
String linkLocalBrName = null;
try {
synchronized (_vms) {
_vms.put(vmName, State.Starting);
}
mounts = mount(vols);
assert mounts.size() == 1 : "System VMs should have only 1 partition but we actually have " + mounts.size();
Ternary<SR, VDI, VolumeVO> mount = mounts.get(0);
if (!patchSystemVm(mount.second(), vmName)) { // FIXME make this
// nonspecific
String msg = "patch system vm failed";
s_logger.warn(msg);
return msg;
}
Set<VM> templates = VM.getByNameLabel(conn, "CentOS 5.3");
if (templates.size() == 0) {
templates = VM.getByNameLabel(conn, "CentOS 5.3 (64-bit)");
if (templates.size() == 0) {
String msg = " can not find template CentOS 5.3 ";
s_logger.warn(msg);
return msg;
}
}
VM template = templates.iterator().next();
vm = template.createClone(conn, vmName);
vm.removeFromOtherConfig(conn, "disks");
vm.setPVBootloader(conn, "pygrub");
long memsize = ramSize * 1024L * 1024L;
setMemory(conn, vm, memsize);
vm.setIsATemplate(conn, false);
vm.setVCPUsAtStartup(conn, 1L);
Host host = Host.getByUuid(conn, _host.uuid);
vm.setAffinity(conn, host);
/* create VBD */
VBD.Record vbdr = new VBD.Record();
vbdr.VM = vm;
vbdr.VDI = mount.second();
vbdr.bootable = true;
vbdr.userdevice = "0";
vbdr.mode = Types.VbdMode.RW;
vbdr.type = Types.VbdType.DISK;
VBD.create(conn, vbdr);
/* create VIF0 */
Network network = null;
if (VirtualMachineName.isValidConsoleProxyName(vmName) || VirtualMachineName.isValidSecStorageVmName(vmName, null)) {
network = Network.getByUuid(conn, _host.linkLocalNetwork);
} else {
network = nw0;
}
createVIF(conn, vm, guestMacAddr, networkRateMbps, "0", network);
/* create VIF1 */
/* For routing vm, set its network as link local bridge */
if (VirtualMachineName.isValidRouterName(vmName) && privateIp.startsWith("169.254")) {
network = Network.getByUuid(conn, _host.linkLocalNetwork);
} else {
network = Network.getByUuid(conn, _host.privateNetwork);
}
createVIF(conn, vm, privateMacAddr, networkRateMbps, "1", network);
/* create VIF2 */
if( !publicMacAddr.equalsIgnoreCase("FE:FF:FF:FF:FF:FF") ) {
network = null;
if ("untagged".equalsIgnoreCase(vlanId)) {
network = Network.getByUuid(conn, _host.publicNetwork);
} else {
network = enableVlanNetwork(Long.valueOf(vlanId), _host.publicPif);
if (network == null) {
throw new InternalErrorException("Failed to enable VLAN network with tag: " + vlanId);
}
}
createVIF(conn, vm, publicMacAddr, networkRateMbps, "2", network);
}
/* set up PV dom argument */
String pvargs = vm.getPVArgs(conn);
pvargs = pvargs + bootArgs;
if (s_logger.isInfoEnabled())
s_logger.info("PV args for system vm are " + pvargs);
vm.setPVArgs(conn, pvargs);
/* destroy console */
Set<Console> consoles = vm.getRecord(conn).consoles;
for (Console console : consoles) {
console.destroy(conn);
}
/* set action after crash as destroy */
vm.setActionsAfterCrash(conn, Types.OnCrashBehaviour.DESTROY);
vm.start(conn, false, true);
if (_canBridgeFirewall) {
String result = callHostPlugin("default_network_rules_systemvm", "vmName", vmName);
if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
s_logger.warn("Failed to program default system vm network rules for " + vmName);
} else {
s_logger.info("Programmed default system vm network rules for " + vmName);
}
}
if (s_logger.isInfoEnabled())
s_logger.info("Ping system vm command port, " + privateIp + ":" + cmdPort);
state = State.Running;
String result = connect(vmName, privateIp, cmdPort);
if (result != null) {
String msg = "Can not ping System vm " + vmName + "due to:" + result;
s_logger.warn(msg);
throw new CloudRuntimeException(msg);
} else {
if (s_logger.isInfoEnabled())
s_logger.info("Ping system vm command port succeeded for vm " + vmName);
}
return null;
} catch (XenAPIException e) {
String msg = "Exception caught while starting System vm " + vmName + " due to " + e.toString();
s_logger.warn(msg, e);
startvmfailhandle(vm, mounts);
state = State.Stopped;
return msg;
} catch (Exception e) {
String msg = "Exception caught while starting System vm " + vmName + " due to " + e.getMessage();
s_logger.warn(msg, e);
startvmfailhandle(vm, mounts);
state = State.Stopped;
return msg;
} finally {
synchronized (_vms) {
_vms.put(vmName, state);
}
}
}
// TODO : need to refactor it to reuse code with StartRouter
protected Answer execute(final StartConsoleProxyCommand cmd) {
final String vmName = cmd.getVmName();
final ConsoleProxyVO proxy = cmd.getProxy();
try {
Connection conn = getConnection();
Network network = Network.getByUuid(conn, _host.privateNetwork);
String bootArgs = cmd.getBootArgs();
bootArgs += " zone=" + _dcId;
bootArgs += " pod=" + _pod;
bootArgs += " guid=Proxy." + proxy.getId();
bootArgs += " proxy_vm=" + proxy.getId();
bootArgs += " localgw=" + _localGateway;
String result = startSystemVM(vmName, proxy.getVlanId(), network, cmd.getVolumes(), bootArgs, proxy.getGuestMacAddress(), proxy.getGuestIpAddress(), proxy
.getPrivateMacAddress(), proxy.getPublicMacAddress(), cmd.getProxyCmdPort(), proxy.getRamSize(), proxy.getGuestOSId(), cmd.getNetworkRateMbps());
if (result == null) {
return new StartConsoleProxyAnswer(cmd);
}
return new StartConsoleProxyAnswer(cmd, result);
} catch (Exception e) {
String msg = "Exception caught while starting router vm " + vmName + " due to " + e.getMessage();
s_logger.warn(msg, e);
return new StartConsoleProxyAnswer(cmd, msg);
}
}
protected boolean patchSystemVm(VDI vdi, String vmName) {
if (vmName.startsWith("r-")) {
return patchSpecialVM(vdi, vmName, "router");
} else if (vmName.startsWith("v-")) {
return patchSpecialVM(vdi, vmName, "consoleproxy");
} else if (vmName.startsWith("s-")) {
return patchSpecialVM(vdi, vmName, "secstorage");
} else {
throw new CloudRuntimeException("Tried to patch unknown type of system vm");
}
}
protected boolean isDeviceUsed(VM vm, Long deviceId) {
// Figure out the disk number to attach the VM to
String msg = null;
try {
Connection conn = getConnection();
Set<String> allowedVBDDevices = vm.getAllowedVBDDevices(conn);
if (allowedVBDDevices.contains(deviceId.toString())) {
return false;
}
return true;
} catch (XmlRpcException e) {
msg = "Catch XmlRpcException due to: " + e.getMessage();
s_logger.warn(msg, e);
} catch (XenAPIException e) {
msg = "Catch XenAPIException due to: " + e.toString();
s_logger.warn(msg, e);
}
throw new CloudRuntimeException("When check deviceId " + msg);
}
protected String getUnusedDeviceNum(VM vm) {
// Figure out the disk number to attach the VM to
try {
Connection conn = getConnection();
Set<String> allowedVBDDevices = vm.getAllowedVBDDevices(conn);
if (allowedVBDDevices.size() == 0)
throw new CloudRuntimeException("Could not find an available slot in VM with name: " + vm.getNameLabel(conn) + " to attach a new disk.");
return allowedVBDDevices.iterator().next();
} catch (XmlRpcException e) {
String msg = "Catch XmlRpcException due to: " + e.getMessage();
s_logger.warn(msg, e);
} catch (XenAPIException e) {
String msg = "Catch XenAPIException due to: " + e.toString();
s_logger.warn(msg, e);
}
throw new CloudRuntimeException("Could not find an available slot in VM with name to attach a new disk.");
}
protected boolean patchSpecialVM(VDI vdi, String vmname, String vmtype) {
// patch special vm here, domr, domp
VBD vbd = null;
Connection conn = getConnection();
try {
Host host = Host.getByUuid(conn, _host.uuid);
Set<VM> vms = host.getResidentVMs(conn);
for (VM vm : vms) {
VM.Record vmrec = null;
try {
vmrec = vm.getRecord(conn);
} catch (Exception e) {
String msg = "VM.getRecord failed due to " + e.toString() + " " + e.getMessage();
s_logger.warn(msg);
continue;
}
if (vmrec.isControlDomain) {
/* create VBD */
VBD.Record vbdr = new VBD.Record();
vbdr.VM = vm;
vbdr.VDI = vdi;
vbdr.bootable = false;
vbdr.userdevice = getUnusedDeviceNum(vm);
vbdr.unpluggable = true;
vbdr.mode = Types.VbdMode.RW;
vbdr.type = Types.VbdType.DISK;
vbd = VBD.create(conn, vbdr);
vbd.plug(conn);
String device = vbd.getDevice(conn);
return patchspecialvm(vmname, device, vmtype);
}
}
} catch (XenAPIException e) {
String msg = "patchSpecialVM faile on " + _host.uuid + " due to " + e.toString();
s_logger.warn(msg, e);
} catch (Exception e) {
String msg = "patchSpecialVM faile on " + _host.uuid + " due to " + e.getMessage();
s_logger.warn(msg, e);
} finally {
if (vbd != null) {
try {
if (vbd.getCurrentlyAttached(conn)) {
vbd.unplug(conn);
}
vbd.destroy(conn);
} catch (XmlRpcException e) {
String msg = "Catch XmlRpcException due to " + e.getMessage();
s_logger.warn(msg, e);
} catch (XenAPIException e) {
String msg = "Catch XenAPIException due to " + e.toString();
s_logger.warn(msg, e);
}
}
}
return false;
}
protected boolean patchspecialvm(String vmname, String device, String vmtype) {
String result = callHostPlugin("patchdomr", "vmname", vmname, "vmtype", vmtype, "device", "/dev/" + device);
if (result == null || result.isEmpty())
return false;
return true;
}
protected String callHostPluginBase(String plugin, String cmd, int timeout, String... params) {
Map<String, String> args = new HashMap<String, String>();
try {
Connection conn = getConnection();
for (int i = 0; i < params.length; i += 2) {
args.put(params[i], params[i + 1]);
}
if (s_logger.isTraceEnabled()) {
s_logger.trace("callHostPlugin executing for command " + cmd + " with " + getArgsString(args));
}
if( _host.host == null ) {
_host.host = Host.getByUuid(conn, _host.uuid);
}
String result = _host.host.callPlugin(conn, plugin, cmd, args);
if (s_logger.isTraceEnabled()) {
s_logger.trace("callHostPlugin Result: " + result);
}
return result.replace("\n", "");
} catch (XenAPIException e) {
s_logger.warn("callHostPlugin failed for cmd: " + cmd + " with args " + getArgsString(args) + " due to " + e.toString());
} catch (XmlRpcException e) {
s_logger.debug("callHostPlugin failed for cmd: " + cmd + " with args " + getArgsString(args) + " due to " + e.getMessage());
}
return null;
}
protected String callHostPlugin(String cmd, String... params) {
return callHostPluginBase("vmops", cmd, 300, params);
}
protected String callHostPluginWithTimeOut(String cmd, int timeout, String... params) {
return callHostPluginBase("vmops", cmd, timeout, params);
}
protected String getArgsString(Map<String, String> args) {
StringBuilder argString = new StringBuilder();
for (Map.Entry<String, String> arg : args.entrySet()) {
argString.append(arg.getKey() + ": " + arg.getValue() + ", ");
}
return argString.toString();
}
protected boolean setIptables() {
String result = callHostPlugin("setIptables");
if (result == null || result.isEmpty())
return false;
return true;
}
protected Nic getLocalNetwork(Connection conn, String name) throws XmlRpcException, XenAPIException {
Set<Network> networks = Network.getByNameLabel(conn, name);
for (Network network : networks) {
Network.Record nr = network.getRecord(conn);
for (PIF pif : nr.PIFs) {
PIF.Record pr = pif.getRecord(conn);
if (_host.uuid.equals(pr.host.getUuid(conn))) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Found a network called " + name + " on host=" + _host.ip + "; Network=" + nr.uuid + "; pif=" + pr.uuid);
}
if (pr.bondMasterOf != null && pr.bondMasterOf.size() > 0) {
if (pr.bondMasterOf.size() > 1) {
String msg = new StringBuilder("Unsupported configuration. Network " + name + " has more than one bond. Network=").append(nr.uuid)
.append("; pif=").append(pr.uuid).toString();
s_logger.warn(msg);
return null;
}
Bond bond = pr.bondMasterOf.iterator().next();
Set<PIF> slaves = bond.getSlaves(conn);
for (PIF slave : slaves) {
PIF.Record spr = slave.getRecord(conn);
if (spr.management) {
Host host = Host.getByUuid(conn, _host.uuid);
if (!transferManagementNetwork(conn, host, slave, spr, pif)) {
String msg = new StringBuilder("Unable to transfer management network. slave=" + spr.uuid + "; master=" + pr.uuid + "; host="
+ _host.uuid).toString();
s_logger.warn(msg);
return null;
}
break;
}
}
}
return new Nic(network, nr, pif, pr);
}
}
}
return null;
}
protected VIF getCorrectVif(VM router, String vlanId) {
try {
Connection conn = getConnection();
Set<VIF> routerVIFs = router.getVIFs(conn);
for (VIF vif : routerVIFs) {
Network vifNetwork = vif.getNetwork(conn);
if (vlanId.equals("untagged")) {
if (vifNetwork.getUuid(conn).equals(_host.publicNetwork)) {
return vif;
}
} else {
if (vifNetwork.getNameLabel(conn).equals("VLAN" + vlanId)) {
return vif;
}
}
}
} catch (XmlRpcException e) {
String msg = "Caught XmlRpcException: " + e.getMessage();
s_logger.warn(msg, e);
} catch (XenAPIException e) {
String msg = "Caught XenAPIException: " + e.toString();
s_logger.warn(msg, e);
}
return null;
}
protected String getLowestAvailableVIFDeviceNum(VM vm) {
try {
Connection conn = getConnection();
Set<String> availableDeviceNums = vm.getAllowedVIFDevices(conn);
Iterator<String> deviceNumsIterator = availableDeviceNums.iterator();
List<Integer> sortedDeviceNums = new ArrayList<Integer>();
while (deviceNumsIterator.hasNext()) {
try {
sortedDeviceNums.add(Integer.valueOf(deviceNumsIterator.next()));
} catch (NumberFormatException e) {
s_logger.debug("Obtained an invalid value for an available VIF device number for VM: " + vm.getNameLabel(conn));
return null;
}
}
Collections.sort(sortedDeviceNums);
return String.valueOf(sortedDeviceNums.get(0));
} catch (XmlRpcException e) {
String msg = "Caught XmlRpcException: " + e.getMessage();
s_logger.warn(msg, e);
} catch (XenAPIException e) {
String msg = "Caught XenAPIException: " + e.toString();
s_logger.warn(msg, e);
}
return null;
}
protected VDI mount(StoragePoolType pooltype, String volumeFolder, String volumePath) {
return getVDIbyUuid(volumePath);
}
protected List<Ternary<SR, VDI, VolumeVO>> mount(List<VolumeVO> vos) {
ArrayList<Ternary<SR, VDI, VolumeVO>> mounts = new ArrayList<Ternary<SR, VDI, VolumeVO>>(vos.size());
for (VolumeVO vol : vos) {
String vdiuuid = vol.getPath();
SR sr = null;
VDI vdi = null;
// Look up the VDI
vdi = getVDIbyUuid(vdiuuid);
Ternary<SR, VDI, VolumeVO> ter = new Ternary<SR, VDI, VolumeVO>(sr, vdi, vol);
if( vol.getVolumeType() == VolumeType.ROOT ) {
mounts.add(0, ter);
} else {
mounts.add(ter);
}
}
return mounts;
}
protected Network getNetworkByName(String name) throws BadServerResponse, XenAPIException, XmlRpcException {
Connection conn = getConnection();
Set<Network> networks = Network.getByNameLabel(conn, name);
if (networks.size() > 0) {
assert networks.size() == 1 : "How did we find more than one network with this name label" + name + "? Strange....";
return networks.iterator().next(); // Found it.
}
return null;
}
protected Network enableVlanNetwork(long tag, String pifUuid) throws XenAPIException, XmlRpcException {
// In XenServer, vlan is added by
// 1. creating a network.
// 2. creating a vlan associating network with the pif.
// We always create
// 1. a network with VLAN[vlan id in decimal]
// 2. a vlan associating the network created with the pif to private
// network.
Connection conn = getConnection();
Network vlanNetwork = null;
String name = "VLAN" + Long.toString(tag);
synchronized (name.intern()) {
vlanNetwork = getNetworkByName(name);
if (vlanNetwork == null) { // Can't find it, then create it.
if (s_logger.isDebugEnabled()) {
s_logger.debug("Creating VLAN Network for " + tag + " on host " + _host.ip);
}
Network.Record nwr = new Network.Record();
nwr.nameLabel = name;
nwr.bridge = name;
vlanNetwork = Network.create(conn, nwr);
}
PIF nPif = PIF.getByUuid(conn, pifUuid);
PIF.Record nPifr = nPif.getRecord(conn);
Network.Record vlanNetworkr = vlanNetwork.getRecord(conn);
if (vlanNetworkr.PIFs != null) {
for (PIF pif : vlanNetworkr.PIFs) {
PIF.Record pifr = pif.getRecord(conn);
if(pifr.host.equals(nPifr.host)) {
if (pifr.device.equals(nPifr.device) ) {
pif.plug(conn);
return vlanNetwork;
} else {
throw new CloudRuntimeException("Creating VLAN " + tag + " on " + nPifr.device + " failed due to this VLAN is already created on " + pifr.device);
}
}
}
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Creating VLAN " + tag + " on host " + _host.ip);
}
VLAN vlan = VLAN.create(conn, nPif, tag, vlanNetwork);
PIF untaggedPif = vlan.getUntaggedPIF(conn);
if (!untaggedPif.getCurrentlyAttached(conn)) {
untaggedPif.plug(conn);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Created VLAN " + tag + " on host " + _host.ip);
}
}
return vlanNetwork;
}
protected void disableVlanNetwork(Network network){
try {
Connection conn = getConnection();
if (network.getVIFs(conn).isEmpty()) {
Iterator<PIF> pifs = network.getPIFs(conn).iterator();
while (pifs.hasNext()) {
PIF pif = pifs.next();
try {
pif.unplug(conn);
} catch (XenAPIException e) {
continue;
}
}
}
} catch (XenAPIException e) {
String msg = e.getClass() + " Unable to disable VLAN network due to " + e.toString();
s_logger.warn(msg, e);
} catch (XmlRpcException e) {
String msg = e.getClass() + " Unable to disable VLAN network due to " + e.getMessage();
s_logger.warn(msg, e);
}
}
protected SR getLocalLVMSR() {
Connection conn = getConnection();
try {
Map<SR, SR.Record> map = SR.getAllRecords(conn);
for (Map.Entry<SR, SR.Record> entry : map.entrySet()) {
SR.Record srRec = entry.getValue();
if (SRType.LVM.equals(srRec.type)) {
Set<PBD> pbds = srRec.PBDs;
if (pbds == null) {
continue;
}
for (PBD pbd : pbds) {
Host host = pbd.getHost(conn);
if (!isRefNull(host) && host.getUuid(conn).equals(_host.uuid)) {
if (!pbd.getCurrentlyAttached(conn)) {
pbd.plug(conn);
}
SR sr = entry.getKey();
sr.scan(conn);
return sr;
}
}
}
}
} catch (XenAPIException e) {
String msg = "Unable to get local LVMSR in host:" + _host.uuid + e.toString();
s_logger.warn(msg);
} catch (XmlRpcException e) {
String msg = "Unable to get local LVMSR in host:" + _host.uuid + e.getCause();
s_logger.warn(msg);
}
return null;
}
protected StartupStorageCommand initializeLocalSR() {
SR lvmsr = getLocalLVMSR();
if (lvmsr == null) {
return null;
}
try {
Connection conn = getConnection();
String lvmuuid = lvmsr.getUuid(conn);
long cap = lvmsr.getPhysicalSize(conn);
if (cap < 0)
return null;
long avail = cap - lvmsr.getPhysicalUtilisation(conn);
lvmsr.setNameLabel(conn, lvmuuid);
String name = "VMOps local storage pool in host : " + _host.uuid;
lvmsr.setNameDescription(conn, name);
Host host = Host.getByUuid(conn, _host.uuid);
String address = host.getAddress(conn);
StoragePoolInfo pInfo = new StoragePoolInfo(name, lvmuuid, address, SRType.LVM.toString(), SRType.LVM.toString(), StoragePoolType.LVM, cap, avail);
StartupStorageCommand cmd = new StartupStorageCommand();
cmd.setPoolInfo(pInfo);
cmd.setGuid(_host.uuid);
cmd.setResourceType(StorageResourceType.STORAGE_POOL);
return cmd;
} catch (XenAPIException e) {
String msg = "build startupstoragecommand err in host:" + _host.uuid + e.toString();
s_logger.warn(msg);
} catch (XmlRpcException e) {
String msg = "build startupstoragecommand err in host:" + _host.uuid + e.getMessage();
s_logger.warn(msg);
}
return null;
}
@Override
public PingCommand getCurrentStatus(long id) {
try {
if (!pingxenserver()) {
Thread.sleep(1000);
if (!pingxenserver()) {
s_logger.warn(" can not ping xenserver " + _host.uuid);
return null;
}
}
HashMap<String, State> newStates = sync();
if (newStates == null) {
newStates = new HashMap<String, State>();
}
if (!_canBridgeFirewall) {
return new PingRoutingCommand(getType(), id, newStates);
} else {
HashMap<String, Pair<Long, Long>> nwGrpStates = syncNetworkGroups(id);
return new PingRoutingWithNwGroupsCommand(getType(), id, newStates, nwGrpStates);
}
} catch (Exception e) {
s_logger.warn("Unable to get current status", e);
return null;
}
}
private HashMap<String, Pair<Long,Long>> syncNetworkGroups(long id) {
HashMap<String, Pair<Long,Long>> states = new HashMap<String, Pair<Long,Long>>();
String result = callHostPlugin("get_rule_logs_for_vms", "host_uuid", _host.uuid);
s_logger.trace("syncNetworkGroups: id=" + id + " got: " + result);
String [] rulelogs = result != null ?result.split(";"): new String [0];
for (String rulesforvm: rulelogs){
String [] log = rulesforvm.split(",");
if (log.length != 6) {
continue;
}
//output = ','.join([vmName, vmID, vmIP, domID, signature, seqno])
try {
states.put(log[0], new Pair<Long,Long>(Long.parseLong(log[1]), Long.parseLong(log[5])));
} catch (NumberFormatException nfe) {
states.put(log[0], new Pair<Long,Long>(-1L, -1L));
}
}
return states;
}
@Override
public Type getType() {
return com.cloud.host.Host.Type.Routing;
}
protected void getPVISO(StartupStorageCommand sscmd) {
Connection conn = getConnection();
try {
Set<VDI> vids = VDI.getByNameLabel(conn, "xs-tools.iso");
if (vids.isEmpty())
return;
VDI pvISO = vids.iterator().next();
String uuid = pvISO.getUuid(conn);
Map<String, TemplateInfo> pvISOtmlt = new HashMap<String, TemplateInfo>();
TemplateInfo tmplt = new TemplateInfo("xs-tools.iso", uuid, pvISO.getVirtualSize(conn), true);
pvISOtmlt.put("xs-tools", tmplt);
sscmd.setTemplateInfo(pvISOtmlt);
} catch (XenAPIException e) {
s_logger.debug("Can't get xs-tools.iso: " + e.toString());
} catch (XmlRpcException e) {
s_logger.debug("Can't get xs-tools.iso: " + e.toString());
}
}
protected boolean can_bridge_firewall() {
return false;
}
protected boolean getHostInfo() throws IllegalArgumentException{
Connection conn = getConnection();
try {
Host myself = Host.getByUuid(conn, _host.uuid);
String name = "cloud-private";
if (_privateNetworkName != null) {
name = _privateNetworkName;
}
_localGateway = callHostPlugin("getgateway", "mgmtIP", myself.getAddress(conn));
if (_localGateway == null || _localGateway.isEmpty()) {
s_logger.warn("can not get gateway for host :" + _host.uuid);
return false;
}
_canBridgeFirewall = can_bridge_firewall();
Nic privateNic = getLocalNetwork(conn, name);
if (privateNic == null) {
s_logger.debug("Unable to find any private network. Trying to determine that by route for host " + _host.ip);
name = callHostPlugin("getnetwork", "mgmtIP", myself.getAddress(conn));
if (name == null || name.isEmpty()) {
s_logger.warn("Unable to determine the private network for host " + _host.ip);
return false;
}
_privateNetworkName = name;
privateNic = getLocalNetwork(conn, name);
if (privateNic == null) {
s_logger.warn("Unable to get private network " + name);
return false;
}
}
name = privateNic.nr.nameLabel;
Nic guestNic = null;
if (_guestNetworkName != null && !_guestNetworkName.equals(name)) {
guestNic = getLocalNetwork(conn, _guestNetworkName);
if (guestNic == null) {
s_logger.warn("Unable to find guest network " + _guestNetworkName);
throw new IllegalArgumentException("Unable to find guest network " + _guestNetworkName + " for host " + _host.ip);
}
} else {
guestNic = privateNic;
_guestNetworkName = _privateNetworkName;
}
name = guestNic.nr.nameLabel;
Nic publicNic = null;
if (_publicNetworkName != null && !_publicNetworkName.equals(name)) {
publicNic = getLocalNetwork(conn, _publicNetworkName);
if (publicNic == null) {
s_logger.warn("Unable to find public network " + _publicNetworkName + " for host " + _host.ip);
throw new IllegalArgumentException("Unable to find public network " + _publicNetworkName + " for host " + _host.ip);
}
} else {
publicNic = guestNic;
_publicNetworkName = _guestNetworkName;
}
name = publicNic.nr.nameLabel;
_host.privatePif = privateNic.pr.uuid;
_host.privateNetwork = privateNic.nr.uuid;
_host.publicPif = publicNic.pr.uuid;
_host.publicNetwork = publicNic.nr.uuid;
_host.guestNetwork = guestNic.nr.uuid;
_host.guestPif = guestNic.pr.uuid;
Nic storageNic1 = getLocalNetwork(conn, _storageNetworkName1);
if (storageNic1 == null) {
storageNic1 = privateNic;
}
_host.storageNetwork1 = storageNic1.nr.uuid;
_host.storagePif1 = storageNic1.pr.uuid;
Nic storageNic2 = getLocalNetwork(conn, _storageNetworkName2);
if (storageNic2 == null) {
storageNic2 = storageNic1;
}
_host.storageNetwork2 = storageNic2.nr.uuid;
_host.storagePif2 = storageNic2.pr.uuid;
s_logger.info("Private Network is " + _privateNetworkName + " for host " + _host.ip);
s_logger.info("Guest Network is " + _guestNetworkName + " for host " + _host.ip);
s_logger.info("Public Network is " + _publicNetworkName + " for host " + _host.ip);
s_logger.info("Storage Network 1 is " + _storageNetworkName1 + " for host " + _host.ip);
s_logger.info("Storage Network 2 is " + _storageNetworkName2 + " for host " + _host.ip);
return true;
} catch (XenAPIException e) {
s_logger.warn("Unable to get host information for " + _host.ip, e);
return false;
} catch (XmlRpcException e) {
s_logger.warn("Unable to get host information for " + _host.ip, e);
return false;
}
}
private void setupLinkLocalNetwork() {
try {
Network.Record rec = new Network.Record();
Connection conn = getConnection();
Set<Network> networks = Network.getByNameLabel(conn, _linkLocalPrivateNetworkName);
Network linkLocal = null;
if (networks.size() == 0) {
rec.nameDescription = "link local network used by system vms";
rec.nameLabel = _linkLocalPrivateNetworkName;
Map<String, String> configs = new HashMap<String, String>();
configs.put("ip_begin", NetUtils.getLinkLocalGateway());
configs.put("ip_end", NetUtils.getLinkLocalIpEnd());
configs.put("netmask", NetUtils.getLinkLocalNetMask());
rec.otherConfig = configs;
linkLocal = Network.create(conn, rec);
} else {
linkLocal = networks.iterator().next();
}
/* Make sure there is a physical bridge on this network */
VIF dom0vif = null;
Pair<VM, VM.Record> vm = getControlDomain(conn);
VM dom0 = vm.first();
Set<VIF> vifs = dom0.getVIFs(conn);
if (vifs.size() != 0) {
for (VIF vif : vifs) {
Map<String, String> otherConfig = vif.getOtherConfig(conn);
if (otherConfig != null) {
String nameLabel = otherConfig.get("nameLabel");
if ((nameLabel != null) && nameLabel.equalsIgnoreCase("link_local_network_vif")) {
dom0vif = vif;
}
}
}
}
/* create temp VIF0 */
if (dom0vif == null) {
s_logger.debug("Can't find a vif on dom0 for link local, creating a new one");
VIF.Record vifr = new VIF.Record();
vifr.VM = dom0;
vifr.device = getLowestAvailableVIFDeviceNum(dom0);
if (vifr.device == null) {
s_logger.debug("Failed to create link local network, no vif available");
return;
}
Map<String, String> config = new HashMap<String, String>();
config.put("nameLabel", "link_local_network_vif");
vifr.otherConfig = config;
vifr.MAC = "FE:FF:FF:FF:FF:FF";
vifr.network = linkLocal;
dom0vif = VIF.create(conn, vifr);
//dom0vif.plug(conn);
} else {
s_logger.debug("already have a vif on dom0 for link local network");
/*if (!dom0vif.getCurrentlyAttached(conn)) {
dom0vif.plug(conn);
}*/
}
String brName = linkLocal.getBridge(conn);
callHostPlugin("setLinkLocalIP", "brName", brName);
_host.linkLocalNetwork = linkLocal.getUuid(conn);
} catch (XenAPIException e) {
s_logger.warn("Unable to create local link network", e);
} catch (XmlRpcException e) {
// TODO Auto-generated catch block
s_logger.warn("Unable to create local link network", e);
}
}
protected boolean transferManagementNetwork(Connection conn, Host host, PIF src, PIF.Record spr, PIF dest) throws XmlRpcException, XenAPIException {
dest.reconfigureIp(conn, spr.ipConfigurationMode, spr.IP, spr.netmask, spr.gateway, spr.DNS);
Host.managementReconfigure(conn, dest);
String hostUuid = null;
int count = 0;
while (count < 10) {
try {
Thread.sleep(10000);
hostUuid = host.getUuid(conn);
if (hostUuid != null) {
break;
}
} catch (XmlRpcException e) {
s_logger.debug("Waiting for host to come back: " + e.getMessage());
} catch (XenAPIException e) {
s_logger.debug("Waiting for host to come back: " + e.getMessage());
} catch (InterruptedException e) {
s_logger.debug("Gotta run");
return false;
}
}
if (hostUuid == null) {
s_logger.warn("Unable to transfer the management network from " + spr.uuid);
return false;
}
src.reconfigureIp(conn, IpConfigurationMode.NONE, null, null, null, null);
return true;
}
@Override
public StartupCommand[] initialize() throws IllegalArgumentException{
disconnected();
setupServer();
if (!getHostInfo()) {
s_logger.warn("Unable to get host information for " + _host.ip);
return null;
}
setupLinkLocalNetwork();
destroyStoppedVm();
StartupRoutingCommand cmd = new StartupRoutingCommand();
fillHostInfo(cmd);
cleanupDiskMounts();
Map<String, State> changes = null;
synchronized (_vms) {
_vms.clear();
changes = sync();
}
_domrIPMap.clear();
if (changes != null) {
for (final Map.Entry<String, State> entry : changes.entrySet()) {
final String vm = entry.getKey();
State state = entry.getValue();
if (VirtualMachineName.isValidRouterName(vm) && (state == State.Running)) {
syncDomRIPMap(vm);
}
}
}
cmd.setHypervisorType(Hypervisor.Type.XenServer);
cmd.setChanges(changes);
cmd.setCluster(_cluster);
StartupStorageCommand sscmd = initializeLocalSR();
if (sscmd != null) {
/* report pv driver iso */
getPVISO(sscmd);
return new StartupCommand[] { cmd, sscmd };
}
return new StartupCommand[] { cmd };
}
protected String getPoolUuid() {
Connection conn = getConnection();
try {
Map<Pool, Pool.Record> pools = Pool.getAllRecords(conn);
assert (pools.size() == 1) : "Tell me how pool size can be " + pools.size();
Pool.Record rec = pools.values().iterator().next();
return rec.uuid;
} catch (XenAPIException e) {
throw new CloudRuntimeException("Unable to get pool ", e);
} catch (XmlRpcException e) {
throw new CloudRuntimeException("Unable to get pool ", e);
}
}
protected void setupServer() {
Connection conn = getConnection();
String version = CitrixResourceBase.class.getPackage().getImplementationVersion();
try {
Host host = Host.getByUuid(conn, _host.uuid);
/* enable host in case it is disabled somehow */
host.enable(conn);
/* push patches to XenServer */
Host.Record hr = host.getRecord(conn);
Iterator<String> it = hr.tags.iterator();
while (it.hasNext()) {
String tag = it.next();
if (tag.startsWith("vmops-version-")) {
if (tag.contains(version)) {
s_logger.info(logX(host, "Host " + hr.address + " is already setup."));
return;
} else {
it.remove();
}
}
}
com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(hr.address, 22);
try {
sshConnection.connect(null, 60000, 60000);
if (!sshConnection.authenticateWithPassword(_username, _password)) {
throw new CloudRuntimeException("Unable to authenticate");
}
SCPClient scp = new SCPClient(sshConnection);
String path = _patchPath.substring(0, _patchPath.lastIndexOf(File.separator) + 1);
List<File> files = getPatchFiles();
if( files == null || files.isEmpty() ) {
throw new CloudRuntimeException("Can not find patch file");
}
for( File file :files) {
Properties props = new Properties();
props.load(new FileInputStream(file));
for (Map.Entry<Object, Object> entry : props.entrySet()) {
String k = (String) entry.getKey();
String v = (String) entry.getValue();
assert (k != null && k.length() > 0 && v != null && v.length() > 0) : "Problems with " + k + "=" + v;
String[] tokens = v.split(",");
String f = null;
if (tokens.length == 3 && tokens[0].length() > 0) {
if (tokens[0].startsWith("/")) {
f = tokens[0];
} else if (tokens[0].startsWith("~")) {
String homedir = System.getenv("HOME");
f = homedir + tokens[0].substring(1) + k;
} else {
f = path + tokens[0] + '/' + k;
}
} else {
f = path + k;
}
String d = tokens[tokens.length - 1];
f = f.replace('/', File.separatorChar);
String p = "0755";
if (tokens.length == 3) {
p = tokens[1];
} else if (tokens.length == 2) {
p = tokens[0];
}
if (!new File(f).exists()) {
s_logger.warn("We cannot locate " + f);
continue;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Copying " + f + " to " + d + " on " + hr.address + " with permission " + p);
}
scp.put(f, d, p);
}
}
} catch (IOException e) {
throw new CloudRuntimeException("Unable to setup the server correctly", e);
} finally {
sshConnection.close();
}
try {
// wait 2 seconds before call plugin
Thread.sleep(2000);
} catch (final InterruptedException ex) {
}
if (!setIptables()) {
s_logger.warn("set xenserver Iptable failed");
}
hr.tags.add("vmops-version-" + version);
host.setTags(conn, hr.tags);
} catch (XenAPIException e) {
String msg = "Xen setup failed due to " + e.toString();
s_logger.warn(msg, e);
throw new CloudRuntimeException("Unable to get host information " + e.toString(), e);
} catch (XmlRpcException e) {
String msg = "Xen setup failed due to " + e.getMessage();
s_logger.warn(msg, e);
throw new CloudRuntimeException("Unable to get host information ", e);
}
}
protected List<File> getPatchFiles() {
List<File> files = new ArrayList<File>();
File file = new File(_patchPath);
files.add(file);
return files;
}
protected SR getSRByNameLabelandHost(String name) throws BadServerResponse, XenAPIException, XmlRpcException {
Connection conn = getConnection();
Set<SR> srs = SR.getByNameLabel(conn, name);
SR ressr = null;
for (SR sr : srs) {
Set<PBD> pbds;
pbds = sr.getPBDs(conn);
for (PBD pbd : pbds) {
PBD.Record pbdr = pbd.getRecord(conn);
if (pbdr.host != null && pbdr.host.getUuid(conn).equals(_host.uuid)) {
if (!pbdr.currentlyAttached) {
pbd.plug(conn);
}
ressr = sr;
break;
}
}
}
return ressr;
}
protected GetStorageStatsAnswer execute(final GetStorageStatsCommand cmd) {
try {
Connection conn = getConnection();
Set<SR> srs = SR.getByNameLabel(conn, cmd.getStorageId());
if (srs.size() != 1) {
String msg = "There are " + srs.size() + " storageid: " + cmd.getStorageId();
s_logger.warn(msg);
return new GetStorageStatsAnswer(cmd, msg);
}
SR sr = srs.iterator().next();
sr.scan(conn);
long capacity = sr.getPhysicalSize(conn);
long used = sr.getPhysicalUtilisation(conn);
return new GetStorageStatsAnswer(cmd, capacity, used);
} catch (XenAPIException e) {
String msg = "GetStorageStats Exception:" + e.toString() + "host:" + _host.uuid + "storageid: " + cmd.getStorageId();
s_logger.warn(msg);
return new GetStorageStatsAnswer(cmd, msg);
} catch (XmlRpcException e) {
String msg = "GetStorageStats Exception:" + e.getMessage() + "host:" + _host.uuid + "storageid: " + cmd.getStorageId();
s_logger.warn(msg);
return new GetStorageStatsAnswer(cmd, msg);
}
}
protected boolean checkSR(SR sr) {
try {
Connection conn = getConnection();
SR.Record srr = sr.getRecord(conn);
Set<PBD> pbds = sr.getPBDs(conn);
if (pbds.size() == 0) {
String msg = "There is no PBDs for this SR: " + srr.nameLabel + " on host:" + _host.uuid;
s_logger.warn(msg);
return false;
}
Set<Host> hosts = null;
if (srr.shared) {
hosts = Host.getAll(conn);
for (Host host : hosts) {
boolean found = false;
for (PBD pbd : pbds) {
if (host.equals(pbd.getHost(conn))) {
PBD.Record pbdr = pbd.getRecord(conn);
if (currentlyAttached(sr, srr, pbd, pbdr)) {
if (!pbdr.currentlyAttached) {
pbd.plug(conn);
}
} else {
if (pbdr.currentlyAttached) {
pbd.unplug(conn);
}
pbd.plug(conn);
}
pbds.remove(pbd);
found = true;
break;
}
}
if (!found) {
PBD.Record pbdr = srr.PBDs.iterator().next().getRecord(conn);
pbdr.host = host;
pbdr.uuid = "";
PBD pbd = PBD.create(conn, pbdr);
pbd.plug(conn);
}
}
} else {
for (PBD pbd : pbds) {
PBD.Record pbdr = pbd.getRecord(conn);
if (!pbdr.currentlyAttached) {
pbd.plug(conn);
}
}
}
} catch (Exception e) {
String msg = "checkSR failed host:" + _host.uuid;
s_logger.warn(msg);
return false;
}
return true;
}
protected Answer execute(ModifyStoragePoolCommand cmd) {
StoragePoolVO pool = cmd.getPool();
StoragePoolTO poolTO = new StoragePoolTO(pool);
try {
Connection conn = getConnection();
SR sr = getStorageRepository(conn, poolTO);
long capacity = sr.getPhysicalSize(conn);
long available = capacity - sr.getPhysicalUtilisation(conn);
if (capacity == -1) {
String msg = "Pool capacity is -1! pool: " + pool.getName() + pool.getHostAddress() + pool.getPath();
s_logger.warn(msg);
return new Answer(cmd, false, msg);
}
Map<String, TemplateInfo> tInfo = new HashMap<String, TemplateInfo>();
ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(cmd, capacity, available, tInfo);
return answer;
} catch (XenAPIException e) {
String msg = "ModifyStoragePoolCommand XenAPIException:" + e.toString() + " host:" + _host.uuid + " pool: " + pool.getName() + pool.getHostAddress() + pool.getPath();
s_logger.warn(msg, e);
return new Answer(cmd, false, msg);
} catch (Exception e) {
String msg = "ModifyStoragePoolCommand XenAPIException:" + e.getMessage() + " host:" + _host.uuid + " pool: " + pool.getName() + pool.getHostAddress() + pool.getPath();
s_logger.warn(msg, e);
return new Answer(cmd, false, msg);
}
}
protected Answer execute(DeleteStoragePoolCommand cmd) {
StoragePoolVO pool = cmd.getPool();
StoragePoolTO poolTO = new StoragePoolTO(pool);
try {
Connection conn = getConnection();
SR sr = getStorageRepository(conn, poolTO);
sr.setNameLabel(conn, pool.getUuid());
sr.setNameDescription(conn, pool.getName());
Answer answer = new Answer(cmd, true, "success");
return answer;
} catch (XenAPIException e) {
String msg = "DeleteStoragePoolCommand XenAPIException:" + e.toString() + " host:" + _host.uuid + " pool: " + pool.getName() + pool.getHostAddress() + pool.getPath();
s_logger.warn(msg, e);
return new Answer(cmd, false, msg);
} catch (Exception e) {
String msg = "DeleteStoragePoolCommand XenAPIException:" + e.getMessage() + " host:" + _host.uuid + " pool: " + pool.getName() + pool.getHostAddress() + pool.getPath();
s_logger.warn(msg, e);
return new Answer(cmd, false, msg);
}
}
public Connection getConnection() {
return _connPool.connect(_host.uuid, _host.pool, _host.ip, _username, _password, _wait);
}
protected void fillHostInfo(StartupRoutingCommand cmd) {
long speed = 0;
int cpus = 0;
long ram = 0;
Connection conn = getConnection();
long dom0Ram = 0;
final StringBuilder caps = new StringBuilder();
try {
Host host = Host.getByUuid(conn, _host.uuid);
Host.Record hr = host.getRecord(conn);
Map<String, String> details = cmd.getHostDetails();
if (details == null) {
details = new HashMap<String, String>();
}
if (_privateNetworkName != null) {
details.put("private.network.device", _privateNetworkName);
}
if (_publicNetworkName != null) {
details.put("public.network.device", _publicNetworkName);
}
if (_guestNetworkName != null) {
details.put("guest.network.device", _guestNetworkName);
}
details.put("can_bridge_firewall", Boolean.toString(_canBridgeFirewall));
cmd.setHostDetails(details);
cmd.setName(hr.nameLabel);
cmd.setGuid(_host.uuid);
cmd.setDataCenter(Long.toString(_dcId));
for (final String cap : hr.capabilities) {
if (cap.length() > 0) {
caps.append(cap).append(" , ");
}
}
if (caps.length() > 0) {
caps.delete(caps.length() - 3, caps.length());
}
cmd.setCaps(caps.toString());
Set<HostCpu> hcs = host.getHostCPUs(conn);
cpus = hcs.size();
for (final HostCpu hc : hcs) {
speed = hc.getSpeed(conn);
}
cmd.setSpeed(speed);
cmd.setCpus(cpus);
long free = 0;
HostMetrics hm = host.getMetrics(conn);
ram = hm.getMemoryTotal(conn);
free = hm.getMemoryFree(conn);
Set<VM> vms = host.getResidentVMs(conn);
for (VM vm : vms) {
if (vm.getIsControlDomain(conn)) {
dom0Ram = vm.getMemoryDynamicMax(conn);
break;
}
}
// assume the memory Virtualization overhead is 1/64
ram = (ram - dom0Ram) * 63/64;
cmd.setMemory(ram);
cmd.setDom0MinMemory(dom0Ram);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Total Ram: " + ram + " Free Ram: " + free + " dom0 Ram: " + dom0Ram);
}
PIF pif = PIF.getByUuid(conn, _host.privatePif);
PIF.Record pifr = pif.getRecord(conn);
if (pifr.IP != null && pifr.IP.length() > 0) {
cmd.setPrivateIpAddress(pifr.IP);
cmd.setPrivateMacAddress(pifr.MAC);
cmd.setPrivateNetmask(pifr.netmask);
}
pif = PIF.getByUuid(conn, _host.storagePif1);
pifr = pif.getRecord(conn);
if (pifr.IP != null && pifr.IP.length() > 0) {
cmd.setStorageIpAddress(pifr.IP);
cmd.setStorageMacAddress(pifr.MAC);
cmd.setStorageNetmask(pifr.netmask);
}
if (_host.storagePif2 != null) {
pif = PIF.getByUuid(conn, _host.storagePif2);
pifr = pif.getRecord(conn);
if (pifr.IP != null && pifr.IP.length() > 0) {
cmd.setStorageIpAddressDeux(pifr.IP);
cmd.setStorageMacAddressDeux(pifr.MAC);
cmd.setStorageNetmaskDeux(pifr.netmask);
}
}
Map<String, String> configs = hr.otherConfig;
cmd.setIqn(configs.get("iscsi_iqn"));
cmd.setPod(_pod);
cmd.setVersion(CitrixResourceBase.class.getPackage().getImplementationVersion());
} catch (final XmlRpcException e) {
throw new CloudRuntimeException("XML RPC Exception" + e.getMessage(), e);
} catch (XenAPIException e) {
throw new CloudRuntimeException("XenAPIException" + e.toString(), e);
}
}
public CitrixResourceBase() {
}
protected String getPatchPath() {
return "scripts/vm/hypervisor/xenserver/xcpserver";
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name;
_host.uuid = (String) params.get("guid");
try {
_dcId = Long.parseLong((String) params.get("zone"));
} catch (NumberFormatException e) {
throw new ConfigurationException("Unable to get the zone " + params.get("zone"));
}
_host.host = null;
_name = _host.uuid;
_host.ip = (String) params.get("url");
_host.pool = (String) params.get("pool");
_username = (String) params.get("username");
_password = (String) params.get("password");
_pod = (String) params.get("pod");
_cluster = (String)params.get("cluster");
_privateNetworkName = (String) params.get("private.network.device");
_publicNetworkName = (String) params.get("public.network.device");
_guestNetworkName = (String)params.get("guest.network.device");
_linkLocalPrivateNetworkName = (String) params.get("private.linkLocal.device");
if (_linkLocalPrivateNetworkName == null)
_linkLocalPrivateNetworkName = "cloud_link_local_network";
_storageNetworkName1 = (String) params.get("storage.network.device1");
if (_storageNetworkName1 == null) {
_storageNetworkName1 = "cloud-stor1";
}
_storageNetworkName2 = (String) params.get("storage.network.device2");
if (_storageNetworkName2 == null) {
_storageNetworkName2 = "cloud-stor2";
}
String value = (String) params.get("wait");
_wait = NumbersUtil.parseInt(value, 1800);
if (_pod == null) {
throw new ConfigurationException("Unable to get the pod");
}
if (_host.ip == null) {
throw new ConfigurationException("Unable to get the host address");
}
if (_username == null) {
throw new ConfigurationException("Unable to get the username");
}
if (_password == null) {
throw new ConfigurationException("Unable to get the password");
}
if (_host.uuid == null) {
throw new ConfigurationException("Unable to get the uuid");
}
String patchPath = getPatchPath();
_patchPath = Script.findScript(patchPath, "patch");
if (_patchPath == null) {
throw new ConfigurationException("Unable to find all of patch files for xenserver");
}
_storage = (StorageLayer) params.get(StorageLayer.InstanceConfigKey);
if (_storage == null) {
value = (String) params.get(StorageLayer.ClassConfigKey);
if (value == null) {
value = "com.cloud.storage.JavaStorageLayer";
}
try {
Class<?> clazz = Class.forName(value);
_storage = (StorageLayer) ComponentLocator.inject(clazz);
_storage.configure("StorageLayer", params);
} catch (ClassNotFoundException e) {
throw new ConfigurationException("Unable to find class " + value);
}
}
return true;
}
void destroyVDI(VDI vdi) {
try {
Connection conn = getConnection();
vdi.destroy(conn);
} catch (Exception e) {
String msg = "destroy VDI failed due to " + e.toString();
s_logger.warn(msg);
}
}
public CreateAnswer execute(CreateCommand cmd) {
StoragePoolTO pool = cmd.getPool();
DiskCharacteristicsTO dskch = cmd.getDiskCharacteristics();
VDI vdi = null;
Connection conn = getConnection();
try {
SR poolSr = getStorageRepository(conn, pool);
if (cmd.getTemplateUrl() != null) {
VDI tmpltvdi = null;
tmpltvdi = getVDIbyUuid(cmd.getTemplateUrl());
vdi = tmpltvdi.createClone(conn, new HashMap<String, String>());
vdi.setNameLabel(conn, dskch.getName());
} else {
VDI.Record vdir = new VDI.Record();
vdir.nameLabel = dskch.getName();
vdir.SR = poolSr;
vdir.type = Types.VdiType.USER;
vdir.virtualSize = dskch.getSize();
vdi = VDI.create(conn, vdir);
}
VDI.Record vdir;
vdir = vdi.getRecord(conn);
s_logger.debug("Succesfully created VDI for " + cmd + ". Uuid = " + vdir.uuid);
VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), StorageResourceType.STORAGE_POOL, pool.getType(), vdir.nameLabel, pool.getPath(), vdir.uuid,
vdir.virtualSize);
return new CreateAnswer(cmd, vol);
} catch (Exception e) {
s_logger.warn("Unable to create volume; Pool=" + pool + "; Disk: " + dskch, e);
return new CreateAnswer(cmd, e);
}
}
protected SR getISOSRbyVmName(String vmName) {
Connection conn = getConnection();
try {
Set<SR> srs = SR.getByNameLabel(conn, vmName + "-ISO");
if (srs.size() == 0) {
return null;
} else if (srs.size() == 1) {
return srs.iterator().next();
} else {
String msg = "getIsoSRbyVmName failed due to there are more than 1 SR having same Label";
s_logger.warn(msg);
}
} catch (XenAPIException e) {
String msg = "getIsoSRbyVmName failed due to " + e.toString();
s_logger.warn(msg, e);
} catch (Exception e) {
String msg = "getIsoSRbyVmName failed due to " + e.getMessage();
s_logger.warn(msg, e);
}
return null;
}
protected SR createNfsSRbyURI(URI uri, boolean shared) {
try {
Connection conn = getConnection();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Creating a " + (shared ? "shared SR for " : "not shared SR for ") + uri);
}
Map<String, String> deviceConfig = new HashMap<String, String>();
String path = uri.getPath();
path = path.replace("//", "/");
deviceConfig.put("server", uri.getHost());
deviceConfig.put("serverpath", path);
String name = UUID.nameUUIDFromBytes(new String(uri.getHost() + path).getBytes()).toString();
if (!shared) {
Set<SR> srs = SR.getByNameLabel(conn, name);
for (SR sr : srs) {
SR.Record record = sr.getRecord(conn);
if (SRType.NFS.equals(record.type) && record.contentType.equals("user") && !record.shared) {
removeSRSync(sr);
}
}
}
Host host = Host.getByUuid(conn, _host.uuid);
SR sr = SR.create(conn, host, deviceConfig, new Long(0), name, uri.getHost() + uri.getPath(), SRType.NFS.toString(), "user", shared, new HashMap<String, String>());
if( !checkSR(sr) ) {
throw new Exception("no attached PBD");
}
if (s_logger.isDebugEnabled()) {
s_logger.debug(logX(sr, "Created a SR; UUID is " + sr.getUuid(conn)));
}
sr.scan(conn);
return sr;
} catch (XenAPIException e) {
String msg = "Can not create second storage SR mountpoint: " + uri.getHost() + uri.getPath() + " due to " + e.toString();
s_logger.warn(msg, e);
throw new CloudRuntimeException(msg, e);
} catch (Exception e) {
String msg = "Can not create second storage SR mountpoint: " + uri.getHost() + uri.getPath() + " due to " + e.getMessage();
s_logger.warn(msg, e);
throw new CloudRuntimeException(msg, e);
}
}
protected SR createIsoSRbyURI(URI uri, String vmName, boolean shared) {
try {
Connection conn = getConnection();
Map<String, String> deviceConfig = new HashMap<String, String>();
String path = uri.getPath();
path = path.replace("//", "/");
deviceConfig.put("location", uri.getHost() + ":" + uri.getPath());
Host host = Host.getByUuid(conn, _host.uuid);
SR sr = SR.create(conn, host, deviceConfig, new Long(0), uri.getHost() + uri.getPath(), "iso", "iso", "iso", shared, new HashMap<String, String>());
sr.setNameLabel(conn, vmName + "-ISO");
sr.setNameDescription(conn, deviceConfig.get("location"));
sr.scan(conn);
return sr;
} catch (XenAPIException e) {
String msg = "createIsoSRbyURI failed! mountpoint: " + uri.getHost() + uri.getPath() + " due to " + e.toString();
s_logger.warn(msg, e);
throw new CloudRuntimeException(msg, e);
} catch (Exception e) {
String msg = "createIsoSRbyURI failed! mountpoint: " + uri.getHost() + uri.getPath() + " due to " + e.getMessage();
s_logger.warn(msg, e);
throw new CloudRuntimeException(msg, e);
}
}
protected VDI getVDIbyLocationandSR(String loc, SR sr) {
Connection conn = getConnection();
try {
Set<VDI> vdis = sr.getVDIs(conn);
for (VDI vdi : vdis) {
if (vdi.getLocation(conn).startsWith(loc)) {
return vdi;
}
}
String msg = "can not getVDIbyLocationandSR " + loc;
s_logger.warn(msg);
return null;
} catch (XenAPIException e) {
String msg = "getVDIbyLocationandSR exception " + loc + " due to " + e.toString();
s_logger.warn(msg, e);
throw new CloudRuntimeException(msg, e);
} catch (Exception e) {
String msg = "getVDIbyLocationandSR exception " + loc + " due to " + e.getMessage();
s_logger.warn(msg, e);
throw new CloudRuntimeException(msg, e);
}
}
protected VDI getVDIbyUuid(String uuid) {
try {
Connection conn = getConnection();
return VDI.getByUuid(conn, uuid);
} catch (XenAPIException e) {
String msg = "VDI getByUuid failed " + uuid + " due to " + e.toString();
s_logger.warn(msg, e);
throw new CloudRuntimeException(msg, e);
} catch (Exception e) {
String msg = "VDI getByUuid failed " + uuid + " due to " + e.getMessage();
s_logger.warn(msg, e);
throw new CloudRuntimeException(msg, e);
}
}
protected SR getIscsiSR(StoragePoolTO pool) {
Connection conn = getConnection();
synchronized (pool.getUuid().intern()) {
Map<String, String> deviceConfig = new HashMap<String, String>();
try {
String target = pool.getHost();
String path = pool.getPath();
if (path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
String tmp[] = path.split("/");
if (tmp.length != 3) {
String msg = "Wrong iscsi path " + pool.getPath() + " it should be /targetIQN/LUN";
s_logger.warn(msg);
throw new CloudRuntimeException(msg);
}
String targetiqn = tmp[1].trim();
String lunid = tmp[2].trim();
String scsiid = "";
Set<SR> srs = SR.getByNameLabel(conn, pool.getUuid());
for (SR sr : srs) {
if (!SRType.LVMOISCSI.equals(sr.getType(conn)))
continue;
Set<PBD> pbds = sr.getPBDs(conn);
if (pbds.isEmpty())
continue;
PBD pbd = pbds.iterator().next();
Map<String, String> dc = pbd.getDeviceConfig(conn);
if (dc == null)
continue;
if (dc.get("target") == null)
continue;
if (dc.get("targetIQN") == null)
continue;
if (dc.get("lunid") == null)
continue;
if (target.equals(dc.get("target")) && targetiqn.equals(dc.get("targetIQN")) && lunid.equals(dc.get("lunid"))) {
if (checkSR(sr)) {
return sr;
}
throw new CloudRuntimeException("SR check failed for storage pool: " + pool.getUuid() + "on host:" + _host.uuid);
}
}
deviceConfig.put("target", target);
deviceConfig.put("targetIQN", targetiqn);
Host host = Host.getByUuid(conn, _host.uuid);
SR sr = null;
try {
sr = SR.create(conn, host, deviceConfig, new Long(0), pool.getUuid(), Long.toString(pool.getId()), SRType.LVMOISCSI.toString(), "user", true,
new HashMap<String, String>());
} catch (XenAPIException e) {
String errmsg = e.toString();
if (errmsg.contains("SR_BACKEND_FAILURE_107")) {
String lun[] = errmsg.split("<LUN>");
boolean found = false;
for (int i = 1; i < lun.length; i++) {
int blunindex = lun[i].indexOf("<LUNid>") + 7;
int elunindex = lun[i].indexOf("</LUNid>");
String ilun = lun[i].substring(blunindex, elunindex);
ilun = ilun.trim();
if (ilun.equals(lunid)) {
int bscsiindex = lun[i].indexOf("<SCSIid>") + 8;
int escsiindex = lun[i].indexOf("</SCSIid>");
scsiid = lun[i].substring(bscsiindex, escsiindex);
scsiid = scsiid.trim();
found = true;
break;
}
}
if (!found) {
String msg = "can not find LUN " + lunid + " in " + errmsg;
s_logger.warn(msg);
throw new CloudRuntimeException(msg);
}
} else {
String msg = "Unable to create Iscsi SR " + deviceConfig + " due to " + e.toString();
s_logger.warn(msg, e);
throw new CloudRuntimeException(msg, e);
}
}
deviceConfig.put("SCSIid", scsiid);
sr = SR.create(conn, host, deviceConfig, new Long(0), pool.getUuid(), Long.toString(pool.getId()), SRType.LVMOISCSI.toString(), "user", true,
new HashMap<String, String>());
sr.scan(conn);
return sr;
} catch (XenAPIException e) {
String msg = "Unable to create Iscsi SR " + deviceConfig + " due to " + e.toString();
s_logger.warn(msg, e);
throw new CloudRuntimeException(msg, e);
} catch (Exception e) {
String msg = "Unable to create Iscsi SR " + deviceConfig + " due to " + e.getMessage();
s_logger.warn(msg, e);
throw new CloudRuntimeException(msg, e);
}
}
}
protected SR getNfsSR(StoragePoolTO pool) {
Connection conn = getConnection();
Map<String, String> deviceConfig = new HashMap<String, String>();
try {
String server = pool.getHost();
String serverpath = pool.getPath();
serverpath = serverpath.replace("//", "/");
Set<SR> srs = SR.getAll(conn);
for (SR sr : srs) {
if (!SRType.NFS.equals(sr.getType(conn)))
continue;
Set<PBD> pbds = sr.getPBDs(conn);
if (pbds.isEmpty())
continue;
PBD pbd = pbds.iterator().next();
Map<String, String> dc = pbd.getDeviceConfig(conn);
if (dc == null)
continue;
if (dc.get("server") == null)
continue;
if (dc.get("serverpath") == null)
continue;
if (server.equals(dc.get("server")) && serverpath.equals(dc.get("serverpath"))) {
if (checkSR(sr)) {
return sr;
}
throw new CloudRuntimeException("SR check failed for storage pool: " + pool.getUuid() + "on host:" + _host.uuid);
}
}
deviceConfig.put("server", server);
deviceConfig.put("serverpath", serverpath);
Host host = Host.getByUuid(conn, _host.uuid);
SR sr = SR.create(conn, host, deviceConfig, new Long(0), pool.getUuid(), Long.toString(pool.getId()), SRType.NFS.toString(), "user", true,
new HashMap<String, String>());
sr.scan(conn);
return sr;
} catch (XenAPIException e) {
throw new CloudRuntimeException("Unable to create NFS SR " + pool.toString(), e);
} catch (XmlRpcException e) {
throw new CloudRuntimeException("Unable to create NFS SR " + pool.toString(), e);
}
}
public Answer execute(DestroyCommand cmd) {
VolumeTO vol = cmd.getVolume();
Connection conn = getConnection();
// Look up the VDI
String volumeUUID = vol.getPath();
VDI vdi = null;
try {
vdi = getVDIbyUuid(volumeUUID);
} catch (Exception e) {
String msg = "getVDIbyUuid for " + volumeUUID + " failed due to " + e.toString();
s_logger.warn(msg);
return new Answer(cmd, true, "Success");
}
Set<VBD> vbds = null;
try {
vbds = vdi.getVBDs(conn);
} catch (Exception e) {
String msg = "VDI getVBDS for " + volumeUUID + " failed due to " + e.toString();
s_logger.warn(msg, e);
return new Answer(cmd, false, msg);
}
for (VBD vbd : vbds) {
try {
vbd.unplug(conn);
vbd.destroy(conn);
} catch (Exception e) {
String msg = "VM destroy for " + volumeUUID + " failed due to " + e.toString();
s_logger.warn(msg, e);
return new Answer(cmd, false, msg);
}
}
try {
vdi.destroy(conn);
} catch (Exception e) {
String msg = "VDI destroy for " + volumeUUID + " failed due to " + e.toString();
s_logger.warn(msg, e);
return new Answer(cmd, false, msg);
}
return new Answer(cmd, true, "Success");
}
public ShareAnswer execute(final ShareCommand cmd) {
if (!cmd.isShare()) {
SR sr = getISOSRbyVmName(cmd.getVmName());
Connection conn = getConnection();
try {
if (sr != null) {
Set<VM> vms = VM.getByNameLabel(conn, cmd.getVmName());
if (vms.size() == 0) {
removeSR(sr);
}
}
} catch (Exception e) {
String msg = "SR.getNameLabel failed due to " + e.getMessage() + e.toString();
s_logger.warn(msg);
}
}
return new ShareAnswer(cmd, new HashMap<String, Integer>());
}
public CopyVolumeAnswer execute(final CopyVolumeCommand cmd) {
String volumeUUID = cmd.getVolumePath();
StoragePoolVO pool = cmd.getPool();
StoragePoolTO poolTO = new StoragePoolTO(pool);
String secondaryStorageURL = cmd.getSecondaryStorageURL();
URI uri = null;
try {
uri = new URI(secondaryStorageURL);
} catch (URISyntaxException e) {
return new CopyVolumeAnswer(cmd, false, "Invalid secondary storage URL specified.", null, null);
}
String remoteVolumesMountPath = uri.getHost() + ":" + uri.getPath() + "/volumes/";
String volumeFolder = String.valueOf(cmd.getVolumeId()) + "/";
boolean toSecondaryStorage = cmd.toSecondaryStorage();
String errorMsg = "Failed to copy volume";
SR primaryStoragePool = null;
SR secondaryStorage = null;
VDI srcVolume = null;
VDI destVolume = null;
Connection conn = getConnection();
try {
if (toSecondaryStorage) {
// Create the volume folder
if (!createSecondaryStorageFolder(remoteVolumesMountPath, volumeFolder)) {
throw new InternalErrorException("Failed to create the volume folder.");
}
// Create a SR for the volume UUID folder
secondaryStorage = createNfsSRbyURI(new URI(secondaryStorageURL + "/volumes/" + volumeFolder), false);
// Look up the volume on the source primary storage pool
srcVolume = getVDIbyUuid(volumeUUID);
// Copy the volume to secondary storage
destVolume = cloudVDIcopy(srcVolume, secondaryStorage);
} else {
// Mount the volume folder
secondaryStorage = createNfsSRbyURI(new URI(secondaryStorageURL + "/volumes/" + volumeFolder), false);
// Look up the volume on secondary storage
Set<VDI> vdis = secondaryStorage.getVDIs(conn);
for (VDI vdi : vdis) {
if (vdi.getUuid(conn).equals(volumeUUID)) {
srcVolume = vdi;
break;
}
}
if (srcVolume == null) {
throw new InternalErrorException("Failed to find volume on secondary storage.");
}
// Copy the volume to the primary storage pool
primaryStoragePool = getStorageRepository(conn, poolTO);
destVolume = cloudVDIcopy(srcVolume, primaryStoragePool);
}
String srUUID;
if (primaryStoragePool == null) {
srUUID = secondaryStorage.getUuid(conn);
} else {
srUUID = primaryStoragePool.getUuid(conn);
}
String destVolumeUUID = destVolume.getUuid(conn);
return new CopyVolumeAnswer(cmd, true, null, srUUID, destVolumeUUID);
} catch (XenAPIException e) {
s_logger.warn(errorMsg + ": " + e.toString(), e);
return new CopyVolumeAnswer(cmd, false, e.toString(), null, null);
} catch (Exception e) {
s_logger.warn(errorMsg + ": " + e.toString(), e);
return new CopyVolumeAnswer(cmd, false, e.getMessage(), null, null);
} finally {
if (!toSecondaryStorage && srcVolume != null) {
// Delete the volume on secondary storage
destroyVDI(srcVolume);
}
removeSR(secondaryStorage);
if (!toSecondaryStorage) {
// Delete the volume folder on secondary storage
deleteSecondaryStorageFolder(remoteVolumesMountPath, volumeFolder);
}
}
}
protected AttachVolumeAnswer execute(final AttachVolumeCommand cmd) {
boolean attach = cmd.getAttach();
String vmName = cmd.getVmName();
Long deviceId = cmd.getDeviceId();
String errorMsg;
if (attach) {
errorMsg = "Failed to attach volume";
} else {
errorMsg = "Failed to detach volume";
}
Connection conn = getConnection();
try {
// Look up the VDI
VDI vdi = mount(cmd.getPooltype(), cmd.getVolumeFolder(),cmd.getVolumePath());
// Look up the VM
VM vm = getVM(conn, vmName);
/* For HVM guest, if no pv driver installed, no attach/detach */
boolean isHVM;
if (vm.getPVBootloader(conn).equalsIgnoreCase(""))
isHVM = true;
else
isHVM = false;
VMGuestMetrics vgm = vm.getGuestMetrics(conn);
boolean pvDrvInstalled = false;
if (!isRefNull(vgm) && vgm.getPVDriversUpToDate(conn)) {
pvDrvInstalled = true;
}
if (isHVM && !pvDrvInstalled) {
s_logger.warn(errorMsg + ": You attempted an operation on a VM which requires PV drivers to be installed but the drivers were not detected");
return new AttachVolumeAnswer(cmd, "You attempted an operation that requires PV drivers to be installed on the VM. Please install them by inserting xen-pv-drv.iso.");
}
if (attach) {
// Figure out the disk number to attach the VM to
String diskNumber = null;
if( deviceId != null ) {
if(isDeviceUsed(vm, deviceId)) {
String msg = "Device " + deviceId + " is used in VM " + vmName;
return new AttachVolumeAnswer(cmd,msg);
}
diskNumber = deviceId.toString();
} else {
diskNumber = getUnusedDeviceNum(vm);
}
// Create a new VBD
VBD.Record vbdr = new VBD.Record();
vbdr.VM = vm;
vbdr.VDI = vdi;
vbdr.bootable = false;
vbdr.userdevice = diskNumber;
vbdr.mode = Types.VbdMode.RW;
vbdr.type = Types.VbdType.DISK;
vbdr.unpluggable = true;
VBD vbd = VBD.create(conn, vbdr);
// Attach the VBD to the VM
vbd.plug(conn);
// Update the VDI's label to include the VM name
vdi.setNameLabel(conn, vmName + "-DATA");
return new AttachVolumeAnswer(cmd, Long.parseLong(diskNumber));
} else {
// Look up all VBDs for this VDI
Set<VBD> vbds = vdi.getVBDs(conn);
// Detach each VBD from its VM, and then destroy it
for (VBD vbd : vbds) {
VBD.Record vbdr = vbd.getRecord(conn);
if (vbdr.currentlyAttached) {
vbd.unplug(conn);
}
vbd.destroy(conn);
}
// Update the VDI's label to be "detached"
vdi.setNameLabel(conn, "detached");
umount(vdi);
return new AttachVolumeAnswer(cmd);
}
} catch (XenAPIException e) {
String msg = errorMsg + " for uuid: " + cmd.getVolumePath() + " due to " + e.toString();
s_logger.warn(msg, e);
return new AttachVolumeAnswer(cmd, msg);
} catch (Exception e) {
String msg = errorMsg + " for uuid: " + cmd.getVolumePath() + " due to " + e.getMessage();
s_logger.warn(msg, e);
return new AttachVolumeAnswer(cmd, msg);
}
}
protected void umount(VDI vdi) {
}
protected Answer execute(final AttachIsoCommand cmd) {
boolean attach = cmd.isAttach();
String vmName = cmd.getVmName();
String isoURL = cmd.getIsoPath();
String errorMsg;
if (attach) {
errorMsg = "Failed to attach ISO";
} else {
errorMsg = "Failed to detach ISO";
}
Connection conn = getConnection();
try {
if (attach) {
VBD isoVBD = null;
// Find the VM
VM vm = getVM(conn, vmName);
// Find the ISO VDI
VDI isoVDI = getIsoVDIByURL(conn, vmName, isoURL);
// Find the VM's CD-ROM VBD
Set<VBD> vbds = vm.getVBDs(conn);
for (VBD vbd : vbds) {
String userDevice = vbd.getUserdevice(conn);
Types.VbdType type = vbd.getType(conn);
if (userDevice.equals("3") && type == Types.VbdType.CD) {
isoVBD = vbd;
break;
}
}
if (isoVBD == null) {
throw new CloudRuntimeException("Unable to find CD-ROM VBD for VM: " + vmName);
} else {
// If an ISO is already inserted, eject it
if (isoVBD.getEmpty(conn) == false) {
isoVBD.eject(conn);
}
// Insert the new ISO
isoVBD.insert(conn, isoVDI);
}
return new Answer(cmd);
} else {
// Find the VM
VM vm = getVM(conn, vmName);
String vmUUID = vm.getUuid(conn);
// Find the ISO VDI
VDI isoVDI = getIsoVDIByURL(conn, vmName, isoURL);
SR sr = isoVDI.getSR(conn);
// Look up all VBDs for this VDI
Set<VBD> vbds = isoVDI.getVBDs(conn);
// Iterate through VBDs, and if the VBD belongs the VM, eject
// the ISO from it
for (VBD vbd : vbds) {
VM vbdVM = vbd.getVM(conn);
String vbdVmUUID = vbdVM.getUuid(conn);
if (vbdVmUUID.equals(vmUUID)) {
// If an ISO is already inserted, eject it
if (!vbd.getEmpty(conn)) {
vbd.eject(conn);
}
break;
}
}
if (!sr.getNameLabel(conn).startsWith("XenServer Tools")) {
removeSR(sr);
}
return new Answer(cmd);
}
} catch (XenAPIException e) {
s_logger.warn(errorMsg + ": " + e.toString(), e);
return new Answer(cmd, false, e.toString());
} catch (Exception e) {
s_logger.warn(errorMsg + ": " + e.toString(), e);
return new Answer(cmd, false, e.getMessage());
}
}
protected ValidateSnapshotAnswer execute(final ValidateSnapshotCommand cmd) {
String primaryStoragePoolNameLabel = cmd.getPrimaryStoragePoolNameLabel();
String volumeUuid = cmd.getVolumeUuid(); // Precondition: not null
String firstBackupUuid = cmd.getFirstBackupUuid();
String previousSnapshotUuid = cmd.getPreviousSnapshotUuid();
String templateUuid = cmd.getTemplateUuid();
// By default assume failure
String details = "Could not validate previous snapshot backup UUID " + "because the primary Storage SR could not be created from the name label: "
+ primaryStoragePoolNameLabel;
boolean success = false;
String expectedSnapshotBackupUuid = null;
String actualSnapshotBackupUuid = null;
String actualSnapshotUuid = null;
Boolean isISCSI = false;
String primaryStorageSRUuid = null;
Connection conn = getConnection();
try {
SR primaryStorageSR = getSRByNameLabelandHost(primaryStoragePoolNameLabel);
if (primaryStorageSR != null) {
primaryStorageSRUuid = primaryStorageSR.getUuid(conn);
isISCSI = SRType.LVMOISCSI.equals(primaryStorageSR.getType(conn));
}
} catch (BadServerResponse e) {
details += ", reason: " + e.getMessage();
s_logger.error(details, e);
} catch (XenAPIException e) {
details += ", reason: " + e.getMessage();
s_logger.error(details, e);
} catch (XmlRpcException e) {
details += ", reason: " + e.getMessage();
s_logger.error(details, e);
}
if (primaryStorageSRUuid != null) {
if (templateUuid == null) {
templateUuid = "";
}
if (firstBackupUuid == null) {
firstBackupUuid = "";
}
if (previousSnapshotUuid == null) {
previousSnapshotUuid = "";
}
String result = callHostPlugin("validateSnapshot", "primaryStorageSRUuid", primaryStorageSRUuid, "volumeUuid", volumeUuid, "firstBackupUuid", firstBackupUuid,
"previousSnapshotUuid", previousSnapshotUuid, "templateUuid", templateUuid, "isISCSI", isISCSI.toString());
if (result == null || result.isEmpty()) {
details = "Validating snapshot backup for volume with UUID: " + volumeUuid + " failed because there was an exception in the plugin";
// callHostPlugin exception which has been logged already
} else {
String[] uuids = result.split("#", -1);
if (uuids.length >= 3) {
expectedSnapshotBackupUuid = uuids[1];
actualSnapshotBackupUuid = uuids[2];
}
if (uuids.length >= 4) {
actualSnapshotUuid = uuids[3];
} else {
actualSnapshotUuid = "";
}
if (uuids[0].equals("1")) {
success = true;
details = null;
} else {
details = "Previous snapshot backup on the primary storage is invalid. " + "Expected: " + expectedSnapshotBackupUuid + " Actual: " + actualSnapshotBackupUuid;
// success is still false
}
s_logger.debug("ValidatePreviousSnapshotBackup returned " + " success: " + success + " details: " + details + " expectedSnapshotBackupUuid: "
+ expectedSnapshotBackupUuid + " actualSnapshotBackupUuid: " + actualSnapshotBackupUuid + " actualSnapshotUuid: " + actualSnapshotUuid);
}
}
return new ValidateSnapshotAnswer(cmd, success, details, expectedSnapshotBackupUuid, actualSnapshotBackupUuid, actualSnapshotUuid);
}
protected ManageSnapshotAnswer execute(final ManageSnapshotCommand cmd) {
long snapshotId = cmd.getSnapshotId();
String snapshotName = cmd.getSnapshotName();
// By default assume failure
boolean success = false;
String cmdSwitch = cmd.getCommandSwitch();
String snapshotOp = "Unsupported snapshot command." + cmdSwitch;
if (cmdSwitch.equals(ManageSnapshotCommand.CREATE_SNAPSHOT)) {
snapshotOp = "create";
} else if (cmdSwitch.equals(ManageSnapshotCommand.DESTROY_SNAPSHOT)) {
snapshotOp = "destroy";
}
String details = "ManageSnapshotCommand operation: " + snapshotOp + " Failed for snapshotId: " + snapshotId;
String snapshotUUID = null;
Connection conn = getConnection();
try {
if (cmdSwitch.equals(ManageSnapshotCommand.CREATE_SNAPSHOT)) {
// Look up the volume
String volumeUUID = cmd.getVolumePath();
VDI volume = getVDIbyUuid(volumeUUID);
// Create a snapshot
VDI snapshot = volume.snapshot(conn, new HashMap<String, String>());
if (snapshotName != null) {
snapshot.setNameLabel(conn, snapshotName);
}
// Determine the UUID of the snapshot
VDI.Record vdir = snapshot.getRecord(conn);
snapshotUUID = vdir.uuid;
success = true;
details = null;
} else if (cmd.getCommandSwitch().equals(ManageSnapshotCommand.DESTROY_SNAPSHOT)) {
// Look up the snapshot
snapshotUUID = cmd.getSnapshotPath();
VDI snapshot = getVDIbyUuid(snapshotUUID);
snapshot.destroy(conn);
snapshotUUID = null;
success = true;
details = null;
}
} catch (XenAPIException e) {
details += ", reason: " + e.toString();
s_logger.warn(details, e);
} catch (Exception e) {
details += ", reason: " + e.toString();
s_logger.warn(details, e);
}
return new ManageSnapshotAnswer(cmd, snapshotId, snapshotUUID, success, details);
}
protected CreatePrivateTemplateAnswer execute(final CreatePrivateTemplateCommand cmd) {
String secondaryStorageURL = cmd.getSecondaryStorageURL();
String snapshotUUID = cmd.getSnapshotPath();
String userSpecifiedName = cmd.getTemplateName();
SR secondaryStorage = null;
VDI privateTemplate = null;
Connection conn = getConnection();
try {
URI uri = new URI(secondaryStorageURL);
String remoteTemplateMountPath = uri.getHost() + ":" + uri.getPath() + "/template/";
String templateFolder = cmd.getAccountId() + "/" + cmd.getTemplateId() + "/";
String templateDownloadFolder = createTemplateDownloadFolder(remoteTemplateMountPath, templateFolder);
String templateInstallFolder = "tmpl/" + templateFolder;
// Create a SR for the secondary storage download folder
secondaryStorage = createNfsSRbyURI(new URI(secondaryStorageURL + "/template/" + templateDownloadFolder), false);
// Look up the snapshot and copy it to secondary storage
VDI snapshot = getVDIbyUuid(snapshotUUID);
privateTemplate = cloudVDIcopy(snapshot, secondaryStorage);
if (userSpecifiedName != null) {
privateTemplate.setNameLabel(conn, userSpecifiedName);
}
// Determine the template file name and install path
VDI.Record vdir = privateTemplate.getRecord(conn);
String templateName = vdir.uuid;
String templateFilename = templateName + ".vhd";
String installPath = "template/" + templateInstallFolder + templateFilename;
// Determine the template's virtual size and then forget the VDI
long virtualSize = privateTemplate.getVirtualSize(conn);
// Create the template.properties file in the download folder, move
// the template and the template.properties file
// to the install folder, and then delete the download folder
if (!postCreatePrivateTemplate(remoteTemplateMountPath, templateDownloadFolder, templateInstallFolder, templateFilename, templateName, userSpecifiedName, null,
virtualSize, cmd.getTemplateId())) {
throw new InternalErrorException("Failed to create the template.properties file.");
}
return new CreatePrivateTemplateAnswer(cmd, true, null, installPath, virtualSize, templateName, ImageFormat.VHD);
} catch (XenAPIException e) {
if (privateTemplate != null) {
destroyVDI(privateTemplate);
}
s_logger.warn("CreatePrivateTemplate Failed due to " + e.toString(), e);
return new CreatePrivateTemplateAnswer(cmd, false, e.toString(), null, 0, null, null);
} catch (Exception e) {
s_logger.warn("CreatePrivateTemplate Failed due to " + e.getMessage(), e);
return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage(), null, 0, null, null);
} finally {
// Remove the secondary storage SR
removeSR(secondaryStorage);
}
}
private String createTemplateDownloadFolder(String remoteTemplateMountPath, String templateFolder) throws InternalErrorException, URISyntaxException {
String templateDownloadFolder = "download/" + _host.uuid + "/" + templateFolder;
// Create the download folder
if (!createSecondaryStorageFolder(remoteTemplateMountPath, templateDownloadFolder)) {
throw new InternalErrorException("Failed to create the template download folder.");
}
return templateDownloadFolder;
}
protected CreatePrivateTemplateAnswer execute(final CreatePrivateTemplateFromSnapshotCommand cmd) {
String primaryStorageNameLabel = cmd.getPrimaryStoragePoolNameLabel();
Long dcId = cmd.getDataCenterId();
Long accountId = cmd.getAccountId();
Long volumeId = cmd.getVolumeId();
String secondaryStoragePoolURL = cmd.getSecondaryStoragePoolURL();
String backedUpSnapshotUuid = cmd.getSnapshotUuid();
String origTemplateInstallPath = cmd.getOrigTemplateInstallPath();
Long newTemplateId = cmd.getNewTemplateId();
String userSpecifiedName = cmd.getTemplateName();
// By default, assume failure
String details = "Failed to create private template " + newTemplateId + " from snapshot for volume: " + volumeId + " with backupUuid: " + backedUpSnapshotUuid;
String newTemplatePath = null;
String templateName = null;
boolean result = false;
long virtualSize = 0;
try {
URI uri = new URI(secondaryStoragePoolURL);
String remoteTemplateMountPath = uri.getHost() + ":" + uri.getPath() + "/template/";
String templateFolder = cmd.getAccountId() + "/" + newTemplateId + "/";
String templateDownloadFolder = createTemplateDownloadFolder(remoteTemplateMountPath, templateFolder);
String templateInstallFolder = "tmpl/" + templateFolder;
// Yes, create a template vhd
Pair<VHDInfo, String> vhdDetails = createVHDFromSnapshot(primaryStorageNameLabel, dcId, accountId, volumeId, secondaryStoragePoolURL, backedUpSnapshotUuid,
origTemplateInstallPath, templateDownloadFolder);
VHDInfo vhdInfo = vhdDetails.first();
String failureDetails = vhdDetails.second();
if (vhdInfo == null) {
if (failureDetails != null) {
details += failureDetails;
}
} else {
templateName = vhdInfo.getUuid();
String templateFilename = templateName + ".vhd";
String templateInstallPath = templateInstallFolder + File.separator + templateFilename;
newTemplatePath = "template" + File.separator + templateInstallPath;
virtualSize = vhdInfo.getVirtualSize();
// create the template.properties file
result = postCreatePrivateTemplate(remoteTemplateMountPath, templateDownloadFolder, templateInstallFolder, templateFilename, templateName, userSpecifiedName, null,
virtualSize, newTemplateId);
if (!result) {
details += ", reason: Could not create the template.properties file on secondary storage dir: " + templateInstallFolder;
} else {
// Aaah, success.
details = null;
}
}
} catch (XenAPIException e) {
details += ", reason: " + e.getMessage();
s_logger.error(details, e);
} catch (Exception e) {
details += ", reason: " + e.getMessage();
s_logger.error(details, e);
}
return new CreatePrivateTemplateAnswer(cmd, result, details, newTemplatePath, virtualSize, templateName, ImageFormat.VHD);
}
protected BackupSnapshotAnswer execute(final BackupSnapshotCommand cmd) {
String primaryStorageNameLabel = cmd.getPrimaryStoragePoolNameLabel();
Long dcId = cmd.getDataCenterId();
Long accountId = cmd.getAccountId();
Long volumeId = cmd.getVolumeId();
String secondaryStoragePoolURL = cmd.getSecondaryStoragePoolURL();
String snapshotUuid = cmd.getSnapshotUuid(); // not null: Precondition.
String prevSnapshotUuid = cmd.getPrevSnapshotUuid();
String prevBackupUuid = cmd.getPrevBackupUuid();
boolean isFirstSnapshotOfRootVolume = cmd.isFirstSnapshotOfRootVolume();
String firstBackupUuid = cmd.getFirstBackupUuid();
// By default assume failure
String details = null;
boolean success = false;
String snapshotBackupUuid = null;
try {
Connection conn = getConnection();
SR primaryStorageSR = getSRByNameLabelandHost(primaryStorageNameLabel);
if (primaryStorageSR == null) {
throw new InternalErrorException("Could not backup snapshot because the primary Storage SR could not be created from the name label: " + primaryStorageNameLabel);
}
String primaryStorageSRUuid = primaryStorageSR.getUuid(conn);
Boolean isISCSI = SRType.LVMOISCSI.equals(primaryStorageSR.getType(conn));
URI uri = new URI(secondaryStoragePoolURL);
String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath();
if (secondaryStorageMountPath == null) {
details = "Couldn't backup snapshot because the URL passed: " + secondaryStoragePoolURL + " is invalid.";
} else {
boolean gcHappened = true;
if (prevSnapshotUuid != null && !isFirstSnapshotOfRootVolume) {
// For the first snapshot of a root volume, the prevSnapshotUuid is set to the template uuid.
// This is to catch the case where the first snapshot is empty.
// But we need not wait for GC as no snapshot has been taken.
// gcHappened = waitForGC(primaryStorageSRUuid, prevSnapshotUuid, firstBackupUuid, isISCSI);
}
if (gcHappened) {
snapshotBackupUuid = backupSnapshot(primaryStorageSRUuid, dcId, accountId, volumeId, secondaryStorageMountPath, snapshotUuid, prevSnapshotUuid, prevBackupUuid,
isFirstSnapshotOfRootVolume, isISCSI);
success = (snapshotBackupUuid != null);
} else {
s_logger.warn("GC hasn't happened yet for previousSnapshotUuid: " + prevSnapshotUuid + ". Will retry again after 1 min");
}
}
if (!success) {
// Mark the snapshot as removed in the database.
// When the next snapshot is taken, it will be
// 1) deleted from the DB 2) The snapshotUuid will be deleted from the primary
// 3) the snapshotBackupUuid will be copied to secondary
// 4) if possible it will be coalesced with the next snapshot.
} else if (prevSnapshotUuid != null && !isFirstSnapshotOfRootVolume) {
// Destroy the previous snapshot, if it exists.
// We destroy the previous snapshot only if the current snapshot
// backup succeeds.
// The aim is to keep the VDI of the last 'successful' snapshot
// so that it doesn't get merged with the
// new one
// and muddle the vhd chain on the secondary storage.
details = "Successfully backedUp the snapshotUuid: " + snapshotUuid + " to secondary storage.";
destroySnapshotOnPrimaryStorage(prevSnapshotUuid);
}
} catch (XenAPIException e) {
details = "BackupSnapshot Failed due to " + e.toString();
s_logger.warn(details, e);
} catch (Exception e) {
details = "BackupSnapshot Failed due to " + e.getMessage();
s_logger.warn(details, e);
}
return new BackupSnapshotAnswer(cmd, success, details, snapshotBackupUuid);
}
protected CreateVolumeFromSnapshotAnswer execute(final CreateVolumeFromSnapshotCommand cmd) {
String primaryStorageNameLabel = cmd.getPrimaryStoragePoolNameLabel();
Long dcId = cmd.getDataCenterId();
Long accountId = cmd.getAccountId();
Long volumeId = cmd.getVolumeId();
String secondaryStoragePoolURL = cmd.getSecondaryStoragePoolURL();
String backedUpSnapshotUuid = cmd.getSnapshotUuid();
String templatePath = cmd.getTemplatePath();
// By default, assume the command has failed and set the params to be
// passed to CreateVolumeFromSnapshotAnswer appropriately
boolean result = false;
// Generic error message.
String details = "Failed to create volume from snapshot for volume: " + volumeId + " with backupUuid: " + backedUpSnapshotUuid;
String vhdUUID = null;
SR temporarySROnSecondaryStorage = null;
String mountPointOfTemporaryDirOnSecondaryStorage = null;
try {
VDI vdi = null;
Connection conn = getConnection();
SR primaryStorageSR = getSRByNameLabelandHost(primaryStorageNameLabel);
if (primaryStorageSR == null) {
throw new InternalErrorException("Could not create volume from snapshot because the primary Storage SR could not be created from the name label: "
+ primaryStorageNameLabel);
}
Boolean isISCSI = SRType.LVMOISCSI.equals(primaryStorageSR.getType(conn));
// Get the absolute path of the template on the secondary storage.
URI uri = new URI(secondaryStoragePoolURL);
String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath();
if (secondaryStorageMountPath == null) {
details += " because the URL passed: " + secondaryStoragePoolURL + " is invalid.";
return new CreateVolumeFromSnapshotAnswer(cmd, result, details, vhdUUID);
}
// Create a volume and not a template
String templateDownloadFolder = "";
VHDInfo vhdInfo = createVHDFromSnapshot(dcId, accountId, volumeId, secondaryStorageMountPath, backedUpSnapshotUuid, templatePath, templateDownloadFolder, isISCSI);
if (vhdInfo == null) {
details += " because the vmops plugin on XenServer failed at some point";
} else {
vhdUUID = vhdInfo.getUuid();
String tempDirRelativePath = "snapshots" + File.separator + accountId + File.separator + volumeId + "_temp";
mountPointOfTemporaryDirOnSecondaryStorage = secondaryStorageMountPath + File.separator + tempDirRelativePath;
uri = new URI("nfs://" + mountPointOfTemporaryDirOnSecondaryStorage);
// No need to check if the SR already exists. It's a temporary
// SR destroyed when this method exits.
// And two createVolumeFromSnapshot operations cannot proceed at
// the same time.
temporarySROnSecondaryStorage = createNfsSRbyURI(uri, false);
if (temporarySROnSecondaryStorage == null) {
details += "because SR couldn't be created on " + mountPointOfTemporaryDirOnSecondaryStorage;
} else {
s_logger.debug("Successfully created temporary SR on secondary storage " + temporarySROnSecondaryStorage.getNameLabel(conn) + "with uuid "
+ temporarySROnSecondaryStorage.getUuid(conn) + " and scanned it");
// createNFSSRbyURI also scans the SR and introduces the VDI
vdi = getVDIbyUuid(vhdUUID);
if (vdi != null) {
s_logger.debug("Successfully created VDI on secondary storage SR " + temporarySROnSecondaryStorage.getNameLabel(conn) + " with uuid " + vhdUUID);
s_logger.debug("Copying VDI: " + vdi.getLocation(conn) + " from secondary to primary");
VDI vdiOnPrimaryStorage = cloudVDIcopy(vdi, primaryStorageSR);
// vdi.copy introduces the vdi into the database. Don't
// need to do a scan on the primary
// storage.
if (vdiOnPrimaryStorage != null) {
vhdUUID = vdiOnPrimaryStorage.getUuid(conn);
s_logger.debug("Successfully copied and introduced VDI on primary storage with path " + vdiOnPrimaryStorage.getLocation(conn) + " and uuid " + vhdUUID);
result = true;
details = null;
} else {
details += ". Could not copy the vdi " + vhdUUID + " to primary storage";
}
// The VHD on temporary was scanned and introduced as a VDI
// destroy it as we don't need it anymore.
vdi.destroy(conn);
} else {
details += ". Could not scan and introduce vdi with uuid: " + vhdUUID;
}
}
}
} catch (XenAPIException e) {
details += " due to " + e.toString();
s_logger.warn(details, e);
} catch (Exception e) {
details += " due to " + e.getMessage();
s_logger.warn(details, e);
} finally {
// In all cases, if the temporary SR was created, forget it.
if (temporarySROnSecondaryStorage != null) {
removeSR(temporarySROnSecondaryStorage);
// Delete the temporary directory created.
File folderPath = new File(mountPointOfTemporaryDirOnSecondaryStorage);
String remoteMountPath = folderPath.getParent();
String folder = folderPath.getName();
deleteSecondaryStorageFolder(remoteMountPath, folder);
}
}
if (!result) {
// Is this logged at a higher level?
s_logger.error(details);
}
// In all cases return something.
return new CreateVolumeFromSnapshotAnswer(cmd, result, details, vhdUUID);
}
protected DeleteSnapshotBackupAnswer execute(final DeleteSnapshotBackupCommand cmd) {
Long dcId = cmd.getDataCenterId();
Long accountId = cmd.getAccountId();
Long volumeId = cmd.getVolumeId();
String secondaryStoragePoolURL = cmd.getSecondaryStoragePoolURL();
String backupUUID = cmd.getSnapshotUuid();
String childUUID = cmd.getChildUUID();
String primaryStorageNameLabel = cmd.getPrimaryStoragePoolNameLabel();
String details = null;
boolean success = false;
SR primaryStorageSR = null;
Boolean isISCSI = false;
try {
Connection conn = getConnection();
primaryStorageSR = getSRByNameLabelandHost(primaryStorageNameLabel);
if (primaryStorageSR == null) {
details = "Primary Storage SR could not be created from the name label: " + primaryStorageNameLabel;
throw new InternalErrorException(details);
}
isISCSI = SRType.LVMOISCSI.equals(primaryStorageSR.getType(conn));
} catch (XenAPIException e) {
details = "Couldn't determine primary SR type " + e.getMessage();
s_logger.error(details, e);
} catch (Exception e) {
details = "Couldn't determine primary SR type " + e.getMessage();
s_logger.error(details, e);
}
if (primaryStorageSR != null) {
URI uri = null;
try {
uri = new URI(secondaryStoragePoolURL);
} catch (URISyntaxException e) {
details = "Error finding the secondary storage URL" + e.getMessage();
s_logger.error(details, e);
}
if (uri != null) {
String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath();
if (secondaryStorageMountPath == null) {
details = "Couldn't delete snapshot because the URL passed: " + secondaryStoragePoolURL + " is invalid.";
} else {
details = deleteSnapshotBackup(dcId, accountId, volumeId, secondaryStorageMountPath, backupUUID, childUUID, isISCSI);
success = (details != null && details.equals("1"));
if (success) {
s_logger.debug("Successfully deleted snapshot backup " + backupUUID);
}
}
}
}
return new DeleteSnapshotBackupAnswer(cmd, success, details);
}
protected Answer execute(DeleteSnapshotsDirCommand cmd) {
Long dcId = cmd.getDataCenterId();
Long accountId = cmd.getAccountId();
Long volumeId = cmd.getVolumeId();
String secondaryStoragePoolURL = cmd.getSecondaryStoragePoolURL();
String snapshotUUID = cmd.getSnapshotUuid();
String primaryStorageNameLabel = cmd.getPrimaryStoragePoolNameLabel();
String details = null;
boolean success = false;
SR primaryStorageSR = null;
try {
primaryStorageSR = getSRByNameLabelandHost(primaryStorageNameLabel);
if (primaryStorageSR == null) {
details = "Primary Storage SR could not be created from the name label: " + primaryStorageNameLabel;
}
} catch (XenAPIException e) {
details = "Couldn't determine primary SR type " + e.getMessage();
s_logger.error(details, e);
} catch (Exception e) {
details = "Couldn't determine primary SR type " + e.getMessage();
s_logger.error(details, e);
}
if (primaryStorageSR != null) {
if (snapshotUUID != null) {
VDI snapshotVDI = getVDIbyUuid(snapshotUUID);
if (snapshotVDI != null) {
destroyVDI(snapshotVDI);
}
}
}
URI uri = null;
try {
uri = new URI(secondaryStoragePoolURL);
} catch (URISyntaxException e) {
details = "Error finding the secondary storage URL" + e.getMessage();
s_logger.error(details, e);
}
if (uri != null) {
String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath();
if (secondaryStorageMountPath == null) {
details = "Couldn't delete snapshotsDir because the URL passed: " + secondaryStoragePoolURL + " is invalid.";
} else {
details = deleteSnapshotsDir(dcId, accountId, volumeId, secondaryStorageMountPath);
success = (details != null && details.equals("1"));
if (success) {
s_logger.debug("Successfully deleted snapshotsDir for volume: " + volumeId);
}
}
}
return new Answer(cmd, success, details);
}
private VM getVM(Connection conn, String vmName) {
// Look up VMs with the specified name
Set<VM> vms;
try {
vms = VM.getByNameLabel(conn, vmName);
} catch (XenAPIException e) {
throw new CloudRuntimeException("Unable to get " + vmName + ": " + e.toString(), e);
} catch (Exception e) {
throw new CloudRuntimeException("Unable to get " + vmName + ": " + e.getMessage(), e);
}
// If there are no VMs, throw an exception
if (vms.size() == 0)
throw new CloudRuntimeException("VM with name: " + vmName + " does not exist.");
// If there is more than one VM, print a warning
if (vms.size() > 1)
s_logger.warn("Found " + vms.size() + " VMs with name: " + vmName);
// Return the first VM in the set
return vms.iterator().next();
}
protected VDI getIsoVDIByURL(Connection conn, String vmName, String isoURL) {
SR isoSR = null;
String mountpoint = null;
if (isoURL.startsWith("xs-tools")) {
try {
Set<VDI> vdis = VDI.getByNameLabel(conn, isoURL);
if (vdis.isEmpty()) {
throw new CloudRuntimeException("Could not find ISO with URL: " + isoURL);
}
return vdis.iterator().next();
} catch (XenAPIException e) {
throw new CloudRuntimeException("Unable to get pv iso: " + isoURL + " due to " + e.toString());
} catch (Exception e) {
throw new CloudRuntimeException("Unable to get pv iso: " + isoURL + " due to " + e.toString());
}
}
int index = isoURL.lastIndexOf("/");
mountpoint = isoURL.substring(0, index);
URI uri;
try {
uri = new URI(mountpoint);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
throw new CloudRuntimeException("isoURL is wrong: " + isoURL);
}
isoSR = getISOSRbyVmName(vmName);
if (isoSR == null) {
isoSR = createIsoSRbyURI(uri, vmName, false);
}
String isoName = isoURL.substring(index + 1);
VDI isoVDI = getVDIbyLocationandSR(isoName, isoSR);
if (isoVDI != null) {
return isoVDI;
} else {
throw new CloudRuntimeException("Could not find ISO with URL: " + isoURL);
}
}
protected SR getStorageRepository(Connection conn, StoragePoolTO pool) {
Set<SR> srs;
try {
srs = SR.getByNameLabel(conn, pool.getUuid());
} catch (XenAPIException e) {
throw new CloudRuntimeException("Unable to get SR " + pool.getUuid() + " due to " + e.toString(), e);
} catch (Exception e) {
throw new CloudRuntimeException("Unable to get SR " + pool.getUuid() + " due to " + e.getMessage(), e);
}
if (srs.size() > 1) {
throw new CloudRuntimeException("More than one storage repository was found for pool with uuid: " + pool.getUuid());
} else if (srs.size() == 1) {
SR sr = srs.iterator().next();
if (s_logger.isDebugEnabled()) {
s_logger.debug("SR retrieved for " + pool.getId() + " is mapped to " + sr.toString());
}
if (checkSR(sr)) {
return sr;
}
throw new CloudRuntimeException("SR check failed for storage pool: " + pool.getUuid() + "on host:" + _host.uuid);
} else {
if (pool.getType() == StoragePoolType.NetworkFilesystem)
return getNfsSR(pool);
else if (pool.getType() == StoragePoolType.IscsiLUN)
return getIscsiSR(pool);
else
throw new CloudRuntimeException("The pool type: " + pool.getType().name() + " is not supported.");
}
}
protected Answer execute(final CheckConsoleProxyLoadCommand cmd) {
return executeProxyLoadScan(cmd, cmd.getProxyVmId(), cmd.getProxyVmName(), cmd.getProxyManagementIp(), cmd.getProxyCmdPort());
}
protected Answer execute(final WatchConsoleProxyLoadCommand cmd) {
return executeProxyLoadScan(cmd, cmd.getProxyVmId(), cmd.getProxyVmName(), cmd.getProxyManagementIp(), cmd.getProxyCmdPort());
}
protected CreateZoneVlanAnswer execute(CreateZoneVlanCommand cmd) {
Connection conn = getConnection();
try {
final DomainRouter router = cmd.getRouter();
VM vm = getVM(conn, router.getInstanceName());
// ToDo: Using vif 3 for now. Sync with multiple public VLAN feature
// to avoid conflict
createVIF(conn, vm, router.getGuestZoneMacAddress(), router.getZoneVlan(), 0, "3", true);
return new CreateZoneVlanAnswer(cmd);
} catch (XenAPIException e) {
String msg = "Exception caught while creating zone vlan: " + e.toString();
s_logger.warn(msg, e);
return new CreateZoneVlanAnswer(cmd, msg);
} catch (Exception e) {
String msg = "Exception caught while creating zone vlan: " + e.getMessage();
s_logger.warn(msg, e);
return new CreateZoneVlanAnswer(cmd, msg);
}
}
protected Answer executeProxyLoadScan(final Command cmd, final long proxyVmId, final String proxyVmName, final String proxyManagementIp, final int cmdPort) {
String result = null;
final StringBuffer sb = new StringBuffer();
sb.append("http://").append(proxyManagementIp).append(":" + cmdPort).append("/cmd/getstatus");
boolean success = true;
try {
final URL url = new URL(sb.toString());
final URLConnection conn = url.openConnection();
// setting TIMEOUTs to avoid possible waiting until death situations
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
final InputStream is = conn.getInputStream();
final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
final StringBuilder sb2 = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null)
sb2.append(line + "\n");
result = sb2.toString();
} catch (final IOException e) {
success = false;
} finally {
try {
is.close();
} catch (final IOException e) {
s_logger.warn("Exception when closing , console proxy address : " + proxyManagementIp);
success = false;
}
}
} catch (final IOException e) {
s_logger.warn("Unable to open console proxy command port url, console proxy address : " + proxyManagementIp);
success = false;
}
return new ConsoleProxyLoadAnswer(cmd, proxyVmId, proxyVmName, success, result);
}
protected boolean createSecondaryStorageFolder(String remoteMountPath, String newFolder) {
String result = callHostPlugin("create_secondary_storage_folder", "remoteMountPath", remoteMountPath, "newFolder", newFolder);
return (result != null);
}
protected boolean deleteSecondaryStorageFolder(String remoteMountPath, String folder) {
String result = callHostPlugin("delete_secondary_storage_folder", "remoteMountPath", remoteMountPath, "folder", folder);
return (result != null);
}
protected boolean postCreatePrivateTemplate(String remoteTemplateMountPath, String templateDownloadFolder, String templateInstallFolder, String templateFilename,
String templateName, String templateDescription, String checksum, long virtualSize, long templateId) {
if (templateDescription == null) {
templateDescription = "";
}
if (checksum == null) {
checksum = "";
}
String result = callHostPluginWithTimeOut("post_create_private_template", 110*60, "remoteTemplateMountPath", remoteTemplateMountPath, "templateDownloadFolder", templateDownloadFolder,
"templateInstallFolder", templateInstallFolder, "templateFilename", templateFilename, "templateName", templateName, "templateDescription", templateDescription,
"checksum", checksum, "virtualSize", String.valueOf(virtualSize), "templateId", String.valueOf(templateId));
boolean success = false;
if (result != null && !result.isEmpty()) {
// Else, command threw an exception which has already been logged.
String[] tmp = result.split("#");
String status = tmp[0];
if (status != null && status.equalsIgnoreCase("1")) {
s_logger.debug("Successfully created template.properties file on secondary storage dir: " + templateInstallFolder);
success = true;
} else {
s_logger.warn("Could not create template.properties file on secondary storage dir: " + templateInstallFolder + " for templateId: " + templateId
+ ". Failed with status " + status);
}
}
return success;
}
// Each argument is put in a separate line for readability.
// Using more lines does not harm the environment.
protected String backupSnapshot(String primaryStorageSRUuid, Long dcId, Long accountId, Long volumeId, String secondaryStorageMountPath, String snapshotUuid,
String prevSnapshotUuid, String prevBackupUuid, Boolean isFirstSnapshotOfRootVolume, Boolean isISCSI) {
String backupSnapshotUuid = null;
if (prevSnapshotUuid == null) {
prevSnapshotUuid = "";
}
if (prevBackupUuid == null) {
prevBackupUuid = "";
}
// Each argument is put in a separate line for readability.
// Using more lines does not harm the environment.
String results = callHostPluginWithTimeOut("backupSnapshot", 110*60, "primaryStorageSRUuid", primaryStorageSRUuid, "dcId", dcId.toString(), "accountId", accountId.toString(), "volumeId",
volumeId.toString(), "secondaryStorageMountPath", secondaryStorageMountPath, "snapshotUuid", snapshotUuid, "prevSnapshotUuid", prevSnapshotUuid, "prevBackupUuid",
prevBackupUuid, "isFirstSnapshotOfRootVolume", isFirstSnapshotOfRootVolume.toString(), "isISCSI", isISCSI.toString());
if (results == null || results.isEmpty()) {
// errString is already logged.
return null;
}
String[] tmp = results.split("#");
String status = tmp[0];
backupSnapshotUuid = tmp[1];
// status == "1" if and only if backupSnapshotUuid != null
// So we don't rely on status value but return backupSnapshotUuid as an
// indicator of success.
String failureString = "Could not copy backupUuid: " + backupSnapshotUuid + " of volumeId: " + volumeId + " from primary storage " + primaryStorageSRUuid
+ " to secondary storage " + secondaryStorageMountPath;
if (status != null && status.equalsIgnoreCase("1") && backupSnapshotUuid != null) {
s_logger.debug("Successfully copied backupUuid: " + backupSnapshotUuid + " of volumeId: " + volumeId + " to secondary storage");
} else {
s_logger.debug(failureString + ". Failed with status: " + status);
}
return backupSnapshotUuid;
}
protected boolean destroySnapshotOnPrimaryStorage(String snapshotUuid) {
// Precondition snapshotUuid != null
try {
Connection conn = getConnection();
VDI snapshot = getVDIbyUuid(snapshotUuid);
if (snapshot == null) {
throw new InternalErrorException("Could not destroy snapshot " + snapshotUuid + " because the snapshot VDI was null");
}
snapshot.destroy(conn);
s_logger.debug("Successfully destroyed snapshotUuid: " + snapshotUuid + " on primary storage");
return true;
} catch (XenAPIException e) {
String msg = "Destroy snapshotUuid: " + snapshotUuid + " on primary storage failed due to " + e.toString();
s_logger.error(msg, e);
} catch (Exception e) {
String msg = "Destroy snapshotUuid: " + snapshotUuid + " on primary storage failed due to " + e.getMessage();
s_logger.warn(msg, e);
}
return false;
}
protected String deleteSnapshotBackup(Long dcId, Long accountId, Long volumeId, String secondaryStorageMountPath, String backupUUID, String childUUID, Boolean isISCSI) {
// If anybody modifies the formatting below again, I'll skin them
String result = callHostPlugin("deleteSnapshotBackup", "backupUUID", backupUUID, "childUUID", childUUID, "dcId", dcId.toString(), "accountId", accountId.toString(),
"volumeId", volumeId.toString(), "secondaryStorageMountPath", secondaryStorageMountPath, "isISCSI", isISCSI.toString());
return result;
}
protected String deleteSnapshotsDir(Long dcId, Long accountId, Long volumeId, String secondaryStorageMountPath) {
// If anybody modifies the formatting below again, I'll skin them
String result = callHostPlugin("deleteSnapshotsDir", "dcId", dcId.toString(), "accountId", accountId.toString(), "volumeId", volumeId.toString(),
"secondaryStorageMountPath", secondaryStorageMountPath);
return result;
}
// If anybody messes up with the formatting, I'll skin them
protected Pair<VHDInfo, String> createVHDFromSnapshot(String primaryStorageNameLabel, Long dcId, Long accountId, Long volumeId, String secondaryStoragePoolURL,
String backedUpSnapshotUuid, String templatePath, String templateDownloadFolder) throws XenAPIException, IOException, XmlRpcException, InternalErrorException,
URISyntaxException {
// Return values
String details = null;
Connection conn = getConnection();
SR primaryStorageSR = getSRByNameLabelandHost(primaryStorageNameLabel);
if (primaryStorageSR == null) {
throw new InternalErrorException("Could not create volume from snapshot " + "because the primary Storage SR could not be created from the name label: "
+ primaryStorageNameLabel);
}
Boolean isISCSI = SRType.LVMOISCSI.equals(primaryStorageSR.getType(conn));
// Get the absolute path of the template on the secondary storage.
URI uri = new URI(secondaryStoragePoolURL);
String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath();
VHDInfo vhdInfo = null;
if (secondaryStorageMountPath == null) {
details = " because the URL passed: " + secondaryStoragePoolURL + " is invalid.";
} else {
vhdInfo = createVHDFromSnapshot(dcId, accountId, volumeId, secondaryStorageMountPath, backedUpSnapshotUuid, templatePath, templateDownloadFolder, isISCSI);
if (vhdInfo == null) {
details = " because the vmops plugin on XenServer failed at some point";
}
}
return new Pair<VHDInfo, String>(vhdInfo, details);
}
protected VHDInfo createVHDFromSnapshot(Long dcId, Long accountId, Long volumeId, String secondaryStorageMountPath, String backedUpSnapshotUuid, String templatePath,
String templateDownloadFolder, Boolean isISCSI) {
String vdiUUID = null;
String failureString = "Could not create volume from " + backedUpSnapshotUuid;
templatePath = (templatePath == null) ? "" : templatePath;
String results = callHostPluginWithTimeOut("createVolumeFromSnapshot", 110*60, "dcId", dcId.toString(), "accountId", accountId.toString(), "volumeId", volumeId.toString(),
"secondaryStorageMountPath", secondaryStorageMountPath, "backedUpSnapshotUuid", backedUpSnapshotUuid, "templatePath", templatePath, "templateDownloadFolder",
templateDownloadFolder, "isISCSI", isISCSI.toString());
if (results == null || results.isEmpty()) {
// Command threw an exception which has already been logged.
return null;
}
String[] tmp = results.split("#");
String status = tmp[0];
vdiUUID = tmp[1];
Long virtualSizeInMB = 0L;
if (tmp.length == 3) {
virtualSizeInMB = Long.valueOf(tmp[2]);
}
// status == "1" if and only if vdiUUID != null
// So we don't rely on status value but return vdiUUID as an indicator
// of success.
if (status != null && status.equalsIgnoreCase("1") && vdiUUID != null) {
s_logger.debug("Successfully created vhd file with all data on secondary storage : " + vdiUUID);
} else {
s_logger.debug(failureString + ". Failed with status " + status + " with vdiUuid " + vdiUUID);
}
return new VHDInfo(vdiUUID, virtualSizeInMB * MB);
}
protected void syncDomRIPMap(String vm) {
// VM is a DomR, get its IP and add to domR-IP map
Connection conn = getConnection();
VM vm1 = getVM(conn, vm);
try {
String pvargs = vm1.getPVArgs(conn);
if (pvargs != null) {
pvargs = pvargs.replaceAll(" ", "\n");
Properties pvargsProps = new Properties();
pvargsProps.load(new StringReader(pvargs));
String ip = pvargsProps.getProperty("eth1ip");
if (ip != null) {
_domrIPMap.put(vm, ip);
}
}
} catch (BadServerResponse e) {
String msg = "Unable to update domR IP map due to: " + e.toString();
s_logger.warn(msg, e);
} catch (XenAPIException e) {
String msg = "Unable to update domR IP map due to: " + e.toString();
s_logger.warn(msg, e);
} catch (XmlRpcException e) {
String msg = "Unable to update domR IP map due to: " + e.toString();
s_logger.warn(msg, e);
} catch (IOException e) {
String msg = "Unable to update domR IP map due to: " + e.toString();
s_logger.warn(msg, e);
}
}
@Override
public boolean start() {
return true;
}
@Override
public boolean stop() {
disconnected();
return true;
}
@Override
public String getName() {
return _name;
}
@Override
public IAgentControl getAgentControl() {
return _agentControl;
}
@Override
public void setAgentControl(IAgentControl agentControl) {
_agentControl = agentControl;
}
private Answer execute(NetworkIngressRulesCmd cmd) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Sending network rules command to " + _host.ip);
}
if (!_canBridgeFirewall) {
s_logger.info("Host " + _host.ip + " cannot do bridge firewalling");
return new NetworkIngressRuleAnswer(cmd, false, "Host " + _host.ip + " cannot do bridge firewalling");
}
String result = callHostPlugin("network_rules",
"vmName", cmd.getVmName(),
"vmIP", cmd.getGuestIp(),
"vmMAC", cmd.getGuestMac(),
"vmID", Long.toString(cmd.getVmId()),
"signature", cmd.getSignature(),
"seqno", Long.toString(cmd.getSeqNum()),
"rules", cmd.stringifyRules());
if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
s_logger.warn("Failed to program network rules for vm " + cmd.getVmName());
return new NetworkIngressRuleAnswer(cmd, false, "programming network rules failed");
} else {
s_logger.info("Programmed network rules for vm " + cmd.getVmName() + " guestIp=" + cmd.getGuestIp() + ", numrules=" + cmd.getRuleSet().length);
return new NetworkIngressRuleAnswer(cmd);
}
}
private Answer execute(PoolEjectCommand cmd) {
Connection conn = getConnection();
String hostuuid = cmd.getHostuuid();
try {
Host host = Host.getByUuid(conn, hostuuid);
Pool.eject(conn, host);
return new Answer(cmd);
} catch (XenAPIException e) {
String msg = "Unable to eject host " + _host.uuid + " due to " + e.toString();
s_logger.warn(msg, e);
return new Answer(cmd, false, msg);
} catch (Exception e) {
s_logger.warn("Unable to eject host " + _host.uuid, e);
String msg = "Unable to eject host " + _host.uuid + " due to " + e.getMessage();
s_logger.warn(msg, e);
return new Answer(cmd, false, msg);
}
}
protected class Nic {
public Network n;
public Network.Record nr;
public PIF p;
public PIF.Record pr;
public Nic(Network n, Network.Record nr, PIF p, PIF.Record pr) {
this.n = n;
this.nr = nr;
this.p = p;
this.pr = pr;
}
}
// A list of UUIDs that are gathered from the XenServer when
// the resource first connects to XenServer. These UUIDs do
// not change over time.
protected class XenServerHost {
public String uuid;
public String ip;
public Host host;
public String publicNetwork;
public String privateNetwork;
public String linkLocalNetwork;
public String storageNetwork1;
public String storageNetwork2;
public String guestNetwork;
public String guestPif;
public String publicPif;
public String privatePif;
public String storagePif1;
public String storagePif2;
public String pool;
}
private class VHDInfo {
private final String uuid;
private final Long virtualSize;
public VHDInfo(String uuid, Long virtualSize) {
this.uuid = uuid;
this.virtualSize = virtualSize;
}
/**
* @return the uuid
*/
public String getUuid() {
return uuid;
}
/**
* @return the virtualSize
*/
public Long getVirtualSize() {
return virtualSize;
}
}
}
| false | false | null | null |
diff --git a/RedditInPictures-Library/src/com/antew/redditinpictures/library/ui/ImageGridActivity.java b/RedditInPictures-Library/src/com/antew/redditinpictures/library/ui/ImageGridActivity.java
index 128eb3f..7ecce47 100644
--- a/RedditInPictures-Library/src/com/antew/redditinpictures/library/ui/ImageGridActivity.java
+++ b/RedditInPictures-Library/src/com/antew/redditinpictures/library/ui/ImageGridActivity.java
@@ -1,784 +1,788 @@
package com.antew.redditinpictures.library.ui;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.antew.redditinpictures.library.BuildConfig;
import com.antew.redditinpictures.library.R;
import com.antew.redditinpictures.library.adapter.SubredditMenuDrawerCursorAdapter;
import com.antew.redditinpictures.library.dialog.LoginDialogFragment;
import com.antew.redditinpictures.library.dialog.LoginDialogFragment.LoginDialogListener;
import com.antew.redditinpictures.library.dialog.LogoutDialogFragment;
import com.antew.redditinpictures.library.dialog.LogoutDialogFragment.LogoutDialogListener;
import com.antew.redditinpictures.library.enums.Age;
import com.antew.redditinpictures.library.enums.Category;
import com.antew.redditinpictures.library.interfaces.RedditDataProvider;
import com.antew.redditinpictures.library.interfaces.ScrollPosReadable;
import com.antew.redditinpictures.library.logging.Log;
import com.antew.redditinpictures.library.preferences.RedditInPicturesPreferences;
import com.antew.redditinpictures.library.preferences.SharedPreferencesHelper;
import com.antew.redditinpictures.library.reddit.LoginData;
import com.antew.redditinpictures.library.reddit.RedditLoginInformation;
+import com.antew.redditinpictures.library.reddit.RedditUrl;
import com.antew.redditinpictures.library.service.RedditService;
import com.antew.redditinpictures.library.ui.base.BaseFragmentActivity;
import com.antew.redditinpictures.library.utils.Consts;
import com.antew.redditinpictures.library.utils.Ln;
import com.antew.redditinpictures.library.utils.SafeAsyncTask;
import com.antew.redditinpictures.library.utils.Strings;
import com.antew.redditinpictures.library.utils.SubredditUtils;
import com.antew.redditinpictures.library.utils.Util;
import com.antew.redditinpictures.sqlite.RedditContract;
import com.antew.redditinpictures.sqlite.RedditDatabase;
import net.simonvt.menudrawer.MenuDrawer;
import java.util.ArrayList;
public class ImageGridActivity extends BaseFragmentActivity implements LoginDialogListener, LogoutDialogListener, RedditDataProvider,
LoaderManager.LoaderCallbacks<Cursor>, ScrollPosReadable {
public static final int EDIT_SUBREDDITS_REQUEST = 10;
public static final int SETTINGS_REQUEST = 20;
private static final String TAG = "ImageGridActivity";
protected boolean mShowNsfwImages;
protected Age mAge = Age.TODAY;
protected Category mCategory = Category.HOT;
protected RelativeLayout mLayoutWrapper;
private ProgressDialog mProgressDialog;
private MenuItem mLoginMenuItem;
private String mUsername;
private MenuDrawer mSubredditDrawer;
private String mSelectedSubreddit;
private SubredditMenuDrawerCursorAdapter mSubredditAdapter;
private ViewType mActiveViewType = ViewType.LIST;
private int mFirstVisiblePos = 0;
private enum ViewType {LIST, GRID, VIEWPAGER}
private BroadcastReceiver mSubredditsSearch = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.hasExtra(Consts.EXTRA_SUBREDDIT_NAMES)) {
Ln.d("Got Back Subreddit Search Result");
final ArrayList<String> subredditNames = intent.getStringArrayListExtra(Consts.EXTRA_SUBREDDIT_NAMES);
AutoCompleteTextView mSubredditFilter = (AutoCompleteTextView) findViewById(R.id.et_subreddit_filter);
if (mSubredditFilter != null) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ImageGridActivity.this, android.R.layout.simple_dropdown_item_1line, subredditNames);
mSubredditFilter.setAdapter(adapter);
mSubredditFilter.showDropDown();
mSubredditFilter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mSelectedSubreddit = subredditNames.get(position);
RedditService.aboutSubreddit(ImageGridActivity.this, mSelectedSubreddit);
mSubredditDrawer.setActiveView(view, position);
mSubredditAdapter.setActivePosition(position);
mSubredditDrawer.closeMenu(true);
loadSubreddit(mSelectedSubreddit);
}
});
mSubredditFilter.setImeActionLabel(getString(R.string.go), KeyEvent.KEYCODE_ENTER);
mSubredditFilter.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
Ln.d("Action: %d Event: %s", actionId, event);
return true;
}
});
}
}
}
};
//@formatter:off
private BroadcastReceiver mMySubreddits = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Received mySubreddits callback");
hideProgressDialog();
}
};
//@formatter:off
private BroadcastReceiver mLoginComplete = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Login request complete");
hideProgressDialog();
}
};
//@formatter:on
@Override
protected void onCreate(Bundle savedInstanceState) {
if (BuildConfig.DEBUG) {
Util.enableStrictMode();
}
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
super.onCreate(savedInstanceState);
initializeActionBar();
mSubredditDrawer = MenuDrawer.attach(this, MenuDrawer.Type.OVERLAY);
mSubredditDrawer.setContentView(R.layout.image_grid_activity);
mSubredditDrawer.setMenuView(R.layout.subreddit_menudrawer);
mSubredditDrawer.setSlideDrawable(R.drawable.ic_drawer);
mSubredditDrawer.setDrawerIndicatorEnabled(true);
mSubredditAdapter = getSubredditMenuAdapter();
ListView mSubredditList = (ListView) findViewById(R.id.lv_subreddits);
mSubredditList.setAdapter(mSubredditAdapter);
mSubredditList.setOnItemClickListener(mSubredditClickListener);
final AutoCompleteTextView mSubredditFilter = (AutoCompleteTextView) findViewById(R.id.et_subreddit_filter);
mSubredditFilter.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
return;
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s == null) {
return;
}
LoaderManager loaderManager = getSupportLoaderManager();
Bundle filterBundle = new Bundle();
filterBundle.putString(Consts.EXTRA_QUERY, s.toString());
loaderManager.restartLoader(Consts.LOADER_SUBREDDITS, filterBundle, ImageGridActivity.this);
}
@Override
public void afterTextChanged(Editable s) {
return;
}
});
Button subredditSearch = (Button) findViewById(R.id.btn_search);
subredditSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RedditService.searchSubreddits(ImageGridActivity.this, mSubredditFilter.getText().toString(), SharedPreferencesHelper.getShowNsfwImages(ImageGridActivity.this));
}
});
SetDefaultSubredditsTask defaultSubredditsTask = new SetDefaultSubredditsTask();
defaultSubredditsTask.execute();
loadSharedPreferences();
// Whether we are in grid or list view
if (savedInstanceState != null && savedInstanceState.containsKey(Consts.ACTIVE_VIEW)) {
mActiveViewType = ViewType.valueOf(savedInstanceState.getString(Consts.ACTIVE_VIEW));
}
changeActiveViewType(mActiveViewType);
LocalBroadcastManager.getInstance(this).registerReceiver(mMySubreddits, new IntentFilter(Consts.BROADCAST_MY_SUBREDDITS));
LocalBroadcastManager.getInstance(this).registerReceiver(mLoginComplete, new IntentFilter(Consts.BROADCAST_LOGIN_COMPLETE));
LocalBroadcastManager.getInstance(this).registerReceiver(mSubredditsSearch, new IntentFilter(Consts.BROADCAST_SUBREDDIT_SEARCH));
initializeLoaders();
}
private void initializeLoaders() {
LoaderManager loaderManager = getSupportLoaderManager();
loaderManager.initLoader(Consts.LOADER_LOGIN, null, this);
loaderManager.initLoader(Consts.LOADER_SUBREDDITS, null, this);
}
private void initializeActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
}
private void loadSharedPreferences() {
mShowNsfwImages = SharedPreferencesHelper.getShowNsfwImages(ImageGridActivity.this);
mAge = SharedPreferencesHelper.getAge(ImageGridActivity.this);
mCategory = SharedPreferencesHelper.getCategory(ImageGridActivity.this);
}
public Fragment getImageGridFragment() {
ImageGridFragment fragment = (ImageGridFragment) getSupportFragmentManager().findFragmentByTag(ImageGridFragment.TAG);
if (fragment == null) {
fragment = getNewImageGridFragment();
}
return fragment;
}
public Fragment getImageListFragment() {
ImageListFragment fragment = (ImageListFragment) getSupportFragmentManager().findFragmentByTag(ImageListFragment.TAG);
if (fragment == null) {
fragment = getNewImageListFragment();
}
return fragment;
}
@Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMySubreddits);
LocalBroadcastManager.getInstance(this).unregisterReceiver(mLoginComplete);
LocalBroadcastManager.getInstance(this).unregisterReceiver(mSubredditsSearch);
super.onPause();
}
/**
* On some version of android the indeterminate progress bar will show when the feature is
* requested, so we make sure it is hidden here
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setSupportProgressBarIndeterminateVisibility(false);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the user is logged in, update the Logout menu item to "Log out <username>"
if (RedditLoginInformation.isLoggedIn()) {
mLoginMenuItem.setTitle(getString(R.string.log_out_) + RedditLoginInformation.getUsername());
mLoginMenuItem.setIcon(R.drawable.ic_action_logout);
} else {
mLoginMenuItem.setTitle(R.string.log_on);
mLoginMenuItem.setIcon(R.drawable.ic_action_login);
}
return true;
}
private SubredditMenuDrawerCursorAdapter getSubredditMenuAdapter() {
mSubredditAdapter = new SubredditMenuDrawerCursorAdapter(ImageGridActivity.this, null, mAge, mCategory);
return mSubredditAdapter;
}
public ImageGridFragment getNewImageGridFragment() {
return new ImageGridFragment();
}
public ImageListFragment getNewImageListFragment() {
return new ImageListFragment();
}
private AdapterView.OnItemClickListener mSubredditClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int mActivePosition = position;
// TODO: Get this working using the cursor adapter
// Right now getting:
// 02-10 22:07:14.820 13737-13737/com.antew.redditinpictures.pro E/AndroidRuntime﹕ FATAL EXCEPTION: main
// java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteQuery: SELECT _id, displayName FROM subreddits ORDER BY displayName COLLATE NOCASE ASC
mSelectedSubreddit = ((TextView) view.findViewById(R.id.subreddit)).getText().toString();
mSubredditDrawer.setActiveView(view, position);
mSubredditAdapter.setActivePosition(position);
mSubredditDrawer.closeMenu(true);
loadSubreddit(mSelectedSubreddit);
}
};
private void loadSubreddit(String subredditName) {
Intent intent = new Intent(Consts.BROADCAST_SUBREDDIT_SELECTED);
getSupportActionBar().setTitle(subredditName);
intent.putExtra(Consts.EXTRA_SELECTED_SUBREDDIT, subredditName);
intent.putExtra(Consts.EXTRA_AGE, mAge.name());
intent.putExtra(Consts.EXTRA_CATEGORY, mCategory.name());
LocalBroadcastManager.getInstance(ImageGridActivity.this).sendBroadcast(intent);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// outState.putInt(Consts.EXTRA_NAV_POSITION, getSupportActionBar().getSelectedNavigationIndex());
outState.putString(Consts.EXTRA_SELECTED_SUBREDDIT, getSubreddit());
outState.putString(Consts.ACTIVE_VIEW, mActiveViewType.name());
super.onSaveInstanceState(outState);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
mLoginMenuItem = menu.findItem(R.id.login);
MenuItem item;
//@formatter:off
// Put a checkmark by the currently selected Category + Age combination
switch (mCategory) {
case CONTROVERSIAL:
switch (mAge)
{
case ALL_TIME: item = menu.findItem(R.id.category_controversial_all_time); item.setChecked(true); break;
case THIS_HOUR: item = menu.findItem(R.id.category_controversial_hour) ; item.setChecked(true); break;
case THIS_MONTH:item = menu.findItem(R.id.category_controversial_month) ; item.setChecked(true); break;
case THIS_WEEK: item = menu.findItem(R.id.category_controversial_week) ; item.setChecked(true); break;
case THIS_YEAR: item = menu.findItem(R.id.category_controversial_year) ; item.setChecked(true); break;
case TODAY: item = menu.findItem(R.id.category_controversial_today) ; item.setChecked(true); break;
}
break;
case HOT:
menu.findItem(R.id.category_hot).setChecked(true);
break;
case NEW:
menu.findItem(R.id.category_new).setChecked(true);
break;
case RISING:
menu.findItem(R.id.category_rising).setChecked(true);
break;
case TOP:
switch (mAge)
{
case ALL_TIME: item = menu.findItem(R.id.category_top_all_time); item.setChecked(true); break;
case THIS_HOUR: item = menu.findItem(R.id.category_top_hour) ; item.setChecked(true); break;
case THIS_MONTH:item = menu.findItem(R.id.category_top_month) ; item.setChecked(true); break;
case THIS_WEEK: item = menu.findItem(R.id.category_top_week) ; item.setChecked(true); break;
case THIS_YEAR: item = menu.findItem(R.id.category_top_year) ; item.setChecked(true); break;
case TODAY: item = menu.findItem(R.id.category_top_today) ; item.setChecked(true); break;
}
break;
default:
mCategory = Category.HOT;
mAge = Age.TODAY;
menu.findItem(R.id.category_hot).setChecked(true);
break;
}
//@formatter:on
MenuItem mActiveViewMenuItem = menu.findItem(R.id.change_view);
switch (mActiveViewType) {
case LIST:
mActiveViewMenuItem.setIcon(R.drawable.ic_action_view_as_grid);
break;
case GRID:
mActiveViewMenuItem.setIcon(R.drawable.ic_action_view_as_list);
break;
case VIEWPAGER:
break;
}
return true;
}
public void startPreferences() {
Intent intent = new Intent(ImageGridActivity.this, getPreferencesClass());
intent.putExtra(Consts.EXTRA_SHOW_NSFW_IMAGES, mShowNsfwImages);
startActivityForResult(intent, SETTINGS_REQUEST);
}
public Class<? extends PreferenceActivity> getPreferencesClass() {
return RedditInPicturesPreferences.class;
}
/**
* Change the current view type to the input viewtype
* @param newViewType {@link ViewType} to switch to.
*/
private void changeActiveViewType(ViewType newViewType) {
mActiveViewType = ViewType.GRID;
FragmentManager fm = getSupportFragmentManager();
final FragmentTransaction ft = fm.beginTransaction();
String oldFragmentTag = null;
String newFragmentTag = null;
Fragment newFragment = null;
switch (newViewType) {
case GRID:
mActiveViewType = ViewType.GRID;
oldFragmentTag = ImageListFragment.TAG;
newFragmentTag = ImageGridFragment.TAG;
newFragment = getImageGridFragment();
break;
case LIST:
mActiveViewType = ViewType.LIST;
oldFragmentTag = ImageGridFragment.TAG;
newFragmentTag = ImageListFragment.TAG;
newFragment = getImageListFragment();
break;
case VIEWPAGER:
break;
}
Fragment oldFragment = fm.findFragmentByTag(oldFragmentTag);
if (oldFragment != null) {
// Setting the first visible item in the
// ImageGridFragment and ImageListFragment
// is dependent on the fragment being
// hidden so that the first visible position
// can be saved and picked up by the next
// image viewing fragment
ft.hide(oldFragment);
}
if (newFragment.isAdded()) {
ft.show(newFragment);
} else {
ft.add(mSubredditDrawer.getContentContainer().getId(), newFragment, newFragmentTag);
}
ft.commit();
invalidateOptionsMenu();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
item.setChecked(true);
boolean loadFromUrl = false;
int itemId = item.getItemId();
if (itemId == android.R.id.home) {
mSubredditDrawer.toggleMenu();
} else if (itemId == R.id.change_view) {
ViewType newViewType = mActiveViewType == ViewType.LIST ? ViewType.GRID : ViewType.LIST;
changeActiveViewType(newViewType);
} else if (itemId == R.id.settings) {
startPreferences();
} else if (itemId == R.id.refresh_all) {
loadSubreddit(getSupportActionBar().getTitle().toString());
} else if (itemId == R.id.login) {
handleLoginAndLogout();
}
//@formatter:off
else if (itemId == R.id.category_hot) { mCategory = Category.HOT; loadFromUrl = true; }
else if (itemId == R.id.category_new) { mCategory = Category.NEW; loadFromUrl = true; }
else if (itemId == R.id.category_rising) { mCategory = Category.RISING; loadFromUrl = true; }
else if (itemId == R.id.category_top_hour) { mCategory = Category.TOP; mAge = Age.THIS_HOUR ; loadFromUrl = true; }
else if (itemId == R.id.category_top_today) { mCategory = Category.TOP; mAge = Age.TODAY ; loadFromUrl = true; }
else if (itemId == R.id.category_top_week) { mCategory = Category.TOP; mAge = Age.THIS_WEEK ; loadFromUrl = true; }
else if (itemId == R.id.category_top_month) { mCategory = Category.TOP; mAge = Age.THIS_MONTH; loadFromUrl = true; }
else if (itemId == R.id.category_top_year) { mCategory = Category.TOP; mAge = Age.THIS_YEAR ; loadFromUrl = true; }
else if (itemId == R.id.category_top_all_time) { mCategory = Category.TOP; mAge = Age.ALL_TIME ; loadFromUrl = true; }
else if (itemId == R.id.category_controversial_hour) { mCategory = Category.CONTROVERSIAL; mAge = Age.THIS_HOUR ; loadFromUrl = true; }
else if (itemId == R.id.category_controversial_today) { mCategory = Category.CONTROVERSIAL; mAge = Age.TODAY ; loadFromUrl = true; }
else if (itemId == R.id.category_controversial_week) { mCategory = Category.CONTROVERSIAL; mAge = Age.THIS_WEEK ; loadFromUrl = true; }
else if (itemId == R.id.category_controversial_month) { mCategory = Category.CONTROVERSIAL; mAge = Age.THIS_MONTH; loadFromUrl = true; }
else if (itemId == R.id.category_controversial_year) { mCategory = Category.CONTROVERSIAL; mAge = Age.THIS_YEAR ; loadFromUrl = true; }
else if (itemId == R.id.category_controversial_all_time) { mCategory = Category.CONTROVERSIAL; mAge = Age.ALL_TIME ; loadFromUrl = true; }
// @formatter:on
if (loadFromUrl) {
SharedPreferencesHelper.saveCategorySelectionLoginInformation(mAge, mCategory, ImageGridActivity.this);
// getSubredditAdapter().notifyDataSetChanged(mCategory, mAge);
Log.i(TAG, "onOptionsItemSelected, loadFromUrl = true, calling populateViewPagerFromSpinner()");
// onNavigationItemSelected(getSupportActionBar().getSelectedNavigationIndex(), 0);
}
return true;
}
public void handleLoginAndLogout() {
if (!RedditLoginInformation.isLoggedIn()) {
LoginDialogFragment loginFragment = LoginDialogFragment.newInstance();
loginFragment.show(getSupportFragmentManager(), Consts.DIALOG_LOGIN);
} else {
DialogFragment logoutFragment = LogoutDialogFragment.newInstance();
logoutFragment.show(getSupportFragmentManager(), Consts.DIALOG_LOGOUT);
}
}
/**
* Take care of popping the fragment back stack or finishing the activity
* as appropriate.
*/
@Override
public void onBackPressed() {
// If the menu drawer is open it, close it. Otherwise go about the normal business.
if (mSubredditDrawer != null && mSubredditDrawer.isMenuVisible()) {
mSubredditDrawer.closeMenu();
return;
}
super.onBackPressed();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == EDIT_SUBREDDITS_REQUEST && resultCode == RESULT_OK) {
// TODO: Make sure the menudrawer updates the list of subreddits
// If the user tapped an item in the subreddit list, select that subreddit and load the
// new images
if (data.hasExtra(Consts.EXTRA_NEWLY_SELECTED_SUBREDDIT)) {
boolean mFirstCall = false;
int pos = getSubredditPosition(data.getStringExtra(Consts.EXTRA_NEWLY_SELECTED_SUBREDDIT));
// onNavigationItemSelected(pos, 0);
return;
}
// If the user didn't choose a subreddit (meaning we are returned the subreddit they
// were previously viewing), select it in the list, if it doesn't exist any longer we
// default to the Front page.
String subredditName = data.getStringExtra(Consts.EXTRA_SELECTED_SUBREDDIT);
if (subredditExistsInNavigation(subredditName)) {
selectSubredditInNavigation(subredditName);
} else {
// Select the Reddit Front Page
// onNavigationItemSelected(Consts.POSITION_FRONTPAGE, 0);
}
} else if (requestCode == SETTINGS_REQUEST && resultCode == RESULT_OK) {
if (data.getBooleanExtra(Consts.EXTRA_SHOW_NSFW_IMAGES_CHANGED, false)) {
mShowNsfwImages = SharedPreferencesHelper.getShowNsfwImages(this);
// If we're removing NSFW images we can modify the adapter in place, otherwise we
// need to refresh
if (mShowNsfwImages) {
// onNavigationItemSelected(getSupportActionBar().getSelectedNavigationIndex(), 0);
} else {
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(Consts.BROADCAST_REMOVE_NSFW_IMAGES));
}
}
}
}
/**
* Return the position of the subreddit in the navigation spinner, or -1 if the subreddit is not
* found.
*
* @param subredditName
* Name of the subreddit to find
* @return The position of the subreddit in the spinner, or -1 if the subreddit is not found
*/
public int getSubredditPosition(String subredditName) {
// for (int i = 0; i < mSpinnerAdapter.getCount(); i++) {
// String curReddit = (String) mSpinnerAdapter.getItem(i);
// if (curReddit.equalsIgnoreCase(subredditName)) {
// return i;
// }
// }
return -1;
}
public void selectSubredditInNavigation(String subredditName) {
int position = getSubredditPosition(subredditName);
if (position == -1) {
if (BuildConfig.DEBUG) {
throw new ArrayIndexOutOfBoundsException("Subreddit \"" + subredditName + "\" does not exist in the navigation!");
} else {
Log.e(TAG, "Subreddit \"" + subredditName + "\" does not exist in the navigation!");
}
} else {
getSupportActionBar().setSelectedNavigationItem(position);
}
}
public boolean subredditExistsInNavigation(String subredditName) {
return getSubredditPosition(subredditName) >= 0;
}
private void showProgressDialog(String title, String message) {
mProgressDialog = ProgressDialog.show(ImageGridActivity.this, title, message, true, false);
}
private void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
@Override
public void onFinishLoginDialog(String username, String password) {
mUsername = username;
showProgressDialog(getString(R.string.log_on), getString(R.string.logging_on));
RedditService.login(this, username, password);
}
@Override
public void onFinishLogoutDialog() {
int rowsDeleted = getContentResolver().delete(RedditContract.Login.CONTENT_URI, null, null);
Log.i(TAG, "rows deleted = " + rowsDeleted);
invalidateOptionsMenu();
// TODO: Reset subreddit list to default subreddits
// getSupportActionBar().setListNavigationCallbacks(getListNavigationSpinner(), this);
// onNavigationItemSelected(getSupportActionBar().getSelectedNavigationIndex(), 0);
}
@Override
public Age getAge() {
return mAge;
}
@Override
public Category getCategory() {
return mCategory;
}
@Override
public String getSubreddit() {
- return mSelectedSubreddit;
+ if (mSelectedSubreddit == null)
+ return null;
+
+ return mSelectedSubreddit.equals("Frontpage") ? RedditUrl.REDDIT_FRONTPAGE : mSelectedSubreddit;
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle paramBundle) {
Log.i(TAG, "onCreateLoader");
switch (id) {
case Consts.LOADER_LOGIN:
return new CursorLoader(this, RedditContract.Login.CONTENT_URI, null, null, null, RedditContract.Login.DEFAULT_SORT);
case Consts.LOADER_SUBREDDITS:
String selection = null;
String[] selectionArgs = null;
if (paramBundle != null && paramBundle.containsKey(Consts.EXTRA_QUERY)) {
String query = paramBundle.getString(Consts.EXTRA_QUERY);
if (Strings.notEmpty(query)) {
selection = RedditContract.SubredditColumns.DISPLAY_NAME + " LIKE ?";
selectionArgs = new String[] {"%" + query + "%"};
}
}
return new CursorLoader(this, RedditContract.Subreddits.CONTENT_URI, RedditContract.Subreddits.SUBREDDITS_PROJECTION, selection, selectionArgs, RedditContract.Subreddits.DEFAULT_SORT);
}
return null;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
switch (loader.getId()) {
case Consts.LOADER_LOGIN:
if (cursor != null) {
Log.i(TAG, "onLoadFinished LOADER_LOGIN, " + cursor.getCount() + " rows");
if (cursor.moveToFirst()) {
mUsername = cursor.getString(cursor.getColumnIndex(RedditContract.Login.USERNAME));
String cookie = cursor.getString(cursor.getColumnIndex(RedditContract.Login.COOKIE));
String modhash = cursor.getString(cursor.getColumnIndex(RedditContract.Login.MODHASH));
Log.i(TAG, "Username = " + mUsername);
Log.i(TAG, "Cookie = " + cookie);
Log.i(TAG, "Modhash = " + modhash);
LoginData data = new LoginData(mUsername, modhash, cookie);
RedditLoginInformation.setLoginData(data);
hideProgressDialog();
invalidateOptionsMenu();
SetDefaultSubredditsTask defaultSubredditsTask = new SetDefaultSubredditsTask();
defaultSubredditsTask.execute();
}
}
break;
case Consts.LOADER_SUBREDDITS:
if (cursor != null) {
Log.i(TAG, "onLoadFinished LOADER_SUBREDDITS, " + cursor.getCount() + " rows");
if (cursor.moveToFirst()) {
mSubredditAdapter.swapCursor(cursor);
hideProgressDialog();
invalidateOptionsMenu();
}
}
break;
}
}
@Override
public void onLoaderReset(Loader<Cursor> paramLoader) {
if (mSubredditAdapter != null)
mSubredditAdapter.swapCursor(null);
}
class SetDefaultSubredditsTask extends SafeAsyncTask<Void> {
boolean forceDefaults = false;
public SetDefaultSubredditsTask(){}
public SetDefaultSubredditsTask(boolean forceDefaults) {
this.forceDefaults = forceDefaults;
}
@Override
public Void call() throws Exception {
// If the user is logged in, we just want to update to what they have set.
if (RedditLoginInformation.isLoggedIn()) {
RedditService.getMySubreddits(ImageGridActivity.this);
} else {
RedditDatabase mDatabaseHelper = new RedditDatabase(ImageGridActivity.this);
SQLiteDatabase mDatabase = mDatabaseHelper.getWritableDatabase();
// Using a separate variable here since I want to consolidate operations and not overwrite the control variable possibly causing more problems.
boolean terminateSubreddits = forceDefaults;
// If we aren't terminating them by default, check to see if they have none. If so we want to set it to the defaults.
if (!terminateSubreddits) {
// See how many Subreddits are in the database. Only needed if not forcing defaults.
long numSubreddits = DatabaseUtils.queryNumEntries(mDatabase, RedditDatabase.Tables.SUBREDDITS);
Ln.d("Number of Subreddits is: %d", numSubreddits);
mDatabase.close();
// Set the indicator to cause the subreddits to be overwritten if we have no records.
if (numSubreddits == 0) {
terminateSubreddits = true;
}
}
// If we either don't have any subreddits or we want to force them to defaults.
if (terminateSubreddits) {
SubredditUtils.setDefaultSubreddits(ImageGridActivity.this);
}
}
return null;
}
}
@Override
public int getFirstVisiblePosition() {
return mFirstVisiblePos;
}
@Override
public void setFirstVisiblePosition(int firstVisiblePosition) {
mFirstVisiblePos = firstVisiblePosition;
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/atlas-web/src/test/java/uk/ac/ebi/gxa/properties/ResourceFileStorageTest.java b/atlas-web/src/test/java/uk/ac/ebi/gxa/properties/ResourceFileStorageTest.java
index 37af483f2..41af1a509 100644
--- a/atlas-web/src/test/java/uk/ac/ebi/gxa/properties/ResourceFileStorageTest.java
+++ b/atlas-web/src/test/java/uk/ac/ebi/gxa/properties/ResourceFileStorageTest.java
@@ -1,80 +1,80 @@
/*
* Copyright 2008-2010 Microarray Informatics Team, EMBL-European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* For further details of the Gene Expression Atlas project, including source code,
* downloads and documentation, please see:
*
* http://gxa.github.com/gxa
*/
package uk.ac.ebi.gxa.properties;
import static junit.framework.Assert.*;
import org.junit.Before;
import org.junit.Test;
import java.util.Collection;
import java.util.Arrays;
/**
* @author pashky
*/
public class ResourceFileStorageTest {
ResourceFileStorage storage;
@Before
public void setup() {
storage = new ResourceFileStorage();
storage.setResourcePath("atlas.properties");
}
@Test
public void test_getProperty() {
- assertEquals("time,individual,age,ALL", storage.getProperty("atlas.facet.ignore.efs"));
+ assertEquals("time,individual,age,ALL", storage.getProperty("atlas.ignore.efs.facet"));
}
@Test
public void test_setProperty() {
// new property
storage.setProperty("dummy", "hoppa");
assertEquals("hoppa", storage.getProperty("dummy"));
// existing property
- storage.setProperty("atlas.facet.ignore.efs", "bugoga");
- assertEquals("bugoga", storage.getProperty("atlas.facet.ignore.efs"));
+ storage.setProperty("atlas.ignore.efs.facet", "bugoga");
+ assertEquals("bugoga", storage.getProperty("atlas.ignore.efs.facet"));
}
@Test
public void test_isWritePersistent() {
assertFalse(storage.isWritePersistent());
}
@Test
public void test_reload() {
storage.setProperty("dummy", "hoppa");
storage.reload();
assertNull(storage.getProperty("dummy"));
}
@Test
public void test_getAvailablePropertyNames() {
Collection<String> propnames = storage.getAvailablePropertyNames();
assertNotNull(propnames);
assertFalse(propnames.isEmpty());
assertTrue(propnames.containsAll(Arrays.asList("atlas.feedback.from.address,atlas.drilldowns.mingenes,atlas.dump.geneidentifiers.filename,atlas.gene.autocomplete.ids.limit,atlas.gene.drilldowns,atlas.query.pagesize,atlas.gene.autocomplete.names.limit,atlas.dump.geneidentifiers,atlas.query.expsPerGene,atlas.gene.list.cache.autogenerate,atlas.feedback.subject,atlas.data.release,atlas.gene.autocomplete.names,atlas.gene.autocomplete.ids,atlas.feedback.smtp.host,atlas.gene.autocomplete.descs,atlas.query.listsize,atlas.feedback.to.address,atlas.dump.ebeye.filename".split(","))));
}
}
| false | false | null | null |
diff --git a/src/com/activeandroid/ModelInfo.java b/src/com/activeandroid/ModelInfo.java
index 3fda0f2..aa6b15e 100644
--- a/src/com/activeandroid/ModelInfo.java
+++ b/src/com/activeandroid/ModelInfo.java
@@ -1,94 +1,94 @@
package com.activeandroid;
import java.io.IOException;
-import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import com.activeandroid.serializer.TypeSerializer;
import com.activeandroid.util.Log;
import com.activeandroid.util.ReflectionUtils;
import dalvik.system.DexFile;
class ModelInfo {
//////////////////////////////////////////////////////////////////////////////////////
// PRIVATE METHODS
//////////////////////////////////////////////////////////////////////////////////////
private Map<Class<? extends Model>, TableInfo> mTableInfos = new HashMap<Class<? extends Model>, TableInfo>();
private Map<Class<?>, TypeSerializer> mTypeSerializers = new HashMap<Class<?>, TypeSerializer>();
//////////////////////////////////////////////////////////////////////////////////////
// CONSTRUCTORS
//////////////////////////////////////////////////////////////////////////////////////
@SuppressWarnings("unchecked")
public ModelInfo(Context context) {
try {
final String path = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0).sourceDir;
final DexFile dexfile = new DexFile(path);
final Enumeration<String> entries = dexfile.entries();
while (entries.hasMoreElements()) {
final String name = entries.nextElement();
- if (name.contains("com.activeandroid")) {
+ if (!name.contains("com.activeandroid.serializer") && name.contains("com.activeandroid")) {
continue;
}
try {
Class<?> discoveredClass = Class.forName(name, false, context.getClass().getClassLoader());
if (ReflectionUtils.isModel(discoveredClass)) {
Class<? extends Model> modelClass = (Class<? extends Model>) discoveredClass;
mTableInfos.put(modelClass, new TableInfo(modelClass));
}
else if (ReflectionUtils.isTypeSerializer(discoveredClass)) {
TypeSerializer typeSerializer = (TypeSerializer) discoveredClass.newInstance();
mTypeSerializers.put(typeSerializer.getClass(), typeSerializer);
}
}
catch (ClassNotFoundException e) {
Log.e("Couldn't create class.", e.getMessage());
}
catch (InstantiationException e) {
Log.e("Couldn't instantiate TypeSerializer.", e.getMessage());
}
catch (IllegalAccessException e) {
Log.e("IllegalAccessException: ", e.getMessage());
}
}
}
catch (IOException e) {
Log.e("Couln't open source path.", e.getMessage());
}
catch (NameNotFoundException e) {
Log.e("Couldn't find ApplicationInfo for package name.", e.getMessage());
}
}
//////////////////////////////////////////////////////////////////////////////////////
// PUBLIC METHODS
//////////////////////////////////////////////////////////////////////////////////////
public List<TableInfo> getTableInfos() {
- return new ArrayList<TableInfo>(mTableInfos.values());
+ return (List<TableInfo>) mTableInfos.values();
}
public TableInfo getTableInfo(Class<? extends Model> type) {
return mTableInfos.get(type);
}
+ @SuppressWarnings("unchecked")
public List<Class<? extends Model>> getModelClasses() {
- return new ArrayList<Class<? extends Model>>(mTableInfos.keySet());
+ return (List<Class<? extends Model>>) mTableInfos.keySet();
}
- public TypeSerializer getParser(Class<?> type) {
+ public TypeSerializer getTypeSerializer(Class<?> type) {
return mTypeSerializers.get(type);
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/info/bytecraft/commands/WhoCommand.java b/src/info/bytecraft/commands/WhoCommand.java
index 4737fdd..c9076db 100644
--- a/src/info/bytecraft/commands/WhoCommand.java
+++ b/src/info/bytecraft/commands/WhoCommand.java
@@ -1,119 +1,122 @@
package info.bytecraft.commands;
import static org.bukkit.ChatColor.*;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import info.bytecraft.Bytecraft;
import info.bytecraft.api.BytecraftPlayer;
+import info.bytecraft.api.Rank;
import info.bytecraft.api.BytecraftPlayer.Flag;
public class WhoCommand extends AbstractCommand
{
public WhoCommand(Bytecraft instance)
{
super(instance, "who");
}
public boolean handlePlayer(BytecraftPlayer player, String[] args)
{
if (args.length == 0) {
StringBuilder sb = new StringBuilder();
String delim = "";
int playerCounter = 0;
for (BytecraftPlayer other : plugin.getOnlinePlayers()) {
if (other.hasFlag(Flag.INVISIBLE)) {
- continue;
+ if(player.getRank() != Rank.ELDER && player.getRank() != Rank.PRINCESS){
+ continue;
+ }
}
sb.append(delim);
sb.append(other.getDisplayName());
delim = ChatColor.WHITE + ", ";
playerCounter++;
}
player.sendMessage(GRAY + "************" + DARK_PURPLE
+ "Player List" + GRAY + "************");
player.sendMessage(sb.toString().trim());
player.sendMessage(GRAY + "************" + GOLD + playerCounter
+ " player(s) online" + GRAY + "*****");
}
else if (args.length == 1) {
if (!player.isAdmin())
return true;
List<BytecraftPlayer> cantidates = plugin.matchPlayer(args[0]);
if (cantidates.size() != 1) {
return true;
}
BytecraftPlayer target = cantidates.get(0);
whoOther(player.getDelegate(), target);
}
return true;
}
public boolean handleOther(Server server, String[] args)
{
ConsoleCommandSender sender = server.getConsoleSender();
if (args.length == 0) {
StringBuilder sb = new StringBuilder();
String delim = "";
int playerCounter = 0;
for (BytecraftPlayer other : plugin.getOnlinePlayers()) {
sb.append(delim);
sb.append(other.getDisplayName());
delim = ChatColor.WHITE + ", ";
playerCounter++;
}
sender.sendMessage(GRAY + "************" + DARK_PURPLE
+ "Player List" + GRAY + "************");
sender.sendMessage(sb.toString().trim());
sender.sendMessage(GRAY + "************" + GOLD + playerCounter
+ " player(s) online" + GRAY + "*****");
}
else if (args.length == 1) {
List<BytecraftPlayer> cantidates = plugin.matchPlayer(args[0]);
if (cantidates.size() != 1) {
return true;
}
BytecraftPlayer target = cantidates.get(0);
whoOther(sender, target);
}
return true;
}
public void whoOther(CommandSender player, BytecraftPlayer whoPlayer)
{
int x = whoPlayer.getLocation().getBlockX();
int y = whoPlayer.getLocation().getBlockY();
int z = whoPlayer.getLocation().getBlockZ();
player.sendMessage(DARK_GRAY + "******************** " + DARK_PURPLE
+ "PLAYER INFO" + DARK_GRAY + " ********************");
player.sendMessage(GOLD + "Player: " + GRAY
+ whoPlayer.getDisplayName());
player.sendMessage(GOLD + "World: " + GRAY
+ whoPlayer.getWorld().getName());
player.sendMessage(GOLD + "Coords: " + GRAY + x + ", " + y + ", " + z);
player.sendMessage(GOLD + "Channel: " + GRAY
+ whoPlayer.getChatChannel());
player.sendMessage(GOLD + "Wallet: " + GRAY + whoPlayer.getBalance()
+ " bytes.");
player.sendMessage(GOLD + "Health: " + GRAY + whoPlayer.getHealth());
player.sendMessage(GOLD + "Country: " + GRAY + whoPlayer.getCountry());
player.sendMessage(GOLD + "City: " + GRAY + whoPlayer.getCity());
player.sendMessage(GOLD + "IP Address: " + GRAY + whoPlayer.getIp());
player.sendMessage(GOLD + "Port: " + GRAY
+ whoPlayer.getAddress().getPort());
player.sendMessage(GOLD + "Gamemode: " + GRAY
+ whoPlayer.getGameMode().toString().toLowerCase());
player.sendMessage(GOLD + "Level: " + GRAY + whoPlayer.getLevel());
player.sendMessage(DARK_GRAY
+ "******************************************************");
}
}
| false | false | null | null |
diff --git a/drools-wb-rest/src/main/java/org/kie/workbench/common/services/rest/ProjectResourceDispatcher.java b/drools-wb-rest/src/main/java/org/kie/workbench/common/services/rest/ProjectResourceDispatcher.java
index ecda0b2e5..0791f386f 100644
--- a/drools-wb-rest/src/main/java/org/kie/workbench/common/services/rest/ProjectResourceDispatcher.java
+++ b/drools-wb-rest/src/main/java/org/kie/workbench/common/services/rest/ProjectResourceDispatcher.java
@@ -1,497 +1,497 @@
package org.kie.workbench.common.services.rest;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Event;
import javax.enterprise.util.TypeLiteral;
import javax.inject.Inject;
import javax.inject.Named;
import org.drools.workbench.screens.testscenario.model.Failure;
import org.drools.workbench.screens.testscenario.model.TestResultMessage;
import org.drools.workbench.screens.testscenario.service.ScenarioTestEditorService;
import org.guvnor.common.services.project.builder.model.BuildMessage;
import org.guvnor.common.services.project.builder.model.BuildResults;
import org.guvnor.common.services.project.builder.model.DeployResult;
import org.guvnor.common.services.project.builder.service.BuildService;
import org.guvnor.common.services.project.model.GAV;
import org.guvnor.common.services.project.model.POM;
import org.guvnor.common.services.project.model.Project;
import org.guvnor.common.services.project.service.ProjectService;
import org.kie.commons.io.IOService;
import org.kie.workbench.common.services.shared.rest.BuildConfig;
import org.kie.workbench.common.services.shared.rest.JobRequest;
import org.kie.workbench.common.services.shared.rest.JobResult;
import org.kie.workbench.common.services.shared.rest.Repository;
import org.uberfire.backend.group.GroupService;
import org.uberfire.backend.group.impl.GroupImpl;
import org.uberfire.backend.repositories.RepositoryService;
import org.uberfire.backend.repositories.impl.git.GitRepository;
import org.uberfire.backend.server.util.Paths;
import org.uberfire.backend.vfs.Path;
@ApplicationScoped
public class ProjectResourceDispatcher {
@Inject
RepositoryService repositoryService;
@Inject
protected ProjectService projectService;
@Inject
private Paths paths;
@Inject
@Named("ioStrategy")
private IOService ioSystemService;
@Inject
protected BuildService buildService;
@Inject
GroupService groupService;
@Inject
private Event<JobResult> jobResultEvent;
@Inject
protected ScenarioTestEditorService scenarioTestEditorService;
public void createOrCloneRepository( String jobId,
Repository repository ) {
System.out.println( "-----ProjectResourceDispatcher:createOrCloneRepository--- , repository name:" + repository.getName() );
JobResult result = new JobResult();
result.setJodId( jobId );
if ( repository.getRequestType() == null || "".equals( repository.getRequestType() )
|| !( "new".equals( repository.getRequestType() ) || ( "clone".equals( repository.getRequestType() ) ) ) ) {
result.setStatus( JobRequest.Status.BAD_REQUEST );
result.setResult( "Repository request type can only be new or clone." );
jobResultEvent.fire( result );
return;
}
final String scheme = "git";
if ( "new".equals( repository.getRequestType() ) ) {
if ( repository.getName() == null || "".equals( repository.getName() ) ) {
result.setStatus( JobRequest.Status.BAD_REQUEST );
result.setResult( "Repository name must be provided" );
jobResultEvent.fire( result );
return;
}
// username and password are optional
final Map<String, Object> env = new HashMap<String, Object>( 3 );
if ( repository.getUserName() != null && !"".equals( repository.getUserName() ) ) {
env.put( "username", repository.getUserName() );
}
if ( repository.getPassword() != null && !"".equals( repository.getPassword() ) ) {
env.put( "crypt:password", repository.getPassword() );
}
env.put( "init", true );
org.uberfire.backend.repositories.Repository newlyCreatedRepo = repositoryService.createRepository( scheme, repository.getName(), env );
if ( newlyCreatedRepo != null ) {
result.setStatus( JobRequest.Status.SUCCESS );
result.setResult( "Alias: " + newlyCreatedRepo.getAlias() + ", Scheme: " + newlyCreatedRepo.getScheme() + ", Uri: " + newlyCreatedRepo.getUri() );
} else {
result.setStatus( JobRequest.Status.FAIL );
}
} else if ( "clone".equals( repository.getRequestType() ) ) {
if ( repository.getName() == null || "".equals( repository.getName() ) || repository.getGitURL() == null
|| "".equals( repository.getGitURL() ) ) {
result.setStatus( JobRequest.Status.BAD_REQUEST );
result.setResult( "Repository name and GitURL must be provided" );
}
// username and password are optional
final Map<String, Object> env = new HashMap<String, Object>( 3 );
if ( repository.getUserName() != null && !"".equals( repository.getUserName() ) ) {
env.put( "username", repository.getUserName() );
}
if ( repository.getPassword() != null && !"".equals( repository.getPassword() ) ) {
env.put( "crypt:password", repository.getPassword() );
}
env.put( "origin", repository.getGitURL() );
org.uberfire.backend.repositories.Repository newlyCreatedRepo = repositoryService.createRepository( scheme, repository.getName(), env );
if ( newlyCreatedRepo != null ) {
result.setStatus( JobRequest.Status.SUCCESS );
result.setResult( "Alias: " + newlyCreatedRepo.getAlias() + ", Scheme: " + newlyCreatedRepo.getScheme() + ", Uri: " + newlyCreatedRepo.getUri() );
} else {
result.setStatus( JobRequest.Status.FAIL );
}
}
jobResultEvent.fire( result );
}
public void removeRepository( String jobId,
String repositoryName ) {
System.out.println( "-----removeRepository--- , repository name:" + repositoryName );
JobResult result = new JobResult();
result.setJodId( jobId );
if ( repositoryName == null || "".equals( repositoryName ) ) {
result.setStatus( JobRequest.Status.BAD_REQUEST );
result.setResult( "Repository name must be provided" );
}
repositoryService.removeRepository( repositoryName );
result.setStatus( JobRequest.Status.SUCCESS );
jobResultEvent.fire( result );
}
public void createProject( String jobId,
String repositoryName,
String projectName ) {
System.out.println( "-----ProjectResourceDispatcher:createProject--- , repositoryName:" + repositoryName + ", project name:" + projectName );
JobResult result = new JobResult();
result.setJodId( jobId );
org.kie.commons.java.nio.file.Path repositoryPath = getRepositoryRootPath( repositoryName );
if ( repositoryPath == null ) {
result.setStatus( JobRequest.Status.RESOURCE_NOT_EXIST );
result.setResult( "Repository [" + repositoryName + "] does not exist" );
jobResultEvent.fire( result );
return;
} else {
POM pom = new POM();
pom.getGav().setArtifactId( projectName );
pom.getGav().setGroupId( projectName );
pom.getGav().setVersion( "1.0" );
-
+
try {
Project project = projectService.newProject( makeRepository( paths.convert( repositoryPath,
false ) ),
projectName,
pom,
"/" );
} catch ( org.kie.commons.java.nio.file.FileAlreadyExistsException e ) {
result.setStatus( JobRequest.Status.DUPLICATE_RESOURCE );
result.setResult( "Project [" + projectName + "] already exists" );
jobResultEvent.fire( result );
return;
}
//TODO: handle errors, exceptions.
result.setStatus( JobRequest.Status.SUCCESS );
jobResultEvent.fire( result );
}
}
private org.uberfire.backend.repositories.Repository makeRepository( final Path repositoryRoot ) {
return new GitRepository() {
@Override
public Path getRoot() {
return repositoryRoot;
}
};
}
public void compileProject( String jobId,
String repositoryName,
String projectName,
BuildConfig mavenConfig ) {
System.out.println( "-----ProjectResourceDispatcher:compileProject--- , repositoryName:" + repositoryName + ", project name:" + projectName );
JobResult result = new JobResult();
result.setJodId( jobId );
org.kie.commons.java.nio.file.Path repositoryPath = getRepositoryRootPath( repositoryName );
if ( repositoryPath == null ) {
result.setStatus( JobRequest.Status.RESOURCE_NOT_EXIST );
result.setResult( "Repository [" + repositoryName + "] does not exist" );
jobResultEvent.fire( result );
} else {
Project project = projectService.resolveProject( paths.convert( repositoryPath.resolve( projectName ), false ) );
if ( project == null ) {
result.setStatus( JobRequest.Status.RESOURCE_NOT_EXIST );
result.setResult( "Project [" + projectName + "] does not exist" );
jobResultEvent.fire( result );
return;
}
BuildResults buildResults = buildService.build( project );
result.setDetailedResult( buildResultsToDetailedStringMessages( buildResults.getMessages() ) );
result.setStatus( buildResults.getMessages().isEmpty() ? JobRequest.Status.SUCCESS : JobRequest.Status.FAIL );
jobResultEvent.fire( result );
}
}
private List<String> buildResultsToDetailedStringMessages( List<BuildMessage> messages ) {
List<String> result = new ArrayList<String>();
for ( BuildMessage message : messages ) {
String detailedStringMessage = "level:" + message.getLevel() +
", path:" + message.getPath() +
", text:" + message.getText();
result.add( detailedStringMessage );
}
return result;
}
public void installProject( String jobId,
String repositoryName,
String projectName,
BuildConfig mavenConfig ) {
System.out.println( "-----ProjectResourceDispatcher:installProject--- , repositoryName:" + repositoryName + ", project name:" + projectName );
JobResult result = new JobResult();
result.setJodId( jobId );
org.kie.commons.java.nio.file.Path repositoryPath = getRepositoryRootPath( repositoryName );
if ( repositoryPath == null ) {
result.setStatus( JobRequest.Status.RESOURCE_NOT_EXIST );
result.setResult( "Repository [" + repositoryName + "] does not exist" );
jobResultEvent.fire( result );
return;
} else {
Project project = projectService.resolveProject( paths.convert( repositoryPath.resolve( projectName ), false ) );
if ( project == null ) {
result.setStatus( JobRequest.Status.RESOURCE_NOT_EXIST );
result.setResult( "Project [" + projectName + "] does not exist" );
jobResultEvent.fire( result );
return;
}
DeployResult buildResults = buildService.buildAndDeploy( project );
result.setDetailedResult( buildResults == null ? null : deployResultToDetailedStringMessages( buildResults ) );
result.setStatus( buildResults.getMessages().isEmpty() ? JobRequest.Status.SUCCESS : JobRequest.Status.FAIL );
jobResultEvent.fire( result );
}
}
private List<String> deployResultToDetailedStringMessages( DeployResult deployResult ) {
GAV gav = deployResult.getGAV();
List<String> result = buildResultsToDetailedStringMessages( deployResult.getMessages() );
String detailedStringMessage = "artifactID:" + gav.getArtifactId() +
", groupId:" + gav.getGroupId() +
", version:" + gav.getVersion();
result.add( detailedStringMessage );
return result;
}
public void testProject( String jobId,
String repositoryName,
String projectName,
BuildConfig config ) {
System.out.println( "-----ProjectResourceDispatcher:testProject--- , repositoryName:" + repositoryName + ", project name:" + projectName );
final JobResult result = new JobResult();
result.setJodId( jobId );
org.kie.commons.java.nio.file.Path repositoryPath = getRepositoryRootPath( repositoryName );
if ( repositoryPath == null ) {
result.setStatus( JobRequest.Status.RESOURCE_NOT_EXIST );
result.setResult( "Repository [" + repositoryName + "] does not exist" );
jobResultEvent.fire( result );
return;
} else {
Project project = projectService.resolveProject( paths.convert( repositoryPath.resolve( projectName ), false ) );
if ( project == null ) {
result.setStatus( JobRequest.Status.RESOURCE_NOT_EXIST );
result.setResult( "Project [" + projectName + "] does not exist" );
jobResultEvent.fire( result );
return;
}
//TODO: Get session from BuildConfig or create a default session for testing if no session is provided.
scenarioTestEditorService.runAllScenarios( project.getPomXMLPath(), new Event<TestResultMessage>() {
@Override
public void fire( TestResultMessage event ) {
result.setDetailedResult( testResultMessageToDetailedStringMessages( event ) );
result.setStatus( event.wasSuccessful() ? JobRequest.Status.SUCCESS : JobRequest.Status.FAIL );
jobResultEvent.fire( result );
}
//@Override
public Event<TestResultMessage> select( Annotation... qualifiers ) {
// TODO Auto-generated method stub
return null;
}
//@Override
public <U extends TestResultMessage> Event<U> select(
Class<U> subtype,
Annotation... qualifiers ) {
// TODO Auto-generated method stub
return null;
}
//@Override
public <U extends TestResultMessage> Event<U> select(
TypeLiteral<U> subtype,
Annotation... qualifiers ) {
// TODO Auto-generated method stub
return null;
}
} );
}
}
private List<String> testResultMessageToDetailedStringMessages( TestResultMessage message ) {
List<String> result = new ArrayList<String>();
result.add( "wasSuccessuful: " + message.wasSuccessful() );
result.add( "RunCoun: " + message.getRunCount() );
result.add( "FailureCount: " + message.getFailureCount() );
for ( Failure failure : message.getFailures() ) {
result.add( "Failure: " + failure.getMessage() );
}
return result;
}
public void deployProject( String jobId,
String repositoryName,
String projectName,
BuildConfig config ) {
System.out.println( "-----ProjectResourceDispatcher:deployProject--- , repositoryName:" + repositoryName + ", project name:" + projectName );
JobResult result = new JobResult();
result.setJodId( jobId );
org.kie.commons.java.nio.file.Path repositoryPath = getRepositoryRootPath( repositoryName );
if ( repositoryPath == null ) {
result.setStatus( JobRequest.Status.RESOURCE_NOT_EXIST );
result.setResult( "Repository [" + repositoryName + "] does not exist" );
jobResultEvent.fire( result );
return;
} else {
Project project = projectService.resolveProject( paths.convert( repositoryPath.resolve( projectName ), false ) );
if ( project == null ) {
result.setStatus( JobRequest.Status.RESOURCE_NOT_EXIST );
result.setResult( "Project [" + projectName + "] does not exist" );
jobResultEvent.fire( result );
return;
}
DeployResult buildResults = buildService.buildAndDeploy( project );
result.setDetailedResult( buildResults == null ? null : deployResultToDetailedStringMessages( buildResults ) );
result.setStatus( buildResults.getMessages().isEmpty() ? JobRequest.Status.SUCCESS : JobRequest.Status.FAIL );
jobResultEvent.fire( result );
}
}
public void createGroup( String jobId,
String groupName,
String groupOwer,
List<String> repositoryNameList ) {
System.out.println( "-----ProjectResourceDispatcher:createGroup--- , Group name:" + groupName + ", Group owner:" + groupOwer );
JobResult result = new JobResult();
result.setJodId( jobId );
if ( groupName == null || groupOwer == null ) {
result.setStatus( JobRequest.Status.BAD_REQUEST );
result.setResult( "Group name and owner must be provided" );
jobResultEvent.fire( result );
return;
}
org.uberfire.backend.group.Group group = null;
List<org.uberfire.backend.repositories.Repository> repositories = new ArrayList<org.uberfire.backend.repositories.Repository>();
if ( repositoryNameList != null && repositoryNameList.size() > 0 ) {
for ( String repoName : repositoryNameList ) {
GitRepository repo = new GitRepository( repoName );
repositories.add( repo );
}
group = groupService.createGroup( groupName, groupOwer, repositories );
} else {
group = groupService.createGroup( groupName, groupOwer );
}
if ( group != null ) {
result.setResult( "Group " + group.getName() + " is created successfully." );
result.setStatus( JobRequest.Status.SUCCESS );
} else {
result.setStatus( JobRequest.Status.FAIL );
}
jobResultEvent.fire( result );
}
public void addRepositoryToGroup( String jobId,
String groupName,
String repositoryName ) {
System.out.println( "-----ProjectResourceDispatcher:addRepositoryToGroup--- , Group name:" + groupName + ", repository name:" + repositoryName );
JobResult result = new JobResult();
result.setJodId( jobId );
if ( groupName == null || repositoryName == null ) {
result.setStatus( JobRequest.Status.BAD_REQUEST );
result.setResult( "Group name and repository name must be provided" );
jobResultEvent.fire( result );
return;
}
GroupImpl group = new GroupImpl( groupName, null );
GitRepository repo = new GitRepository( repositoryName );
try {
groupService.addRepository( group, repo );
} catch ( IllegalArgumentException e ) {
result.setStatus( JobRequest.Status.BAD_REQUEST );
result.setResult( "Group " + group.getName() + " not found" );
jobResultEvent.fire( result );
return;
}
result.setStatus( JobRequest.Status.SUCCESS );
jobResultEvent.fire( result );
}
public void removeRepositoryFromGroup( String jobId,
String groupName,
String repositoryName ) {
System.out.println( "-----ProjectResourceDispatcher:removeRepositoryFromGroup--- , Group name:" + groupName + ", repository name:" + repositoryName );
JobResult result = new JobResult();
result.setJodId( jobId );
if ( groupName == null || repositoryName == null ) {
result.setStatus( JobRequest.Status.BAD_REQUEST );
result.setResult( "Group name and repository name must be provided" );
jobResultEvent.fire( result );
return;
}
GroupImpl group = new GroupImpl( groupName, null );
GitRepository repo = new GitRepository( repositoryName );
try {
groupService.addRepository( group, repo );
} catch ( IllegalArgumentException e ) {
result.setStatus( JobRequest.Status.BAD_REQUEST );
result.setResult( "Group " + group.getName() + " not found" );
jobResultEvent.fire( result );
return;
}
result.setStatus( JobRequest.Status.SUCCESS );
jobResultEvent.fire( result );
}
public org.kie.commons.java.nio.file.Path getRepositoryRootPath( String repositoryName ) {
org.uberfire.backend.repositories.Repository repo = repositoryService.getRepository( repositoryName );
if ( repo == null ) {
return null;
}
return paths.convert( repo.getRoot() );
}
}
| true | false | null | null |
diff --git a/Mediasystem/src/main/java/hs/mediasystem/framework/MediaItem.java b/Mediasystem/src/main/java/hs/mediasystem/framework/MediaItem.java
index b33f5325..bee49996 100644
--- a/Mediasystem/src/main/java/hs/mediasystem/framework/MediaItem.java
+++ b/Mediasystem/src/main/java/hs/mediasystem/framework/MediaItem.java
@@ -1,48 +1,49 @@
package hs.mediasystem.framework;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
+import javafx.beans.property.SimpleStringProperty;
+import javafx.beans.property.StringProperty;
public class MediaItem {
public final ObjectProperty<MediaData> mediaData = new SimpleObjectProperty<>();
-
- private final String uri;
+ public final StringProperty uri = new SimpleStringProperty();
public MediaItem(String uri) {
assert uri != null;
- this.uri = uri;
+ this.uri.set(uri);
}
public String getUri() {
- return uri;
+ return uri.get();
}
public void reloadMetaData() {
// getEnrichCache().reload(cacheKey); TODO Fix option to reload metadata
}
@Override
public int hashCode() {
return uri.hashCode();
}
@Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(obj == null || getClass() != obj.getClass()) {
return false;
}
MediaItem other = (MediaItem)obj;
return uri.equals(other.uri);
}
@Override
public String toString() {
return "MediaItem[uri='" + uri +"']";
}
}
diff --git a/Mediasystem/src/main/java/hs/mediasystem/framework/SettingUpdater.java b/Mediasystem/src/main/java/hs/mediasystem/framework/SettingUpdater.java
index d640b13c..26342ced 100644
--- a/Mediasystem/src/main/java/hs/mediasystem/framework/SettingUpdater.java
+++ b/Mediasystem/src/main/java/hs/mediasystem/framework/SettingUpdater.java
@@ -1,44 +1,44 @@
package hs.mediasystem.framework;
import hs.mediasystem.dao.Setting.PersistLevel;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.util.StringConverter;
public class SettingUpdater<T> implements ChangeListener<T> {
private final SettingsStore settingsStore;
private final StringConverter<T> converter;
private StringProperty valueProperty;
public SettingUpdater(SettingsStore settingsStore, StringConverter<T> converter) {
this.settingsStore = settingsStore;
this.converter = converter;
}
public T getStoredValue() {
return valueProperty == null ? null : converter.fromString(valueProperty.get());
}
public T getStoredValue(T defaultValue) {
T storedValue = getStoredValue();
return storedValue == null ? defaultValue : storedValue;
}
public void clearBackingSetting() {
valueProperty = null;
}
public void setBackingSetting(String system, PersistLevel level, String key) {
valueProperty = settingsStore.getValueProperty(system, level, key);
}
@Override
public void changed(ObservableValue<? extends T> observable, T oldValue, T newValue) {
- if(valueProperty != null) {
+ if(valueProperty != null && newValue != null) { // TODO allow nulls?
valueProperty.set(converter.toString(newValue));
}
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/DesktopExport/src/org/gephi/desktop/io/export/api/GraphFileExporterUI.java b/DesktopExport/src/org/gephi/desktop/io/export/api/GraphFileExporterUI.java
index c45c68510..a8d30e6bc 100644
--- a/DesktopExport/src/org/gephi/desktop/io/export/api/GraphFileExporterUI.java
+++ b/DesktopExport/src/org/gephi/desktop/io/export/api/GraphFileExporterUI.java
@@ -1,254 +1,254 @@
/*
Copyright 2008 WebAtlas
Authors : Mathieu Bastian, Mathieu Jacomy, Julian Bilcke
Website : http://www.gephi.org
This file is part of Gephi.
Gephi is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Gephi is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Gephi. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gephi.desktop.io.export.api;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.gephi.desktop.io.export.GraphFileExporterUIPanel;
import org.gephi.desktop.io.export.spi.ExporterClassUI;
import org.gephi.desktop.io.export.spi.ExporterClassUI;
import org.gephi.io.exporter.api.ExportController;
import org.gephi.io.exporter.api.FileType;
import org.gephi.io.exporter.spi.ExporterUI;
import org.gephi.io.exporter.spi.FileExporter;
import org.gephi.io.exporter.spi.GraphFileExporter;
import org.gephi.ui.utils.DialogFileFilter;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;
import org.openide.util.NbPreferences;
import org.openide.util.lookup.ServiceProvider;
/**
*
* @author Mathieu Bastian
*/
@ServiceProvider(service = ExporterClassUI.class)
public final class GraphFileExporterUI implements ExporterClassUI {
private GraphFileExporter selectedExporter;
private File selectedFile;
private boolean visibleOnlyGraph = false;
public String getName() {
return NbBundle.getMessage(GraphFileExporterUI.class, "GraphFileExporterUI_title");
}
public boolean isEnable() {
return true;
}
public void action() {
final String LAST_PATH = "GraphFileExporterUI_Last_Path";
final String LAST_PATH_DEFAULT = "GraphFileExporterUI_Last_Path_Default";
final ExportController exportController = Lookup.getDefault().lookup(ExportController.class);
if (exportController == null) {
return;
}
//Get last directory
String lastPathDefault = NbPreferences.forModule(GraphFileExporterUI.class).get(LAST_PATH_DEFAULT, null);
String lastPath = NbPreferences.forModule(GraphFileExporterUI.class).get(LAST_PATH, lastPathDefault);
//Options panel
FlowLayout layout = new FlowLayout(FlowLayout.RIGHT);
JPanel optionsPanel = new JPanel(layout);
final JButton optionsButton = new JButton(NbBundle.getMessage(GraphFileExporterUI.class, "GraphFileExporterUI_optionsButton_name"));
optionsPanel.add(optionsButton);
optionsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ExporterUI exporterUI = exportController.getUI(selectedExporter);
if (exporterUI != null) {
JPanel panel = exporterUI.getPanel();
exporterUI.setup(selectedExporter);
DialogDescriptor dd = new DialogDescriptor(panel, NbBundle.getMessage(GraphFileExporterUI.class, "GraphFileExporterUI_optionsDialog_title", selectedExporter.getName()));
Object result = DialogDisplayer.getDefault().notify(dd);
exporterUI.unsetup(result == NotifyDescriptor.OK_OPTION);
}
}
});
//Graph Settings Panel
final JPanel southPanel = new JPanel(new BorderLayout());
southPanel.add(optionsPanel, BorderLayout.NORTH);
GraphFileExporterUIPanel graphSettings = new GraphFileExporterUIPanel();
graphSettings.setVisibleOnlyGraph(visibleOnlyGraph);
southPanel.add(graphSettings, BorderLayout.CENTER);
//Optionable file chooser
final JFileChooser chooser = new JFileChooser(lastPath) {
@Override
protected JDialog createDialog(Component parent) throws HeadlessException {
JDialog dialog = super.createDialog(parent);
Component c = dialog.getContentPane().getComponent(0);
if (c != null && c instanceof JComponent) {
Insets insets = ((JComponent) c).getInsets();
southPanel.setBorder(BorderFactory.createEmptyBorder(insets.top, insets.left, insets.bottom, insets.right));
}
dialog.getContentPane().add(southPanel, BorderLayout.SOUTH);
return dialog;
}
@Override
public void approveSelection() {
if (canExport(this)) {
super.approveSelection();
}
}
};
chooser.setDialogTitle(NbBundle.getMessage(GraphFileExporterUI.class, "GraphFileExporterUI_filechooser_title"));
chooser.addPropertyChangeListener(JFileChooser.FILE_FILTER_CHANGED_PROPERTY, new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
DialogFileFilter fileFilter = (DialogFileFilter) evt.getNewValue();
//Options panel enabling
selectedExporter = getExporter(fileFilter);
if (selectedExporter != null && exportController.hasUI(selectedExporter)) {
optionsButton.setEnabled(true);
} else {
optionsButton.setEnabled(false);
}
//Selected file extension change
- if (selectedFile != null) {
+ if (selectedFile != null && fileFilter != null) {
String filePath = selectedFile.getAbsolutePath();
filePath = filePath.substring(0, filePath.lastIndexOf("."));
filePath = filePath.concat(fileFilter.getExtensions().get(0));
selectedFile = new File(filePath);
chooser.setSelectedFile(selectedFile);
}
}
});
chooser.addPropertyChangeListener(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY, new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() != null) {
selectedFile = (File) evt.getNewValue();
}
}
});
//File filters
DialogFileFilter defaultFilter = null;
for (FileExporter graphFileExporter : exportController.getGraphFileExporters()) {
for (FileType fileType : graphFileExporter.getFileTypes()) {
DialogFileFilter dialogFileFilter = new DialogFileFilter(fileType.getName());
dialogFileFilter.addExtensions(fileType.getExtensions());
- if(defaultFilter==null) {
+ if (defaultFilter == null) {
defaultFilter = dialogFileFilter;
}
chooser.addChoosableFileFilter(dialogFileFilter);
}
}
chooser.setAcceptAllFileFilterUsed(false);
chooser.setFileFilter(defaultFilter);
selectedFile = new File(chooser.getCurrentDirectory(), "Untilted" + defaultFilter.getExtensions().get(0));
chooser.setSelectedFile(selectedFile);
//Show
int returnFile = chooser.showSaveDialog(null);
if (returnFile == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
file = FileUtil.normalizeFile(file);
FileObject fileObject = FileUtil.toFileObject(file);
//Save last path
NbPreferences.forModule(GraphFileExporterUI.class).put(LAST_PATH, file.getAbsolutePath());
//Save variable
visibleOnlyGraph = graphSettings.isVisibleOnlyGraph();
//Do
exportController.doExport(selectedExporter, fileObject, visibleOnlyGraph);
}
}
private boolean canExport(JFileChooser chooser) {
File file = chooser.getSelectedFile();
String defaultExtention = selectedExporter.getFileTypes()[0].getExtension();
try {
if (!file.getPath().endsWith(defaultExtention)) {
file = new File(file.getPath() + defaultExtention);
selectedFile = file;
chooser.setSelectedFile(file);
}
if (!file.exists()) {
if (!file.createNewFile()) {
String failMsg = NbBundle.getMessage(GraphFileExporterUI.class, "GraphFileExporterUI_SaveFailed", new Object[]{file.getPath()});
JOptionPane.showMessageDialog(null, failMsg);
return false;
}
} else {
String overwriteMsg = NbBundle.getMessage(GraphFileExporterUI.class, "GraphFileExporterUI_overwriteDialog_message", new Object[]{file.getPath()});
if (JOptionPane.showConfirmDialog(null, overwriteMsg, NbBundle.getMessage(GraphFileExporterUI.class, "GraphFileExporterUI_overwriteDialog_title"), JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) {
return false;
}
}
} catch (IOException ex) {
NotifyDescriptor.Message msg = new NotifyDescriptor.Message(ex.getMessage(), NotifyDescriptor.WARNING_MESSAGE);
DialogDisplayer.getDefault().notifyLater(msg);
return false;
}
return true;
}
private GraphFileExporter getExporter(DialogFileFilter fileFilter) {
final ExportController exportController = Lookup.getDefault().lookup(ExportController.class);
//Find fileFilter
for (GraphFileExporter graphFileExporter : exportController.getGraphFileExporters()) {
for (FileType fileType : graphFileExporter.getFileTypes()) {
DialogFileFilter tempFilter = new DialogFileFilter(fileType.getName());
tempFilter.addExtensions(fileType.getExtensions());
if (tempFilter.equals(fileFilter)) {
return graphFileExporter;
}
}
}
return null;
}
}
diff --git a/DesktopExport/src/org/gephi/desktop/io/export/api/VectorialFileExporterUI.java b/DesktopExport/src/org/gephi/desktop/io/export/api/VectorialFileExporterUI.java
index ed37f48c6..493697b8f 100644
--- a/DesktopExport/src/org/gephi/desktop/io/export/api/VectorialFileExporterUI.java
+++ b/DesktopExport/src/org/gephi/desktop/io/export/api/VectorialFileExporterUI.java
@@ -1,244 +1,244 @@
/*
Copyright 2008 WebAtlas
Authors : Mathieu Bastian, Mathieu Jacomy, Julian Bilcke
Website : http://www.gephi.org
This file is part of Gephi.
Gephi is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Gephi is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Gephi. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gephi.desktop.io.export.api;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.gephi.desktop.io.export.spi.ExporterClassUI;
import org.gephi.io.exporter.api.ExportController;
import org.gephi.io.exporter.api.FileType;
import org.gephi.io.exporter.spi.ExporterUI;
import org.gephi.io.exporter.spi.FileExporter;
import org.gephi.io.exporter.spi.VectorialFileExporter;
import org.gephi.ui.utils.DialogFileFilter;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;
import org.openide.util.NbPreferences;
import org.openide.util.lookup.ServiceProvider;
/**
*
* @author Mathieu Bastian
*/
@ServiceProvider(service = ExporterClassUI.class)
public final class VectorialFileExporterUI implements ExporterClassUI {
private VectorialFileExporter selectedExporter;
private File selectedFile;
public String getName() {
return NbBundle.getMessage(VectorialFileExporterUI.class, "VectorialFileExporterUI_title");
}
public boolean isEnable() {
return !Lookup.getDefault().lookupAll(VectorialFileExporter.class).isEmpty();
}
public void action() {
final String LAST_PATH = "VectorialFileExporterUI_Last_Path";
final String LAST_PATH_DEFAULT = "VectorialFileExporterUI_Last_Path_Default";
final ExportController exportController = Lookup.getDefault().lookup(ExportController.class);
if (exportController == null) {
return;
}
//Get last directory
String lastPathDefault = NbPreferences.forModule(VectorialFileExporterUI.class).get(LAST_PATH_DEFAULT, null);
String lastPath = NbPreferences.forModule(VectorialFileExporterUI.class).get(LAST_PATH, lastPathDefault);
//Options panel
FlowLayout layout = new FlowLayout(FlowLayout.RIGHT);
JPanel optionsPanel = new JPanel(layout);
final JButton optionsButton = new JButton(NbBundle.getMessage(VectorialFileExporterUI.class, "VectorialFileExporterUI_optionsButton_name"));
optionsPanel.add(optionsButton);
optionsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ExporterUI exporterUI = exportController.getUI(selectedExporter);
if (exporterUI != null) {
JPanel panel = exporterUI.getPanel();
exporterUI.setup(selectedExporter);
DialogDescriptor dd = new DialogDescriptor(panel, NbBundle.getMessage(VectorialFileExporterUI.class, "VectorialFileExporterUI_optionsDialog_title", selectedExporter.getName()));
Object result = DialogDisplayer.getDefault().notify(dd);
exporterUI.unsetup(result == NotifyDescriptor.OK_OPTION);
}
}
});
//Graph Settings Panel
final JPanel southPanel = new JPanel(new BorderLayout());
southPanel.add(optionsPanel, BorderLayout.NORTH);
//Optionable file chooser
final JFileChooser chooser = new JFileChooser(lastPath) {
@Override
protected JDialog createDialog(Component parent) throws HeadlessException {
JDialog dialog = super.createDialog(parent);
Component c = dialog.getContentPane().getComponent(0);
if (c != null && c instanceof JComponent) {
Insets insets = ((JComponent) c).getInsets();
southPanel.setBorder(BorderFactory.createEmptyBorder(insets.top, insets.left, insets.bottom, insets.right));
}
dialog.getContentPane().add(southPanel, BorderLayout.SOUTH);
return dialog;
}
@Override
public void approveSelection() {
if (canExport(this)) {
super.approveSelection();
}
}
};
chooser.setDialogTitle(NbBundle.getMessage(VectorialFileExporterUI.class, "VectorialFileExporterUI_filechooser_title"));
chooser.addPropertyChangeListener(JFileChooser.FILE_FILTER_CHANGED_PROPERTY, new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
DialogFileFilter fileFilter = (DialogFileFilter) evt.getNewValue();
//Options panel enabling
selectedExporter = getExporter(fileFilter);
if (selectedExporter != null && exportController.hasUI(selectedExporter)) {
optionsButton.setEnabled(true);
} else {
optionsButton.setEnabled(false);
}
//Selected file extension change
- if (selectedFile != null) {
+ if (selectedFile != null && fileFilter != null) {
String filePath = selectedFile.getAbsolutePath();
filePath = filePath.substring(0, filePath.lastIndexOf("."));
filePath = filePath.concat(fileFilter.getExtensions().get(0));
selectedFile = new File(filePath);
chooser.setSelectedFile(selectedFile);
}
}
});
chooser.addPropertyChangeListener(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY, new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() != null) {
selectedFile = (File) evt.getNewValue();
}
}
});
//File filters
DialogFileFilter defaultFilter = null;
for (FileExporter vectorialFileExporter : exportController.getVectorialFileExporters()) {
for (FileType fileType : vectorialFileExporter.getFileTypes()) {
DialogFileFilter dialogFileFilter = new DialogFileFilter(fileType.getName());
dialogFileFilter.addExtensions(fileType.getExtensions());
if (defaultFilter == null) {
defaultFilter = dialogFileFilter;
}
chooser.addChoosableFileFilter(dialogFileFilter);
}
}
chooser.setAcceptAllFileFilterUsed(false);
chooser.setFileFilter(defaultFilter);
selectedFile = new File(chooser.getCurrentDirectory(), "Untilted" + defaultFilter.getExtensions().get(0));
chooser.setSelectedFile(selectedFile);
//Show
int returnFile = chooser.showSaveDialog(null);
if (returnFile == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
file = FileUtil.normalizeFile(file);
FileObject fileObject = FileUtil.toFileObject(file);
//Save last path
NbPreferences.forModule(VectorialFileExporterUI.class).put(LAST_PATH, file.getAbsolutePath());
//Do
exportController.doExport(selectedExporter, fileObject);
}
}
private boolean canExport(JFileChooser chooser) {
File file = chooser.getSelectedFile();
String defaultExtention = selectedExporter.getFileTypes()[0].getExtension();
try {
if (!file.getPath().endsWith(defaultExtention)) {
file = new File(file.getPath() + defaultExtention);
chooser.setSelectedFile(file);
}
if (!file.exists()) {
if (!file.createNewFile()) {
String failMsg = NbBundle.getMessage(VectorialFileExporterUI.class, "VectorialFileExporterUI_SaveFailed", new Object[]{file.getPath()});
JOptionPane.showMessageDialog(null, failMsg);
return false;
}
} else {
String overwriteMsg = NbBundle.getMessage(VectorialFileExporterUI.class, "VectorialFileExporterUI_overwriteDialog_message", new Object[]{file.getPath()});
if (JOptionPane.showConfirmDialog(null, overwriteMsg, NbBundle.getMessage(VectorialFileExporterUI.class, "VectorialFileExporterUI_overwriteDialog_title"), JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) {
return false;
}
}
} catch (IOException ex) {
NotifyDescriptor.Message msg = new NotifyDescriptor.Message(ex.getMessage(), NotifyDescriptor.WARNING_MESSAGE);
DialogDisplayer.getDefault().notifyLater(msg);
return false;
}
return true;
}
private VectorialFileExporter getExporter(DialogFileFilter fileFilter) {
final ExportController exportController = Lookup.getDefault().lookup(ExportController.class);
//Find fileFilter
for (VectorialFileExporter vectorialFileExporter : exportController.getVectorialFileExporters()) {
for (FileType fileType : vectorialFileExporter.getFileTypes()) {
DialogFileFilter tempFilter = new DialogFileFilter(fileType.getName());
tempFilter.addExtensions(fileType.getExtensions());
if (tempFilter.equals(fileFilter)) {
return vectorialFileExporter;
}
}
}
return null;
}
}
| false | false | null | null |
diff --git a/fest-swing/src/test/java/org/fest/swing/fixture/FEST303_JFileChooserNotFoundOnMacOS_Test.java b/fest-swing/src/test/java/org/fest/swing/fixture/FEST303_JFileChooserNotFoundOnMacOS_Test.java
index ee3696a2..3ab5942f 100644
--- a/fest-swing/src/test/java/org/fest/swing/fixture/FEST303_JFileChooserNotFoundOnMacOS_Test.java
+++ b/fest-swing/src/test/java/org/fest/swing/fixture/FEST303_JFileChooserNotFoundOnMacOS_Test.java
@@ -1,80 +1,80 @@
/*
* Created on Mar 11, 2010
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
* Copyright @2010 the original author or authors.
*/
package org.fest.swing.fixture;
+import static org.fest.swing.edt.GuiActionRunner.execute;
import static org.fest.swing.timing.Timeout.timeout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import org.fest.swing.annotation.RunsInCurrentThread;
import org.fest.swing.annotation.RunsInEDT;
-import org.fest.swing.edt.GuiActionRunner;
import org.fest.swing.edt.GuiQuery;
import org.fest.swing.test.core.RobotBasedTestCase;
import org.fest.swing.test.swing.TestWindow;
import org.junit.Test;
/**
* Test case for bug <a href="http://jira.codehaus.org/browse/FEST-303" target="_blank">FEST-303</a>.
*
* @author Alex Ruiz
*/
public class FEST303_JFileChooserNotFoundOnMacOS_Test extends RobotBasedTestCase {
private FrameFixture frame;
@Override protected void onSetUp() {
frame = new FrameFixture(robot, MyWindow.createNew());
frame.show();
}
@Test
public void should_find_JFileChooser() {
frame.button().click();
frame.fileChooser(timeout(5000));
}
private static class MyWindow extends TestWindow {
private static final long serialVersionUID = 1L;
final JButton button = new JButton("Click me");
final JFileChooser chooser = new JFileChooser();
@RunsInEDT
static MyWindow createNew() {
- return GuiActionRunner.execute(new GuiQuery<MyWindow>() {
+ return execute(new GuiQuery<MyWindow>() {
protected MyWindow executeInEDT() {
return new MyWindow();
}
});
}
@RunsInCurrentThread
private MyWindow() {
super(FEST303_JFileChooserNotFoundOnMacOS_Test.class);
add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
chooser.showOpenDialog(MyWindow.this);
}
});
}
}
}
| false | false | null | null |
diff --git a/plugins/appfuse-maven-plugin/src/main/java/org/appfuse/tool/RenamePackages.java b/plugins/appfuse-maven-plugin/src/main/java/org/appfuse/tool/RenamePackages.java
index 5a25e7d1..df484681 100644
--- a/plugins/appfuse-maven-plugin/src/main/java/org/appfuse/tool/RenamePackages.java
+++ b/plugins/appfuse-maven-plugin/src/main/java/org/appfuse/tool/RenamePackages.java
@@ -1,1258 +1,1253 @@
package org.appfuse.tool;
+import org.apache.commons.io.FileUtils;
+import org.apache.maven.plugin.logging.Log;
+import org.apache.maven.plugin.logging.SystemStreamLog;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.types.FileSet;
-import org.apache.maven.plugin.logging.SystemStreamLog;
-import org.apache.maven.plugin.logging.Log;
-import java.io.BufferedOutputStream;
-import java.io.BufferedReader;
-import java.io.DataOutputStream;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.FileReader;
-import java.io.IOException;
+import java.io.*;
import java.util.Iterator;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This class is almost a complete copy of replacepackages
* by Ben Gill. These utility methods can be used in the
* plugin to change package names of appfuse source
* contributions. Liberties have been taken to make this
* open source code just work here. Some methods were removed
* and logging now uses SystemStreamLog from Apache (Maven)
*
* @author <a href="mailto:[email protected]">David L. Whitehurst</a>
*/
public class RenamePackages {
static final boolean SAVE_FILE = true;
static final boolean DONT_SAVE_FILE = false;
boolean debug = false;
private String baseDir = "src"; // root
private String workBaseDir = "null"; // actually called null
private String existingPkgName = "org.appfuse"; // AppFuse
private String newPkgName;
private String existingPkgPath;
private String newPkgPath;
protected transient final Log log = new SystemStreamLog();
StringBuffer logOutput = new StringBuffer();
String[] invalidFileTypes = new String[] { "class", "jar", "jpg", "gif", "png", "ico" };
private Vector filesets = new Vector();
/**
* Constructor
*/
public RenamePackages(String newPackage) {
this.newPkgName = newPackage;
}
/**
* simple method to add filesets
* @param fileset
*/
public void addFileset(FileSet fileset) {
filesets.add(fileset);
}
/**
* Override the default set of invalid file types that will be moved to the
* new package structure.
*
* The invalidFileTypes must be a comma
* separated list of file extensions
* for example "class,jar,exe"
*
* @param invalidFileTypes
*/
public void setInvalidFileTypes(String invalidFileTypes)
{
this.invalidFileTypes = invalidFileTypes.split(",");
if (debug) {
log.debug("default invalidFileTypes overriden with [" + invalidFileTypes
+ "]");
}
}
/**
* Set the base directory. The base directory will be where the Task starts
* to recursively look for files with the given package name in it. This
* method will be called by ANT when it invokes the Task.
*
* @param baseDir
*/
public void setBaseDir(String baseDir)
{
if (!new File(baseDir.trim()).exists())
{
throw new ExceptionInInitializerError("Base dir [" + baseDir.trim()
+ "] does not exist");
}
this.baseDir = correctFileSeparators(baseDir.trim());
if (this.baseDir != null)
{
if (this.baseDir.endsWith(File.separator)) {
this.workBaseDir = this.baseDir.substring(0, this.baseDir
.length())
+ ".work";
} else
{
this.workBaseDir = this.baseDir + ".work";
}
if (debug) {
log.debug("Set workBaseDir to [" + this.workBaseDir + "]");
}
}
}
/**
* Validates the packagename
*
* @param packageName
* @throws ExceptionInInitializerError
* if the package name is invalid
*/
private void validatePackageName(String packageName)
throws ExceptionInInitializerError
{
if (packageName.indexOf("/") != -1)
{
throw new ExceptionInInitializerError("packageName [" + packageName
+ "] is invalid because it contains slashes");
}
if (packageName.indexOf("\\") != -1)
{
throw new ExceptionInInitializerError("packageName [" + packageName
+ "] is invalid because it contains slashes");
}
}
/**
* Strips out start and end dots
*
* @param packageName
* @return package name without starting and ending dots
*/
private String stripUnwantedDots(String packageName)
{
while (packageName.endsWith("."))
{
packageName = packageName.substring(0, packageName.length() - 1);
}
while (packageName.startsWith("."))
{
packageName = packageName.substring(1);
}
if (debug) {
log.debug("returning stripped package name of [" + packageName + "]");
}
return packageName;
}
/**
* Set the existing package name. This will become the string that the Task
* looks to replace in the files look for files with the given package name
* in it. This method will be called by ANT when it invokes the Task.
*
* @param existingPkgName
*/
public void setExistingPkgName(String existingPkgName) throws Exception
{
log.info("existingPkgName came in as [" + existingPkgName + "]");
this.existingPkgName = stripUnwantedDots(existingPkgName.trim());
validatePackageName(this.existingPkgName);
if (this.existingPkgName.length() == 0)
{
throw new Exception("Unsupported operation - cannot "
+ " repackage from empty package name as would "
+ " not know which imports to expand out");
}
}
/**
* Set the new package name. This will become the package name and replace
* the existing package name in the source files. This method will be called
* by ANT when it invokes the Task.
*
* @param newPkgName
* @throws Exception
*/
public void setNewPkgName(String newPkgName) throws Exception
{
log.info("newPkgName came in as [" + newPkgName + "]");
this.newPkgName = stripUnwantedDots(newPkgName.trim());
validatePackageName(this.newPkgName);
if (this.newPkgName.length() == 0)
{
throw new Exception("Unimplemented operation");
}
}
/**
* Set the package paths. Replace the . delimiter with the relevant file
* separator based on the o/s we are running on.
*/
private void setPackagePaths()
{
this.existingPkgPath = getPackagePath(existingPkgName);
this.newPkgPath = getPackagePath(newPkgName);
if (debug) {
log.debug("Set existing package path as [" + existingPkgPath + "]");
log.debug("Set new package path as [" + newPkgPath + "]");
}
}
/**
* Set the new package name. This will become the package name and replace
* the existing package name in the source files. This method will be called
* by ANT when it invokes the Task.
*
* @param pkgName
* @return path of the pkg name
*/
private String getPackagePath(String pkgName)
{
String[] pkgNames = pkgName.split("\\.");
String aPath = "";
for (int i = 0; i < pkgNames.length; i++)
{
if (aPath.length() != 0)
{
aPath += File.separator;
}
aPath += pkgNames[i];
}
return aPath;
}
/**
* Creates a new directory, if it does not exist already
*
* @param directoryName
*/
private void createDirectory(String directoryName)
{
File dir = new File(directoryName);
if (!dir.exists())
{
if (dir.mkdirs())
{
String message = "Created directory [" + directoryName + "]";
if (debug) {
log.debug(message);
}
}
else
{
log.error("Failed to create directory [" + directoryName + "]");
}
}
}
/*
* This method gets called recursively (mainly by itself) and walks through
* the directory structure looking for files with existingPkgPath in their
* fully qualified (absolute) names.
*
* If a file is found, then it is parsed for the existingPkgName and any
* instance of this string will be replaced by the newPkgName. The file is
* then saved back out in its new package directory.
*
* @param inDirName the directory to search
*/
private void repackage(String inDirName, String inWorkDirName)
throws IOException {
if (debug) {
log.debug("Inside repackage inDirName is [" + inDirName + "]");
log.debug("Inside repackage inWorkDirName is [" + inWorkDirName + "]");
}
String[] files = new File(inDirName).list();
if (files == null)
{
return;
}
if (debug) {
log.debug("There are [" + files.length + "] files in dir [" + inDirName
+ "]");
}
for (int i = 0; i < files.length; i++)
{
if (debug) {
log.debug("file is [" + files[i] + "]");
}
String fileName = inDirName + File.separator + files[i];
File aFile = new File(fileName);
if (files[i].equals("CVS"))
{
if (debug) {
log.debug("ignoring CVS dir");
}
}
else if (aFile.isDirectory())
{
if (debug) {
log.debug("Got a dir [" + fileName + "]");
}
String newDirName = inDirName + File.separator + files[i];
String newWorkDirName = inWorkDirName + File.separator
+ files[i];
if (isOldPackageDir(fileName))
{
String newPath = convertOldPackageDirName(fileName);
if (debug) {
log.debug("found old package dir [" + fileName + "] "
+ "newPath is [" + newPath.toString() + "]");
}
createDirectory(newPath.toString());
}
if (debug) {
log.debug("Recursing with [" + newDirName + "]");
}
repackage(newDirName, newWorkDirName);
}
else
{
// Normal file
if (debug) {
log.debug("Processing file [" + fileName + "] existingPkgPath is ["
+ existingPkgPath + "]");
}
// Should we process this file at all or leave it?
int existingPathIndexPos = fileName.indexOf(existingPkgPath);
if (existingPathIndexPos != -1)
{
// Normal file in old package structure
if (debug) {
log.debug("found file with existing package name ["
+ fileName + "]");
}
String newPath = convertOldPackageDirName(fileName
.substring(0, fileName.lastIndexOf(File.separator)));
String newFileName = newPath
+ fileName.substring(fileName
.lastIndexOf(File.separator));
if (debug) {
log.debug("creating directory [" + newPath + "]");
}
createDirectory(newPath);
if (isValidFileType(fileName))
{
String output = changePackageNamesInFile(fileName,
RenamePackages.DONT_SAVE_FILE);
if (debug) {
log.debug("Saving file [" + fileName
+ "] to new package directory ["
+ newFileName + "]");
}
toFile(newFileName, output);
}
else
{
if (debug) {
log.debug("Renaming file non valid file type ["
+ fileName + "]");
}
if (!aFile.renameTo(new File(newFileName)))
{
log.error("Failed to rename file [" + fileName + "] to ["
+ newFileName + "]");
}
}
}
else
{
// Normal file - not in old package structure
// Stip off existing baseDir
String newFileName = this.workBaseDir
+ fileName.substring(this.baseDir.length());
String newPath = newFileName.substring(0, newFileName
.lastIndexOf(File.separator));
if (debug) {
log.debug("Creating dir [" + newPath + "]");
}
createDirectory(newPath);
if (aFile.renameTo(new File(newFileName)))
{
if (debug) {
log.debug("Saved file [" + newFileName
+ "] to new directory structure");
}
} else
{
log.error("Failed to rename file [" + fileName + "] to ["
+ newFileName + "] to new directory structure");
}
}
}
}
}
/*
* This method gets called recursively (mainly by itself) and walks through
* the directory structure looking for ANY valid files with existingPkgPath.
*
* If a file is found, then it is parsed then it is output for the caller to
* check.
*
* @param inDirName the directory to search
*/
private void checkSummary(String inDirName)
throws IOException
{
if (debug) {
log.debug("Inside checkSummary inDirName is [" + inDirName + "]");
}
String[] files = new File(inDirName).list();
if (files == null)
{
return;
}
if (debug) {
log.debug("There are [" + files.length + "] files in dir [" + inDirName + "]");
}
for (String file : files) {
if (debug) {
log.debug("file is [" + file + "]");
}
String fileName = inDirName + File.separator + file;
File aFile = new File(fileName);
if (aFile.isDirectory()) {
if (debug) {
log.debug("Got a dir [" + fileName + "]");
}
String newDirName = inDirName + File.separator + file;
if (debug) {
log.debug("Recursing with [" + newDirName + "]");
}
checkSummary(newDirName);
} else {
// Normal file
if (debug) {
log.debug("Checking file [" + fileName + "] existingPkgPath is ["
+ existingPkgPath + "]");
}
if (isValidFileType(fileName)) {
if (hasFileOldPathOrPkg(fileName)) {
if (debug) {
log.debug("File [" + fileName + "] still has old pkg [" + existingPkgPath + "]");
}
}
}
}
}
}
private boolean matches(String patternStr, String fileContents) {
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(fileContents);
return matcher.matches();
}
private boolean hasFileOldPathOrPkg(String fileName) {
try {
String fileContents = fromFile(fileName);
String patternStr = escape(existingPkgPath);
if (matches(patternStr, fileContents)) {
return true;
}
patternStr = getUnixPath(existingPkgPath);
patternStr = escape(patternStr);
if (matches(patternStr, fileContents)) {
return true;
}
patternStr = getWindowsPath(existingPkgPath);
patternStr = escape(patternStr);
return matches(patternStr, fileContents);
} catch (IOException e) {
log.error("Error loading fileContents in hasFileOldPathOrPkg [" + e.getMessage() + "]");
return false;
}
}
private String convertOldPackageDirName(String dirName)
{
// Need to create new package directory
int startExistingPathIndexPos = dirName.indexOf(existingPkgPath);
int endExistingPathIndexPos = startExistingPathIndexPos
+ existingPkgPath.length();
StringBuffer newPath = new StringBuffer();
newPath.append(this.workBaseDir);
// Get the front bit
if (debug) {
log.debug("startExistingPathIndexPos is [" + startExistingPathIndexPos + "]");
log.debug("about to do substring on [" + dirName + "] positions ["
+ this.baseDir.length() + "] and [" + startExistingPathIndexPos
+ "]");
}
String firstPartFileName = dirName.substring(this.baseDir.length(),
startExistingPathIndexPos);
if (debug) {
log.debug("firstPartFileName is [" + firstPartFileName + "]");
}
newPath.append(firstPartFileName);
newPath.append(newPkgPath);
String lastPartFileName = dirName.substring(endExistingPathIndexPos);
if (debug) {
log.debug("appending lastPartFileName [" + lastPartFileName + "]");
}
newPath.append(lastPartFileName);
return newPath.toString();
}
private boolean isOldPackageDir(String dirName)
{
if (debug) {
log.debug("inside isOldPackageDir with [" + dirName + "]");
}
// Should we process this file at all or leave it?
int existingPathIndexPos = dirName.indexOf(existingPkgPath);
if (existingPathIndexPos != -1)
{
if (debug) {
log.debug("found dir with existing package name [" + dirName + "]");
}
return true;
}
if (debug) {
log.debug("dir [" + dirName + "] is not old package dir");
}
return false;
}
/*
* This method reads a file and returns a string suitable for some regex
* operation
*
* @param fileName the file name to open and read @return the file contents
*/
public String fromFile(String fileName) throws IOException
{
- BufferedReader in = new BufferedReader(new FileReader(fileName));
+ /*BufferedReader in = new BufferedReader(new FileReader(fileName));
StringBuffer fileContents = new StringBuffer();
String str;
while ((str = in.readLine()) != null)
{
fileContents.append(str);
fileContents.append("\n");
}
in.close();
- return fileContents.toString();
+ return fileContents.toString();*/
+ return FileUtils.readFileToString(new File(fileName), "UTF-8");
}
/*
* This method saves a file to disk
*
* @param fileName the name of the file @param contents the files contents
* @throws IOException if there is an error writing the file
*/
public void toFile(String fileName, String contents) throws IOException
{
if (debug) {
log.debug("Saving file to fileName [" + fileName + "]");
}
- BufferedOutputStream bout = new BufferedOutputStream(
+ FileUtils.writeStringToFile(new File(fileName), contents, "UTF-8");
+ /*BufferedOutputStream bout = new BufferedOutputStream(
new DataOutputStream(new FileOutputStream(fileName)));
bout.write(contents.getBytes());
bout.flush();
- bout.close();
+ bout.close();*/
}
/**
* Checks to see if the file is a valid type
*
* @return true if the file is a valid type, else false
*/
private boolean isValidFileType(String fileName)
{
for (int i = 0; i < invalidFileTypes.length; i++)
{
if (fileName.endsWith(invalidFileTypes[i]))
{
if (debug) {
log.debug("File [" + fileName
+ "] will just be moved as it is not a valid type");
}
return false;
}
}
return true;
}
/**
* Escapes the search token so it is fit for a regex replacement
*
* @return true if the file is a valid type, else false
*/
private String escape(String str)
{
String newStr = "";
char[] strArr = str.toCharArray();
for (int i = 0; i < strArr.length; i++)
{
if (strArr[i] == '.')
{
newStr += "\\";
}
if (strArr[i] == '\\')
{
newStr += "\\";
}
newStr += strArr[i];
}
if (debug) {
log.debug("escaped str is [" + newStr + "]");
}
return newStr;
}
/**
* This method changes the name of any strings in the file and saves the
* file back to disk
*
* With paths, there may be both \ path delimiters or / so we need to run
* the regex twice to ensure we have replaced both types
*
* @return the contents of the file after the package names have been
* changed
*/
private String changePackagePaths(String fileContents)
{
String output = changeWindowsPaths(fileContents);
output = changeUnixPaths(output);
return output;
}
/**
* This method changes the name of any strings in the file and saves the
* file back to disk
*
* With paths, there may be both \ path delimiters or / so we need to run
* the regex twice to ensure we have replaced both types
*
* @return the contents of the file after the package names have been
* changed
*/
private String changeUnixPaths(String fileContents)
{
if (debug) {
log.debug("inside changeUnixPaths");
}
String patternStr;
if (newPkgPath.length() == 0)
{
patternStr = getUnixPath(existingPkgPath) + "/";
}
else
{
if (debug) {
log.debug("before calling getUnixPath existingPkgPath is ["
+ existingPkgPath + "]");
}
patternStr = getUnixPath(existingPkgPath);
}
if (debug) {
log.debug("patternStr before escaping is [" + patternStr + "]");
}
patternStr = escape(patternStr);
if (debug) {
log.debug("after escaping the search/match string is [" + patternStr
+ "]");
log.debug("newPkgPath is [" + newPkgPath + "] about to escape it");
}
String replacementStr = escape(getUnixPath(newPkgPath));
if (debug) {
log.debug("replacementStr after escaping is [" + replacementStr + "]");
}
return performReplacement(fileContents, patternStr, replacementStr);
}
/**
* This method replaces any UNIX style path separators for Windows style
* separators
*
* @return the path
*/
private String getWindowsPath(String path)
{
String newStr = "";
char[] strArr = path.toCharArray();
for (int i = 0; i < strArr.length; i++)
{
if (strArr[i] == '/')
{
newStr += "\\";
} else
{
newStr += strArr[i];
}
}
if (debug) {
log.debug("escaped str is [" + newStr + "]");
}
return newStr;
}
/**
* This method replaces any Windows style path separators for UNIX style
* separators
*
* @return the path
*/
private String getUnixPath(String path)
{
if (debug) {
log.debug("inside getUnixPath with path [" + path + "]");
}
String newStr = "";
char[] strArr = path.toCharArray();
for (int i = 0; i < strArr.length; i++)
{
if (strArr[i] == '\\')
{
newStr += "/";
} else
{
newStr += strArr[i];
}
}
if (debug) {
log.debug("escaped str is [" + newStr + "]");
}
return newStr;
}
/**
* This method changes the name of any strings in the file and saves the
* file back to disk
*
* With paths, there may be both \ path delimiters or / so we need to run
* the regex twice to ensure we have replaced both types
*
* @return the contents of the file after the package names have been
* changed
*/
private String changeWindowsPaths(String fileContents)
{
if (debug) {
log.debug("inside changeWindowsPaths");
}
String patternStr;
if (newPkgPath.length() == 0)
{
patternStr = getWindowsPath(existingPkgPath) + "\\";
}
else
{
if (debug) {
log.debug("existingPkgPath is currently [" + existingPkgPath
+ "] before calling getWindowsPath");
}
patternStr = getWindowsPath(existingPkgPath);
}
if (debug) {
log.debug("patternStr is [" + patternStr
+ "] after calling getWindowsPath");
}
patternStr = escape(patternStr);
if (debug) {
log.debug("After escaping the pattern/search str it is [" + patternStr
+ "]");
log.debug("Before escaping and calling getWindowsPath the newPkgPath it is ["
+ newPkgPath + "]");
}
String replacementStr = escape(getWindowsPath(newPkgPath));
if (debug) {
log.debug("After escaping it, it is now [" + replacementStr + "]");
}
return performReplacement(fileContents, patternStr, replacementStr);
}
/**
* This method changes the name of any strings in the file and saves the
* file back to disk
*
* With paths, there may be both \ path delimiters or / so we need to run
* the regex twice to ensure we have replaced both types
*
* @return the contents of the file after the package names have been
* changed
*/
private String performReplacement(String fileContents, String patternStr,
String replacementStr)
{
if (debug) {
log.debug("replacing [" + patternStr + "] with [" + replacementStr + "]");
}
// Compile regular expression
Pattern pattern = Pattern.compile(patternStr);
// Replace all occurrences of pattern in input
Matcher matcher = pattern.matcher(fileContents);
String output = matcher.replaceAll(replacementStr);
/*
* if (debug) { debug("output is [" + output + "]"); }
*/
return output;
}
/**
* This method changes the name of any strings in the file and saves the
* file back to disk
*
* @return the contents of the file after the package names have been
* changed
*/
private String changePackageNames(String fileContents)
{
String patternStr;
if (newPkgName.length() == 0)
{
patternStr = existingPkgName + ".";
}
else
{
patternStr = existingPkgName;
}
patternStr = escape(patternStr);
String replacementStr = escape(newPkgName);
return performReplacement(fileContents, patternStr, replacementStr);
}
/**
* This method changes the name of any strings in the file and saves the
* file back to disk
*
* @return the contents of the file after the package names have been
* changed
*/
private String changePackageNamesInFile(String fileName,
boolean saveToSameFile) throws IOException
{
if (debug) {
log.debug("calling fromFile with fileName [" + fileName + "]");
}
String inputStr = fromFile(fileName);
String output = changePackageNames(inputStr);
output = changePackagePaths(output);
if (saveToSameFile)
{
if (debug)
{
log.debug("replaced package names in file and now saving it to ["
+ fileName + "]");
}
toFile(fileName, output);
}
return output;
}
/**
* This method corrects the File separators on the file name
*
* @return the correct path to the file
*/
private String correctFileSeparators(String fileName)
{
String localSeparator = File.separator;
if (localSeparator.equals("\\"))
{
return fileName.replace('/', '\\');
}
else
{
return fileName.replace('\\', '/');
}
}
/**
* This method changes the name of any strings in the file and saves the
* file back to disk, the difference is, it uses Spring Ant-style paths
* to load the files
*/
private void renameOtherFiles()
{
if (debug) {
log.debug("Inside renameOtherFiles");
}
try
{
for (Iterator itFSets = filesets.iterator(); itFSets.hasNext(); )
{
FileSet fs = (FileSet)itFSets.next();
fs.setDir(new File(workBaseDir));
if (debug) {
log.debug("got fileset fs [" + fs + "]");
}
DirectoryScanner ds = fs.getDirectoryScanner(new org.apache.tools.ant.Project());
if (debug) {
log.debug("ds baseDir is [" + ds.getBasedir().getAbsolutePath() + "]");
}
ds.scan();
String[] includedFiles = ds.getIncludedFiles();
if (debug) {
log.debug("Got includedFiles [" + includedFiles + "]");
}
if (includedFiles != null)
{
for(int i=0; i<includedFiles.length; i++) {
processOtherFile(includedFiles[i]);
}
}
else
{
if (debug) {
log.debug("Did not find any matching files for one of the filesets");
}
}
}
}
catch (Exception e)
{
log.error("Exception at end of renaming other files [" + e.getMessage()
+ "]");
}
}
/**
* This method changes paths and package names in the given file
*/
private void processOtherFile(String fileName)
{
try
{
if (debug) {
log.debug("Processing file [" + fileName + "]");
}
if (isValidFileType(fileName))
{
fileName = correctFileSeparators(fileName);
if (debug) {
log.debug("After correcting file separators fileName is ["
+ fileName + "]");
log.debug("file is valid so changing package names");
}
fileName = workBaseDir + File.separator + fileName;
changePackageNamesInFile(fileName,
RenamePackages.SAVE_FILE);
if (debug) {
log.debug("processing change package names on other file ["
+ fileName + "]");
}
}
else
{
log.error("Not processing file [" + fileName + "] as it is not a valid type");
}
}
catch (FileNotFoundException f)
{
// continue and process next
log.error("could not find resource from path ["
+ fileName
+ "]");
}
catch (IOException e)
{
log.error("IOException when renaming other files [" + e.getMessage() + "]");
}
}
/**
* This method removes directory structures
*/
public void deleteAll(String fileName)
{
File aFile = new File(fileName);
if (debug) {
log.debug("inside deleteAll with fileName [" + fileName + "]");
}
if (aFile.exists())
{
boolean isDir = aFile.isDirectory();
if (isDir)
{
String[] inFiles = aFile.list();
for (int fileNum = 0; fileNum < inFiles.length; fileNum++)
{
String subFileName = fileName + File.separator
+ inFiles[fileNum];
deleteAll(subFileName);
}
}
if (debug) {
log.debug("About to delete file inside deleteAll [" + fileName + "]");
}
if (aFile.delete())
{
if (debug) {
if (isDir)
{
log.debug("Deleted dir [" + fileName + "]");
} else
{
log.debug("Deleted file [" + fileName + "]");
}
}
}
else
{
log.error("Failed to delete file/dir [" + fileName + "]");
}
}
}
private void refactorNonPackageFiles() {
try
{
String[] extensions = {"page","application","properties","tld","xml"};
- Iterator filesInMain = org.apache.commons.io.FileUtils.iterateFiles(
- new File(this.workBaseDir), extensions, true);
+ Iterator filesInMain = FileUtils.iterateFiles(new File(this.workBaseDir), extensions, true);
while (filesInMain.hasNext()) {
File f = (File) filesInMain.next();
changePackageNamesInFile(f.getAbsolutePath(), RenamePackages.SAVE_FILE);
}
} catch (IOException ioex) {
log.error("IOException: " + ioex.getMessage());
}
}
/**
* This is the main method that gets invoked when ANT calls this task
*/
public void execute()
{
try
{
if (newPkgName == null)
{
throw new BuildException(
"The new package path needs to be set using <renamepackages "
+ "newPkgName=\"${new.pkg.name}\"");
}
if (baseDir == null)
{
throw new BuildException(
"The base directory needs to be set using <renamepackages "
+ "baseDir=\"${src.base.dir}\"/>\n");
}
if (debug) {
log.info("existingPkgName is [" + this.existingPkgName + "]");
log.info("newPkgName is [" + this.newPkgName + "]");
}
setPackagePaths();
if (debug) {
log.info("Package paths set");
}
repackage(this.baseDir, this.workBaseDir);
if (debug) {
log.info("RePackage directories");
}
renameOtherFiles();
if (debug) {
log.info("Rename other files");
}
// fix files with qualified names other than old package
refactorNonPackageFiles();
// Check the new dir structures for any files left over with the old pkg name in
checkSummary(this.workBaseDir);
if (debug) {
log.info("CheckSummary");
}
deleteAll(this.baseDir);
if (debug) {
log.info("Delete all");
}
File workBaseDir = new File(this.workBaseDir);
if (workBaseDir.renameTo(new File(this.baseDir)))
{
if (debug) {
log.info("Successfully renamed work dir back to base dir");
}
}
else
{
log.error("Error could not rename work dir");
}
}
catch (IOException ioe)
{
log.error("Caught an IO:" + ioe.getMessage());
}
catch (Exception e)
{
log.error("Uncaught exception caught [" + e.getMessage() + "]");
}
// success!
log.info("[AppFuse] Refactored all 'org.appfuse' packages and paths to '" + newPkgName + "'.");
}
}
| false | false | null | null |
diff --git a/caintegrator2-war/src/gov/nih/nci/caintegrator2/web/action/study/management/EditGenomicSourceAction.java b/caintegrator2-war/src/gov/nih/nci/caintegrator2/web/action/study/management/EditGenomicSourceAction.java
index 718ba4f63..96870aaa5 100644
--- a/caintegrator2-war/src/gov/nih/nci/caintegrator2/web/action/study/management/EditGenomicSourceAction.java
+++ b/caintegrator2-war/src/gov/nih/nci/caintegrator2/web/action/study/management/EditGenomicSourceAction.java
@@ -1,259 +1,268 @@
/**
* The software subject to this notice and license includes both human readable
* source code form and machine readable, binary, object code form. The caIntegrator2
* Software was developed in conjunction with the National Cancer Institute
* (NCI) by NCI employees, 5AM Solutions, Inc. (5AM), ScenPro, Inc. (ScenPro)
* and Science Applications International Corporation (SAIC). To the extent
* government employees are authors, any rights in such works shall be subject
* to Title 17 of the United States Code, section 105.
*
* This caIntegrator2 Software License (the License) is between NCI and You. You (or
* Your) shall mean a person or an entity, and all other entities that control,
* are controlled by, or are under common control with the entity. Control for
* purposes of this definition means (i) the direct or indirect power to cause
* the direction or management of such entity, whether by contract or otherwise,
* or (ii) ownership of fifty percent (50%) or more of the outstanding shares,
* or (iii) beneficial ownership of such entity.
*
* This License is granted provided that You agree to the conditions described
* below. NCI grants You a non-exclusive, worldwide, perpetual, fully-paid-up,
* no-charge, irrevocable, transferable and royalty-free right and license in
* its rights in the caIntegrator2 Software to (i) use, install, access, operate,
* execute, copy, modify, translate, market, publicly display, publicly perform,
* and prepare derivative works of the caIntegrator2 Software; (ii) distribute and
* have distributed to and by third parties the caIntegrator2 Software and any
* modifications and derivative works thereof; and (iii) sublicense the
* foregoing rights set out in (i) and (ii) to third parties, including the
* right to license such rights to further third parties. For sake of clarity,
* and not by way of limitation, NCI shall have no right of accounting or right
* of payment from You or Your sub-licensees for the rights granted under this
* License. This License is granted at no charge to You.
*
* Your redistributions of the source code for the Software must retain the
* above copyright notice, this list of conditions and the disclaimer and
* limitation of liability of Article 6, below. Your redistributions in object
* code form must reproduce the above copyright notice, this list of conditions
* and the disclaimer of Article 6 in the documentation and/or other materials
* provided with the distribution, if any.
*
* Your end-user documentation included with the redistribution, if any, must
* include the following acknowledgment: This product includes software
* developed by 5AM, ScenPro, SAIC and the National Cancer Institute. If You do
* not include such end-user documentation, You shall include this acknowledgment
* in the Software itself, wherever such third-party acknowledgments normally
* appear.
*
* You may not use the names "The National Cancer Institute", "NCI", "ScenPro",
* "SAIC" or "5AM" to endorse or promote products derived from this Software.
* This License does not authorize You to use any trademarks, service marks,
* trade names, logos or product names of either NCI, ScenPro, SAID or 5AM,
* except as required to comply with the terms of this License.
*
* For sake of clarity, and not by way of limitation, You may incorporate this
* Software into Your proprietary programs and into any third party proprietary
* programs. However, if You incorporate the Software into third party
* proprietary programs, You agree that You are solely responsible for obtaining
* any permission from such third parties required to incorporate the Software
* into such third party proprietary programs and for informing Your a
* sub-licensees, including without limitation Your end-users, of their
* obligation to secure any required permissions from such third parties before
* incorporating the Software into such third party proprietary software
* programs. In the event that You fail to obtain such permissions, You agree
* to indemnify NCI for any claims against NCI by such third parties, except to
* the extent prohibited by law, resulting from Your failure to obtain such
* permissions.
*
* For sake of clarity, and not by way of limitation, You may add Your own
* copyright statement to Your modifications and to the derivative works, and
* You may provide additional or different license terms and conditions in Your
* sublicenses of modifications of the Software, or any derivative works of the
* Software as a whole, provided Your use, reproduction, and distribution of the
* Work otherwise complies with the conditions stated in this License.
*
* THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES,
* (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO
* EVENT SHALL THE NATIONAL CANCER INSTITUTE, 5AM SOLUTIONS, INC., SCENPRO, INC.,
* SCIENCE APPLICATIONS INTERNATIONAL CORPORATION OR THEIR
* AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.nih.nci.caintegrator2.web.action.study.management;
import gov.nih.nci.caintegrator2.application.arraydata.ArrayDataService;
import gov.nih.nci.caintegrator2.application.arraydata.PlatformVendorEnum;
import gov.nih.nci.caintegrator2.application.study.GenomicDataSourceConfiguration;
import gov.nih.nci.caintegrator2.application.study.Status;
import gov.nih.nci.caintegrator2.domain.genomic.Platform;
import gov.nih.nci.caintegrator2.external.ConnectionException;
import gov.nih.nci.caintegrator2.external.ServerConnectionProfile;
import gov.nih.nci.caintegrator2.external.caarray.CaArrayFacade;
import gov.nih.nci.caintegrator2.external.caarray.ExperimentNotFoundException;
import gov.nih.nci.caintegrator2.web.ajax.IGenomicDataSourceAjaxUpdater;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
/**
* Action called to create or edit a <code>GenomicDataSourceConfiguration</code>.
*/
public class EditGenomicSourceAction extends AbstractGenomicSourceAction {
private static final long serialVersionUID = 1L;
private IGenomicDataSourceAjaxUpdater updater;
private ArrayDataService arrayDataService;
private CaArrayFacade caArrayFacade;
/**
* {@inheritDoc}
*/
@Override
public String execute() {
return SUCCESS;
}
/**
* Cancels the creation of a genomic source to return back to study screen.
* @return struts string.
*/
public String cancel() {
return SUCCESS;
}
/**
* Delete a genomic source file.
* @return struts string.
*/
public String delete() {
if (getGenomicSource() == null
|| !getStudyConfiguration().getGenomicDataSources().contains(getGenomicSource())) {
return SUCCESS;
}
getStudyManagementService().delete(getStudyConfiguration(), getGenomicSource());
return SUCCESS;
}
/**
* {@inheritDoc}
*/
public String save() {
if (!validateSave()) {
return INPUT;
}
getStudyConfiguration().setStatus(Status.NOT_DEPLOYED);
if (getGenomicSource().getId() == null) {
runAsynchronousGenomicDataRetrieval(getGenomicSource());
} else { // Need to create a new source, delete the old one, and load the new one
GenomicDataSourceConfiguration newGenomicSource = createNewGenomicSource();
delete();
runAsynchronousGenomicDataRetrieval(newGenomicSource);
}
return SUCCESS;
}
private GenomicDataSourceConfiguration createNewGenomicSource() {
GenomicDataSourceConfiguration configuration = new GenomicDataSourceConfiguration();
ServerConnectionProfile newProfile = configuration.getServerProfile();
ServerConnectionProfile oldProfile = getGenomicSource().getServerProfile();
newProfile.setHostname(oldProfile.getHostname());
newProfile.setPort(oldProfile.getPort());
newProfile.setUsername(oldProfile.getUsername());
newProfile.setPassword(oldProfile.getPassword());
configuration.setExperimentIdentifier(getGenomicSource().getExperimentIdentifier());
configuration.setPlatformVendor(getGenomicSource().getPlatformVendor());
configuration.setPlatformName(getGenomicSource().getPlatformName());
return configuration;
}
private void runAsynchronousGenomicDataRetrieval(GenomicDataSourceConfiguration genomicSource) {
getDisplayableWorkspace().setCurrentStudyConfiguration(getStudyConfiguration());
genomicSource.setStatus(Status.PROCESSING);
getStudyManagementService().addGenomicSourceToStudy(getStudyConfiguration(), genomicSource);
updater.runJob(genomicSource.getId());
}
private boolean validateSave() {
if (PlatformVendorEnum.AGILENT.getValue().equals(getGenomicSource().getPlatformVendor())
&& StringUtils.isEmpty(getGenomicSource().getPlatformName())) {
addFieldError("genomicSource.platformName", "Platform name is required for Agilent");
return false;
}
try {
caArrayFacade.validateGenomicSourceConnection(getGenomicSource());
} catch (ConnectionException e) {
addFieldError("genomicSource.serverProfile.hostname", "Unable to connect to server.");
return false;
} catch (ExperimentNotFoundException e) {
addFieldError("genomicSource.experimentIdentifier", "Experiment identifier not found on server.");
return false;
}
return true;
}
/**
* @return all platform names
*/
public List<String> getAgilentPlatformNames() {
List<String> platformNames = new ArrayList<String>();
platformNames.add("");
for (Platform platform : getArrayDataService().getPlatforms()) {
if (platform.getVendor().equals(PlatformVendorEnum.AGILENT)) {
platformNames.add(platform.getName());
}
}
return platformNames;
}
+
+ /**
+ * Disabled status for the platform name selection.
+ * @return whether to disable the platform names.
+ */
+ public String getPlatformNameDisable() {
+ return PlatformVendorEnum.AGILENT.getValue().equals(getGenomicSource().getPlatformVendor())
+ ? "false" : "true";
+ }
/**
* @return the arrayDataService
*/
public ArrayDataService getArrayDataService() {
return arrayDataService;
}
/**
* @param arrayDataService the arrayDataService to set
*/
public void setArrayDataService(ArrayDataService arrayDataService) {
this.arrayDataService = arrayDataService;
}
/**
* @return the updater
*/
public IGenomicDataSourceAjaxUpdater getUpdater() {
return updater;
}
/**
* @param updater the updater to set
*/
public void setUpdater(IGenomicDataSourceAjaxUpdater updater) {
this.updater = updater;
}
/**
* @return the caArrayFacade
*/
public CaArrayFacade getCaArrayFacade() {
return caArrayFacade;
}
/**
* @param caArrayFacade the caArrayFacade to set
*/
public void setCaArrayFacade(CaArrayFacade caArrayFacade) {
this.caArrayFacade = caArrayFacade;
}
}
diff --git a/caintegrator2-war/test/src/gov/nih/nci/caintegrator2/web/action/study/management/EditGenomicSourceActionTest.java b/caintegrator2-war/test/src/gov/nih/nci/caintegrator2/web/action/study/management/EditGenomicSourceActionTest.java
index b0078130a..93bf5641d 100644
--- a/caintegrator2-war/test/src/gov/nih/nci/caintegrator2/web/action/study/management/EditGenomicSourceActionTest.java
+++ b/caintegrator2-war/test/src/gov/nih/nci/caintegrator2/web/action/study/management/EditGenomicSourceActionTest.java
@@ -1,215 +1,223 @@
/**
* The software subject to this notice and license includes both human readable
* source code form and machine readable, binary, object code form. The caIntegrator2
* Software was developed in conjunction with the National Cancer Institute
* (NCI) by NCI employees, 5AM Solutions, Inc. (5AM), ScenPro, Inc. (ScenPro)
* and Science Applications International Corporation (SAIC). To the extent
* government employees are authors, any rights in such works shall be subject
* to Title 17 of the United States Code, section 105.
*
* This caIntegrator2 Software License (the License) is between NCI and You. You (or
* Your) shall mean a person or an entity, and all other entities that control,
* are controlled by, or are under common control with the entity. Control for
* purposes of this definition means (i) the direct or indirect power to cause
* the direction or management of such entity, whether by contract or otherwise,
* or (ii) ownership of fifty percent (50%) or more of the outstanding shares,
* or (iii) beneficial ownership of such entity.
*
* This License is granted provided that You agree to the conditions described
* below. NCI grants You a non-exclusive, worldwide, perpetual, fully-paid-up,
* no-charge, irrevocable, transferable and royalty-free right and license in
* its rights in the caIntegrator2 Software to (i) use, install, access, operate,
* execute, copy, modify, translate, market, publicly display, publicly perform,
* and prepare derivative works of the caIntegrator2 Software; (ii) distribute and
* have distributed to and by third parties the caIntegrator2 Software and any
* modifications and derivative works thereof; and (iii) sublicense the
* foregoing rights set out in (i) and (ii) to third parties, including the
* right to license such rights to further third parties. For sake of clarity,
* and not by way of limitation, NCI shall have no right of accounting or right
* of payment from You or Your sub-licensees for the rights granted under this
* License. This License is granted at no charge to You.
*
* Your redistributions of the source code for the Software must retain the
* above copyright notice, this list of conditions and the disclaimer and
* limitation of liability of Article 6, below. Your redistributions in object
* code form must reproduce the above copyright notice, this list of conditions
* and the disclaimer of Article 6 in the documentation and/or other materials
* provided with the distribution, if any.
*
* Your end-user documentation included with the redistribution, if any, must
* include the following acknowledgment: This product includes software
* developed by 5AM, ScenPro, SAIC and the National Cancer Institute. If You do
* not include such end-user documentation, You shall include this acknowledgment
* in the Software itself, wherever such third-party acknowledgments normally
* appear.
*
* You may not use the names "The National Cancer Institute", "NCI", "ScenPro",
* "SAIC" or "5AM" to endorse or promote products derived from this Software.
* This License does not authorize You to use any trademarks, service marks,
* trade names, logos or product names of either NCI, ScenPro, SAID or 5AM,
* except as required to comply with the terms of this License.
*
* For sake of clarity, and not by way of limitation, You may incorporate this
* Software into Your proprietary programs and into any third party proprietary
* programs. However, if You incorporate the Software into third party
* proprietary programs, You agree that You are solely responsible for obtaining
* any permission from such third parties required to incorporate the Software
* into such third party proprietary programs and for informing Your a
* sub-licensees, including without limitation Your end-users, of their
* obligation to secure any required permissions from such third parties before
* incorporating the Software into such third party proprietary software
* programs. In the event that You fail to obtain such permissions, You agree
* to indemnify NCI for any claims against NCI by such third parties, except to
* the extent prohibited by law, resulting from Your failure to obtain such
* permissions.
*
* For sake of clarity, and not by way of limitation, You may add Your own
* copyright statement to Your modifications and to the derivative works, and
* You may provide additional or different license terms and conditions in Your
* sublicenses of modifications of the Software, or any derivative works of the
* Software as a whole, provided Your use, reproduction, and distribution of the
* Work otherwise complies with the conditions stated in this License.
*
* THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES,
* (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO
* EVENT SHALL THE NATIONAL CANCER INSTITUTE, 5AM SOLUTIONS, INC., SCENPRO, INC.,
* SCIENCE APPLICATIONS INTERNATIONAL CORPORATION OR THEIR
* AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.nih.nci.caintegrator2.web.action.study.management;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import gov.nih.nci.caintegrator2.AcegiAuthenticationStub;
import gov.nih.nci.caintegrator2.application.arraydata.PlatformVendorEnum;
import gov.nih.nci.caintegrator2.application.study.GenomicDataSourceConfiguration;
import gov.nih.nci.caintegrator2.application.study.StudyConfiguration;
import gov.nih.nci.caintegrator2.application.study.StudyManagementServiceStub;
import gov.nih.nci.caintegrator2.external.ConnectionException;
import gov.nih.nci.caintegrator2.external.caarray.CaArrayFacadeStub;
import gov.nih.nci.caintegrator2.external.caarray.ExperimentNotFoundException;
import gov.nih.nci.caintegrator2.web.ajax.IGenomicDataSourceAjaxUpdater;
import java.util.HashMap;
import org.acegisecurity.context.SecurityContextHolder;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
@SuppressWarnings("PMD")
public class EditGenomicSourceActionTest {
private EditGenomicSourceAction action;
private StudyManagementServiceStub studyManagementServiceStub;
private CaArrayFacadeStubForAction caArrayFacadeStub;
@Before
public void setUp() {
ApplicationContext context = new ClassPathXmlApplicationContext("study-management-action-test-config.xml", EditGenomicSourceActionTest.class);
action = (EditGenomicSourceAction) context.getBean("editGenomicSourceAction");
studyManagementServiceStub = (StudyManagementServiceStub) context.getBean("studyManagementService");
studyManagementServiceStub.clear();
action.setUpdater(new GenomicDataSourceAjaxUpdaterStub());
SecurityContextHolder.getContext().setAuthentication(new AcegiAuthenticationStub());
ActionContext.getContext().setSession(new HashMap<String, Object>());
caArrayFacadeStub = new CaArrayFacadeStubForAction();
action.setCaArrayFacade(caArrayFacadeStub);
}
+
+ @Test
+ public void testGetPlatformNameDisable() {
+ action.getGenomicSource().setPlatformVendor(PlatformVendorEnum.AGILENT.getValue());
+ assertEquals("false", action.getPlatformNameDisable());
+ action.getGenomicSource().setPlatformVendor(PlatformVendorEnum.AFFYMETRIX.getValue());
+ assertEquals("true", action.getPlatformNameDisable());
+ }
@Test
public void testGetAgilentPlatformNames() {
assertEquals(2, action.getAgilentPlatformNames().size());
}
@Test
public void testExecute() {
assertEquals(Action.SUCCESS, action.execute());
}
@Test
public void testSave() {
assertEquals(Action.SUCCESS, action.save());
GenomicDataSourceAjaxUpdaterStub updaterStub = (GenomicDataSourceAjaxUpdaterStub) action.getUpdater();
assertTrue(updaterStub.runJobCalled);
updaterStub.runJobCalled = false;
studyManagementServiceStub.clear();
action.getGenomicSource().setId(1L);
StudyConfiguration studyConfiguration = new StudyConfiguration();
studyConfiguration.getGenomicDataSources().add(action.getGenomicSource());
action.getGenomicSource().setStudyConfiguration(studyConfiguration);
action.setStudyConfiguration(studyConfiguration);
assertEquals(Action.SUCCESS, action.save());
assertTrue(studyManagementServiceStub.deleteCalled);
assertTrue(updaterStub.runJobCalled);
// Test platform validation.
action.getGenomicSource().setPlatformVendor(PlatformVendorEnum.AGILENT.getValue());
action.getGenomicSource().setPlatformName("");
assertEquals(Action.INPUT, action.save());
action.getGenomicSource().setPlatformName("Name");
assertEquals(Action.SUCCESS, action.save());
// Test server validation.
caArrayFacadeStub.throwConnectionException = true;
assertEquals(Action.INPUT, action.save());
caArrayFacadeStub.clear();
caArrayFacadeStub.throwExperimentNotFoundException = true;
assertEquals(Action.INPUT, action.save());
}
@Test
public void testPrepare() {
action.getGenomicSource().setId(1L);
action.prepare();
assertTrue(studyManagementServiceStub.getRefreshedStudyEntityCalled);
}
private static class GenomicDataSourceAjaxUpdaterStub implements IGenomicDataSourceAjaxUpdater {
public boolean runJobCalled = false;
public void initializeJsp() {
}
public void runJob(Long id) {
runJobCalled = true;
}
}
private static class CaArrayFacadeStubForAction extends CaArrayFacadeStub {
public boolean throwConnectionException = false;
public boolean throwExperimentNotFoundException = false;
public void clear() {
throwConnectionException = false;
throwExperimentNotFoundException = false;
}
@Override
public void validateGenomicSourceConnection(GenomicDataSourceConfiguration genomicSource)
throws ConnectionException, ExperimentNotFoundException {
if (throwConnectionException) {
throw new ConnectionException("Exception Thrown");
}
if (throwExperimentNotFoundException) {
throw new ExperimentNotFoundException("Exception Thrown");
}
}
}
}
| false | false | null | null |
diff --git a/src/main/java/de/downgra/jitertools/JIterTools.java b/src/main/java/de/downgra/jitertools/JIterTools.java
index 461c771..d550b08 100644
--- a/src/main/java/de/downgra/jitertools/JIterTools.java
+++ b/src/main/java/de/downgra/jitertools/JIterTools.java
@@ -1,524 +1,525 @@
package de.downgra.jitertools;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import de.downgra.jitertools.utils.IFunctor;
import de.downgra.jitertools.utils.IPredicate;
import de.downgra.jitertools.utils.IteratorFunctor;
import de.downgra.jitertools.utils.Pair;
public class JIterTools {
public static Iterable<Integer> range(final int end) {
return range(0, end, 1);
}
public static Iterable<Integer> range(final int start, final int end) {
return range(start, end, 1);
}
public static Iterable<Integer> range(final int start, final int end,
final int step) {
assert step != 0;
return new Iterable<Integer>() {
@Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private int _current = start;
@Override
public boolean hasNext() {
if (step < 0) {
return _current > end;
} else {
return _current < end;
}
}
@Override
public Integer next() {
int tmp = _current;
_current += step;
return tmp;
}
@Override
public void remove() {
}
};
}
};
}
public static <E, T> Iterable<E> map(final IFunctor<E, T> function,
final Iterable<T> iterable) {
return new Iterable<E>() {
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
private final Iterator<T> _iterator = iterable.iterator();
@Override
public boolean hasNext() {
return _iterator.hasNext();
}
@Override
public E next() {
return function.call(_iterator.next());
}
@Override
public void remove() {
}
};
}
};
}
public static <T> List<T> list(final Iterable<T> iterable) {
// any better way?
ArrayList<T> r = new ArrayList<T>();
for (T item : iterable) {
r.add(item);
}
return r;
}
public static <T> T reduce(final IFunctor<T, Pair<T, T>> function,
final Iterable<T> iterable) {
Iterator<T> it = iterable.iterator();
T res = it.next();
while (it.hasNext()) {
res = function.call(Pair.create(res, it.next()));
}
return res;
}
public static <T> T reduce(final IFunctor<T, Pair<T, T>> function,
final Iterable<T> iterable, final T initial) {
T res = initial;
for (T item : iterable) {
res = function.call(Pair.create(res, item));
}
return res;
}
public static <T> Iterable<T> chain(final Iterable<T>... iterables) {
return chain(Arrays.asList(iterables));
}
public static <T> Iterable<T> chain(final Iterable<Iterable<T>> iterables) {
if (!iterables.iterator().hasNext()) {
return new ArrayList<T>();
} else {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private Iterator<Iterable<T>> _outer = iterables
.iterator();
private Iterator<T> _current = _outer.next().iterator();
private void consume() {
while (!_current.hasNext() && _outer.hasNext()) {
_current = _outer.next().iterator();
}
}
@Override
public boolean hasNext() {
consume();
return _current.hasNext();
}
@Override
public T next() {
consume();
return _current.next();
}
@Override
public void remove() {
}
};
}
};
}
}
public static Iterable<Integer> count() {
return count(0);
}
public static Iterable<Integer> count(final int n) {
return new Iterable<Integer>() {
@Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private int _i = n;
@Override
public boolean hasNext() {
return true;
}
@Override
public Integer next() {
return _i++;
}
@Override
public void remove() {
}
};
}
};
}
public static <T> Iterable<T> cycle(final Iterable<T> iterable) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private Iterator<T> _iterator = iterable.iterator();
private ArrayList<T> _saved = new ArrayList<T>();
private boolean _firstCycle = true;
@Override
public boolean hasNext() {
return _iterator.hasNext();
}
@Override
public T next() {
if (_iterator.hasNext() && _firstCycle) {
T item = _iterator.next();
_saved.add(item);
return item;
}
_firstCycle = false;
if (!_iterator.hasNext()) {
_iterator = _saved.iterator();
}
return _iterator.next();
}
@Override
public void remove() {
}
};
}
};
}
public static <T> Iterable<T> dropwhile(final IPredicate<T> predicate,
final Iterable<T> iterable) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private Iterator<T> _iterator = iterable.iterator();
private T _first = null;
private boolean _onFirst = false;
private boolean consume() {
if (_first == null) {
while (_iterator.hasNext()) {
_first = _iterator.next();
if (!predicate.call(_first)) {
_onFirst = true;
return true;
}
}
}
return false;
}
@Override
public boolean hasNext() {
return consume() || _iterator.hasNext();
}
@Override
public T next() {
consume();
if (_onFirst) {
_onFirst = false;
return _first;
}
return _iterator.next();
}
@Override
public void remove() {
}
};
}
};
}
public static <T> Iterable<T> filter(final IPredicate<T> predicate,
final Iterable<T> iterable) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private final Iterator<T> _iterator = iterable.iterator();
private T _last = null;
private boolean consume() {
if (_last == null) {
while (_iterator.hasNext()) {
_last = _iterator.next();
if (predicate.call(_last)) {
return true;
}
}
_last = null;
}
return false;
}
@Override
public boolean hasNext() {
return consume() || _iterator.hasNext();
}
@Override
public T next() {
consume();
T tmp = _last;
_last = null;
return tmp;
}
@Override
public void remove() {
}
};
}
};
}
public static <T> Iterable<T> filterfalse(final IPredicate<T> predicate,
final Iterable<T> iterable) {
return filter(new IPredicate<T>() {
@Override
public Boolean call(T object) {
return !predicate.call(object);
}
}, iterable);
}
public static <T> Iterable<T> takewhile(final IPredicate<T> predicate,
final Iterable<T> iterable) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private final Iterator<T> _iterator = iterable.iterator();
private T _last = null;
private boolean consume() {
if (_last == null) {
if (_iterator.hasNext()) {
_last = _iterator.next();
if (predicate.call(_last)) {
return true;
}
}
}
return false;
}
@Override
public boolean hasNext() {
return consume();
}
@Override
public T next() {
consume();
T tmp = _last;
_last = null;
return tmp;
}
@Override
public void remove() {
}
};
}
};
}
public static <T> Iterable<List<T>> zip(final Iterable<T>... iterables) {
return zip(Arrays.asList(iterables));
}
public static <T> Iterable<List<T>> zip(
final Iterable<Iterable<T>> iterables) {
return new Iterable<List<T>>() {
@Override
public Iterator<List<T>> iterator() {
return new Iterator<List<T>>() {
private List<Iterator<T>> _outer = list(map(
new IteratorFunctor<T>(), iterables));
@Override
public boolean hasNext() {
for (Iterator<T> inner : _outer) {
if (!inner.hasNext())
return false;
}
return true && _outer.size() != 0;
}
@Override
public List<T> next() {
ArrayList<T> ret = new ArrayList<T>(_outer.size());
for (Iterator<T> inner : _outer) {
ret.add(inner.next());
}
return ret;
}
@Override
public void remove() {
}
};
}
};
}
public static <T> Iterable<List<T>> zip(final T filler,
final Iterable<T>... iterables) {
return zip(filler, Arrays.asList(iterables));
}
public static <T> Iterable<List<T>> zip(final T filler,
final Iterable<Iterable<T>> iterables) {
return new Iterable<List<T>>() {
@Override
public Iterator<List<T>> iterator() {
return new Iterator<List<T>>() {
private List<Iterator<T>> _outer = list(map(
new IteratorFunctor<T>(), iterables));
@Override
public boolean hasNext() {
for (Iterator<T> inner : _outer) {
if (inner.hasNext())
return true;
}
return false;
}
@Override
public List<T> next() {
ArrayList<T> ret = new ArrayList<T>(_outer.size());
for (Iterator<T> inner : _outer) {
if (inner.hasNext()) {
ret.add(inner.next());
} else {
ret.add(filler);
}
}
return ret;
}
@Override
public void remove() {
}
};
}
};
}
public static <T> Iterable<T> repeat(final T object) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
@Override
public boolean hasNext() {
return true;
}
@Override
public T next() {
return object;
}
@Override
public void remove() {
}
};
}
};
}
public static <T> Iterable<T> repeat(final T object, final int times) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int _count = times;
@Override
public boolean hasNext() {
- return _count-- > 0;
+ return _count > 0;
}
@Override
public T next() {
+ _count--;
return object;
}
@Override
public void remove() {
}
};
}
};
}
public static <T> Iterable<Pair<Integer, T>> enumerate(
final Iterable<T> iterable) {
return enumerate(iterable, 0);
}
public static <T> Iterable<Pair<Integer, T>> enumerate(
final Iterable<T> iterable, final int start) {
return new Iterable<Pair<Integer, T>>() {
@Override
public Iterator<Pair<Integer, T>> iterator() {
return new Iterator<Pair<Integer, T>>() {
private Iterator<T> _iterator = iterable.iterator();
private int _counter = start;
@Override
public boolean hasNext() {
return _iterator.hasNext();
}
@Override
public Pair<Integer, T> next() {
return Pair.create(_counter++, _iterator.next());
}
@Override
public void remove() {
}
};
}
};
}
}
| false | false | null | null |
diff --git a/StevenDimDoors/mod_pocketDim/DDTeleporter.java b/StevenDimDoors/mod_pocketDim/DDTeleporter.java
index bb9ca30..97aae3f 100644
--- a/StevenDimDoors/mod_pocketDim/DDTeleporter.java
+++ b/StevenDimDoors/mod_pocketDim/DDTeleporter.java
@@ -1,376 +1,376 @@
package StevenDimDoors.mod_pocketDim;
import java.util.Random;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.entity.item.EntityMinecart;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.packet.Packet41EntityEffect;
import net.minecraft.network.packet.Packet43Experience;
import net.minecraft.network.packet.Packet9Respawn;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.DimensionManager;
import StevenDimDoors.mod_pocketDim.core.DimLink;
import StevenDimDoors.mod_pocketDim.core.LinkTypes;
import StevenDimDoors.mod_pocketDim.core.PocketManager;
import StevenDimDoors.mod_pocketDim.util.Point4D;
import StevenDimDoors.mod_pocketDim.world.PocketBuilder;
import cpw.mods.fml.common.registry.GameRegistry;
public class DDTeleporter
{
private static final Random random = new Random();
public static int cooldown = 0;
private DDTeleporter() { }
private static void placeInPortal(Entity entity, WorldServer world, Point4D destination, DDProperties properties)
{
int x = destination.getX();
int y = destination.getY();
int z = destination.getZ();
int orientation = getDestinationOrientation(destination, properties);
if (entity instanceof EntityPlayer)
{
EntityPlayer player = (EntityPlayer) entity;
player.rotationYaw=(orientation*90)+90;
if(orientation==2||orientation==6)
{
player.setPositionAndUpdate( x+1.5, y-1, z+.5 );
}
else if(orientation==3||orientation==7)
{
player.setPositionAndUpdate( x+.5, y-1, z+1.5 );
}
else if(orientation==0||orientation==4)
{
player.setPositionAndUpdate(x-.5, y-1, z+.5);
}
else if(orientation==1||orientation==5)
{
player.setPositionAndUpdate(x+.5, y-1, z-.5);
}
else
{
player.setPositionAndUpdate(x, y-1, z);
}
}
else if (entity instanceof EntityMinecart)
{
entity.motionX=0;
entity.motionZ=0;
entity.motionY=0;
entity.rotationYaw=(orientation*90)+90;
if(orientation==2||orientation==6)
{
DDTeleporter.setEntityPosition(entity, x+1.5, y, z+.5 );
entity.motionX =.39;
entity.worldObj.updateEntityWithOptionalForce(entity, false);
}
else if(orientation==3||orientation==7)
{
DDTeleporter.setEntityPosition(entity, x+.5, y, z+1.5 );
entity.motionZ =.39;
entity.worldObj.updateEntityWithOptionalForce(entity, false);
}
else if(orientation==0||orientation==4)
{
DDTeleporter.setEntityPosition(entity,x-.5, y, z+.5);
entity.motionX =-.39;
entity.worldObj.updateEntityWithOptionalForce(entity, false);
}
else if(orientation==1||orientation==5)
{
DDTeleporter.setEntityPosition(entity,x+.5, y, z-.5);
entity.motionZ =-.39;
entity.worldObj.updateEntityWithOptionalForce(entity, false);
}
else
{
DDTeleporter.setEntityPosition(entity,x, y, z);
}
}
else if (entity instanceof Entity)
{
entity.rotationYaw=(orientation*90)+90;
if(orientation==2||orientation==6)
{
DDTeleporter.setEntityPosition(entity, x+1.5, y, z+.5 );
}
else if(orientation==3||orientation==7)
{
DDTeleporter.setEntityPosition(entity, x+.5, y, z+1.5 );
}
else if(orientation==0||orientation==4)
{
DDTeleporter.setEntityPosition(entity,x-.5, y, z+.5);
}
else if(orientation==1||orientation==5)
{
DDTeleporter.setEntityPosition(entity,x+.5, y, z-.5);
}
else
{
DDTeleporter.setEntityPosition(entity,x, y, z);
}
}
}
private static void setEntityPosition(Entity entity, double x, double y, double z)
{
entity.lastTickPosX = entity.prevPosX = entity.posX = x;
entity.lastTickPosY = entity.prevPosY = entity.posY = y + (double)entity.yOffset;
entity.lastTickPosZ = entity.prevPosZ = entity.posZ = z;
entity.setPosition(x, y, z);
}
private static int getDestinationOrientation(Point4D door, DDProperties properties)
{
World world = DimensionManager.getWorld(door.getDimension());
if (world == null)
{
throw new IllegalStateException("The destination world should be loaded!");
}
- //Check if the block at that point is actually a door
- int blockID = world.getBlockId(door.getX(), door.getY(), door.getZ());
+ //Check if the block below that point is actually a door
+ int blockID = world.getBlockId(door.getX(), door.getY() - 1, door.getZ());
if (blockID != properties.DimensionalDoorID && blockID != properties.WarpDoorID &&
blockID != properties.TransientDoorID && blockID != properties.UnstableDoorID)
{
//Return the pocket's orientation instead
return PocketManager.getDimensionData(door.getDimension()).orientation();
}
//Return the orientation portion of its metadata
- return world.getBlockMetadata(door.getX(), door.getY(), door.getZ()) & 3;
+ return world.getBlockMetadata(door.getX(), door.getY() - 1, door.getZ()) & 3;
}
public static Entity teleportEntity(Entity entity, Point4D destination)
{
if (entity == null)
{
throw new IllegalArgumentException("entity cannot be null.");
}
if (destination == null)
{
throw new IllegalArgumentException("destination cannot be null.");
}
//This beautiful teleport method is based off of xCompWiz's teleport function.
WorldServer oldWorld = (WorldServer) entity.worldObj;
WorldServer newWorld;
EntityPlayerMP player = (entity instanceof EntityPlayerMP) ? (EntityPlayerMP) entity : null;
DDProperties properties = DDProperties.instance();
// Is something riding? Handle it first.
if (entity.riddenByEntity != null)
{
return teleportEntity(entity.riddenByEntity, destination);
}
// Are we riding something? Dismount and tell the mount to go first.
Entity cart = entity.ridingEntity;
if (cart != null)
{
entity.mountEntity(null);
cart = teleportEntity(cart, destination);
// We keep track of both so we can remount them on the other side.
}
// Determine if our destination is in another realm.
boolean difDest = entity.dimension != destination.getDimension();
if (difDest)
{
// Destination isn't loaded? Then we need to load it.
newWorld = DimensionManager.getWorld(destination.getDimension());
if (newWorld == null)
{
DimensionManager.initDimension(destination.getDimension());
newWorld = DimensionManager.getWorld(destination.getDimension());
}
}
else
{
newWorld = (WorldServer) oldWorld;
}
// GreyMaria: What is this even accomplishing? We're doing the exact same thing at the end of this all.
// TODO Check to see if this is actually vital.
DDTeleporter.placeInPortal(entity, newWorld, destination, properties);
if (difDest) // Are we moving our target to a new dimension?
{
if(player != null) // Are we working with a player?
{
// We need to do all this special stuff to move a player between dimensions.
// Set the new dimension and inform the client that it's moving to a new world.
player.dimension = destination.getDimension();
player.playerNetServerHandler.sendPacketToPlayer(new Packet9Respawn(player.dimension, (byte)player.worldObj.difficultySetting, newWorld.getWorldInfo().getTerrainType(), newWorld.getHeight(), player.theItemInWorldManager.getGameType()));
// GreyMaria: Used the safe player entity remover before.
// This should fix an apparently unreported bug where
// the last non-sleeping player leaves the Overworld
// for a pocket dimension, causing all sleeping players
// to remain asleep instead of progressing to day.
oldWorld.removePlayerEntityDangerously(player);
player.isDead = false;
// Creates sanity by ensuring that we're only known to exist where we're supposed to be known to exist.
oldWorld.getPlayerManager().removePlayer(player);
newWorld.getPlayerManager().addPlayer(player);
player.theItemInWorldManager.setWorld((WorldServer)newWorld);
// Synchronize with the server so the client knows what time it is and what it's holding.
player.mcServer.getConfigurationManager().updateTimeAndWeatherForPlayer(player, (WorldServer)newWorld);
player.mcServer.getConfigurationManager().syncPlayerInventory(player);
for(Object potionEffect : player.getActivePotionEffects())
{
PotionEffect effect = (PotionEffect)potionEffect;
player.playerNetServerHandler.sendPacketToPlayer(new Packet41EntityEffect(player.entityId, effect));
}
player.playerNetServerHandler.sendPacketToPlayer(new Packet43Experience(player.experience, player.experienceTotal, player.experienceLevel));
}
// Creates sanity by removing the entity from its old location's chunk entity list, if applicable.
int entX = entity.chunkCoordX;
int entZ = entity.chunkCoordZ;
if ((entity.addedToChunk) && (oldWorld.getChunkProvider().chunkExists(entX, entZ)))
{
oldWorld.getChunkFromChunkCoords(entX, entZ).removeEntity(entity);
oldWorld.getChunkFromChunkCoords(entX, entZ).isModified = true;
}
// Memory concerns.
oldWorld.releaseEntitySkin(entity);
if (player == null) // Are we NOT working with a player?
{
NBTTagCompound entityNBT = new NBTTagCompound();
entity.isDead = false;
entity.addEntityID(entityNBT);
entity.isDead = true;
entity = EntityList.createEntityFromNBT(entityNBT, newWorld);
if (entity == null)
{
// TODO FIXME IMPLEMENT NULL CHECKS THAT ACTUALLY DO SOMETHING.
/*
* shit ourselves in an organized fashion, preferably
* in a neat pile instead of all over our users' games
*/
}
}
// Finally, respawn the entity in its new home.
newWorld.spawnEntityInWorld(entity);
entity.setWorld(newWorld);
}
entity.worldObj.updateEntityWithOptionalForce(entity, false);
// Hey, remember me? It's time to remount.
if (cart != null)
{
// Was there a player teleported? If there was, it's important that we update shit.
if (player != null)
{
entity.worldObj.updateEntityWithOptionalForce(entity, true);
}
entity.mountEntity(cart);
}
// Did we teleport a player? Load the chunk for them.
if (player != null)
{
newWorld.getChunkProvider().loadChunk(MathHelper.floor_double(entity.posX) >> 4, MathHelper.floor_double(entity.posZ) >> 4);
// Tell Forge we're moving its players so everyone else knows.
// Let's try doing this down here in case this is what's killing NEI.
GameRegistry.onPlayerChangedDimension((EntityPlayer)entity);
}
DDTeleporter.placeInPortal(entity, newWorld, destination, properties);
return entity;
}
/**
* Primary function used to teleport the player using doors. Performs numerous null checks, and also generates the destination door/pocket if it has not done so already.
* Also ensures correct orientation relative to the door.
* @param world - world the player is currently in
* @param link - the link the player is using to teleport; sends the player to its destination
* @param player - the instance of the player to be teleported
*/
public static void traverseDimDoor(World world, DimLink link, Entity entity)
{
if (world == null)
{
throw new IllegalArgumentException("world cannot be null.");
}
if (link == null)
{
throw new IllegalArgumentException("link cannot be null.");
}
if (entity == null)
{
throw new IllegalArgumentException("entity cannot be null.");
}
if (world.isRemote)
{
return;
}
if (cooldown == 0 || entity instanceof EntityPlayer)
{
cooldown = 2 + random.nextInt(2);
}
else
{
return;
}
if (!initializeDestination(link, DDProperties.instance()))
{
return;
}
entity = teleportEntity(entity, link.destination());
entity.worldObj.playSoundEffect(entity.posX, entity.posY, entity.posZ, "mob.endermen.portal", 1.0F, 1.0F);
}
private static boolean initializeDestination(DimLink link, DDProperties properties)
{
//FIXME: Change this later to support rooms that have been wiped and must be regenerated.
if (link.hasDestination())
{
return true;
}
//Check the destination type and respond accordingly
//FIXME: Add missing link types.
//FIXME: Add code for restoring the destination-side door.
switch (link.linkType())
{
case LinkTypes.DUNGEON:
return PocketBuilder.generateNewDungeonPocket(link, properties);
case LinkTypes.POCKET:
return PocketBuilder.generateNewPocket(link, properties);
case LinkTypes.NORMAL:
return true;
default:
throw new IllegalArgumentException("link has an unrecognized link type.");
}
}
}
diff --git a/StevenDimDoors/mod_pocketDim/world/PocketBuilder.java b/StevenDimDoors/mod_pocketDim/world/PocketBuilder.java
index 98e51a4..e8afbe0 100644
--- a/StevenDimDoors/mod_pocketDim/world/PocketBuilder.java
+++ b/StevenDimDoors/mod_pocketDim/world/PocketBuilder.java
@@ -1,438 +1,438 @@
package StevenDimDoors.mod_pocketDim.world;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
import net.minecraftforge.common.DimensionManager;
import StevenDimDoors.mod_pocketDim.DDProperties;
import StevenDimDoors.mod_pocketDim.Point3D;
import StevenDimDoors.mod_pocketDim.core.DimLink;
import StevenDimDoors.mod_pocketDim.core.NewDimData;
import StevenDimDoors.mod_pocketDim.core.PocketManager;
import StevenDimDoors.mod_pocketDim.dungeon.DungeonData;
import StevenDimDoors.mod_pocketDim.dungeon.DungeonSchematic;
import StevenDimDoors.mod_pocketDim.dungeon.pack.DungeonPackConfig;
import StevenDimDoors.mod_pocketDim.helpers.DungeonHelper;
import StevenDimDoors.mod_pocketDim.helpers.yCoordHelper;
import StevenDimDoors.mod_pocketDim.schematic.BlockRotator;
import StevenDimDoors.mod_pocketDim.util.Pair;
import StevenDimDoors.mod_pocketDim.util.Point4D;
public class PocketBuilder
{
public static final int MIN_POCKET_SIZE = 5;
public static final int MAX_POCKET_SIZE = 51;
public static final int DEFAULT_POCKET_SIZE = 39;
public static final int MIN_POCKET_WALL_THICKNESS = 1;
public static final int MAX_POCKET_WALL_THICKNESS = 10;
public static final int DEFAULT_POCKET_WALL_THICKNESS = 5;
private static final Random random = new Random();
private PocketBuilder() { }
public static boolean generateNewDungeonPocket(DimLink link, DDProperties properties)
{
if (link == null)
{
throw new IllegalArgumentException("link cannot be null.");
}
if (properties == null)
{
throw new IllegalArgumentException("properties cannot be null.");
}
if (link.hasDestination())
{
throw new IllegalArgumentException("link cannot have a destination assigned already.");
}
try
{
//Register a new dimension
NewDimData parent = PocketManager.getDimensionData(link.source().getDimension());
NewDimData dimension = PocketManager.registerPocket(parent, true);
//Load a world
World world = DimensionManager.getWorld(dimension.id());
if (world == null)
{
DimensionManager.initDimension(dimension.id());
world = DimensionManager.getWorld(dimension.id());
}
if (world != null && world.provider == null)
{
DimensionManager.initDimension(dimension.id());
}
if (world == null || world.provider == null)
{
System.err.println("Could not initialize dimension for a dungeon!");
return false;
}
//Choose a dungeon to generate
Pair<DungeonData, DungeonSchematic> pair = selectDungeon(dimension, random, properties);
if (pair == null)
{
System.err.println("Could not select a dungeon for generation!");
return false;
}
DungeonData dungeon = pair.getFirst();
DungeonSchematic schematic = pair.getSecond();
//Calculate the destination point
DungeonPackConfig packConfig = dungeon.dungeonType().Owner != null ? dungeon.dungeonType().Owner.getConfig() : null;
Point4D source = link.source();
int orientation = getDoorOrientation(source, properties);
Point3D destination;
if (packConfig != null && packConfig.doDistortDoorCoordinates())
{
destination = calculateNoisyDestination(source, dimension, orientation);
}
else
{
destination = new Point3D(source.getX(), source.getY(), source.getZ());
}
destination.setY( yCoordHelper.adjustDestinationY(destination.getY(), world.getHeight(), schematic.getEntranceDoorLocation().getY(), schematic.getHeight()) );
//Generate the dungeon
schematic.copyToWorld(world, destination, orientation, link, random);
//Finish up destination initialization
dimension.initializeDungeon(destination.getX(), destination.getY(), destination.getZ(), orientation, link, dungeon);
dimension.setFilled(true);
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
private static Point3D calculateNoisyDestination(Point4D source, NewDimData dimension, int orientation)
{
int depth = dimension.packDepth();
int forwardNoise = MathHelper.getRandomIntegerInRange(random, -50 * depth, 150 * depth);
int sidewaysNoise = MathHelper.getRandomIntegerInRange(random, -10 * depth, 10 * depth);
//Rotate the link destination noise to point in the same direction as the door exit
//and add it to the door's location. Use EAST as the reference orientation since linkDestination
//is constructed as if pointing East.
Point3D linkDestination = new Point3D(forwardNoise, 0, sidewaysNoise);
Point3D sourcePoint = new Point3D(source.getX(), source.getY(), source.getZ());
Point3D zeroPoint = new Point3D(0, 0, 0);
BlockRotator.transformPoint(linkDestination, zeroPoint, orientation - BlockRotator.EAST_DOOR_METADATA, sourcePoint);
return linkDestination;
}
private static Pair<DungeonData, DungeonSchematic> selectDungeon(NewDimData dimension, Random random, DDProperties properties)
{
//We assume the dimension doesn't have a dungeon assigned
if (dimension.dungeon() != null)
{
throw new IllegalArgumentException("dimension cannot have a dungeon assigned already.");
}
DungeonData dungeon = null;
DungeonSchematic schematic = null;
dungeon = DungeonHelper.instance().selectDungeon(dimension, random);
if (dungeon != null)
{
schematic = loadAndValidateDungeon(dungeon, properties);
}
else
{
System.err.println("Could not select a dungeon at all!");
}
if (schematic == null)
{
//TODO: In the future, remove this dungeon from the generation lists altogether.
//That will have to wait until our code is updated to support that more easily.
try
{
System.err.println("Loading the default error dungeon instead...");
dungeon = DungeonHelper.instance().getDefaultErrorDungeon();
schematic = loadAndValidateDungeon(dungeon, properties);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
return new Pair<DungeonData, DungeonSchematic>(dungeon, schematic);
}
private static DungeonSchematic loadAndValidateDungeon(DungeonData dungeon, DDProperties properties)
{
try
{
DungeonSchematic schematic = dungeon.loadSchematic();
//Validate the dungeon's dimensions
if (hasValidDimensions(schematic))
{
schematic.applyImportFilters(properties);
//Check that the dungeon has an entrance or we'll have a crash
if (schematic.getEntranceDoorLocation() == null)
{
System.err.println("The following schematic file does not have an entrance: " + dungeon.schematicPath());
return null;
}
}
else
{
System.err.println("The following schematic file has dimensions that exceed the maximum permitted dimensions for dungeons: " + dungeon.schematicPath());
return null;
}
return schematic;
}
catch (Exception e)
{
System.err.println("An error occurred while loading the following schematic: " + dungeon.schematicPath());
System.err.println(e.getMessage());
return null;
}
}
private static boolean hasValidDimensions(DungeonSchematic schematic)
{
return (schematic.getWidth() <= DungeonHelper.MAX_DUNGEON_WIDTH &&
schematic.getHeight() <= DungeonHelper.MAX_DUNGEON_HEIGHT &&
schematic.getLength() <= DungeonHelper.MAX_DUNGEON_LENGTH);
}
public static boolean generateNewPocket(DimLink link, DDProperties properties)
{
return generateNewPocket(link, DEFAULT_POCKET_SIZE, DEFAULT_POCKET_WALL_THICKNESS, properties);
}
private static int getDoorOrientation(Point4D source, DDProperties properties)
{
World world = DimensionManager.getWorld(source.getDimension());
if (world == null)
{
throw new IllegalStateException("The link's source world should be loaded!");
}
- //Check if the block at that point is actually a door
- int blockID = world.getBlockId(source.getX(), source.getY(), source.getZ());
+ //Check if the block below that point is actually a door
+ int blockID = world.getBlockId(source.getX(), source.getY() - 1, source.getZ());
if (blockID != properties.DimensionalDoorID && blockID != properties.WarpDoorID &&
blockID != properties.TransientDoorID)
{
throw new IllegalStateException("The link's source is not a door block. It should be impossible to traverse a rift without a door!");
}
//Return the orientation portion of its metadata
- int orientation = world.getBlockMetadata(source.getX(), source.getY(), source.getZ()) & 3;
+ int orientation = world.getBlockMetadata(source.getX(), source.getY() - 1, source.getZ()) & 3;
return orientation;
}
public static boolean generateNewPocket(DimLink link, int size, int wallThickness, DDProperties properties)
{
if (link == null)
{
throw new IllegalArgumentException();
}
if (properties == null)
{
throw new IllegalArgumentException("properties cannot be null.");
}
if (link.hasDestination())
{
throw new IllegalArgumentException("link cannot have a destination assigned already.");
}
if (size < MIN_POCKET_SIZE || size > MAX_POCKET_SIZE)
{
throw new IllegalArgumentException("size must be between " + MIN_POCKET_SIZE + " and " + MAX_POCKET_SIZE + ", inclusive.");
}
if (wallThickness < MIN_POCKET_WALL_THICKNESS || wallThickness > MAX_POCKET_WALL_THICKNESS)
{
throw new IllegalArgumentException("wallThickness must be between " + MIN_POCKET_WALL_THICKNESS + " and " + MAX_POCKET_WALL_THICKNESS + ", inclusive.");
}
if (size % 2 == 0)
{
throw new IllegalArgumentException("size must be an odd number.");
}
if (size < 2 * wallThickness + 3)
{
throw new IllegalArgumentException("size must be large enough to fit the specified wall thickness and some air space.");
}
try
{
//Register a new dimension
NewDimData parent = PocketManager.getDimensionData(link.source().getDimension());
NewDimData dimension = PocketManager.registerPocket(parent, false);
//Load a world
World world = DimensionManager.getWorld(dimension.id());
if (world == null)
{
DimensionManager.initDimension(dimension.id());
world = DimensionManager.getWorld(dimension.id());
}
if (world != null && world.provider == null)
{
DimensionManager.initDimension(dimension.id());
}
if (world == null || world.provider == null)
{
System.err.println("Could not initialize dimension for a pocket!");
return false;
}
//Calculate the destination point
Point4D source = link.source();
int destinationY = yCoordHelper.adjustDestinationY(source.getY(), world.getHeight(), wallThickness + 1, size);
int orientation = getDoorOrientation(source, properties);
//Build the actual pocket area
buildPocket(world, source.getX(), destinationY, source.getZ(), orientation, size, wallThickness, properties);
//Finish up destination initialization
dimension.initializePocket(source.getX(), destinationY, source.getZ(), orientation, link);
dimension.setFilled(true);
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
private static void buildPocket(World world, int x, int y, int z, int orientation, int size, int wallThickness, DDProperties properties)
{
if (properties == null)
{
throw new IllegalArgumentException("properties cannot be null.");
}
if (size < MIN_POCKET_SIZE || size > MAX_POCKET_SIZE)
{
throw new IllegalArgumentException("size must be between " + MIN_POCKET_SIZE + " and " + MAX_POCKET_SIZE + ", inclusive.");
}
if (wallThickness < MIN_POCKET_WALL_THICKNESS || wallThickness > MAX_POCKET_WALL_THICKNESS)
{
throw new IllegalArgumentException("wallThickness must be between " + MIN_POCKET_WALL_THICKNESS + " and " + MAX_POCKET_WALL_THICKNESS + ", inclusive.");
}
if (size % 2 == 0)
{
throw new IllegalArgumentException("size must be an odd number.");
}
if (size < 2 * wallThickness + 3)
{
throw new IllegalArgumentException("size must be large enough to fit the specified wall thickness and some air space.");
}
Point3D center = new Point3D(x - wallThickness + 1 + (size / 2), y - wallThickness - 1 + (size / 2), z);
Point3D door = new Point3D(x, y, z);
BlockRotator.transformPoint(center, door, orientation - BlockRotator.EAST_DOOR_METADATA, door);
//Build the outer layer of Eternal Fabric
buildBox(world, center.getX(), center.getY(), center.getZ(), (size / 2), properties.PermaFabricBlockID, false, 0);
//Build the (wallThickness - 1) layers of Fabric of Reality
for (int layer = 1; layer < wallThickness; layer++)
{
buildBox(world, center.getX(), center.getY(), center.getZ(), (size / 2) - layer, properties.FabricBlockID,
layer < (wallThickness - 1) && properties.TNFREAKINGT_Enabled, properties.NonTntWeight);
}
//Build the door
int metadata = BlockRotator.transformMetadata(BlockRotator.EAST_DOOR_METADATA, orientation - BlockRotator.EAST_DOOR_METADATA, properties.DimensionalDoorID);
setBlockDirectly(world, x, y, z, properties.DimensionalDoorID, metadata);
setBlockDirectly(world, x, y - 1, z, properties.DimensionalDoorID, metadata);
}
private static void buildBox(World world, int centerX, int centerY, int centerZ, int radius, int blockID, boolean placeTnt, int nonTntWeight)
{
int x, y, z;
final int startX = centerX - radius;
final int startY = centerY - radius;
final int startZ = centerZ - radius;
final int endX = centerX + radius;
final int endY = centerY + radius;
final int endZ = centerZ + radius;
//Build faces of the box
for (x = startX; x <= endX; x++)
{
for (z = startZ; z <= endZ; z++)
{
setBlockDirectlySpecial(world, x, startY, z, blockID, 0, placeTnt, nonTntWeight);
setBlockDirectlySpecial(world, x, endY, z, blockID, 0, placeTnt, nonTntWeight);
}
for (y = startY; y <= endY; y++)
{
setBlockDirectlySpecial(world, x, y, startZ, blockID, 0, placeTnt, nonTntWeight);
setBlockDirectlySpecial(world, x, y, endZ, blockID, 0, placeTnt, nonTntWeight);
}
}
for (y = startY; y <= endY; y++)
{
for (z = startZ; z <= endZ; z++)
{
setBlockDirectlySpecial(world, startX, y, z, blockID, 0, placeTnt, nonTntWeight);
setBlockDirectlySpecial(world, endX, y, z, blockID, 0, placeTnt, nonTntWeight);
}
}
}
private static void setBlockDirectlySpecial(World world, int x, int y, int z, int blockID, int metadata, boolean placeTnt, int nonTntWeight)
{
if (placeTnt && random.nextInt(nonTntWeight + 1) == 0)
{
setBlockDirectly(world, x, y, z, Block.tnt.blockID, 1);
}
else
{
setBlockDirectly(world, x, y, z, blockID, metadata);
}
}
private static void setBlockDirectly(World world, int x, int y, int z, int blockID, int metadata)
{
if (blockID != 0 && Block.blocksList[blockID] == null)
{
return;
}
int cX = x >> 4;
int cZ = z >> 4;
int cY = y >> 4;
Chunk chunk;
int localX = (x % 16) < 0 ? (x % 16) + 16 : (x % 16);
int localZ = (z % 16) < 0 ? (z % 16) + 16 : (z % 16);
ExtendedBlockStorage extBlockStorage;
chunk = world.getChunkFromChunkCoords(cX, cZ);
extBlockStorage = chunk.getBlockStorageArray()[cY];
if (extBlockStorage == null)
{
extBlockStorage = new ExtendedBlockStorage(cY << 4, !world.provider.hasNoSky);
chunk.getBlockStorageArray()[cY] = extBlockStorage;
}
extBlockStorage.setExtBlockID(localX, y & 15, localZ, blockID);
extBlockStorage.setExtBlockMetadata(localX, y & 15, localZ, metadata);
}
}
| false | false | null | null |
diff --git a/jython/src/org/python/modules/jffi/Memory.java b/jython/src/org/python/modules/jffi/Memory.java
index 67ab9441..b71a4d3d 100644
--- a/jython/src/org/python/modules/jffi/Memory.java
+++ b/jython/src/org/python/modules/jffi/Memory.java
@@ -1,355 +1,355 @@
package org.python.modules.jffi;
/**
* Abstracted memory operations.
* <p>
* This abstracts read/write operations to either a native memory area, or a java
* ByteBuffer.
* </p>
*/
public interface Memory {
/**
* Checks if the memory area is NULL.
*
* @return <tt>true</tt> if the memory area is invalid.
*/
public boolean isNull();
/**
* Checks if the memory area is a native memory pointer.
*
* @return <tt>true</tt> if the memory area is a native pointer.
*/
public boolean isDirect();
/**
* Creates a new MemoryIO pointing to a subset of the memory area of this
* <tt>MemoryIO</tt>.
* @param offset The offset within the existing memory area to start the
* new <tt>MemoryIO</tt> at.
* @return A <tt>MemoryIO</tt> instance.
*/
public Memory slice(long offset);
/**
* Reads an 8 bit integer value from the memory area.
*
* @param offset The offset within the memory area to read the value.
* @return The 8 bit integer value read from <tt>offset</tt>
*/
public byte getByte(long offset);
/**
* Reads a 16 bit integer value from the memory area.
*
* @param offset The offset within the memory area to read the value.
* @return The 16 bit integer value read from <tt>offset</tt>
*/
public short getShort(long offset);
/**
* Reads a 32 bit integer value from the memory area.
*
* @param offset The offset within the memory area to read the value.
* @return The 32 bit integer value read from <tt>offset</tt>
*/
public int getInt(long offset);
/**
* Reads a 64 bit integer value from the memory area.
*
* @param offset The offset within the memory area to read the value.
* @return The 64 bit integer value read from <tt>offset</tt>
*/
public long getLong(long offset);
/**
* Reads a native long integer value from the memory area.
* <p>
* A native long is 32bits on either ILP32 or LLP64 architectures, and
* 64 bits on an LP64 architecture.
* </p>
* <p>
* This means that it will always read a 32bit value on Windows, but on
* Unix systems such as MacOS or Linux, it will read a 32bit value on 32bit
* systems, and a 64bit value on 64bit systems.
*
* @param offset The offset within the memory area to read the value.
* @return The native long value read from <tt>offset</tt>
*/
public long getNativeLong(long offset);
/**
* Reads a float value from the memory area.
*
* @param offset The offset within the memory area to read the value.
* @return The float value read from <tt>offset</tt>
*/
public float getFloat(long offset);
/**
* Reads a double value from the memory area.
*
* @param offset The offset within the memory area to read the value.
* @return The double value read from <tt>offset</tt>
*/
public double getDouble(long offset);
/**
* Reads a pointer value at the specified offset within the memory area.
*
* @param offset The offset within the memory area to read the value.
* @return A <tt>long</tt> value that represents the address.
*/
public long getAddress(long offset);
/**
* Reads a pointer value at the specified offset within the memory area, and
* wraps it in an abstract memory accessor.
*
* @param offset The offset within the memory area to read the value.
* @return A <tt>DirectMemory</tt> accessor that can be used to access the memory
* pointed to by the address.
*/
public DirectMemory getMemory(long offset);
/**
* Reads a zero terminated byte array (e.g. an ascii or utf-8 string)
*
* @param offset The offset within the memory area of the start of the string.
* @return A byte array containing a copy of the data.
*/
public byte[] getZeroTerminatedByteArray(long offset);
/**
* Writes an 8 bit integer value to the memory area at the specified offset.
*
* @param offset The offset within the memory area to write the value.
* @param value The 8 bit integer value to write to the memory location.
*/
public void putByte(long offset, byte value);
/**
* Writes a 16 bit integer value to the memory area at the specified offset.
*
* @param offset The offset within the memory area to write the value.
* @param value The 16 bit integer value to write to the memory location.
*/
public void putShort(long offset, short value);
/**
* Writes a 32 bit integer value to the memory area at the specified offset.
*
* @param offset The offset within the memory area to write the value.
* @param value The 32 bit integer value to write to the memory location.
*/
public void putInt(long offset, int value);
/**
* Writes a 64 bit integer value to the memory area at the specified offset.
*
* @param offset The offset within the memory area to write the value.
* @param value The 64 bit integer value to write to the memory location.
*/
public void putLong(long offset, long value);
/**
* Writes a native long integer value to the memory area at the specified offset.
*
* @param offset The offset within the memory area to write the value.
* @param value The native long integer value to write to the memory location.
*/
public void putNativeLong(long offset, long value);
/**
* Writes a 32 bit float value to the memory area at the specified offset.
*
* @param offset The offset within the memory area to write the value.
* @param value The 32 bit float value to write to the memory location.
*/
public void putFloat(long offset, float value);
/**
* Writes a 64 bit float value to the memory area at the specified offset.
*
* @param offset The offset within the memory area to write the value.
* @param value The 64 bit float value to write to the memory location.
*/
public void putDouble(long offset, double value);
/**
* Writes a pointer value to the memory area at the specified offset.
*
* @param offset The offset within the memory area to write the value.
* @param value The pointer value to write to the memory location.
*/
public void putAddress(long offset, Memory value);
/**
* Writes a pointer value to the memory area at the specified offset.
*
* @param offset The offset within the memory area to write the value.
* @param value The pointer value to write to the memory location.
*/
public void putAddress(long offset, long value);
/**
* Writes a byte array to memory, and appends a zero terminator
*
* @param offset The offset within the memory area of the start of the string.
* @param bytes The byte array to write to the memory.
* @param off The offset with the byte array to start copying.
- * @param maxlen The number of bytes of the byte array to write to the memory area. (not including zero byte)
+ * @param len The number of bytes of the byte array to write to the memory area. (not including zero byte)
*/
public void putZeroTerminatedByteArray(long offset, byte[] bytes, int off, int len);
/**
* Reads an array of bytes from the memory area at the specified offset.
*
* @param offset The offset within the memory area to read the bytes.
* @param dst The output byte array to place the data.
* @param off The offset within the byte array to start copying.
* @param len The length of data to read.
*/
public void get(long offset, byte[] dst, int off, int len);
/**
* Writes an array of bytes to the memory area at the specified offset.
*
* @param offset The offset within the memory area to start writing the bytes.
* @param src The byte array to write to the memory area.
* @param off The offset within the byte array to start copying.
* @param len The length of data to write.
*/
public void put(long offset, byte[] src, int off, int len);
/**
* Reads an array of shorts from the memory area at the specified offset.
*
* @param offset The offset within the memory area to read the shorts.
* @param dst The output array to place the data in.
* @param off The offset within the array to start copying.
* @param len The number of shorts to read.
*/
public void get(long offset, short[] dst, int off, int len);
/**
* Writes an array of shorts to the memory area at the specified offset.
*
* @param offset The offset within the memory area to start writing the shorts.
* @param src The array to write to the memory area.
* @param off The offset within the array to start copying.
* @param len The number of shorts to write.
*/
public void put(long offset, short[] src, int off, int len);
/**
* Reads an array of ints from the memory area at the specified offset.
*
* @param offset The offset within the memory area to read the ints.
* @param dst The output array to place the data in.
* @param off The offset within the array to start copying.
* @param len The number of ints to read.
*/
public void get(long offset, int[] dst, int off, int len);
/**
* Writes an array of ints to the memory area at the specified offset.
*
* @param offset The offset within the memory area to start writing the ints.
* @param src The array to write to the memory area.
* @param off The offset within the array to start copying.
* @param len The number of ints to write.
*/
public void put(long offset, int[] src, int off, int len);
/**
* Reads an array of longs from the memory area at the specified offset.
*
* @param offset The offset within the memory area to read the longs.
* @param dst The output array to place the data in.
* @param off The offset within the array to start copying.
* @param len The number of longs to read.
*/
public void get(long offset, long[] dst, int off, int len);
/**
* Writes an array of longs to the memory area at the specified offset.
*
* @param offset The offset within the memory area to start writing the longs.
* @param src The array to write to the memory area.
* @param off The offset within the array to start copying.
* @param len The number of longs to write.
*/
public void put(long offset, long[] src, int off, int len);
/**
* Reads an array of floats from the memory area at the specified offset.
*
* @param offset The offset within the memory area to read the floats.
* @param dst The output array to place the data in.
* @param off The offset within the array to start copying.
* @param len The number of floats to read.
*/
public void get(long offset, float[] dst, int off, int len);
/**
* Writes an array of floats to the memory area at the specified offset.
*
* @param offset The offset within the memory area to start writing the floats.
* @param src The array to write to the memory area.
* @param off The offset within the array to start copying.
* @param len The number of floats to write.
*/
public void put(long offset, float[] src, int off, int len);
/**
* Reads an array of doubles from the memory area at the specified offset.
*
* @param offset The offset within the memory area to read the doubles.
* @param dst The output array to place the data in.
* @param off The offset within the array to start copying.
* @param len The number of doubles to read.
*/
public void get(long offset, double[] dst, int off, int len);
/**
* Writes an array of doubles to the memory area at the specified offset.
*
* @param offset The offset within the memory area to start writing the doubles.
* @param src The array to write to the memory area.
* @param off The offset within the array to start copying.
* @param len The number of doubles to write.
*/
public void put(long offset, double[] src, int off, int len);
/**
* Gets the first index within the memory area of a particular 8 bit value.
*
* @param offset The offset within the memory area to start searching.
* @param value The value to search for.
*
* @return The index of the value, relative to offset.
*/
public int indexOf(long offset, byte value);
/**
* Gets the first index within the memory area of a particular 8 bit value.
*
* @param offset The offset within the memory area to start searching.
* @param value The value to search for.
*
* @return The index of the value, relative to offset.
*/
public int indexOf(long offset, byte value, int maxlen);
/**
* Sets the contents of the memory area to the value.
*
* @param offset The offset within the memory area to start writing.
* @param size The number of bytes to set to the value.
* @param value The value to set each byte to.
*/
public void setMemory(long offset, long size, byte value);
}
| true | false | null | null |
diff --git a/src/org/jrubyparser/parser/Ruby19Parser.java b/src/org/jrubyparser/parser/Ruby19Parser.java
index 65d3acc..95e0d42 100644
--- a/src/org/jrubyparser/parser/Ruby19Parser.java
+++ b/src/org/jrubyparser/parser/Ruby19Parser.java
@@ -1,4247 +1,4247 @@
// created by jay 1.0.2 (c) 2002-2004 [email protected]
// skeleton Java 1.0 (c) 2002 [email protected]
// line 2 "Ruby19parser.y"
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2008-2009 Thomas E Enebo <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jrubyparser.parser;
import java.io.IOException;
import org.jrubyparser.ast.ArgsNode;
import org.jrubyparser.ast.ArgumentNode;
import org.jrubyparser.ast.ArrayNode;
import org.jrubyparser.ast.AssignableNode;
import org.jrubyparser.ast.BackRefNode;
import org.jrubyparser.ast.BeginNode;
import org.jrubyparser.ast.BlockAcceptingNode;
import org.jrubyparser.ast.BlockArgNode;
import org.jrubyparser.ast.BlockNode;
import org.jrubyparser.ast.BlockPassNode;
import org.jrubyparser.ast.BreakNode;
import org.jrubyparser.ast.ClassNode;
import org.jrubyparser.ast.ClassVarNode;
import org.jrubyparser.ast.Colon3Node;
import org.jrubyparser.ast.ConstDeclNode;
import org.jrubyparser.ast.DStrNode;
import org.jrubyparser.ast.DSymbolNode;
import org.jrubyparser.ast.DXStrNode;
import org.jrubyparser.ast.DefinedNode;
import org.jrubyparser.ast.DefnNode;
import org.jrubyparser.ast.DefsNode;
import org.jrubyparser.ast.DotNode;
import org.jrubyparser.ast.EnsureNode;
import org.jrubyparser.ast.EvStrNode;
import org.jrubyparser.ast.FixnumNode;
import org.jrubyparser.ast.FloatNode;
import org.jrubyparser.ast.ForNode;
import org.jrubyparser.ast.GlobalVarNode;
import org.jrubyparser.ast.HashNode;
import org.jrubyparser.ast.IfNode;
import org.jrubyparser.ast.InstVarNode;
import org.jrubyparser.ast.IterNode;
import org.jrubyparser.ast.LambdaNode;
import org.jrubyparser.ast.ListNode;
import org.jrubyparser.ast.LiteralNode;
import org.jrubyparser.ast.ModuleNode;
import org.jrubyparser.ast.MultipleAsgn19Node;
import org.jrubyparser.ast.NextNode;
import org.jrubyparser.ast.NilImplicitNode;
import org.jrubyparser.ast.Node;
import org.jrubyparser.ast.NotNode;
import org.jrubyparser.ast.OpAsgnAndNode;
import org.jrubyparser.ast.OpAsgnNode;
import org.jrubyparser.ast.OpAsgnOrNode;
import org.jrubyparser.ast.OptArgNode;
import org.jrubyparser.ast.PostExeNode;
import org.jrubyparser.ast.PreExe19Node;
import org.jrubyparser.ast.RedoNode;
import org.jrubyparser.ast.RegexpNode;
import org.jrubyparser.ast.RescueBodyNode;
import org.jrubyparser.ast.RescueNode;
import org.jrubyparser.ast.RestArgNode;
import org.jrubyparser.ast.RetryNode;
import org.jrubyparser.ast.ReturnNode;
import org.jrubyparser.ast.SClassNode;
import org.jrubyparser.ast.SelfNode;
import org.jrubyparser.ast.StarNode;
import org.jrubyparser.ast.StrNode;
import org.jrubyparser.ast.SymbolNode;
import org.jrubyparser.ast.UnnamedRestArgNode;
import org.jrubyparser.ast.UntilNode;
import org.jrubyparser.ast.VAliasNode;
import org.jrubyparser.ast.WhileNode;
import org.jrubyparser.ast.XStrNode;
import org.jrubyparser.ast.YieldNode;
import org.jrubyparser.ast.ZArrayNode;
import org.jrubyparser.ast.ZSuperNode;
import org.jrubyparser.ast.ZYieldNode;
import org.jrubyparser.ast.ILiteralNode;
import org.jrubyparser.BlockStaticScope;
import org.jrubyparser.IRubyWarnings;
import org.jrubyparser.IRubyWarnings.ID;
import org.jrubyparser.SourcePosition;
import org.jrubyparser.ISourcePositionHolder;
import org.jrubyparser.lexer.LexerSource;
import org.jrubyparser.lexer.Lexer;
import org.jrubyparser.lexer.Lexer.LexState;
import org.jrubyparser.lexer.StrTerm;
import org.jrubyparser.lexer.SyntaxException;
import org.jrubyparser.lexer.SyntaxException.PID;
import org.jrubyparser.lexer.Token;
public class Ruby19Parser implements RubyParser {
protected ParserSupport19 support;
protected Lexer lexer;
public Ruby19Parser() {
this(new ParserSupport19());
}
public Ruby19Parser(ParserSupport19 support) {
this.support = support;
lexer = new Lexer(false);
lexer.setParserSupport(support);
support.setLexer(lexer);
}
public void setWarnings(IRubyWarnings warnings) {
support.setWarnings(warnings);
lexer.setWarnings(warnings);
}
// line 138 "-"
// %token constants
public static final int kCLASS = 257;
public static final int kMODULE = 258;
public static final int kDEF = 259;
public static final int kUNDEF = 260;
public static final int kBEGIN = 261;
public static final int kRESCUE = 262;
public static final int kENSURE = 263;
public static final int kEND = 264;
public static final int kIF = 265;
public static final int kUNLESS = 266;
public static final int kTHEN = 267;
public static final int kELSIF = 268;
public static final int kELSE = 269;
public static final int kCASE = 270;
public static final int kWHEN = 271;
public static final int kWHILE = 272;
public static final int kUNTIL = 273;
public static final int kFOR = 274;
public static final int kBREAK = 275;
public static final int kNEXT = 276;
public static final int kREDO = 277;
public static final int kRETRY = 278;
public static final int kIN = 279;
public static final int kDO = 280;
public static final int kDO_COND = 281;
public static final int kDO_BLOCK = 282;
public static final int kRETURN = 283;
public static final int kYIELD = 284;
public static final int kSUPER = 285;
public static final int kSELF = 286;
public static final int kNIL = 287;
public static final int kTRUE = 288;
public static final int kFALSE = 289;
public static final int kAND = 290;
public static final int kOR = 291;
public static final int kNOT = 292;
public static final int kIF_MOD = 293;
public static final int kUNLESS_MOD = 294;
public static final int kWHILE_MOD = 295;
public static final int kUNTIL_MOD = 296;
public static final int kRESCUE_MOD = 297;
public static final int kALIAS = 298;
public static final int kDEFINED = 299;
public static final int klBEGIN = 300;
public static final int klEND = 301;
public static final int k__LINE__ = 302;
public static final int k__FILE__ = 303;
public static final int k__ENCODING__ = 304;
public static final int kDO_LAMBDA = 305;
public static final int tIDENTIFIER = 306;
public static final int tFID = 307;
public static final int tGVAR = 308;
public static final int tIVAR = 309;
public static final int tCONSTANT = 310;
public static final int tCVAR = 311;
public static final int tLABEL = 312;
public static final int tCHAR = 313;
public static final int tUPLUS = 314;
public static final int tUMINUS = 315;
public static final int tUMINUS_NUM = 316;
public static final int tPOW = 317;
public static final int tCMP = 318;
public static final int tEQ = 319;
public static final int tEQQ = 320;
public static final int tNEQ = 321;
public static final int tGEQ = 322;
public static final int tLEQ = 323;
public static final int tANDOP = 324;
public static final int tOROP = 325;
public static final int tMATCH = 326;
public static final int tNMATCH = 327;
public static final int tDOT = 328;
public static final int tDOT2 = 329;
public static final int tDOT3 = 330;
public static final int tAREF = 331;
public static final int tASET = 332;
public static final int tLSHFT = 333;
public static final int tRSHFT = 334;
public static final int tCOLON2 = 335;
public static final int tCOLON3 = 336;
public static final int tOP_ASGN = 337;
public static final int tASSOC = 338;
public static final int tLPAREN = 339;
public static final int tLPAREN2 = 340;
public static final int tRPAREN = 341;
public static final int tLPAREN_ARG = 342;
public static final int tLBRACK = 343;
public static final int tRBRACK = 344;
public static final int tLBRACE = 345;
public static final int tLBRACE_ARG = 346;
public static final int tSTAR = 347;
public static final int tSTAR2 = 348;
public static final int tAMPER = 349;
public static final int tAMPER2 = 350;
public static final int tTILDE = 351;
public static final int tPERCENT = 352;
public static final int tDIVIDE = 353;
public static final int tPLUS = 354;
public static final int tMINUS = 355;
public static final int tLT = 356;
public static final int tGT = 357;
public static final int tPIPE = 358;
public static final int tBANG = 359;
public static final int tCARET = 360;
public static final int tLCURLY = 361;
public static final int tRCURLY = 362;
public static final int tBACK_REF2 = 363;
public static final int tSYMBEG = 364;
public static final int tSTRING_BEG = 365;
public static final int tXSTRING_BEG = 366;
public static final int tREGEXP_BEG = 367;
public static final int tWORDS_BEG = 368;
public static final int tQWORDS_BEG = 369;
public static final int tSTRING_DBEG = 370;
public static final int tSTRING_DVAR = 371;
public static final int tSTRING_END = 372;
public static final int tLAMBDA = 373;
public static final int tLAMBEG = 374;
public static final int tNTH_REF = 375;
public static final int tBACK_REF = 376;
public static final int tSTRING_CONTENT = 377;
public static final int tINTEGER = 378;
public static final int tFLOAT = 379;
public static final int tREGEXP_END = 380;
public static final int tCOMMENT = 381;
public static final int tWHITESPACE = 382;
public static final int tDOCUMENTATION = 383;
public static final int tLOWEST = 384;
public static final int yyErrorCode = 256;
/** number of final state.
*/
protected static final int yyFinal = 1;
/** parser tables.
Order is mandated by <i>jay</i>.
*/
protected static final short[] yyLhs = {
//yyLhs 542
-1, 117, 0, 34, 33, 35, 35, 35, 35, 120,
36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
121, 36, 36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 37, 37, 37, 37, 37,
37, 41, 32, 32, 32, 32, 32, 55, 55, 55,
123, 94, 40, 40, 40, 40, 40, 40, 40, 40,
95, 95, 106, 106, 96, 96, 96, 96, 96, 96,
96, 96, 96, 96, 67, 67, 81, 81, 85, 85,
68, 68, 68, 68, 68, 68, 68, 68, 73, 73,
73, 73, 73, 73, 73, 73, 7, 7, 31, 31,
31, 8, 8, 8, 8, 8, 99, 99, 100, 100,
57, 124, 57, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 115, 115, 115, 115, 115, 115, 115, 115,
115, 115, 115, 115, 115, 115, 115, 115, 115, 115,
115, 115, 115, 115, 115, 115, 115, 115, 115, 115,
115, 115, 115, 115, 115, 115, 115, 115, 115, 115,
115, 115, 115, 115, 38, 38, 38, 38, 38, 38,
38, 38, 38, 38, 38, 38, 38, 38, 38, 38,
38, 38, 38, 38, 38, 38, 38, 38, 38, 38,
38, 38, 38, 38, 38, 38, 38, 38, 38, 38,
38, 38, 38, 38, 38, 38, 38, 38, 38, 69,
72, 72, 72, 72, 49, 53, 53, 109, 109, 47,
47, 47, 47, 47, 126, 51, 88, 87, 87, 87,
75, 75, 75, 75, 66, 66, 66, 39, 39, 39,
39, 39, 39, 39, 39, 39, 39, 127, 39, 39,
39, 39, 39, 39, 39, 39, 39, 39, 39, 39,
39, 39, 39, 39, 39, 39, 39, 129, 131, 39,
132, 133, 39, 39, 39, 134, 135, 39, 136, 39,
138, 139, 39, 140, 39, 141, 39, 142, 143, 39,
39, 39, 39, 39, 42, 128, 128, 128, 130, 130,
45, 45, 43, 43, 108, 108, 110, 110, 80, 80,
111, 111, 111, 111, 111, 111, 111, 111, 111, 63,
63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
63, 63, 63, 63, 65, 65, 64, 64, 64, 103,
103, 102, 102, 112, 112, 144, 105, 62, 62, 104,
104, 145, 93, 54, 54, 54, 24, 24, 24, 24,
24, 24, 24, 24, 24, 146, 92, 147, 92, 70,
44, 44, 97, 97, 71, 71, 71, 46, 46, 48,
48, 28, 28, 28, 16, 17, 17, 17, 18, 19,
20, 25, 25, 77, 77, 27, 27, 26, 26, 76,
76, 21, 21, 22, 22, 23, 148, 23, 149, 23,
58, 58, 58, 58, 3, 2, 2, 2, 2, 30,
29, 29, 29, 29, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 52, 98, 59, 59,
50, 150, 50, 50, 61, 61, 60, 60, 60, 60,
60, 60, 60, 60, 60, 60, 60, 60, 60, 60,
60, 116, 116, 116, 116, 10, 10, 101, 101, 78,
78, 56, 107, 86, 86, 79, 79, 12, 12, 14,
14, 13, 13, 91, 90, 90, 15, 151, 15, 84,
84, 82, 82, 83, 83, 4, 4, 4, 5, 5,
5, 5, 6, 6, 6, 11, 11, 118, 118, 122,
122, 113, 114, 125, 125, 125, 137, 137, 119, 119,
74, 89,
}, yyLen = {
//yyLen 542
2, 0, 2, 4, 2, 1, 1, 3, 2, 0,
4, 3, 3, 3, 2, 3, 3, 3, 3, 3,
0, 5, 4, 3, 3, 3, 6, 5, 5, 5,
3, 3, 3, 3, 1, 1, 3, 3, 3, 2,
1, 1, 1, 1, 2, 2, 2, 1, 4, 4,
0, 5, 2, 3, 4, 5, 4, 5, 2, 2,
1, 3, 1, 3, 1, 2, 3, 5, 2, 4,
2, 4, 1, 3, 1, 3, 2, 3, 1, 3,
1, 4, 3, 3, 3, 3, 2, 1, 1, 4,
3, 3, 3, 3, 2, 1, 1, 1, 2, 1,
3, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 0, 4, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 3, 5, 3, 5, 6, 5,
5, 5, 5, 4, 3, 3, 3, 3, 3, 3,
3, 3, 3, 4, 4, 2, 2, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2, 2, 3, 3, 3, 3, 3, 6, 1, 1,
1, 2, 4, 2, 3, 1, 1, 1, 1, 1,
2, 2, 4, 1, 0, 2, 2, 2, 1, 1,
1, 2, 3, 4, 3, 4, 2, 1, 1, 1,
1, 1, 1, 1, 1, 1, 3, 0, 4, 3,
3, 2, 3, 3, 1, 4, 3, 1, 5, 4,
3, 2, 1, 2, 2, 6, 6, 0, 0, 7,
0, 0, 7, 5, 4, 0, 0, 9, 0, 6,
0, 0, 8, 0, 5, 0, 6, 0, 0, 9,
1, 1, 1, 1, 1, 1, 1, 2, 1, 1,
1, 5, 1, 2, 1, 1, 1, 3, 1, 3,
1, 4, 6, 3, 5, 2, 4, 1, 3, 6,
8, 4, 6, 4, 2, 6, 2, 4, 6, 2,
4, 2, 4, 1, 1, 1, 3, 1, 4, 1,
2, 1, 3, 1, 1, 0, 3, 4, 2, 3,
3, 0, 5, 2, 4, 4, 2, 4, 4, 3,
3, 3, 2, 1, 4, 0, 5, 0, 5, 5,
1, 1, 6, 0, 1, 1, 1, 2, 1, 2,
1, 1, 1, 1, 1, 1, 1, 2, 3, 3,
3, 3, 3, 0, 3, 1, 2, 3, 3, 0,
3, 0, 2, 0, 2, 1, 0, 3, 0, 4,
1, 1, 1, 1, 2, 1, 1, 1, 1, 3,
1, 1, 2, 2, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 0, 4, 2, 3, 2, 6, 8, 4, 6,
4, 6, 2, 4, 6, 2, 4, 2, 4, 1,
0, 1, 1, 1, 1, 1, 1, 1, 3, 1,
3, 3, 3, 1, 3, 1, 3, 1, 1, 2,
1, 1, 1, 2, 2, 0, 1, 0, 4, 1,
2, 1, 3, 3, 2, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 0, 1, 0,
1, 2, 2, 0, 1, 1, 1, 1, 1, 2,
0, 0,
}, yyDefRed = {
//yyDefRed 946
1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 287, 290, 0, 0, 0, 312, 313, 0,
0, 0, 450, 449, 451, 452, 0, 0, 0, 20,
0, 454, 453, 455, 0, 0, 446, 445, 0, 448,
405, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 421, 423, 423, 0, 0, 365, 458,
459, 440, 441, 0, 402, 0, 258, 0, 406, 259,
260, 0, 261, 262, 257, 401, 403, 35, 2, 0,
0, 0, 0, 0, 0, 0, 263, 0, 43, 0,
0, 74, 0, 5, 0, 0, 60, 0, 0, 310,
311, 274, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 456, 0, 99, 0, 314, 0, 264, 303,
152, 163, 153, 176, 149, 169, 159, 158, 174, 157,
156, 151, 177, 161, 150, 164, 168, 170, 162, 155,
171, 178, 173, 0, 0, 0, 0, 148, 167, 166,
179, 180, 181, 182, 183, 147, 154, 145, 146, 0,
0, 0, 0, 103, 0, 137, 138, 134, 116, 117,
118, 125, 122, 124, 119, 120, 139, 140, 126, 127,
507, 131, 130, 115, 136, 133, 132, 128, 129, 123,
121, 113, 135, 114, 141, 305, 104, 0, 506, 105,
172, 165, 175, 160, 142, 143, 144, 101, 102, 107,
106, 109, 0, 108, 110, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 536, 537, 0, 0,
0, 538, 0, 0, 0, 0, 0, 0, 324, 325,
0, 0, 0, 0, 0, 0, 239, 45, 0, 0,
0, 511, 243, 46, 44, 0, 59, 0, 0, 382,
58, 0, 530, 0, 0, 9, 0, 0, 0, 205,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 230, 0, 0, 0, 509, 0, 0, 0, 0,
0, 0, 0, 0, 221, 39, 220, 437, 436, 438,
434, 435, 0, 0, 0, 0, 0, 0, 0, 0,
284, 0, 387, 385, 376, 0, 281, 407, 283, 4,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 371, 373, 0, 0, 0, 0,
0, 0, 76, 0, 0, 0, 0, 0, 0, 0,
442, 443, 0, 96, 0, 98, 0, 461, 298, 460,
0, 0, 0, 0, 0, 0, 525, 526, 307, 111,
0, 0, 266, 0, 316, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 539, 0, 0,
0, 0, 0, 0, 295, 514, 251, 246, 0, 0,
240, 249, 0, 241, 0, 276, 0, 245, 238, 237,
0, 0, 280, 38, 11, 13, 12, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 269, 0,
0, 272, 0, 534, 231, 0, 233, 510, 273, 0,
78, 0, 0, 0, 0, 0, 428, 426, 439, 425,
424, 408, 422, 409, 410, 411, 412, 415, 0, 417,
418, 0, 0, 483, 482, 481, 484, 0, 0, 498,
497, 502, 501, 487, 0, 0, 0, 495, 0, 0,
0, 0, 479, 489, 485, 0, 0, 50, 53, 0,
15, 16, 17, 18, 19, 36, 37, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 520, 0, 0, 521, 380,
0, 0, 0, 0, 379, 0, 381, 0, 518, 519,
0, 0, 30, 0, 0, 23, 0, 31, 250, 0,
0, 0, 0, 77, 24, 33, 0, 25, 0, 0,
463, 0, 0, 0, 0, 0, 0, 100, 0, 0,
0, 0, 0, 0, 0, 0, 395, 0, 0, 396,
0, 0, 322, 0, 317, 0, 0, 0, 0, 0,
0, 0, 0, 0, 294, 319, 288, 318, 291, 0,
0, 0, 0, 0, 0, 513, 0, 0, 0, 247,
512, 275, 531, 234, 279, 10, 0, 0, 22, 0,
0, 0, 0, 268, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 414, 416, 420, 0, 486, 0,
0, 326, 0, 328, 0, 0, 499, 503, 0, 477,
0, 359, 368, 0, 0, 366, 0, 472, 0, 475,
357, 0, 355, 0, 354, 0, 0, 0, 0, 0,
0, 236, 0, 377, 235, 0, 0, 378, 0, 0,
0, 48, 374, 49, 375, 0, 0, 0, 75, 0,
0, 0, 301, 0, 0, 384, 304, 508, 0, 465,
0, 308, 112, 0, 0, 398, 323, 0, 3, 400,
0, 320, 0, 0, 0, 0, 0, 0, 293, 0,
0, 0, 0, 0, 0, 253, 242, 278, 21, 232,
79, 0, 0, 430, 431, 432, 427, 433, 491, 0,
0, 0, 0, 488, 0, 0, 504, 363, 0, 361,
364, 0, 0, 0, 0, 490, 0, 496, 0, 0,
0, 0, 0, 0, 353, 0, 493, 0, 0, 0,
0, 0, 27, 0, 28, 0, 55, 29, 0, 0,
57, 0, 532, 0, 0, 0, 0, 0, 0, 462,
299, 464, 306, 0, 0, 0, 0, 0, 397, 0,
399, 0, 285, 0, 286, 252, 0, 0, 0, 296,
429, 327, 0, 0, 0, 329, 367, 0, 478, 0,
370, 369, 0, 470, 0, 468, 0, 473, 476, 0,
0, 351, 0, 0, 346, 0, 349, 356, 388, 386,
0, 0, 372, 26, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 390, 389, 391, 289, 292, 0,
0, 0, 0, 0, 362, 0, 0, 0, 0, 0,
0, 0, 358, 0, 0, 0, 0, 494, 51, 302,
0, 0, 0, 0, 0, 0, 392, 0, 0, 0,
0, 471, 0, 466, 469, 474, 271, 0, 352, 0,
343, 0, 341, 0, 347, 350, 309, 0, 321, 297,
0, 0, 0, 0, 0, 0, 0, 0, 467, 345,
0, 339, 342, 348, 0, 340,
}, yyDgoto = {
//yyDgoto 152
1, 218, 300, 64, 113, 586, 554, 114, 210, 548,
493, 388, 494, 495, 496, 197, 66, 67, 68, 69,
70, 303, 302, 470, 71, 72, 73, 478, 74, 75,
76, 115, 77, 215, 216, 79, 80, 81, 82, 83,
84, 220, 270, 731, 875, 732, 724, 428, 728, 556,
378, 256, 86, 693, 87, 88, 497, 212, 756, 222,
592, 593, 499, 781, 682, 683, 567, 90, 91, 248,
406, 598, 280, 223, 93, 249, 309, 307, 500, 501,
662, 94, 250, 251, 287, 461, 783, 420, 252, 421,
669, 766, 316, 355, 508, 95, 96, 391, 224, 213,
214, 503, 768, 672, 675, 310, 278, 786, 240, 430,
663, 664, 769, 425, 699, 199, 504, 2, 229, 230,
437, 267, 426, 686, 595, 454, 257, 450, 395, 232,
616, 741, 233, 742, 624, 879, 582, 396, 579, 808,
383, 385, 594, 813, 311, 543, 506, 505, 653, 652,
581, 384,
}, yySindex = {
//yySindex 946
0, 0, 14286, 14533, 5754, 17116, 17824, 17716, 14286, 16378,
16378, 12474, 0, 0, 16870, 14656, 14656, 0, 0, 14656,
-218, -207, 0, 0, 0, 0, -3, 17608, 152, 0,
-176, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 16501, 16501, -135, -76, 14410, 16378, 15025, 15394, 12647,
16501, 16624, 17931, 0, 0, 0, 223, 228, 0, 0,
0, 0, 0, 0, 0, -208, 0, -95, 0, 0,
0, -205, 0, 0, 0, 0, 0, 0, 0, 90,
1218, 58, 4667, 0, -8, 335, 0, -100, 0, -48,
259, 0, 244, 0, 16993, 250, 0, -20, 1218, 0,
0, 0, -218, -207, -11, 152, 0, 0, 164, 16378,
-200, 14286, 0, -208, 0, 66, 0, 378, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, -56, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 276, 0, 0, 74, 88, 62, 0, 58,
83, 446, -5, 295, 113, 83, 0, 0, 90, 206,
432, 0, 16378, 16378, 211, 0, 488, 0, 0, 0,
245, 16501, 16501, 16501, 16501, 4667, 0, 0, 201, 500,
503, 0, 0, 0, 0, 3238, 0, 14656, 14656, 0,
0, 4224, 0, 16378, -150, 0, 15517, 191, 14286, 0,
575, 260, 263, 273, 288, 14410, 256, 0, 152, 58,
292, 0, 72, 160, 201, 0, 160, 302, 347, 17239,
0, 592, 0, 625, 0, 0, 0, 0, 0, 0,
0, 0, -86, 278, 655, 369, 299, 730, 303, -132,
0, 2263, 0, 0, 0, 338, 0, 0, 0, 0,
14162, 16378, 16378, 16378, 16378, 14533, 16378, 16378, 16501, 16501,
16501, 16501, 16501, 16501, 16501, 16501, 16501, 16501, 16501, 16501,
16501, 16501, 16501, 16501, 16501, 16501, 16501, 16501, 16501, 16501,
16501, 16501, 16501, 16501, 0, 0, 1849, 2207, 14656, 18533,
18533, 16624, 0, 15640, 14410, 14039, 645, 15640, 16624, 351,
0, 0, 58, 0, 0, 0, 90, 0, 0, 0,
2737, 3723, 14656, 14286, 16378, 2278, 0, 0, 0, 0,
15763, 428, 0, 288, 0, 14286, 433, 6321, 18093, 14656,
16501, 16501, 16501, 14286, 206, 15886, 452, 0, 35, 35,
0, 18148, 18203, 14656, 0, 0, 0, 0, 16501, 14779,
0, 0, 15148, 0, 152, 0, 376, 0, 0, 0,
152, 270, 0, 0, 0, 0, 0, 17716, 16378, 4667,
14286, 356, 6321, 18093, 16501, 16501, 16501, 152, 0, 0,
152, 0, 15271, 0, 0, 15394, 0, 0, 0, 0,
0, 677, 18258, 18313, 14656, 17239, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 143, 0,
0, 692, 671, 0, 0, 0, 0, 1614, 2341, 0,
0, 0, 0, 0, 427, 430, 693, 0, 685, -198,
704, 707, 0, 0, 0, -117, -117, 0, 0, 1218,
0, 0, 0, 0, 0, 0, 0, 260, 2827, 2827,
2827, 2827, 2350, 2350, 4301, 3771, 2827, 2827, 2785, 2785,
1450, 1450, 260, 2685, 260, 260, 325, 325, 2350, 2350,
2645, 2645, 2152, -117, 419, 0, 420, -207, 0, 0,
429, 0, 443, -207, 0, 0, 0, 152, 0, 0,
-207, -207, 0, 4667, 16501, 0, 4736, 0, 0, 721,
152, 17239, 726, 0, 0, 0, 0, 0, 5227, 90,
0, 16378, 14286, -207, 0, 0, -207, 0, 152, 529,
270, 2341, 90, 14286, 18038, 17716, 0, 0, 459, 0,
14286, 547, 0, 298, 0, 461, 474, 477, 443, 152,
4736, 428, 553, 962, 0, 0, 0, 0, 0, 0,
0, 0, 0, 152, 16378, 0, 16501, 201, 503, 0,
0, 0, 0, 0, 0, 0, 270, 453, 0, 260,
260, 4667, 0, 0, 160, 17239, 0, 0, 0, 0,
152, 677, 14286, 844, 0, 0, 0, 16501, 0, 1614,
641, 0, 774, 0, 152, 685, 0, 0, 1680, 0,
1347, 0, 0, 14286, 14286, 0, 2341, 0, 2341, 0,
0, 937, 0, 14286, 0, 14286, -117, 764, 14286, 16624,
16624, 0, 338, 0, 0, 16624, 16501, 0, 338, 494,
489, 0, 0, 0, 0, 0, 16501, 16009, 0, 677,
17239, 16501, 0, 90, 568, 0, 0, 0, 152, 0,
570, 0, 0, 17362, 83, 0, 0, 14286, 0, 0,
16378, 0, 585, 16501, 16501, 16501, 515, 595, 0, 16132,
14286, 14286, 14286, 0, 35, 0, 0, 0, 0, 0,
0, 0, 496, 0, 0, 0, 0, 0, 0, 152,
1266, 819, 1701, 0, 152, 822, 0, 0, 823, 0,
0, 604, 508, 830, 833, 0, 835, 0, 822, 821,
840, 685, 842, 845, 0, 548, 0, 634, 543, 14286,
16501, 643, 0, 4667, 0, 4667, 0, 0, 4667, 4667,
0, 16624, 0, 4667, 16501, 0, 677, 4667, 14286, 0,
0, 0, 0, 2278, 598, 0, 636, 0, 0, 14286,
0, 83, 0, 16501, 0, 0, 33, 660, 664, 0,
0, 0, 885, 1266, 829, 0, 0, 1680, 0, 1347,
0, 0, 1680, 0, 2341, 0, 1680, 0, 0, 17485,
1680, 0, 572, 2347, 0, 2347, 0, 0, 0, 0,
577, 4667, 0, 0, 4667, 0, 689, 14286, 0, 18368,
18423, 14656, 74, 14286, 0, 0, 0, 0, 0, 14286,
1266, 885, 1266, 912, 0, 822, 913, 822, 822, 651,
717, 822, 0, 918, 923, 924, 822, 0, 0, 0,
706, 0, 0, 0, 0, 152, 0, 298, 720, 885,
1266, 0, 1680, 0, 0, 0, 0, 18478, 0, 1680,
0, 2347, 0, 1680, 0, 0, 0, 0, 0, 0,
885, 822, 0, 0, 822, 948, 822, 822, 0, 0,
1680, 0, 0, 0, 822, 0,
}, yyRindex = {
//yyRindex 946
0, 0, 209, 0, 0, 0, 0, 0, 593, 0,
0, 723, 0, 0, 0, 12812, 12918, 0, 0, 13060,
4552, 4059, 0, 0, 0, 0, 16747, 0, 16255, 0,
0, 0, 0, 0, 1964, 3073, 0, 0, 2087, 0,
0, 0, 0, 0, 0, 68, 0, 653, 646, 54,
0, 0, 787, 0, 0, 0, 860, -90, 0, 0,
0, 0, 0, 13163, 0, 14902, 0, 6685, 0, 0,
0, 6786, 0, 0, 0, 0, 0, 0, 0, 633,
582, 10194, 1054, 6930, 1417, 0, 0, 13811, 0, 13277,
0, 0, 0, 0, 107, 0, 0, 0, 1002, 0,
0, 0, 7034, 5991, 0, 669, 11442, 11566, 0, 0,
0, 68, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1280, 2326, 2677, 2819, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 3312,
3663, 3805, 4298, 0, 5133, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 11209, 0, 0, 490, 0, 0, 6105, 5159,
0, 0, 6437, 0, 0, 0, 0, 0, 723, 0,
743, 0, 0, 0, 0, 708, 0, 734, 0, 0,
0, 0, 0, 0, 0, 11138, 0, 0, 13522, 4670,
4670, 0, 0, 0, 0, 674, 0, 0, 22, 0,
0, 674, 0, 0, 0, 0, 0, 0, 2, 0,
0, 7395, 7147, 7279, 13411, 68, 0, 111, 674, 70,
0, 0, 673, 673, 0, 0, 657, 0, 0, 0,
449, 0, 916, 110, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, -43, 0, 0, 0, 13626, 0, 0, 0, 0,
827, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 9, 0,
0, 0, 0, 0, 68, 129, 137, 0, 0, 0,
0, 0, 124, 0, 11958, 0, 0, 0, 0, 0,
0, 0, 9, 593, 0, 144, 0, 0, 0, 0,
296, 323, 0, 6571, 0, 28, 12082, 0, 0, 9,
0, 0, 0, 735, 0, 0, 0, 0, 0, 0,
751, 0, 0, 9, 0, 0, 0, 0, 0, 5648,
0, 0, 5648, 0, 674, 0, 0, 0, 0, 0,
674, 674, 0, 0, 0, 0, 0, 0, 0, 1302,
2, 0, 0, 0, 0, 0, 0, 674, 0, 188,
674, 0, 676, 0, 0, -114, 0, 0, 0, 5039,
0, 176, 0, 0, 9, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 102, 0, 0, 0, 0, 0, 79, 0,
0, 0, 0, 0, 134, 0, 130, 0, -197, 0,
130, 130, 0, 0, 0, 12216, 12351, 0, 0, 1216,
0, 0, 0, 0, 0, 0, 0, 7496, 9460, 9582,
9700, 9797, 9005, 9125, 9883, 10156, 9973, 10070, 10246, 10286,
8425, 8547, 7611, 8670, 7744, 7859, 8208, 8321, 9245, 9342,
8788, 8896, 965, 12216, 4913, 0, 5036, 4429, 0, 0,
5406, 3443, 5529, 14902, 0, 3566, 0, 684, 0, 0,
1603, 1603, 0, 1775, 0, 0, 13977, 0, 0, 0,
674, 0, 185, 0, 0, 0, 1169, 0, 11226, 0,
0, 0, 593, 6239, 11700, 11824, 0, 0, 684, 0,
674, 131, 0, 593, 0, 0, 0, 594, 207, 0,
320, 769, 0, 769, 0, 2457, 2580, 2950, 3936, 684,
11322, 769, 0, 0, 0, 0, 0, 0, 0, 850,
1283, 1724, 279, 684, 0, 0, 0, 13565, 4670, 0,
0, 0, 0, 0, 0, 0, 674, 0, 0, 7960,
8076, 10371, 138, 0, 673, 0, 1490, 1657, 1753, 694,
684, 186, 2, 0, 0, 0, 0, 0, 0, 0,
142, 0, 149, 0, 674, 22, 0, 0, 0, 0,
0, 0, 0, 648, 2, 0, 0, 0, 0, 0,
0, 682, 0, 648, 0, 2, 12351, 0, 648, 0,
0, 0, 13662, 0, 0, 0, 0, 0, 13747, 12711,
0, 0, 0, 0, 0, 13854, 0, 0, 0, 208,
0, 0, 0, 0, 0, 0, 0, 0, 674, 0,
0, 0, 0, 0, 0, 0, 0, 648, 0, 0,
0, 0, 0, 0, 0, 0, 5890, 0, 0, 0,
712, 648, 648, 1132, 0, 0, 0, 0, 0, 0,
0, 5865, 0, 0, 0, 0, 0, 0, 0, 674,
0, 154, 0, 0, 674, 130, 0, 0, 141, 0,
0, 0, 0, 130, 130, 0, 130, 0, 130, 172,
-32, 682, -32, -32, 0, 0, 0, 0, 0, 2,
0, 0, 0, 10467, 0, 10552, 0, 0, 10613, 10710,
0, 0, 0, 10796, 0, 13891, 210, 10905, 593, 0,
0, 0, 0, 144, 0, 1001, 0, 1118, 0, 593,
0, 0, 0, 0, 0, 0, 769, 0, 0, 0,
0, 0, 155, 0, 159, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, -4, 0, 0, 0, 0, 0, 0,
0, 10966, 0, 0, 11052, 13941, 0, 593, 1181, 0,
0, 9, 490, 28, 0, 0, 0, 0, 0, 648,
0, 178, 0, 181, 0, 130, 130, 130, 130, 0,
183, -32, 0, -32, -32, -32, -32, 0, 0, 0,
0, 133, 713, 826, 991, 684, 0, 769, 0, 187,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 407, 0, 0,
190, 130, 980, 1335, -32, -32, -32, -32, 0, 0,
0, 0, 0, 0, -32, 0,
}, yyGindex = {
//yyGindex 152
0, 551, 0, 10, 248, -261, 0, -68, -1, -6,
-332, 0, 0, 0, 851, 0, 0, 0, 971, 0,
0, 0, 540, -202, 0, 0, 0, 0, 0, 0,
26, 1037, 6, 680, -370, 0, 40, 1196, 1394, 69,
43, 75, 20, -382, 0, 139, 0, 748, 0, 589,
0, -15, 1041, 120, 0, 0, -608, 0, 0, 798,
-223, 246, 0, 0, 0, -376, -264, -83, -46, -28,
-390, 0, 0, 46, 277, -29, 0, 0, 1105, 381,
-649, 0, -7, -320, 0, -398, 212, -235, -104, 0,
610, -301, 992, 0, -487, 1056, 165, 196, 615, 0,
-19, -599, 0, -602, 0, 0, -162, -727, 0, -290,
-658, 413, 237, 535, -443, 0, -618, 0, 11, 998,
0, 0, -24, 0, 0, -239, 0, 0, -199, 0,
-312, 0, 0, 0, 0, 0, 0, 45, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0,
};
protected static final short[] yyTable = Ruby19YyTables.yyTable();
protected static final short[] yyCheck = Ruby19YyTables.yyCheck();
/** maps symbol value to printable name.
@see #yyExpecting
*/
protected static final String[] yyNames = {
"end-of-file",null,null,null,null,null,null,null,null,null,"'\\n'",
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,"' '",null,null,null,null,null,
null,null,null,null,null,null,"','",null,null,null,null,null,null,
null,null,null,null,null,null,null,"':'","';'",null,"'='",null,"'?'",
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,
"'['",null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,
"kCLASS","kMODULE","kDEF","kUNDEF","kBEGIN","kRESCUE","kENSURE",
"kEND","kIF","kUNLESS","kTHEN","kELSIF","kELSE","kCASE","kWHEN",
"kWHILE","kUNTIL","kFOR","kBREAK","kNEXT","kREDO","kRETRY","kIN",
"kDO","kDO_COND","kDO_BLOCK","kRETURN","kYIELD","kSUPER","kSELF",
"kNIL","kTRUE","kFALSE","kAND","kOR","kNOT","kIF_MOD","kUNLESS_MOD",
"kWHILE_MOD","kUNTIL_MOD","kRESCUE_MOD","kALIAS","kDEFINED","klBEGIN",
"klEND","k__LINE__","k__FILE__","k__ENCODING__","kDO_LAMBDA",
"tIDENTIFIER","tFID","tGVAR","tIVAR","tCONSTANT","tCVAR","tLABEL",
"tCHAR","tUPLUS","tUMINUS","tUMINUS_NUM","tPOW","tCMP","tEQ","tEQQ",
"tNEQ","tGEQ","tLEQ","tANDOP","tOROP","tMATCH","tNMATCH","tDOT",
"tDOT2","tDOT3","tAREF","tASET","tLSHFT","tRSHFT","tCOLON2","tCOLON3",
"tOP_ASGN","tASSOC","tLPAREN","tLPAREN2","tRPAREN","tLPAREN_ARG",
"tLBRACK","tRBRACK","tLBRACE","tLBRACE_ARG","tSTAR","tSTAR2","tAMPER",
"tAMPER2","tTILDE","tPERCENT","tDIVIDE","tPLUS","tMINUS","tLT","tGT",
"tPIPE","tBANG","tCARET","tLCURLY","tRCURLY","tBACK_REF2","tSYMBEG",
"tSTRING_BEG","tXSTRING_BEG","tREGEXP_BEG","tWORDS_BEG","tQWORDS_BEG",
"tSTRING_DBEG","tSTRING_DVAR","tSTRING_END","tLAMBDA","tLAMBEG",
"tNTH_REF","tBACK_REF","tSTRING_CONTENT","tINTEGER","tFLOAT",
"tREGEXP_END","tCOMMENT","tWHITESPACE","tDOCUMENTATION","tLOWEST",
};
/** printable rules for debugging.
*/
protected static final String [] yyRule = {
"$accept : program",
"$$1 :",
"program : $$1 compstmt",
"bodystmt : compstmt opt_rescue opt_else opt_ensure",
"compstmt : stmts opt_terms",
"stmts : none",
"stmts : stmt",
"stmts : stmts terms stmt",
"stmts : error stmt",
"$$2 :",
"stmt : kALIAS fitem $$2 fitem",
"stmt : kALIAS tGVAR tGVAR",
"stmt : kALIAS tGVAR tBACK_REF",
"stmt : kALIAS tGVAR tNTH_REF",
"stmt : kUNDEF undef_list",
"stmt : stmt kIF_MOD expr_value",
"stmt : stmt kUNLESS_MOD expr_value",
"stmt : stmt kWHILE_MOD expr_value",
"stmt : stmt kUNTIL_MOD expr_value",
"stmt : stmt kRESCUE_MOD stmt",
"$$3 :",
"stmt : klBEGIN $$3 tLCURLY compstmt tRCURLY",
"stmt : klEND tLCURLY compstmt tRCURLY",
"stmt : lhs '=' command_call",
"stmt : mlhs '=' command_call",
"stmt : var_lhs tOP_ASGN command_call",
"stmt : primary_value '[' opt_call_args rbracket tOP_ASGN command_call",
"stmt : primary_value tDOT tIDENTIFIER tOP_ASGN command_call",
"stmt : primary_value tDOT tCONSTANT tOP_ASGN command_call",
"stmt : primary_value tCOLON2 tIDENTIFIER tOP_ASGN command_call",
"stmt : backref tOP_ASGN command_call",
"stmt : lhs '=' mrhs",
"stmt : mlhs '=' arg_value",
"stmt : mlhs '=' mrhs",
"stmt : expr",
"expr : command_call",
"expr : expr kAND expr",
"expr : expr kOR expr",
"expr : kNOT opt_nl expr",
"expr : tBANG command_call",
"expr : arg",
"expr_value : expr",
"command_call : command",
"command_call : block_command",
"command_call : kRETURN call_args",
"command_call : kBREAK call_args",
"command_call : kNEXT call_args",
"block_command : block_call",
"block_command : block_call tDOT operation2 command_args",
"block_command : block_call tCOLON2 operation2 command_args",
"$$4 :",
"cmd_brace_block : tLBRACE_ARG $$4 opt_block_param compstmt tRCURLY",
"command : operation command_args",
"command : operation command_args cmd_brace_block",
"command : primary_value tDOT operation2 command_args",
"command : primary_value tDOT operation2 command_args cmd_brace_block",
"command : primary_value tCOLON2 operation2 command_args",
"command : primary_value tCOLON2 operation2 command_args cmd_brace_block",
"command : kSUPER command_args",
"command : kYIELD command_args",
"mlhs : mlhs_basic",
"mlhs : tLPAREN mlhs_inner rparen",
"mlhs_inner : mlhs_basic",
"mlhs_inner : tLPAREN mlhs_inner rparen",
"mlhs_basic : mlhs_head",
"mlhs_basic : mlhs_head mlhs_item",
"mlhs_basic : mlhs_head tSTAR mlhs_node",
"mlhs_basic : mlhs_head tSTAR mlhs_node ',' mlhs_post",
"mlhs_basic : mlhs_head tSTAR",
"mlhs_basic : mlhs_head tSTAR ',' mlhs_post",
"mlhs_basic : tSTAR mlhs_node",
"mlhs_basic : tSTAR mlhs_node ',' mlhs_post",
"mlhs_basic : tSTAR",
"mlhs_basic : tSTAR ',' mlhs_post",
"mlhs_item : mlhs_node",
"mlhs_item : tLPAREN mlhs_inner rparen",
"mlhs_head : mlhs_item ','",
"mlhs_head : mlhs_head mlhs_item ','",
"mlhs_post : mlhs_item",
"mlhs_post : mlhs_post ',' mlhs_item",
"mlhs_node : variable",
"mlhs_node : primary_value '[' opt_call_args rbracket",
"mlhs_node : primary_value tDOT tIDENTIFIER",
"mlhs_node : primary_value tCOLON2 tIDENTIFIER",
"mlhs_node : primary_value tDOT tCONSTANT",
"mlhs_node : primary_value tCOLON2 tCONSTANT",
"mlhs_node : tCOLON3 tCONSTANT",
"mlhs_node : backref",
"lhs : variable",
"lhs : primary_value '[' opt_call_args rbracket",
"lhs : primary_value tDOT tIDENTIFIER",
"lhs : primary_value tCOLON2 tIDENTIFIER",
"lhs : primary_value tDOT tCONSTANT",
"lhs : primary_value tCOLON2 tCONSTANT",
"lhs : tCOLON3 tCONSTANT",
"lhs : backref",
"cname : tIDENTIFIER",
"cname : tCONSTANT",
"cpath : tCOLON3 cname",
"cpath : cname",
"cpath : primary_value tCOLON2 cname",
"fname : tIDENTIFIER",
"fname : tCONSTANT",
"fname : tFID",
"fname : op",
"fname : reswords",
"fsym : fname",
"fsym : symbol",
"fitem : fsym",
"fitem : dsym",
"undef_list : fitem",
"$$5 :",
"undef_list : undef_list ',' $$5 fitem",
"op : tPIPE",
"op : tCARET",
"op : tAMPER2",
"op : tCMP",
"op : tEQ",
"op : tEQQ",
"op : tMATCH",
"op : tNMATCH",
"op : tGT",
"op : tGEQ",
"op : tLT",
"op : tLEQ",
"op : tNEQ",
"op : tLSHFT",
"op : tRSHFT",
"op : tPLUS",
"op : tMINUS",
"op : tSTAR2",
"op : tSTAR",
"op : tDIVIDE",
"op : tPERCENT",
"op : tPOW",
"op : tBANG",
"op : tTILDE",
"op : tUPLUS",
"op : tUMINUS",
"op : tAREF",
"op : tASET",
"op : tBACK_REF2",
"reswords : k__LINE__",
"reswords : k__FILE__",
"reswords : k__ENCODING__",
"reswords : klBEGIN",
"reswords : klEND",
"reswords : kALIAS",
"reswords : kAND",
"reswords : kBEGIN",
"reswords : kBREAK",
"reswords : kCASE",
"reswords : kCLASS",
"reswords : kDEF",
"reswords : kDEFINED",
"reswords : kDO",
"reswords : kELSE",
"reswords : kELSIF",
"reswords : kEND",
"reswords : kENSURE",
"reswords : kFALSE",
"reswords : kFOR",
"reswords : kIN",
"reswords : kMODULE",
"reswords : kNEXT",
"reswords : kNIL",
"reswords : kNOT",
"reswords : kOR",
"reswords : kREDO",
"reswords : kRESCUE",
"reswords : kRETRY",
"reswords : kRETURN",
"reswords : kSELF",
"reswords : kSUPER",
"reswords : kTHEN",
"reswords : kTRUE",
"reswords : kUNDEF",
"reswords : kWHEN",
"reswords : kYIELD",
"reswords : kIF_MOD",
"reswords : kUNLESS_MOD",
"reswords : kWHILE_MOD",
"reswords : kUNTIL_MOD",
"reswords : kRESCUE_MOD",
"arg : lhs '=' arg",
"arg : lhs '=' arg kRESCUE_MOD arg",
"arg : var_lhs tOP_ASGN arg",
"arg : var_lhs tOP_ASGN arg kRESCUE_MOD arg",
"arg : primary_value '[' opt_call_args rbracket tOP_ASGN arg",
"arg : primary_value tDOT tIDENTIFIER tOP_ASGN arg",
"arg : primary_value tDOT tCONSTANT tOP_ASGN arg",
"arg : primary_value tCOLON2 tIDENTIFIER tOP_ASGN arg",
"arg : primary_value tCOLON2 tCONSTANT tOP_ASGN arg",
"arg : tCOLON3 tCONSTANT tOP_ASGN arg",
"arg : backref tOP_ASGN arg",
"arg : arg tDOT2 arg",
"arg : arg tDOT3 arg",
"arg : arg tPLUS arg",
"arg : arg tMINUS arg",
"arg : arg tSTAR2 arg",
"arg : arg tDIVIDE arg",
"arg : arg tPERCENT arg",
"arg : arg tPOW arg",
"arg : tUMINUS_NUM tINTEGER tPOW arg",
"arg : tUMINUS_NUM tFLOAT tPOW arg",
"arg : tUPLUS arg",
"arg : tUMINUS arg",
"arg : arg tPIPE arg",
"arg : arg tCARET arg",
"arg : arg tAMPER2 arg",
"arg : arg tCMP arg",
"arg : arg tGT arg",
"arg : arg tGEQ arg",
"arg : arg tLT arg",
"arg : arg tLEQ arg",
"arg : arg tEQ arg",
"arg : arg tEQQ arg",
"arg : arg tNEQ arg",
"arg : arg tMATCH arg",
"arg : arg tNMATCH arg",
"arg : tBANG arg",
"arg : tTILDE arg",
"arg : arg tLSHFT arg",
"arg : arg tRSHFT arg",
"arg : arg tANDOP arg",
"arg : arg tOROP arg",
"arg : kDEFINED opt_nl arg",
"arg : arg '?' arg opt_nl ':' arg",
"arg : primary",
"arg_value : arg",
"aref_args : none",
"aref_args : args trailer",
"aref_args : args ',' assocs trailer",
"aref_args : assocs trailer",
"paren_args : tLPAREN2 opt_call_args rparen",
"opt_paren_args : none",
"opt_paren_args : paren_args",
"opt_call_args : none",
"opt_call_args : call_args",
"call_args : command",
"call_args : args opt_block_arg",
"call_args : assocs opt_block_arg",
"call_args : args ',' assocs opt_block_arg",
"call_args : block_arg",
"$$6 :",
"command_args : $$6 call_args",
"block_arg : tAMPER arg_value",
"opt_block_arg : ',' block_arg",
"opt_block_arg : ','",
"opt_block_arg : none_block_pass",
"args : arg_value",
"args : tSTAR arg_value",
"args : args ',' arg_value",
"args : args ',' tSTAR arg_value",
"mrhs : args ',' arg_value",
"mrhs : args ',' tSTAR arg_value",
"mrhs : tSTAR arg_value",
"primary : literal",
"primary : strings",
"primary : xstring",
"primary : regexp",
"primary : words",
"primary : qwords",
"primary : var_ref",
"primary : backref",
"primary : tFID",
"primary : kBEGIN bodystmt kEND",
"$$7 :",
"primary : tLPAREN_ARG expr $$7 rparen",
"primary : tLPAREN compstmt tRPAREN",
"primary : primary_value tCOLON2 tCONSTANT",
"primary : tCOLON3 tCONSTANT",
"primary : tLBRACK aref_args tRBRACK",
"primary : tLBRACE assoc_list tRCURLY",
"primary : kRETURN",
"primary : kYIELD tLPAREN2 call_args rparen",
"primary : kYIELD tLPAREN2 rparen",
"primary : kYIELD",
"primary : kDEFINED opt_nl tLPAREN2 expr rparen",
"primary : kNOT tLPAREN2 expr rparen",
"primary : kNOT tLPAREN2 rparen",
"primary : operation brace_block",
"primary : method_call",
"primary : method_call brace_block",
"primary : tLAMBDA lambda",
"primary : kIF expr_value then compstmt if_tail kEND",
"primary : kUNLESS expr_value then compstmt opt_else kEND",
"$$8 :",
"$$9 :",
"primary : kWHILE $$8 expr_value do $$9 compstmt kEND",
"$$10 :",
"$$11 :",
"primary : kUNTIL $$10 expr_value do $$11 compstmt kEND",
"primary : kCASE expr_value opt_terms case_body kEND",
"primary : kCASE opt_terms case_body kEND",
"$$12 :",
"$$13 :",
"primary : kFOR for_var kIN $$12 expr_value do $$13 compstmt kEND",
"$$14 :",
"primary : kCLASS cpath superclass $$14 bodystmt kEND",
"$$15 :",
"$$16 :",
"primary : kCLASS tLSHFT expr $$15 term $$16 bodystmt kEND",
"$$17 :",
"primary : kMODULE cpath $$17 bodystmt kEND",
"$$18 :",
"primary : kDEF fname $$18 f_arglist bodystmt kEND",
"$$19 :",
"$$20 :",
"primary : kDEF singleton dot_or_colon $$19 fname $$20 f_arglist bodystmt kEND",
"primary : kBREAK",
"primary : kNEXT",
"primary : kREDO",
"primary : kRETRY",
"primary_value : primary",
"then : term",
"then : kTHEN",
"then : term kTHEN",
"do : term",
"do : kDO_COND",
"if_tail : opt_else",
"if_tail : kELSIF expr_value then compstmt if_tail",
"opt_else : none",
"opt_else : kELSE compstmt",
"for_var : lhs",
"for_var : mlhs",
"f_marg : f_norm_arg",
"f_marg : tLPAREN f_margs rparen",
"f_marg_list : f_marg",
"f_marg_list : f_marg_list ',' f_marg",
"f_margs : f_marg_list",
"f_margs : f_marg_list ',' tSTAR f_norm_arg",
"f_margs : f_marg_list ',' tSTAR f_norm_arg ',' f_marg_list",
"f_margs : f_marg_list ',' tSTAR",
"f_margs : f_marg_list ',' tSTAR ',' f_marg_list",
"f_margs : tSTAR f_norm_arg",
"f_margs : tSTAR f_norm_arg ',' f_marg_list",
"f_margs : tSTAR",
"f_margs : tSTAR ',' f_marg_list",
"block_param : f_arg ',' f_block_optarg ',' f_rest_arg opt_f_block_arg",
"block_param : f_arg ',' f_block_optarg ',' f_rest_arg ',' f_arg opt_f_block_arg",
"block_param : f_arg ',' f_block_optarg opt_f_block_arg",
"block_param : f_arg ',' f_block_optarg ',' f_arg opt_f_block_arg",
"block_param : f_arg ',' f_rest_arg opt_f_block_arg",
"block_param : f_arg ','",
"block_param : f_arg ',' f_rest_arg ',' f_arg opt_f_block_arg",
"block_param : f_arg opt_f_block_arg",
"block_param : f_block_optarg ',' f_rest_arg opt_f_block_arg",
"block_param : f_block_optarg ',' f_rest_arg ',' f_arg opt_f_block_arg",
"block_param : f_block_optarg opt_f_block_arg",
"block_param : f_block_optarg ',' f_arg opt_f_block_arg",
"block_param : f_rest_arg opt_f_block_arg",
"block_param : f_rest_arg ',' f_arg opt_f_block_arg",
"block_param : f_block_arg",
"opt_block_param : none",
"opt_block_param : block_param_def",
"block_param_def : tPIPE opt_bv_decl tPIPE",
"block_param_def : tOROP",
"block_param_def : tPIPE block_param opt_bv_decl tPIPE",
"opt_bv_decl : none",
"opt_bv_decl : ';' bv_decls",
"bv_decls : bvar",
"bv_decls : bv_decls ',' bvar",
"bvar : tIDENTIFIER",
"bvar : f_bad_arg",
"$$21 :",
"lambda : $$21 f_larglist lambda_body",
"f_larglist : tLPAREN2 f_args opt_bv_decl rparen",
"f_larglist : f_args opt_bv_decl",
"lambda_body : tLAMBEG compstmt tRCURLY",
"lambda_body : kDO_LAMBDA compstmt kEND",
"$$22 :",
"do_block : kDO_BLOCK $$22 opt_block_param compstmt kEND",
"block_call : command do_block",
"block_call : block_call tDOT operation2 opt_paren_args",
"block_call : block_call tCOLON2 operation2 opt_paren_args",
"method_call : operation paren_args",
"method_call : primary_value tDOT operation2 opt_paren_args",
"method_call : primary_value tCOLON2 operation2 paren_args",
"method_call : primary_value tCOLON2 operation3",
"method_call : primary_value tDOT paren_args",
"method_call : primary_value tCOLON2 paren_args",
"method_call : kSUPER paren_args",
"method_call : kSUPER",
"method_call : primary_value '[' opt_call_args rbracket",
"$$23 :",
"brace_block : tLCURLY $$23 opt_block_param compstmt tRCURLY",
"$$24 :",
"brace_block : kDO $$24 opt_block_param compstmt kEND",
"case_body : kWHEN args then compstmt cases",
"cases : opt_else",
"cases : case_body",
"opt_rescue : kRESCUE exc_list exc_var then compstmt opt_rescue",
"opt_rescue :",
"exc_list : arg_value",
"exc_list : mrhs",
"exc_list : none",
"exc_var : tASSOC lhs",
"exc_var : none",
"opt_ensure : kENSURE compstmt",
"opt_ensure : none",
"literal : numeric",
"literal : symbol",
"literal : dsym",
"strings : string",
"string : tCHAR",
"string : string1",
"string : string string1",
"string1 : tSTRING_BEG string_contents tSTRING_END",
"xstring : tXSTRING_BEG xstring_contents tSTRING_END",
"regexp : tREGEXP_BEG xstring_contents tREGEXP_END",
"words : tWORDS_BEG ' ' tSTRING_END",
"words : tWORDS_BEG word_list tSTRING_END",
"word_list :",
"word_list : word_list word ' '",
"word : string_content",
"word : word string_content",
"qwords : tQWORDS_BEG ' ' tSTRING_END",
"qwords : tQWORDS_BEG qword_list tSTRING_END",
"qword_list :",
"qword_list : qword_list tSTRING_CONTENT ' '",
"string_contents :",
"string_contents : string_contents string_content",
"xstring_contents :",
"xstring_contents : xstring_contents string_content",
"string_content : tSTRING_CONTENT",
"$$25 :",
"string_content : tSTRING_DVAR $$25 string_dvar",
"$$26 :",
"string_content : tSTRING_DBEG $$26 compstmt tRCURLY",
"string_dvar : tGVAR",
"string_dvar : tIVAR",
"string_dvar : tCVAR",
"string_dvar : backref",
"symbol : tSYMBEG sym",
"sym : fname",
"sym : tIVAR",
"sym : tGVAR",
"sym : tCVAR",
"dsym : tSYMBEG xstring_contents tSTRING_END",
"numeric : tINTEGER",
"numeric : tFLOAT",
"numeric : tUMINUS_NUM tINTEGER",
"numeric : tUMINUS_NUM tFLOAT",
"variable : tIDENTIFIER",
"variable : tIVAR",
"variable : tGVAR",
"variable : tCONSTANT",
"variable : tCVAR",
"variable : kNIL",
"variable : kSELF",
"variable : kTRUE",
"variable : kFALSE",
"variable : k__FILE__",
"variable : k__LINE__",
"variable : k__ENCODING__",
"var_ref : variable",
"var_lhs : variable",
"backref : tNTH_REF",
"backref : tBACK_REF",
"superclass : term",
"$$27 :",
"superclass : tLT $$27 expr_value term",
"superclass : error term",
"f_arglist : tLPAREN2 f_args rparen",
"f_arglist : f_args term",
"f_args : f_arg ',' f_optarg ',' f_rest_arg opt_f_block_arg",
"f_args : f_arg ',' f_optarg ',' f_rest_arg ',' f_arg opt_f_block_arg",
"f_args : f_arg ',' f_optarg opt_f_block_arg",
"f_args : f_arg ',' f_optarg ',' f_arg opt_f_block_arg",
"f_args : f_arg ',' f_rest_arg opt_f_block_arg",
"f_args : f_arg ',' f_rest_arg ',' f_arg opt_f_block_arg",
"f_args : f_arg opt_f_block_arg",
"f_args : f_optarg ',' f_rest_arg opt_f_block_arg",
"f_args : f_optarg ',' f_rest_arg ',' f_arg opt_f_block_arg",
"f_args : f_optarg opt_f_block_arg",
"f_args : f_optarg ',' f_arg opt_f_block_arg",
"f_args : f_rest_arg opt_f_block_arg",
"f_args : f_rest_arg ',' f_arg opt_f_block_arg",
"f_args : f_block_arg",
"f_args :",
"f_bad_arg : tCONSTANT",
"f_bad_arg : tIVAR",
"f_bad_arg : tGVAR",
"f_bad_arg : tCVAR",
"f_norm_arg : f_bad_arg",
"f_norm_arg : tIDENTIFIER",
"f_arg_item : f_norm_arg",
"f_arg_item : tLPAREN f_margs rparen",
"f_arg : f_arg_item",
"f_arg : f_arg ',' f_arg_item",
"f_opt : tIDENTIFIER '=' arg_value",
"f_block_opt : tIDENTIFIER '=' primary_value",
"f_block_optarg : f_block_opt",
"f_block_optarg : f_block_optarg ',' f_block_opt",
"f_optarg : f_opt",
"f_optarg : f_optarg ',' f_opt",
"restarg_mark : tSTAR2",
"restarg_mark : tSTAR",
"f_rest_arg : restarg_mark tIDENTIFIER",
"f_rest_arg : restarg_mark",
"blkarg_mark : tAMPER2",
"blkarg_mark : tAMPER",
"f_block_arg : blkarg_mark tIDENTIFIER",
"opt_f_block_arg : ',' f_block_arg",
"opt_f_block_arg :",
"singleton : var_ref",
"$$28 :",
"singleton : tLPAREN2 $$28 expr rparen",
"assoc_list : none",
"assoc_list : assocs trailer",
"assocs : assoc",
"assocs : assocs ',' assoc",
"assoc : arg_value tASSOC arg_value",
"assoc : tLABEL arg_value",
"operation : tIDENTIFIER",
"operation : tCONSTANT",
"operation : tFID",
"operation2 : tIDENTIFIER",
"operation2 : tCONSTANT",
"operation2 : tFID",
"operation2 : op",
"operation3 : tIDENTIFIER",
"operation3 : tFID",
"operation3 : op",
"dot_or_colon : tDOT",
"dot_or_colon : tCOLON2",
"opt_terms :",
"opt_terms : terms",
"opt_nl :",
"opt_nl : '\\n'",
"rparen : opt_nl tRPAREN",
"rbracket : opt_nl tRBRACK",
"trailer :",
"trailer : '\\n'",
"trailer : ','",
"term : ';'",
"term : '\\n'",
"terms : term",
"terms : terms ';'",
"none :",
"none_block_pass :",
};
/** debugging support, requires the package <tt>jay.yydebug</tt>.
Set to <tt>null</tt> to suppress debugging messages.
*/
protected jay.yydebug.yyDebug yydebug;
/** index-checked interface to {@link #yyNames}.
@param token single character or <tt>%token</tt> value.
@return token name or <tt>[illegal]</tt> or <tt>[unknown]</tt>.
*/
public static final String yyName (int token) {
if (token < 0 || token > yyNames.length) return "[illegal]";
String name;
if ((name = yyNames[token]) != null) return name;
return "[unknown]";
}
/** computes list of expected tokens on error by tracing the tables.
@param state for which to compute the list.
@return list of token names.
*/
protected String[] yyExpecting (int state) {
int token, n, len = 0;
boolean[] ok = new boolean[yyNames.length];
if ((n = yySindex[state]) != 0)
for (token = n < 0 ? -n : 0;
token < yyNames.length && n+token < yyTable.length; ++ token)
if (yyCheck[n+token] == token && !ok[token] && yyNames[token] != null) {
++ len;
ok[token] = true;
}
if ((n = yyRindex[state]) != 0)
for (token = n < 0 ? -n : 0;
token < yyNames.length && n+token < yyTable.length; ++ token)
if (yyCheck[n+token] == token && !ok[token] && yyNames[token] != null) {
++ len;
ok[token] = true;
}
String result[] = new String[len];
for (n = token = 0; n < len; ++ token)
if (ok[token]) result[n++] = yyNames[token];
return result;
}
/** the generated parser, with debugging messages.
Maintains a dynamic state and value stack.
@param yyLex scanner.
@param yydebug debug message writer implementing <tt>yyDebug</tt>, or <tt>null</tt>.
@return result of the last reduction, if any.
*/
public Object yyparse (Lexer yyLex, Object ayydebug)
throws java.io.IOException {
this.yydebug = (jay.yydebug.yyDebug)ayydebug;
return yyparse(yyLex);
}
/** initial size and increment of the state/value stack [default 256].
This is not final so that it can be overwritten outside of invocations
of {@link #yyparse}.
*/
protected int yyMax;
/** executed at the beginning of a reduce action.
Used as <tt>$$ = yyDefault($1)</tt>, prior to the user-specified action, if any.
Can be overwritten to provide deep copy, etc.
@param first value for <tt>$1</tt>, or <tt>null</tt>.
@return first.
*/
protected Object yyDefault (Object first) {
return first;
}
/** the generated parser.
Maintains a dynamic state and value stack.
@param yyLex scanner.
@return result of the last reduction, if any.
*/
public Object yyparse (Lexer yyLex) throws java.io.IOException {
if (yyMax <= 0) yyMax = 256; // initial size
int yyState = 0, yyStates[] = new int[yyMax]; // state stack
Object yyVal = null, yyVals[] = new Object[yyMax]; // value stack
int yyToken = -1; // current input
int yyErrorFlag = 0; // #tokens to shift
yyLoop: for (int yyTop = 0;; ++ yyTop) {
if (yyTop >= yyStates.length) { // dynamically increase
int[] i = new int[yyStates.length+yyMax];
System.arraycopy(yyStates, 0, i, 0, yyStates.length);
yyStates = i;
Object[] o = new Object[yyVals.length+yyMax];
System.arraycopy(yyVals, 0, o, 0, yyVals.length);
yyVals = o;
}
yyStates[yyTop] = yyState;
yyVals[yyTop] = yyVal;
if (yydebug != null) yydebug.push(yyState, yyVal);
yyDiscarded: for (;;) { // discarding a token does not change stack
int yyN;
if ((yyN = yyDefRed[yyState]) == 0) { // else [default] reduce (yyN)
if (yyToken < 0) {
// yyToken = yyLex.advance() ? yyLex.token() : 0;
yyToken = yyLex.nextToken();
if (yydebug != null)
yydebug.lex(yyState, yyToken, yyName(yyToken), yyLex.value());
}
if ((yyN = yySindex[yyState]) != 0 && (yyN += yyToken) >= 0
&& yyN < yyTable.length && yyCheck[yyN] == yyToken) {
if (yydebug != null)
yydebug.shift(yyState, yyTable[yyN], yyErrorFlag-1);
yyState = yyTable[yyN]; // shift to yyN
yyVal = yyLex.value();
yyToken = -1;
if (yyErrorFlag > 0) -- yyErrorFlag;
continue yyLoop;
}
if ((yyN = yyRindex[yyState]) != 0 && (yyN += yyToken) >= 0
&& yyN < yyTable.length && yyCheck[yyN] == yyToken)
yyN = yyTable[yyN]; // reduce (yyN)
else
switch (yyErrorFlag) {
case 0:
support.yyerror("syntax error", yyExpecting(yyState), yyNames[yyToken]);
if (yydebug != null) yydebug.error("syntax error");
case 1: case 2:
yyErrorFlag = 3;
do {
if ((yyN = yySindex[yyStates[yyTop]]) != 0
&& (yyN += yyErrorCode) >= 0 && yyN < yyTable.length
&& yyCheck[yyN] == yyErrorCode) {
if (yydebug != null)
yydebug.shift(yyStates[yyTop], yyTable[yyN], 3);
yyState = yyTable[yyN];
yyVal = yyLex.value();
continue yyLoop;
}
if (yydebug != null) yydebug.pop(yyStates[yyTop]);
} while (-- yyTop >= 0);
if (yydebug != null) yydebug.reject();
support.yyerror("irrecoverable syntax error");
case 3:
if (yyToken == 0) {
if (yydebug != null) yydebug.reject();
support.yyerror("irrecoverable syntax error at end-of-file");
}
if (yydebug != null)
yydebug.discard(yyState, yyToken, yyName(yyToken),
yyLex.value());
yyToken = -1;
continue yyDiscarded; // leave stack alone
}
}
int yyV = yyTop + 1-yyLen[yyN];
if (yydebug != null)
yydebug.reduce(yyState, yyStates[yyV-1], yyN, yyRule[yyN], yyLen[yyN]);
ParserState state = states[yyN];
if (state == null) {
yyVal = yyDefault(yyV > yyTop ? null : yyVals[yyV]);
} else {
yyVal = state.execute(support, lexer, yyVal, yyVals, yyTop);
}
// switch (yyN) {
// ACTIONS_END
// }
yyTop -= yyLen[yyN];
yyState = yyStates[yyTop];
int yyM = yyLhs[yyN];
if (yyState == 0 && yyM == 0) {
if (yydebug != null) yydebug.shift(0, yyFinal);
yyState = yyFinal;
if (yyToken < 0) {
yyToken = yyLex.nextToken();
// yyToken = yyLex.advance() ? yyLex.token() : 0;
if (yydebug != null)
yydebug.lex(yyState, yyToken,yyName(yyToken), yyLex.value());
}
if (yyToken == 0) {
if (yydebug != null) yydebug.accept(yyVal);
return yyVal;
}
continue yyLoop;
}
if ((yyN = yyGindex[yyM]) != 0 && (yyN += yyState) >= 0
&& yyN < yyTable.length && yyCheck[yyN] == yyState)
yyState = yyTable[yyN];
else
yyState = yyDgoto[yyM];
if (yydebug != null) yydebug.shift(yyStates[yyTop], yyState);
continue yyLoop;
}
}
}
static ParserState[] states = new ParserState[542];
static {
states[368] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((ArgsNode)yyVals[-1+yyTop]);
((ISourcePositionHolder)yyVal).setPosition(support.union(((ArgsNode)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])));
return yyVal;
}
};
states[33] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
((AssignableNode)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = ((MultipleAsgn19Node)yyVals[-2+yyTop]);
((MultipleAsgn19Node)yyVals[-2+yyTop]).setPosition(support.union(((MultipleAsgn19Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])));
return yyVal;
}
};
states[234] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[-1+yyTop]);
if (yyVal != null) ((Node)yyVal).setPosition(support.union(((Token)yyVals[-2+yyTop]), ((Token)yyVals[0+yyTop])));
return yyVal;
}
};
states[100] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_colon2(support.union(((Node)yyVals[-2+yyTop]), ((Token)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]), (String) ((Token)yyVals[0+yyTop]).getValue());
return yyVal;
}
};
states[301] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new Integer(support.getInSingle());
support.setInSingle(0);
support.pushLocalScope();
return yyVal;
}
};
states[536] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
return yyVal;
}
};
states[469] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((ListNode)yyVals[-5+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), ((ListNode)yyVals[-5+yyTop]), ((ListNode)yyVals[-3+yyTop]), null, ((ListNode)yyVals[-1+yyTop]), ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[402] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
/* FIXME: We may be intern'ing more than once.*/
yyVal = new SymbolNode(((Token)yyVals[0+yyTop]).getPosition(), ((String) ((Token)yyVals[0+yyTop]).getValue()).intern());
return yyVal;
}
};
states[335] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new MultipleAsgn19Node(support.getPosition(((Token)yyVals[-1+yyTop])), null, support.assignable(((Token)yyVals[0+yyTop]), null), null);
return yyVal;
}
};
states[201] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "%", ((Node)yyVals[0+yyTop]), support.getPosition(null));
return yyVal;
}
};
states[67] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new MultipleAsgn19Node(support.getPosition(((ListNode)yyVals[-4+yyTop])), ((ListNode)yyVals[-4+yyTop]), ((Node)yyVals[-2+yyTop]), ((ListNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[268] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.warning(ID.GROUPED_EXPRESSION, support.getPosition(((Token)yyVals[-3+yyTop])), "(...) interpreted as grouped expression");
yyVal = ((Node)yyVals[-2+yyTop]);
return yyVal;
}
};
states[503] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
if (!support.is_local_id(((Token)yyVals[0+yyTop]))) {
support.yyerror("block argument must be local variable");
}
yyVal = new BlockArgNode(support.arg_var(support.shadowing_lvar(((Token)yyVals[0+yyTop]))));
return yyVal;
}
};
states[369] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[-1+yyTop]);
return yyVal;
}
};
states[302] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new SClassNode(support.union(((Token)yyVals[-7+yyTop]), ((Token)yyVals[0+yyTop])), ((Node)yyVals[-5+yyTop]), support.getCurrentScope(), ((Node)yyVals[-1+yyTop]));
support.popCurrentScope();
support.setInDef(((Boolean)yyVals[-4+yyTop]).booleanValue());
support.setInSingle(((Integer)yyVals[-2+yyTop]).intValue());
return yyVal;
}
};
states[470] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((ListNode)yyVals[-3+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), ((ListNode)yyVals[-3+yyTop]), null, ((RestArgNode)yyVals[-1+yyTop]), null, ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[336] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new MultipleAsgn19Node(support.getPosition(((Token)yyVals[-3+yyTop])), null, support.assignable(((Token)yyVals[-2+yyTop]), null), ((ListNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[202] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "**", ((Node)yyVals[0+yyTop]), support.getPosition(null));
return yyVal;
}
};
states[68] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new MultipleAsgn19Node(support.getPosition(((ListNode)yyVals[-1+yyTop])), ((ListNode)yyVals[-1+yyTop]), new StarNode(support.getPosition(null)), null);
return yyVal;
}
};
states[269] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
if (((Node)yyVals[-1+yyTop]) != null) {
/* compstmt position includes both parens around it*/
((ISourcePositionHolder) ((Node)yyVals[-1+yyTop])).setPosition(support.union(((Token)yyVals[-2+yyTop]), ((Token)yyVals[0+yyTop])));
}
yyVal = ((Node)yyVals[-1+yyTop]);
return yyVal;
}
};
states[1] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
lexer.setState(LexState.EXPR_BEG);
support.initTopLocalVariables();
return yyVal;
}
};
states[504] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((BlockArgNode)yyVals[0+yyTop]);
return yyVal;
}
};
states[370] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[-1+yyTop]);
return yyVal;
}
};
states[303] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
if (support.isInDef() || support.isInSingle()) {
support.yyerror("module definition in method body");
}
support.pushLocalScope();
return yyVal;
}
};
states[471] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((ListNode)yyVals[-5+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), ((ListNode)yyVals[-5+yyTop]), null, ((RestArgNode)yyVals[-3+yyTop]), ((ListNode)yyVals[-1+yyTop]), ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[404] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[0+yyTop]) instanceof EvStrNode ? new DStrNode(support.getPosition(((Node)yyVals[0+yyTop]))).add(((Node)yyVals[0+yyTop])) : ((Node)yyVals[0+yyTop]);
/*
NODE *node = $1;
if (!node) {
node = NEW_STR(STR_NEW0());
} else {
node = evstr2dstr(node);
}
$$ = node;
*/
return yyVal;
}
};
states[337] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new MultipleAsgn19Node(support.getPosition(((Token)yyVals[0+yyTop])), null, new StarNode(support.getPosition(null)), null);
return yyVal;
}
};
states[69] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new MultipleAsgn19Node(support.getPosition(((ListNode)yyVals[-3+yyTop])), ((ListNode)yyVals[-3+yyTop]), new StarNode(support.getPosition(null)), ((ListNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[270] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_colon2(support.union(((Node)yyVals[-2+yyTop]), ((Token)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]), (String) ((Token)yyVals[0+yyTop]).getValue());
return yyVal;
}
};
states[2] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
/* ENEBO: Removed !compile_for_eval which probably is to reduce warnings*/
if (((Node)yyVals[0+yyTop]) != null) {
/* last expression should not be void */
if (((Node)yyVals[0+yyTop]) instanceof BlockNode) {
support.checkUselessStatement(((BlockNode)yyVals[0+yyTop]).getLast());
} else {
support.checkUselessStatement(((Node)yyVals[0+yyTop]));
}
}
support.getResult().setAST(support.addRootNode(((Node)yyVals[0+yyTop]), support.getPosition(((Node)yyVals[0+yyTop]))));
return yyVal;
}
};
states[203] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "**", ((Node)yyVals[0+yyTop]), support.getPosition(null)), "-@");
return yyVal;
}
};
states[505] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = null;
return yyVal;
}
};
states[371] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.pushBlockScope();
return yyVal;
}
};
states[36] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.newAndNode(support.getPosition(((Token)yyVals[-1+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[304] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
Node body = ((Node)yyVals[-1+yyTop]) == null ? NilImplicitNode.NIL : ((Node)yyVals[-1+yyTop]);
yyVal = new ModuleNode(support.union(((Token)yyVals[-4+yyTop]), ((Token)yyVals[0+yyTop])), ((Colon3Node)yyVals[-3+yyTop]), support.getCurrentScope(), body);
support.popCurrentScope();
return yyVal;
}
};
states[539] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
return yyVal;
}
};
states[472] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((ListNode)yyVals[-1+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), ((ListNode)yyVals[-1+yyTop]), null, null, null, ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[405] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new StrNode(((Token)yyVals[-1+yyTop]).getPosition(), (String) ((Token)yyVals[0+yyTop]).getValue());
return yyVal;
}
};
states[338] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new MultipleAsgn19Node(support.getPosition(((Token)yyVals[-2+yyTop])), null, null, ((ListNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[70] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new MultipleAsgn19Node(support.getPosition(((Token)yyVals[-1+yyTop])), null, ((Node)yyVals[0+yyTop]), null);
return yyVal;
}
};
states[271] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_colon3(support.union(((Token)yyVals[-1+yyTop]), ((Token)yyVals[0+yyTop])), (String) ((Token)yyVals[0+yyTop]).getValue());
return yyVal;
}
};
states[3] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
Node node = ((Node)yyVals[-3+yyTop]);
if (((RescueBodyNode)yyVals[-2+yyTop]) != null) {
node = new RescueNode(support.getPosition(((Node)yyVals[-3+yyTop]), true), ((Node)yyVals[-3+yyTop]), ((RescueBodyNode)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
} else if (((Node)yyVals[-1+yyTop]) != null) {
support.warn(ID.ELSE_WITHOUT_RESCUE, support.getPosition(((Node)yyVals[-3+yyTop])), "else without rescue is useless");
node = support.appendToBlock(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
}
if (((Node)yyVals[0+yyTop]) != null) {
if (node == null) node = NilImplicitNode.NIL;
node = new EnsureNode(support.getPosition(((Node)yyVals[-3+yyTop])), node, ((Node)yyVals[0+yyTop]));
}
yyVal = node;
return yyVal;
}
};
states[204] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(support.getOperatorCallNode(((FloatNode)yyVals[-2+yyTop]), "**", ((Node)yyVals[0+yyTop]), support.getPosition(null)), "-@");
return yyVal;
}
};
states[506] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
if (!(((Node)yyVals[0+yyTop]) instanceof SelfNode)) {
support.checkExpression(((Node)yyVals[0+yyTop]));
}
yyVal = ((Node)yyVals[0+yyTop]);
return yyVal;
}
};
states[439] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
lexer.setState(LexState.EXPR_END);
/* DStrNode: :"some text #{some expression}"*/
/* StrNode: :"some text"*/
/* EvStrNode :"#{some expression}"*/
/* Ruby 1.9 allows empty strings as symbols*/
if (((Node)yyVals[-1+yyTop]) == null) {
yyVal = new SymbolNode(((Token)yyVals[-2+yyTop]).getPosition(), "");
} else if (((Node)yyVals[-1+yyTop]) instanceof DStrNode) {
yyVal = new DSymbolNode(support.union(((Token)yyVals[-2+yyTop]), ((Token)yyVals[0+yyTop])), ((DStrNode)yyVals[-1+yyTop]));
} else if (((Node)yyVals[-1+yyTop]) instanceof StrNode) {
yyVal = new SymbolNode(support.union(((Token)yyVals[-2+yyTop]), ((Token)yyVals[0+yyTop])), ((StrNode)yyVals[-1+yyTop]).getValue().toString().intern());
} else {
SourcePosition position = support.union(((Node)yyVals[-1+yyTop]), ((Token)yyVals[0+yyTop]));
/* We substract one since tsymbeg is longer than one*/
/* and we cannot union it directly so we assume quote*/
/* is one character long and subtract for it.*/
position.adjustStartOffset(-1);
((Node)yyVals[-1+yyTop]).setPosition(position);
yyVal = new DSymbolNode(support.union(((Token)yyVals[-2+yyTop]), ((Token)yyVals[0+yyTop])));
((DSymbolNode)yyVal).add(((Node)yyVals[-1+yyTop]));
}
return yyVal;
}
};
states[372] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new IterNode(support.getPosition(((Token)yyVals[-4+yyTop])), ((ArgsNode)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), support.getCurrentScope());
support.popCurrentScope();
return yyVal;
}
};
states[104] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
lexer.setState(LexState.EXPR_ENDFN);
yyVal = ((Token)yyVals[0+yyTop]);
return yyVal;
}
};
states[305] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.setInDef(true);
support.pushLocalScope();
return yyVal;
}
};
states[37] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.newOrNode(support.getPosition(((Token)yyVals[-1+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[540] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = null;
return yyVal;
}
};
states[473] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((ListNode)yyVals[-3+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), null, ((ListNode)yyVals[-3+yyTop]), ((RestArgNode)yyVals[-1+yyTop]), null, ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[406] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[0+yyTop]);
return yyVal;
}
};
states[339] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((ListNode)yyVals[-5+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), ((ListNode)yyVals[-5+yyTop]), ((ListNode)yyVals[-3+yyTop]), ((RestArgNode)yyVals[-1+yyTop]), null, ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[71] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new MultipleAsgn19Node(support.getPosition(((Token)yyVals[-3+yyTop])), null, ((Node)yyVals[-2+yyTop]), ((ListNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[272] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
SourcePosition position = support.union(((Token)yyVals[-2+yyTop]), ((Token)yyVals[0+yyTop]));
if (((Node)yyVals[-1+yyTop]) == null) {
yyVal = new ZArrayNode(position); /* zero length array */
} else {
yyVal = ((Node)yyVals[-1+yyTop]);
((ISourcePositionHolder)yyVal).setPosition(position);
}
return yyVal;
}
};
states[4] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
if (((Node)yyVals[-1+yyTop]) instanceof BlockNode) {
support.checkUselessStatements(((BlockNode)yyVals[-1+yyTop]));
}
yyVal = ((Node)yyVals[-1+yyTop]);
return yyVal;
}
};
states[205] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(((Node)yyVals[0+yyTop]), "+@");
return yyVal;
}
};
states[507] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
lexer.setState(LexState.EXPR_BEG);
return yyVal;
}
};
states[440] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[0+yyTop]);
return yyVal;
}
};
states[373] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
/* Workaround for JRUBY-2326 (MRI does not enter this production for some reason)*/
if (((Node)yyVals[-1+yyTop]) instanceof YieldNode) {
throw new SyntaxException(PID.BLOCK_GIVEN_TO_YIELD, support.getPosition(((Node)yyVals[-1+yyTop])), "block given to yield");
}
if (((BlockAcceptingNode)yyVals[-1+yyTop]).getIterNode() instanceof BlockPassNode) {
throw new SyntaxException(PID.BLOCK_ARG_AND_BLOCK_GIVEN, support.getPosition(((Node)yyVals[-1+yyTop])), "Both block arg and actual block given.");
}
yyVal = ((BlockAcceptingNode)yyVals[-1+yyTop]).setIterNode(((IterNode)yyVals[0+yyTop]));
((Node)yyVal).setPosition(support.union(((Node)yyVals[-1+yyTop]), ((IterNode)yyVals[0+yyTop])));
return yyVal;
}
};
states[239] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.newArrayNode(support.getPosition(((Node)yyVals[0+yyTop])), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[105] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
lexer.setState(LexState.EXPR_ENDFN);
yyVal = ((Token)yyVals[0+yyTop]);
return yyVal;
}
};
states[306] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
/* TODO: We should use implicit nil for body, but problem (punt til later)*/
Node body = ((Node)yyVals[-1+yyTop]); /*$5 == null ? NilImplicitNode.NIL : $5;*/
yyVal = new DefnNode(support.union(((Token)yyVals[-5+yyTop]), ((Token)yyVals[0+yyTop])), new ArgumentNode(((Token)yyVals[-4+yyTop]).getPosition(), (String) ((Token)yyVals[-4+yyTop]).getValue()), ((ArgsNode)yyVals[-2+yyTop]), support.getCurrentScope(), body);
support.popCurrentScope();
support.setInDef(false);
return yyVal;
}
};
states[38] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(support.getConditionNode(((Node)yyVals[0+yyTop])), "!");
return yyVal;
}
};
states[541] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = null;
return yyVal;
}
};
states[474] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((ListNode)yyVals[-5+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), null, ((ListNode)yyVals[-5+yyTop]), ((RestArgNode)yyVals[-3+yyTop]), ((ListNode)yyVals[-1+yyTop]), ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[407] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.literal_concat(support.getPosition(((Node)yyVals[-1+yyTop])), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[340] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((ListNode)yyVals[-7+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), ((ListNode)yyVals[-7+yyTop]), ((ListNode)yyVals[-5+yyTop]), ((RestArgNode)yyVals[-3+yyTop]), ((ListNode)yyVals[-1+yyTop]), ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[72] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new MultipleAsgn19Node(support.getPosition(((Token)yyVals[0+yyTop])), null, new StarNode(support.getPosition(null)), null);
return yyVal;
}
};
states[273] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new HashNode(support.union(((Token)yyVals[-2+yyTop]), ((Token)yyVals[0+yyTop])), ((ListNode)yyVals[-1+yyTop]));
return yyVal;
}
};
states[206] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(((Node)yyVals[0+yyTop]), "-@");
return yyVal;
}
};
states[508] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
if (((Node)yyVals[-1+yyTop]) == null) {
support.yyerror("can't define single method for ().");
} else if (((Node)yyVals[-1+yyTop]) instanceof ILiteralNode) {
support.yyerror("can't define single method for literals.");
}
support.checkExpression(((Node)yyVals[-1+yyTop]));
yyVal = ((Node)yyVals[-1+yyTop]);
return yyVal;
}
};
states[441] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((FloatNode)yyVals[0+yyTop]);
return yyVal;
}
};
states[374] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((Token)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]), null);
return yyVal;
}
};
states[106] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new LiteralNode(((Token)yyVals[0+yyTop]));
return yyVal;
}
};
states[307] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
lexer.setState(LexState.EXPR_FNAME);
return yyVal;
}
};
states[39] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(support.getConditionNode(((Node)yyVals[0+yyTop])), "!");
return yyVal;
}
};
states[240] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.arg_blk_pass(((Node)yyVals[-1+yyTop]), ((BlockPassNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[475] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((ListNode)yyVals[-1+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), null, ((ListNode)yyVals[-1+yyTop]), null, null, ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[408] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[-1+yyTop]);
((ISourcePositionHolder)yyVal).setPosition(support.union(((Token)yyVals[-2+yyTop]), ((Token)yyVals[0+yyTop])));
int extraLength = ((String) ((Token)yyVals[-2+yyTop]).getValue()).length() - 1;
/* We may need to subtract addition offset off of first */
/* string fragment (we optimistically take one off in*/
/* ParserSupport.literal_concat). Check token length*/
/* and subtract as neeeded.*/
if ((((Node)yyVals[-1+yyTop]) instanceof DStrNode) && extraLength > 0) {
Node strNode = ((DStrNode)((Node)yyVals[-1+yyTop])).get(0);
assert strNode != null;
strNode.getPosition().adjustStartOffset(-extraLength);
}
return yyVal;
}
};
states[341] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((ListNode)yyVals[-3+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), ((ListNode)yyVals[-3+yyTop]), ((ListNode)yyVals[-1+yyTop]), null, null, ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[73] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new MultipleAsgn19Node(support.getPosition(((Token)yyVals[-2+yyTop])), null, new StarNode(support.getPosition(null)), ((ListNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[274] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new ReturnNode(((Token)yyVals[0+yyTop]).getPosition(), NilImplicitNode.NIL);
return yyVal;
}
};
states[6] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.newline_node(((Node)yyVals[0+yyTop]), support.getPosition(((Node)yyVals[0+yyTop]), true));
return yyVal;
}
};
states[207] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "|", ((Node)yyVals[0+yyTop]), support.getPosition(null));
return yyVal;
}
};
states[509] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new ArrayNode(support.getPosition(null));
return yyVal;
}
};
states[442] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.negateInteger(((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[375] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((Token)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]), null);
return yyVal;
}
};
states[107] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new LiteralNode(((Token)yyVals[0+yyTop]));
return yyVal;
}
};
states[308] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.setInSingle(support.getInSingle() + 1);
support.pushLocalScope();
lexer.setState(LexState.EXPR_ENDFN); /* force for args */
return yyVal;
}
};
states[241] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.newArrayNode(support.getPosition(((ListNode)yyVals[-1+yyTop])), new HashNode(support.getPosition(null), ((ListNode)yyVals[-1+yyTop])));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[476] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((ListNode)yyVals[-3+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), null, ((ListNode)yyVals[-3+yyTop]), null, ((ListNode)yyVals[-1+yyTop]), ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[409] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
SourcePosition position = support.union(((Token)yyVals[-2+yyTop]), ((Token)yyVals[0+yyTop]));
if (((Node)yyVals[-1+yyTop]) == null) {
yyVal = new XStrNode(position, null);
} else if (((Node)yyVals[-1+yyTop]) instanceof StrNode) {
yyVal = new XStrNode(position, ((StrNode)yyVals[-1+yyTop]).getValue());
} else if (((Node)yyVals[-1+yyTop]) instanceof DStrNode) {
yyVal = new DXStrNode(position, ((DStrNode)yyVals[-1+yyTop]));
((Node)yyVal).setPosition(position);
} else {
yyVal = new DXStrNode(position).add(((Node)yyVals[-1+yyTop]));
}
return yyVal;
}
};
states[342] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((ListNode)yyVals[-5+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), ((ListNode)yyVals[-5+yyTop]), ((ListNode)yyVals[-3+yyTop]), null, ((ListNode)yyVals[-1+yyTop]), ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[275] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_yield(support.union(((Token)yyVals[-3+yyTop]), ((Token)yyVals[0+yyTop])), ((Node)yyVals[-1+yyTop]));
return yyVal;
}
};
states[7] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.appendToBlock(((Node)yyVals[-2+yyTop]), support.newline_node(((Node)yyVals[0+yyTop]), support.getPosition(((Node)yyVals[0+yyTop]), true)));
return yyVal;
}
};
states[208] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "^", ((Node)yyVals[0+yyTop]), support.getPosition(null));
return yyVal;
}
};
states[510] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((ListNode)yyVals[-1+yyTop]);
return yyVal;
}
};
states[443] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.negateFloat(((FloatNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[376] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_fcall(((Token)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]), null);
return yyVal;
}
};
states[108] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((LiteralNode)yyVals[0+yyTop]);
return yyVal;
}
};
states[309] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
/* TODO: We should use implicit nil for body, but problem (punt til later)*/
Node body = ((Node)yyVals[-1+yyTop]); /*$8 == null ? NilImplicitNode.NIL : $8;*/
yyVal = new DefsNode(support.union(((Token)yyVals[-8+yyTop]), ((Token)yyVals[0+yyTop])), ((Node)yyVals[-7+yyTop]), new ArgumentNode(((Token)yyVals[-4+yyTop]).getPosition(), (String) ((Token)yyVals[-4+yyTop]).getValue()), ((ArgsNode)yyVals[-2+yyTop]), support.getCurrentScope(), body);
support.popCurrentScope();
support.setInSingle(support.getInSingle() - 1);
return yyVal;
}
};
states[41] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.checkExpression(((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[242] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.arg_append(((Node)yyVals[-3+yyTop]), new HashNode(support.getPosition(null), ((ListNode)yyVals[-1+yyTop])));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[477] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((RestArgNode)yyVals[-1+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), null, null, ((RestArgNode)yyVals[-1+yyTop]), null, ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[410] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.newRegexpNode(support.union(((Token)yyVals[-2+yyTop]), ((RegexpNode)yyVals[0+yyTop])), ((Node)yyVals[-1+yyTop]), (RegexpNode) ((RegexpNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[343] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((ListNode)yyVals[-3+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), ((ListNode)yyVals[-3+yyTop]), null, ((RestArgNode)yyVals[-1+yyTop]), null, ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[276] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new ZYieldNode(support.union(((Token)yyVals[-2+yyTop]), ((Token)yyVals[0+yyTop])));
return yyVal;
}
};
states[8] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[0+yyTop]);
return yyVal;
}
};
states[209] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "&", ((Node)yyVals[0+yyTop]), support.getPosition(null));
return yyVal;
}
};
states[75] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[-1+yyTop]);
return yyVal;
}
};
states[377] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((Token)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]), null);
return yyVal;
}
};
states[109] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[0+yyTop]);
return yyVal;
}
};
states[310] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new BreakNode(((Token)yyVals[0+yyTop]).getPosition(), NilImplicitNode.NIL);
return yyVal;
}
};
states[243] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
return yyVal;
}
};
states[478] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((RestArgNode)yyVals[-3+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), null, null, ((RestArgNode)yyVals[-3+yyTop]), ((ListNode)yyVals[-1+yyTop]), ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[411] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new ZArrayNode(support.union(((Token)yyVals[-2+yyTop]), ((Token)yyVals[0+yyTop])));
return yyVal;
}
};
states[344] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
RestArgNode rest = new UnnamedRestArgNode(((ListNode)yyVals[-1+yyTop]).getPosition(), support.getCurrentScope().addVariable("*"));
yyVal = support.new_args(((ListNode)yyVals[-1+yyTop]).getPosition(), ((ListNode)yyVals[-1+yyTop]), null, rest, null, null);
return yyVal;
}
};
states[9] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
lexer.setState(LexState.EXPR_FNAME);
return yyVal;
}
};
states[210] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "<=>", ((Node)yyVals[0+yyTop]), support.getPosition(null));
return yyVal;
}
};
states[76] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.newArrayNode(((Node)yyVals[-1+yyTop]).getPosition(), ((Node)yyVals[-1+yyTop]));
return yyVal;
}
};
states[277] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new ZYieldNode(((Token)yyVals[0+yyTop]).getPosition());
return yyVal;
}
};
states[512] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((ListNode)yyVals[-2+yyTop]).addAll(((ListNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[378] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((Token)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]), null);
return yyVal;
}
};
states[110] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.newUndef(support.getPosition(((Node)yyVals[0+yyTop])), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[311] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new NextNode(((Token)yyVals[0+yyTop]).getPosition(), NilImplicitNode.NIL);
return yyVal;
}
};
states[244] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new Long(lexer.getCmdArgumentState().begin());
return yyVal;
}
};
states[479] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(((BlockArgNode)yyVals[0+yyTop]).getPosition(), null, null, null, null, ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[412] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((ListNode)yyVals[-1+yyTop]);
return yyVal;
}
};
states[345] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((ListNode)yyVals[-5+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), ((ListNode)yyVals[-5+yyTop]), null, ((RestArgNode)yyVals[-3+yyTop]), ((ListNode)yyVals[-1+yyTop]), ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[10] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.newAlias(support.union(((Token)yyVals[-3+yyTop]), ((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[211] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), ">", ((Node)yyVals[0+yyTop]), support.getPosition(null));
return yyVal;
}
};
states[77] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((ListNode)yyVals[-2+yyTop]).add(((Node)yyVals[-1+yyTop]));
return yyVal;
}
};
states[278] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new DefinedNode(support.getPosition(((Token)yyVals[-4+yyTop])), ((Node)yyVals[-1+yyTop]));
return yyVal;
}
};
states[513] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
SourcePosition pos;
if (((Node)yyVals[-2+yyTop]) == null && ((Node)yyVals[0+yyTop]) == null) {
pos = support.getPosition(((Token)yyVals[-1+yyTop]));
} else {
pos = support.union(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
yyVal = support.newArrayNode(pos, ((Node)yyVals[-2+yyTop])).add(((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[379] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_call(((Node)yyVals[-2+yyTop]), ((Token)yyVals[0+yyTop]), null, null);
return yyVal;
}
};
states[312] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new RedoNode(((Token)yyVals[0+yyTop]).getPosition());
return yyVal;
}
};
states[44] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new ReturnNode(support.union(((Token)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])), support.ret_args(((Node)yyVals[0+yyTop]), support.getPosition(((Token)yyVals[-1+yyTop]))));
return yyVal;
}
};
states[245] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
lexer.getCmdArgumentState().reset(((Long)yyVals[-1+yyTop]).longValue());
yyVal = ((Node)yyVals[0+yyTop]);
return yyVal;
}
};
states[111] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
lexer.setState(LexState.EXPR_FNAME);
return yyVal;
}
};
states[480] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.getPosition(null), null, null, null, null, null);
return yyVal;
}
};
states[413] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new ArrayNode(support.getPosition(null));
return yyVal;
}
};
states[346] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((ListNode)yyVals[-1+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), ((ListNode)yyVals[-1+yyTop]), null, null, null, ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[11] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new VAliasNode(support.getPosition(((Token)yyVals[-2+yyTop])), (String) ((Token)yyVals[-1+yyTop]).getValue(), (String) ((Token)yyVals[0+yyTop]).getValue());
return yyVal;
}
};
states[212] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), ">=", ((Node)yyVals[0+yyTop]), support.getPosition(null));
return yyVal;
}
};
states[78] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.newArrayNode(((Node)yyVals[0+yyTop]).getPosition(), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[279] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(support.getConditionNode(((Node)yyVals[-1+yyTop])), "!");
return yyVal;
}
};
states[514] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
SourcePosition pos = support.union(((Token)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
yyVal = support.newArrayNode(pos, new SymbolNode(pos, (String) ((Token)yyVals[-1+yyTop]).getValue())).add(((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[380] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_call(((Node)yyVals[-2+yyTop]), new Token("call", ((Node)yyVals[-2+yyTop]).getPosition()), ((Node)yyVals[0+yyTop]), null);
return yyVal;
}
};
states[313] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new RetryNode(((Token)yyVals[0+yyTop]).getPosition());
return yyVal;
}
};
states[45] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new BreakNode(support.union(((Token)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])), support.ret_args(((Node)yyVals[0+yyTop]), support.getPosition(((Token)yyVals[-1+yyTop]))));
return yyVal;
}
};
states[246] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new BlockPassNode(support.union(((Token)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[112] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.appendToBlock(((Node)yyVals[-3+yyTop]), support.newUndef(support.getPosition(((Node)yyVals[-3+yyTop])), ((Node)yyVals[0+yyTop])));
return yyVal;
}
};
states[481] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.yyerror("formal argument cannot be a constant");
return yyVal;
}
};
states[414] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((ListNode)yyVals[-2+yyTop]).add(((Node)yyVals[-1+yyTop]) instanceof EvStrNode ? new DStrNode(support.getPosition(((ListNode)yyVals[-2+yyTop]))).add(((Node)yyVals[-1+yyTop])) : ((Node)yyVals[-1+yyTop]));
return yyVal;
}
};
states[347] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((ListNode)yyVals[-3+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), null, ((ListNode)yyVals[-3+yyTop]), ((RestArgNode)yyVals[-1+yyTop]), null, ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[12] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new VAliasNode(support.getPosition(((Token)yyVals[-2+yyTop])), (String) ((Token)yyVals[-1+yyTop]).getValue(), "$" + ((BackRefNode)yyVals[0+yyTop]).getType());
return yyVal;
}
};
states[213] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "<", ((Node)yyVals[0+yyTop]), support.getPosition(null));
return yyVal;
}
};
states[79] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((ListNode)yyVals[-2+yyTop]).add(((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[280] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(NilImplicitNode.NIL, "!");
return yyVal;
}
};
states[381] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_call(((Node)yyVals[-2+yyTop]), new Token("call", ((Node)yyVals[-2+yyTop]).getPosition()), ((Node)yyVals[0+yyTop]), null);
return yyVal;
}
};
states[46] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new NextNode(support.union(((Token)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])), support.ret_args(((Node)yyVals[0+yyTop]), support.getPosition(((Token)yyVals[-1+yyTop]))));
return yyVal;
}
};
states[247] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((BlockPassNode)yyVals[0+yyTop]);
return yyVal;
}
};
states[314] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]);
if (yyVal == null) yyVal = NilImplicitNode.NIL;
return yyVal;
}
};
states[482] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.yyerror("formal argument cannot be an instance variable");
return yyVal;
}
};
states[348] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((ListNode)yyVals[-5+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), null, ((ListNode)yyVals[-5+yyTop]), ((RestArgNode)yyVals[-3+yyTop]), ((ListNode)yyVals[-1+yyTop]), ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[13] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.yyerror("can't make alias for the number variables");
return yyVal;
}
};
states[214] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "<=", ((Node)yyVals[0+yyTop]), support.getPosition(null));
return yyVal;
}
};
states[80] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.assignable(((Token)yyVals[0+yyTop]), NilImplicitNode.NIL);
return yyVal;
}
};
states[281] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_fcall(((Token)yyVals[-1+yyTop]), null, ((IterNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[449] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new Token("nil", Tokens.kNIL, ((Token)yyVals[0+yyTop]).getPosition());
return yyVal;
}
};
states[382] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_super(((Node)yyVals[0+yyTop]), ((Token)yyVals[-1+yyTop]));
return yyVal;
}
};
states[248] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = null;
return yyVal;
}
};
states[483] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.yyerror("formal argument cannot be a global variable");
return yyVal;
}
};
states[416] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.literal_concat(support.getPosition(((Node)yyVals[-1+yyTop])), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[349] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((ListNode)yyVals[-1+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), null, ((ListNode)yyVals[-1+yyTop]), null, null, ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[14] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[0+yyTop]);
return yyVal;
}
};
states[215] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "==", ((Node)yyVals[0+yyTop]), support.getPosition(null));
return yyVal;
}
};
states[81] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.aryset(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
return yyVal;
}
};
states[450] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new Token("self", Tokens.kSELF, ((Token)yyVals[0+yyTop]).getPosition());
return yyVal;
}
};
states[383] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new ZSuperNode(((Token)yyVals[0+yyTop]).getPosition());
return yyVal;
}
};
states[48] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((Token)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]), null);
return yyVal;
}
};
states[484] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.yyerror("formal argument cannot be a class variable");
return yyVal;
}
};
states[417] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new ZArrayNode(support.union(((Token)yyVals[-2+yyTop]), ((Token)yyVals[0+yyTop])));
return yyVal;
}
};
states[350] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((ListNode)yyVals[-3+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), null, ((ListNode)yyVals[-3+yyTop]), null, ((ListNode)yyVals[-1+yyTop]), ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[15] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new IfNode(support.union(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])), support.getConditionNode(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]), null);
return yyVal;
}
};
states[216] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "===", ((Node)yyVals[0+yyTop]), support.getPosition(null));
return yyVal;
}
};
states[82] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.attrset(((Node)yyVals[-2+yyTop]), (String) ((Token)yyVals[0+yyTop]).getValue());
return yyVal;
}
};
states[283] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
if (((Node)yyVals[-1+yyTop]) != null &&
((BlockAcceptingNode)yyVals[-1+yyTop]).getIterNode() instanceof BlockPassNode) {
throw new SyntaxException(PID.BLOCK_ARG_AND_BLOCK_GIVEN, support.getPosition(((Node)yyVals[-1+yyTop])), "Both block arg and actual block given.");
}
yyVal = ((BlockAcceptingNode)yyVals[-1+yyTop]).setIterNode(((IterNode)yyVals[0+yyTop]));
((Node)yyVal).setPosition(support.union(((Node)yyVals[-1+yyTop]), ((IterNode)yyVals[0+yyTop])));
return yyVal;
}
};
states[451] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new Token("true", Tokens.kTRUE, ((Token)yyVals[0+yyTop]).getPosition());
return yyVal;
}
};
states[384] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
if (((Node)yyVals[-3+yyTop]) instanceof SelfNode) {
yyVal = support.new_fcall(new Token("[]", support.union(((Node)yyVals[-3+yyTop]), ((Token)yyVals[0+yyTop]))), ((Node)yyVals[-1+yyTop]), null);
} else {
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), new Token("[]", support.union(((Node)yyVals[-3+yyTop]), ((Token)yyVals[0+yyTop]))), ((Node)yyVals[-1+yyTop]), null);
}
return yyVal;
}
};
states[49] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((Token)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]), null);
return yyVal;
}
};
states[250] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.newArrayNode(support.getPosition2(((Node)yyVals[0+yyTop])), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[418] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((ListNode)yyVals[-1+yyTop]);
((ISourcePositionHolder)yyVal).setPosition(support.union(((Token)yyVals[-2+yyTop]), ((Token)yyVals[0+yyTop])));
return yyVal;
}
};
states[351] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((RestArgNode)yyVals[-1+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), null, null, ((RestArgNode)yyVals[-1+yyTop]), null, ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[16] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new IfNode(support.union(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])), support.getConditionNode(((Node)yyVals[0+yyTop])), null, ((Node)yyVals[-2+yyTop]));
return yyVal;
}
};
states[217] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "!=", ((Node)yyVals[0+yyTop]), support.getPosition(null));
return yyVal;
}
};
states[83] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.attrset(((Node)yyVals[-2+yyTop]), (String) ((Token)yyVals[0+yyTop]).getValue());
return yyVal;
}
};
states[284] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((LambdaNode)yyVals[0+yyTop]);
return yyVal;
}
};
states[452] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new Token("false", Tokens.kFALSE, ((Token)yyVals[0+yyTop]).getPosition());
return yyVal;
}
};
states[385] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.pushBlockScope();
return yyVal;
}
};
states[184] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.node_assign(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
/* FIXME: Consider fixing node_assign itself rather than single case*/
((Node)yyVal).setPosition(support.union(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])));
return yyVal;
}
};
states[50] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.pushBlockScope();
return yyVal;
}
};
states[251] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.newSplatNode(support.union(((Token)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[486] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.formal_argument(((Token)yyVals[0+yyTop]));
return yyVal;
}
};
states[419] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new ArrayNode(support.getPosition(null));
return yyVal;
}
};
states[352] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((RestArgNode)yyVals[-3+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), null, null, ((RestArgNode)yyVals[-3+yyTop]), ((ListNode)yyVals[-1+yyTop]), ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[17] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
if (((Node)yyVals[-2+yyTop]) != null && ((Node)yyVals[-2+yyTop]) instanceof BeginNode) {
yyVal = new WhileNode(support.getPosition(((Node)yyVals[-2+yyTop])), support.getConditionNode(((Node)yyVals[0+yyTop])), ((BeginNode)yyVals[-2+yyTop]).getBodyNode(), false);
} else {
yyVal = new WhileNode(support.getPosition(((Node)yyVals[-2+yyTop])), support.getConditionNode(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]), true);
}
return yyVal;
}
};
states[218] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getMatchNode(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
/* ENEBO
$$ = match_op($1, $3);
if (nd_type($1) == NODE_LIT && TYPE($1->nd_lit) == T_REGEXP) {
$$ = reg_named_capture_assign($1->nd_lit, $$);
}
*/
return yyVal;
}
};
states[84] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.attrset(((Node)yyVals[-2+yyTop]), (String) ((Token)yyVals[0+yyTop]).getValue());
return yyVal;
}
};
states[285] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new IfNode(support.union(((Token)yyVals[-5+yyTop]), ((Token)yyVals[0+yyTop])), support.getConditionNode(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
return yyVal;
}
};
states[453] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new Token("__FILE__", Tokens.k__FILE__, ((Token)yyVals[0+yyTop]).getPosition());
return yyVal;
}
};
states[386] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
- yyVal = new IterNode(support.getPosition(((Token)yyVals[-4+yyTop])), ((ArgsNode)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), support.getCurrentScope());
+ yyVal = new IterNode(support.union(((Token)yyVals[-4+yyTop]), ((Token)yyVals[0+yyTop])), ((ArgsNode)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), support.getCurrentScope());
support.popCurrentScope();
return yyVal;
}
};
states[51] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new IterNode(support.getPosition(((Token)yyVals[-4+yyTop])), ((ArgsNode)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), support.getCurrentScope());
support.popCurrentScope();
return yyVal;
}
};
states[252] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
Node node = support.splat_array(((Node)yyVals[-2+yyTop]));
if (node != null) {
yyVal = support.list_append(node, ((Node)yyVals[0+yyTop]));
} else {
yyVal = support.arg_append(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
return yyVal;
}
};
states[185] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
SourcePosition position = support.union(((Token)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
Node body = ((Node)yyVals[0+yyTop]) == null ? NilImplicitNode.NIL : ((Node)yyVals[0+yyTop]);
yyVal = support.node_assign(((Node)yyVals[-4+yyTop]), new RescueNode(position, ((Node)yyVals[-2+yyTop]), new RescueBodyNode(position, null, body, null), null));
return yyVal;
}
};
states[487] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.arg_var(((Token)yyVals[0+yyTop]));
/*
$$ = new ArgAuxiliaryNode($1.getPosition(), (String) $1.getValue(), 1);
*/
return yyVal;
}
};
states[420] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((ListNode)yyVals[-2+yyTop]).add(((Node)yyVals[-1+yyTop]));
return yyVal;
}
};
states[353] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.getPosition(((BlockArgNode)yyVals[0+yyTop])), null, null, null, null, ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[219] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new NotNode(support.union(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])), support.getMatchNode(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])));
return yyVal;
}
};
states[85] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
if (support.isInDef() || support.isInSingle()) {
support.yyerror("dynamic constant assignment");
}
SourcePosition position = support.union(((Node)yyVals[-2+yyTop]), ((Token)yyVals[0+yyTop]));
yyVal = new ConstDeclNode(position, null, support.new_colon2(position, ((Node)yyVals[-2+yyTop]), (String) ((Token)yyVals[0+yyTop]).getValue()), NilImplicitNode.NIL);
return yyVal;
}
};
states[286] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new IfNode(support.union(((Token)yyVals[-5+yyTop]), ((Token)yyVals[0+yyTop])), support.getConditionNode(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[-2+yyTop]));
return yyVal;
}
};
states[18] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
if (((Node)yyVals[-2+yyTop]) != null && ((Node)yyVals[-2+yyTop]) instanceof BeginNode) {
yyVal = new UntilNode(support.getPosition(((Node)yyVals[-2+yyTop])), support.getConditionNode(((Node)yyVals[0+yyTop])), ((BeginNode)yyVals[-2+yyTop]).getBodyNode(), false);
} else {
yyVal = new UntilNode(support.getPosition(((Node)yyVals[-2+yyTop])), support.getConditionNode(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]), true);
}
return yyVal;
}
};
states[454] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new Token("__LINE__", Tokens.k__LINE__, ((Token)yyVals[0+yyTop]).getPosition());
return yyVal;
}
};
states[387] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.pushBlockScope();
return yyVal;
}
};
states[52] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_fcall(((Token)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]), null);
return yyVal;
}
};
states[253] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
Node node = null;
/* FIXME: lose syntactical elements here (and others like this)*/
if (((Node)yyVals[0+yyTop]) instanceof ArrayNode &&
(node = support.splat_array(((Node)yyVals[-3+yyTop]))) != null) {
yyVal = support.list_concat(node, ((Node)yyVals[0+yyTop]));
} else {
yyVal = support.arg_concat(support.union(((Node)yyVals[-3+yyTop]), ((Node)yyVals[0+yyTop])), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[0+yyTop]));
}
return yyVal;
}
};
states[186] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.checkExpression(((Node)yyVals[0+yyTop]));
String asgnOp = (String) ((Token)yyVals[-1+yyTop]).getValue();
if (asgnOp.equals("||")) {
((AssignableNode)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = new OpAsgnOrNode(support.union(((AssignableNode)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])), support.gettable2(((AssignableNode)yyVals[-2+yyTop])), ((AssignableNode)yyVals[-2+yyTop]));
} else if (asgnOp.equals("&&")) {
((AssignableNode)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = new OpAsgnAndNode(support.union(((AssignableNode)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])), support.gettable2(((AssignableNode)yyVals[-2+yyTop])), ((AssignableNode)yyVals[-2+yyTop]));
} else {
((AssignableNode)yyVals[-2+yyTop]).setValueNode(support.getOperatorCallNode(support.gettable2(((AssignableNode)yyVals[-2+yyTop])), asgnOp, ((Node)yyVals[0+yyTop])));
((AssignableNode)yyVals[-2+yyTop]).setPosition(support.union(((AssignableNode)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])));
yyVal = ((AssignableNode)yyVals[-2+yyTop]);
}
return yyVal;
}
};
states[488] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[-1+yyTop]);
/* {
ID tid = internal_id();
arg_var(tid);
if (dyna_in_block()) {
$2->nd_value = NEW_DVAR(tid);
}
else {
$2->nd_value = NEW_LVAR(tid);
}
$$ = NEW_ARGS_AUX(tid, 1);
$$->nd_next = $2;*/
return yyVal;
}
};
states[421] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new StrNode(((Token)yyVals[0+yyTop]).getPosition(), "");
return yyVal;
}
};
states[354] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
/* was $$ = null;*/
yyVal = support.new_args(support.getPosition(null), null, null, null, null, null);
return yyVal;
}
};
states[220] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(support.getConditionNode(((Node)yyVals[0+yyTop])), "!");
return yyVal;
}
};
states[86] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
if (support.isInDef() || support.isInSingle()) {
support.yyerror("dynamic constant assignment");
}
SourcePosition position = support.union(((Token)yyVals[-1+yyTop]), ((Token)yyVals[0+yyTop]));
yyVal = new ConstDeclNode(position, null, support.new_colon3(position, (String) ((Token)yyVals[0+yyTop]).getValue()), NilImplicitNode.NIL);
return yyVal;
}
};
states[287] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
lexer.getConditionState().begin();
return yyVal;
}
};
states[19] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
Node body = ((Node)yyVals[0+yyTop]) == null ? NilImplicitNode.NIL : ((Node)yyVals[0+yyTop]);
yyVal = new RescueNode(support.getPosition(((Node)yyVals[-2+yyTop])), ((Node)yyVals[-2+yyTop]), new RescueBodyNode(support.getPosition(((Node)yyVals[-2+yyTop])), null, body, null), null);
return yyVal;
}
};
states[455] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new Token("__ENCODING__", Tokens.k__ENCODING__, ((Token)yyVals[0+yyTop]).getPosition());
return yyVal;
}
};
states[388] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new IterNode(support.union(((Token)yyVals[-4+yyTop]), ((Token)yyVals[0+yyTop])), ((ArgsNode)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), support.getCurrentScope());
((ISourcePositionHolder)yyVals[-5+yyTop]).setPosition(support.union(((ISourcePositionHolder)yyVals[-5+yyTop]), ((ISourcePositionHolder)yyVal)));
support.popCurrentScope();
return yyVal;
}
};
states[53] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_fcall(((Token)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), ((IterNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[254] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
Node node = support.splat_array(((Node)yyVals[-2+yyTop]));
if (node != null) {
yyVal = support.list_append(node, ((Node)yyVals[0+yyTop]));
} else {
yyVal = support.arg_append(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
return yyVal;
}
};
states[321] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new IfNode(support.getPosition(((Token)yyVals[-4+yyTop])), support.getConditionNode(((Node)yyVals[-3+yyTop])), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[187] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.checkExpression(((Node)yyVals[-2+yyTop]));
SourcePosition position = support.union(((Token)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
Node body = ((Node)yyVals[0+yyTop]) == null ? NilImplicitNode.NIL : ((Node)yyVals[0+yyTop]);
Node rest;
String asgnOp = (String) ((Token)yyVals[-3+yyTop]).getValue();
if (asgnOp.equals("||")) {
((AssignableNode)yyVals[-4+yyTop]).setValueNode(((Node)yyVals[-2+yyTop]));
rest = new OpAsgnOrNode(support.union(((AssignableNode)yyVals[-4+yyTop]), ((Node)yyVals[-2+yyTop])), support.gettable2(((AssignableNode)yyVals[-4+yyTop])), ((AssignableNode)yyVals[-4+yyTop]));
} else if (asgnOp.equals("&&")) {
((AssignableNode)yyVals[-4+yyTop]).setValueNode(((Node)yyVals[-2+yyTop]));
rest = new OpAsgnAndNode(support.union(((AssignableNode)yyVals[-4+yyTop]), ((Node)yyVals[-2+yyTop])), support.gettable2(((AssignableNode)yyVals[-4+yyTop])), ((AssignableNode)yyVals[-4+yyTop]));
} else {
((AssignableNode)yyVals[-4+yyTop]).setValueNode(support.getOperatorCallNode(support.gettable2(((AssignableNode)yyVals[-4+yyTop])), asgnOp, ((Node)yyVals[-2+yyTop])));
((AssignableNode)yyVals[-4+yyTop]).setPosition(support.union(((AssignableNode)yyVals[-4+yyTop]), ((Node)yyVals[-2+yyTop])));
rest = ((AssignableNode)yyVals[-4+yyTop]);
}
yyVal = new RescueNode(((Token)yyVals[-1+yyTop]).getPosition(), rest, new RescueBodyNode(((Token)yyVals[-1+yyTop]).getPosition(), null, body, null), null);
return yyVal;
}
};
states[489] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new ArrayNode(support.getPosition(null), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[422] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.literal_concat(support.getPosition(((Node)yyVals[-1+yyTop])), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[355] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
lexer.commandStart = true;
yyVal = ((ArgsNode)yyVals[0+yyTop]);
return yyVal;
}
};
states[221] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(((Node)yyVals[0+yyTop]), "~");
return yyVal;
}
};
states[87] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.backrefAssignError(((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[288] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
lexer.getConditionState().end();
return yyVal;
}
};
states[20] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
/* FIXME: the == here is gross; need a cleaner way to check t*/
if (support.isInDef() || support.isInSingle() || support.getCurrentScope().getClass() == BlockStaticScope.class) {
support.yyerror("BEGIN in method, singleton, or block");
}
return yyVal;
}
};
states[456] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.gettable(((Token)yyVals[0+yyTop]));
return yyVal;
}
};
states[389] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.newWhenNode(support.union(((Token)yyVals[-4+yyTop]), support.unwrapNewlineNode(((Node)yyVals[-1+yyTop]))), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[54] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((Token)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]), null);
return yyVal;
}
};
states[255] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
Node node = null;
if (((Node)yyVals[0+yyTop]) instanceof ArrayNode &&
(node = support.splat_array(((Node)yyVals[-3+yyTop]))) != null) {
yyVal = support.list_concat(node, ((Node)yyVals[0+yyTop]));
} else {
yyVal = support.arg_concat(support.union(((Node)yyVals[-3+yyTop]), ((Node)yyVals[0+yyTop])), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[0+yyTop]));
}
return yyVal;
}
};
states[188] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
/* FIXME: arg_concat missing for opt_call_args*/
yyVal = support.new_opElementAsgnNode(support.getPosition(((Node)yyVals[-5+yyTop])), ((Node)yyVals[-5+yyTop]), (String) ((Token)yyVals[-1+yyTop]).getValue(), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[490] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
((ListNode)yyVals[-2+yyTop]).add(((Node)yyVals[0+yyTop]));
yyVal = ((ListNode)yyVals[-2+yyTop]);
return yyVal;
}
};
states[423] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = null;
return yyVal;
}
};
states[356] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.getPosition(null), null, null, null, null, null);
return yyVal;
}
};
states[88] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
/* if (!($$ = assignable($1, 0))) $$ = NEW_BEGIN(0);*/
yyVal = support.assignable(((Token)yyVals[0+yyTop]), NilImplicitNode.NIL);
return yyVal;
}
};
states[289] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
Node body = ((Node)yyVals[-1+yyTop]) == null ? NilImplicitNode.NIL : ((Node)yyVals[-1+yyTop]);
yyVal = new WhileNode(support.union(((Token)yyVals[-6+yyTop]), ((Token)yyVals[0+yyTop])), support.getConditionNode(((Node)yyVals[-4+yyTop])), body);
return yyVal;
}
};
states[21] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.getResult().addBeginNode(new PreExe19Node(support.getPosition(((Node)yyVals[-1+yyTop])), support.getCurrentScope(), ((Node)yyVals[-1+yyTop])));
yyVal = null;
return yyVal;
}
};
states[222] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "<<", ((Node)yyVals[0+yyTop]), support.getPosition(null));
return yyVal;
}
};
states[457] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.assignable(((Token)yyVals[0+yyTop]), NilImplicitNode.NIL);
return yyVal;
}
};
states[256] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.newSplatNode(support.getPosition(((Token)yyVals[-1+yyTop])), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[323] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[0+yyTop]);
return yyVal;
}
};
states[189] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new OpAsgnNode(support.getPosition(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), (String) ((Token)yyVals[-2+yyTop]).getValue(), (String) ((Token)yyVals[-1+yyTop]).getValue());
return yyVal;
}
};
states[55] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_call(((Node)yyVals[-4+yyTop]), ((Token)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), ((IterNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[491] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.arg_var(support.formal_argument(((Token)yyVals[-2+yyTop])));
yyVal = new OptArgNode(((Token)yyVals[-2+yyTop]).getPosition(), support.assignable(((Token)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])));
return yyVal;
}
};
states[424] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.literal_concat(support.getPosition(((Node)yyVals[-1+yyTop])), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[357] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.getPosition(null), null, null, null, null, null);
return yyVal;
}
};
states[89] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.aryset(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
return yyVal;
}
};
states[290] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
lexer.getConditionState().begin();
return yyVal;
}
};
states[22] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
if (support.isInDef() || support.isInSingle()) {
support.warn(ID.END_IN_METHOD, support.getPosition(((Token)yyVals[-3+yyTop])), "END in method; use at_exit");
}
yyVal = new PostExeNode(support.getPosition(((Node)yyVals[-1+yyTop])), ((Node)yyVals[-1+yyTop]));
return yyVal;
}
};
states[223] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), ">>", ((Node)yyVals[0+yyTop]), support.getPosition(null));
return yyVal;
}
};
states[458] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[0+yyTop]);
return yyVal;
}
};
states[190] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new OpAsgnNode(support.getPosition(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), (String) ((Token)yyVals[-2+yyTop]).getValue(), (String) ((Token)yyVals[-1+yyTop]).getValue());
return yyVal;
}
};
states[56] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((Token)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]), null);
return yyVal;
}
};
states[492] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.arg_var(support.formal_argument(((Token)yyVals[-2+yyTop])));
yyVal = new OptArgNode(((Token)yyVals[-2+yyTop]).getPosition(), support.assignable(((Token)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])));
return yyVal;
}
};
states[425] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[0+yyTop]);
return yyVal;
}
};
states[358] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((ArgsNode)yyVals[-2+yyTop]);
return yyVal;
}
};
states[90] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.attrset(((Node)yyVals[-2+yyTop]), (String) ((Token)yyVals[0+yyTop]).getValue());
return yyVal;
}
};
states[291] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
lexer.getConditionState().end();
return yyVal;
}
};
states[23] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = support.node_assign(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[224] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.newAndNode(support.getPosition(((Token)yyVals[-1+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[459] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[0+yyTop]);
return yyVal;
}
};
states[392] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
Node node;
if (((Node)yyVals[-3+yyTop]) != null) {
node = support.appendToBlock(support.node_assign(((Node)yyVals[-3+yyTop]), new GlobalVarNode(support.getPosition(((Token)yyVals[-5+yyTop])), "$!")), ((Node)yyVals[-1+yyTop]));
if (((Node)yyVals[-1+yyTop]) != null) {
node.setPosition(support.unwrapNewlineNode(((Node)yyVals[-1+yyTop])).getPosition());
}
} else {
node = ((Node)yyVals[-1+yyTop]);
}
Node body = node == null ? NilImplicitNode.NIL : node;
yyVal = new RescueBodyNode(support.getPosition(((Token)yyVals[-5+yyTop]), true), ((Node)yyVals[-4+yyTop]), body, ((RescueBodyNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[325] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
return yyVal;
}
};
states[191] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new OpAsgnNode(support.getPosition(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), (String) ((Token)yyVals[-2+yyTop]).getValue(), (String) ((Token)yyVals[-1+yyTop]).getValue());
return yyVal;
}
};
states[57] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_call(((Node)yyVals[-4+yyTop]), ((Token)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), ((IterNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[493] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new BlockNode(support.getPosition(((Node)yyVals[0+yyTop]))).add(((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[426] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = lexer.getStrTerm();
lexer.setStrTerm(null);
lexer.setState(LexState.EXPR_BEG);
return yyVal;
}
};
states[91] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.attrset(((Node)yyVals[-2+yyTop]), (String) ((Token)yyVals[0+yyTop]).getValue());
return yyVal;
}
};
states[292] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
Node body = ((Node)yyVals[-1+yyTop]) == null ? NilImplicitNode.NIL : ((Node)yyVals[-1+yyTop]);
yyVal = new UntilNode(support.getPosition(((Token)yyVals[-6+yyTop])), support.getConditionNode(((Node)yyVals[-4+yyTop])), body);
return yyVal;
}
};
states[24] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.checkExpression(((Node)yyVals[0+yyTop]));
((MultipleAsgn19Node)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = ((MultipleAsgn19Node)yyVals[-2+yyTop]);
return yyVal;
}
};
states[225] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.newOrNode(support.getPosition(((Token)yyVals[-1+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[460] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = null;
return yyVal;
}
};
states[393] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = null;
return yyVal;
}
};
states[326] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.assignable(((Token)yyVals[0+yyTop]), NilImplicitNode.NIL);
return yyVal;
}
};
states[192] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.yyerror("constant re-assignment");
return yyVal;
}
};
states[58] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_super(((Node)yyVals[0+yyTop]), ((Token)yyVals[-1+yyTop])); /* .setPosFrom($2);*/
return yyVal;
}
};
states[494] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.appendToBlock(((ListNode)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[427] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
lexer.setStrTerm(((StrTerm)yyVals[-1+yyTop]));
yyVal = new EvStrNode(support.union(((Token)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[360] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = null;
return yyVal;
}
};
states[293] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.newCaseNode(support.union(((Token)yyVals[-4+yyTop]), ((Token)yyVals[0+yyTop])), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
return yyVal;
}
};
states[25] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.checkExpression(((Node)yyVals[0+yyTop]));
String asgnOp = (String) ((Token)yyVals[-1+yyTop]).getValue();
if (asgnOp.equals("||")) {
((AssignableNode)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = new OpAsgnOrNode(support.union(((AssignableNode)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])), support.gettable2(((AssignableNode)yyVals[-2+yyTop])), ((AssignableNode)yyVals[-2+yyTop]));
} else if (asgnOp.equals("&&")) {
((AssignableNode)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = new OpAsgnAndNode(support.union(((AssignableNode)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])), support.gettable2(((AssignableNode)yyVals[-2+yyTop])), ((AssignableNode)yyVals[-2+yyTop]));
} else {
((AssignableNode)yyVals[-2+yyTop]).setValueNode(support.getOperatorCallNode(support.gettable2(((AssignableNode)yyVals[-2+yyTop])), asgnOp, ((Node)yyVals[0+yyTop])));
((AssignableNode)yyVals[-2+yyTop]).setPosition(support.union(((AssignableNode)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])));
yyVal = ((AssignableNode)yyVals[-2+yyTop]);
}
return yyVal;
}
};
states[226] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
/* ENEBO: arg surrounded by in_defined set/unset*/
yyVal = new DefinedNode(support.getPosition(((Token)yyVals[-2+yyTop])), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[92] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.attrset(((Node)yyVals[-2+yyTop]), (String) ((Token)yyVals[0+yyTop]).getValue());
return yyVal;
}
};
states[461] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
lexer.setState(LexState.EXPR_BEG);
return yyVal;
}
};
states[394] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.newArrayNode(((Node)yyVals[0+yyTop]).getPosition(), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[327] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[-1+yyTop]);
return yyVal;
}
};
states[193] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.yyerror("constant re-assignment");
return yyVal;
}
};
states[59] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_yield(support.union(((Token)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[495] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new BlockNode(support.getPosition(((Node)yyVals[0+yyTop]))).add(((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[428] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = lexer.getStrTerm();
lexer.getConditionState().stop();
lexer.getCmdArgumentState().stop();
lexer.setStrTerm(null);
lexer.setState(LexState.EXPR_BEG);
return yyVal;
}
};
states[361] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = null;
return yyVal;
}
};
states[294] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.newCaseNode(support.union(((Token)yyVals[-3+yyTop]), ((Token)yyVals[0+yyTop])), null, ((Node)yyVals[-1+yyTop]));
return yyVal;
}
};
states[26] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
/* FIXME: arg_concat logic missing for opt_call_args*/
yyVal = support.new_opElementAsgnNode(support.getPosition(((Node)yyVals[-5+yyTop])), ((Node)yyVals[-5+yyTop]), (String) ((Token)yyVals[-1+yyTop]).getValue(), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[227] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new IfNode(support.getPosition(((Node)yyVals[-5+yyTop])), support.getConditionNode(((Node)yyVals[-5+yyTop])), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[93] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
if (support.isInDef() || support.isInSingle()) {
support.yyerror("dynamic constant assignment");
}
SourcePosition position = support.union(((Node)yyVals[-2+yyTop]), ((Token)yyVals[0+yyTop]));
yyVal = new ConstDeclNode(position, null, support.new_colon2(position, ((Node)yyVals[-2+yyTop]), (String) ((Token)yyVals[0+yyTop]).getValue()), NilImplicitNode.NIL);
return yyVal;
}
};
states[462] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[-1+yyTop]);
return yyVal;
}
};
states[395] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.splat_array(((Node)yyVals[0+yyTop]));
if (yyVal == null) yyVal = ((Node)yyVals[0+yyTop]);
return yyVal;
}
};
states[328] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.newArrayNode(((Node)yyVals[0+yyTop]).getPosition(), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[194] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.backrefAssignError(((Node)yyVals[-2+yyTop]));
return yyVal;
}
};
states[496] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.appendToBlock(((ListNode)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[429] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
lexer.setStrTerm(((StrTerm)yyVals[-2+yyTop]));
yyVal = support.newEvStrNode(support.union(((Token)yyVals[-3+yyTop]), ((Token)yyVals[0+yyTop])), ((Node)yyVals[-1+yyTop]));
return yyVal;
}
};
states[362] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = null;
return yyVal;
}
};
states[295] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
lexer.getConditionState().begin();
return yyVal;
}
};
states[27] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new OpAsgnNode(support.getPosition(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), (String) ((Token)yyVals[-2+yyTop]).getValue(), (String) ((Token)yyVals[-1+yyTop]).getValue());
return yyVal;
}
};
states[228] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[0+yyTop]);
return yyVal;
}
};
states[94] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
if (support.isInDef() || support.isInSingle()) {
support.yyerror("dynamic constant assignment");
}
SourcePosition position = support.union(((Token)yyVals[-1+yyTop]), ((Token)yyVals[0+yyTop]));
yyVal = new ConstDeclNode(position, null, support.new_colon3(position, (String) ((Token)yyVals[0+yyTop]).getValue()), NilImplicitNode.NIL);
return yyVal;
}
};
states[463] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = null;
return yyVal;
}
};
states[329] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((ListNode)yyVals[-2+yyTop]).add(((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[195] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.checkExpression(((Node)yyVals[-2+yyTop]));
support.checkExpression(((Node)yyVals[0+yyTop]));
boolean isLiteral = ((Node)yyVals[-2+yyTop]) instanceof FixnumNode && ((Node)yyVals[0+yyTop]) instanceof FixnumNode;
yyVal = new DotNode(support.union(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]), false, isLiteral);
return yyVal;
}
};
states[61] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[-1+yyTop]);
return yyVal;
}
};
states[430] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new GlobalVarNode(((Token)yyVals[0+yyTop]).getPosition(), (String) ((Token)yyVals[0+yyTop]).getValue());
return yyVal;
}
};
states[363] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.new_bv(((Token)yyVals[0+yyTop]));
return yyVal;
}
};
states[28] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new OpAsgnNode(support.getPosition(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), (String) ((Token)yyVals[-2+yyTop]).getValue(), (String) ((Token)yyVals[-1+yyTop]).getValue());
return yyVal;
}
};
states[229] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]) != null ? ((Node)yyVals[0+yyTop]) : NilImplicitNode.NIL;
return yyVal;
}
};
states[95] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.backrefAssignError(((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[296] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
lexer.getConditionState().end();
return yyVal;
}
};
states[531] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Token)yyVals[0+yyTop]);
return yyVal;
}
};
states[464] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((ArgsNode)yyVals[-1+yyTop]);
((ISourcePositionHolder)yyVal).setPosition(support.union(((Token)yyVals[-2+yyTop]), ((Token)yyVals[0+yyTop])));
lexer.setState(LexState.EXPR_BEG);
return yyVal;
}
};
states[397] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[0+yyTop]);
return yyVal;
}
};
states[330] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new MultipleAsgn19Node(support.getPosition(((ListNode)yyVals[0+yyTop])), ((ListNode)yyVals[0+yyTop]), null, null);
return yyVal;
}
};
states[196] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.checkExpression(((Node)yyVals[-2+yyTop]));
support.checkExpression(((Node)yyVals[0+yyTop]));
boolean isLiteral = ((Node)yyVals[-2+yyTop]) instanceof FixnumNode && ((Node)yyVals[0+yyTop]) instanceof FixnumNode;
yyVal = new DotNode(support.union(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]), true, isLiteral);
return yyVal;
}
};
states[62] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((MultipleAsgn19Node)yyVals[0+yyTop]);
return yyVal;
}
};
states[431] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new InstVarNode(((Token)yyVals[0+yyTop]).getPosition(), (String) ((Token)yyVals[0+yyTop]).getValue());
return yyVal;
}
};
states[364] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = null;
return yyVal;
}
};
states[29] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new OpAsgnNode(support.getPosition(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), (String) ((Token)yyVals[-2+yyTop]).getValue(), (String) ((Token)yyVals[-1+yyTop]).getValue());
return yyVal;
}
};
states[96] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.yyerror("class/module name must be CONSTANT");
return yyVal;
}
};
states[297] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
/* ENEBO: Lots of optz in 1.9 parser here*/
yyVal = new ForNode(support.union(((Token)yyVals[-8+yyTop]), ((Token)yyVals[0+yyTop])), ((Node)yyVals[-7+yyTop]), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[-4+yyTop]), support.getCurrentScope());
return yyVal;
}
};
states[532] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Token)yyVals[0+yyTop]);
return yyVal;
}
};
states[465] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((ArgsNode)yyVals[-1+yyTop]);
return yyVal;
}
};
states[331] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new MultipleAsgn19Node(support.getPosition(((ListNode)yyVals[-3+yyTop])), ((ListNode)yyVals[-3+yyTop]), support.assignable(((Token)yyVals[0+yyTop]), null), null);
return yyVal;
}
};
states[197] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "+", ((Node)yyVals[0+yyTop]), support.getPosition(null));
return yyVal;
}
};
states[63] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new MultipleAsgn19Node(support.getPosition(((Token)yyVals[-2+yyTop])), support.newArrayNode(support.getPosition(((Token)yyVals[-2+yyTop])), ((Node)yyVals[-1+yyTop])), null, null);
return yyVal;
}
};
states[499] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
if (!support.is_local_id(((Token)yyVals[0+yyTop]))) {
support.yyerror("duplicate rest argument name");
}
yyVal = new RestArgNode(support.arg_var(support.shadowing_lvar(((Token)yyVals[0+yyTop]))));
return yyVal;
}
};
states[432] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new ClassVarNode(((Token)yyVals[0+yyTop]).getPosition(), (String) ((Token)yyVals[0+yyTop]).getValue());
return yyVal;
}
};
states[365] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.pushBlockScope();
yyVal = lexer.getLeftParenBegin();
lexer.setLeftParenBegin(lexer.incrementParenNest());
return yyVal;
}
};
states[30] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
support.backrefAssignError(((Node)yyVals[-2+yyTop]));
return yyVal;
}
};
states[231] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[-1+yyTop]);
return yyVal;
}
};
states[298] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
if (support.isInDef() || support.isInSingle()) {
support.yyerror("class definition in method body");
}
support.pushLocalScope();
return yyVal;
}
};
states[466] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((ListNode)yyVals[-5+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), ((ListNode)yyVals[-5+yyTop]), ((ListNode)yyVals[-3+yyTop]), ((RestArgNode)yyVals[-1+yyTop]), null, ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[399] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((Node)yyVals[0+yyTop]);
return yyVal;
}
};
states[332] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new MultipleAsgn19Node(support.getPosition(((ListNode)yyVals[-5+yyTop])), ((ListNode)yyVals[-5+yyTop]), support.assignable(((Token)yyVals[-2+yyTop]), null), ((ListNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[198] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "-", ((Node)yyVals[0+yyTop]), support.getPosition(null));
return yyVal;
}
};
states[64] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new MultipleAsgn19Node(support.getPosition(((ListNode)yyVals[0+yyTop])), ((ListNode)yyVals[0+yyTop]), null, null);
return yyVal;
}
};
states[265] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_fcall(((Token)yyVals[0+yyTop]), null, null);
return yyVal;
}
};
states[500] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new UnnamedRestArgNode(((Token)yyVals[0+yyTop]).getPosition(), support.getCurrentScope().getLocalScope().addVariable("*"));
return yyVal;
}
};
states[366] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new LambdaNode(support.union(((ArgsNode)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])), ((ArgsNode)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]), support.getCurrentScope());
support.popCurrentScope();
lexer.setLeftParenBegin(((Integer)yyVals[-2+yyTop]));
return yyVal;
}
};
states[31] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.node_assign(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
return yyVal;
}
};
states[232] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.arg_append(((Node)yyVals[-3+yyTop]), new HashNode(support.getPosition(null), ((ListNode)yyVals[-1+yyTop])));
return yyVal;
}
};
states[98] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_colon3(support.union(((Token)yyVals[-1+yyTop]), ((Token)yyVals[0+yyTop])), (String) ((Token)yyVals[0+yyTop]).getValue());
return yyVal;
}
};
states[299] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
Node body = ((Node)yyVals[-1+yyTop]) == null ? NilImplicitNode.NIL : ((Node)yyVals[-1+yyTop]);
yyVal = new ClassNode(support.union(((Token)yyVals[-5+yyTop]), ((Token)yyVals[0+yyTop])), ((Colon3Node)yyVals[-4+yyTop]), support.getCurrentScope(), body, ((Node)yyVals[-3+yyTop]));
support.popCurrentScope();
return yyVal;
}
};
states[467] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((ListNode)yyVals[-7+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), ((ListNode)yyVals[-7+yyTop]), ((ListNode)yyVals[-5+yyTop]), ((RestArgNode)yyVals[-3+yyTop]), ((ListNode)yyVals[-1+yyTop]), ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[333] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new MultipleAsgn19Node(support.getPosition(((ListNode)yyVals[-2+yyTop])), ((ListNode)yyVals[-2+yyTop]), new StarNode(support.getPosition(null)), null);
return yyVal;
}
};
states[199] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "*", ((Node)yyVals[0+yyTop]), support.getPosition(null));
return yyVal;
}
};
states[65] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new MultipleAsgn19Node(support.union(((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])), ((ListNode)yyVals[-1+yyTop]).add(((Node)yyVals[0+yyTop])), null, null);
return yyVal;
}
};
states[266] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new BeginNode(support.union(((Token)yyVals[-2+yyTop]), ((Token)yyVals[0+yyTop])), ((Node)yyVals[-1+yyTop]) == null ? NilImplicitNode.NIL : ((Node)yyVals[-1+yyTop]));
return yyVal;
}
};
states[434] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
lexer.setState(LexState.EXPR_END);
yyVal = ((Token)yyVals[0+yyTop]);
((ISourcePositionHolder)yyVal).setPosition(support.union(((Token)yyVals[-1+yyTop]), ((Token)yyVals[0+yyTop])));
return yyVal;
}
};
states[367] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = ((ArgsNode)yyVals[-2+yyTop]);
((ISourcePositionHolder)yyVal).setPosition(support.union(((Token)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop])));
return yyVal;
}
};
states[32] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
((MultipleAsgn19Node)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = ((MultipleAsgn19Node)yyVals[-2+yyTop]);
return yyVal;
}
};
states[233] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.newArrayNode(support.getPosition(((ListNode)yyVals[-1+yyTop])), new HashNode(support.getPosition(null), ((ListNode)yyVals[-1+yyTop])));
return yyVal;
}
};
states[99] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_colon2(((Token)yyVals[0+yyTop]).getPosition(), null, (String) ((Token)yyVals[0+yyTop]).getValue());
return yyVal;
}
};
states[300] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new Boolean(support.isInDef());
support.setInDef(false);
return yyVal;
}
};
states[468] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.new_args(support.union(((ListNode)yyVals[-3+yyTop]), ((BlockArgNode)yyVals[0+yyTop])), ((ListNode)yyVals[-3+yyTop]), ((ListNode)yyVals[-1+yyTop]), null, null, ((BlockArgNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[334] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new MultipleAsgn19Node(support.getPosition(((ListNode)yyVals[-4+yyTop])), ((ListNode)yyVals[-4+yyTop]), new StarNode(support.getPosition(null)), ((ListNode)yyVals[0+yyTop]));
return yyVal;
}
};
states[200] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "/", ((Node)yyVals[0+yyTop]), support.getPosition(null));
return yyVal;
}
};
states[66] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
yyVal = new MultipleAsgn19Node(support.getPosition(((ListNode)yyVals[-2+yyTop])), ((ListNode)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]), (ListNode) null);
return yyVal;
}
};
states[267] = new ParserState() {
public Object execute(ParserSupport support, Lexer lexer, Object yyVal, Object[] yyVals, int yyTop) {
lexer.setState(LexState.EXPR_ENDARG);
return yyVal;
}
};
}
// line 1984 "Ruby19parser.y"
/** The parse method use an lexer stream and parse it to an AST node
* structure
*/
public ParserResult parse(ParserConfiguration configuration, LexerSource source) throws IOException {
support.reset();
support.setConfiguration(configuration);
support.setResult(new ParserResult());
lexer.reset();
lexer.setSource(source);
Object debugger = null;
if (configuration.isDebug()) {
try {
Class yyDebugAdapterClass = Class.forName("jay.yydebug.yyDebugAdapter");
debugger = yyDebugAdapterClass.newInstance();
} catch (IllegalAccessException iae) {
// ignore, no debugger present
} catch (InstantiationException ie) {
// ignore, no debugger present
} catch (ClassNotFoundException cnfe) {
// ignore, no debugger present
}
}
//yyparse(lexer, new jay.yydebug.yyAnim("JRuby", 9));
yyparse(lexer, debugger);
return support.getResult();
}
// +++
// Helper Methods
}
// line 8033 "-"
| true | false | null | null |
diff --git a/src/main/java/com/wesabe/bouncer/servlets/HealthServlet.java b/src/main/java/com/wesabe/bouncer/servlets/HealthServlet.java
index d690863..030e5d4 100644
--- a/src/main/java/com/wesabe/bouncer/servlets/HealthServlet.java
+++ b/src/main/java/com/wesabe/bouncer/servlets/HealthServlet.java
@@ -1,62 +1,70 @@
package com.wesabe.bouncer.servlets;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import net.spy.memcached.MemcachedClientIF;
/**
* Responds to GET requests with 200 OK if the database and memcache connections
* are live; 500 Internal Service Error otherwise.
*
* @author coda
*
*/
public class HealthServlet extends HttpServlet {
private static final long serialVersionUID = -8313510800154929279L;
private final DataSource dataSource;
private final MemcachedClientIF memcached;
public HealthServlet(DataSource dataSource, MemcachedClientIF memcached) {
this.dataSource = dataSource;
this.memcached = memcached;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
if (databaseWorks() && memcacheWorks()) {
resp.sendError(HttpServletResponse.SC_OK);
} else {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
-
+
private boolean memcacheWorks() {
return !memcached.getStats().isEmpty();
}
private boolean databaseWorks() {
try {
final Connection connection = dataSource.getConnection();
try {
final PreparedStatement statement = connection.prepareStatement("SELECT 1");
- final ResultSet results = statement.executeQuery();
- return results.first() && (results.getInt(1) == 1);
+ try {
+ final ResultSet results = statement.executeQuery();
+ try {
+ return results.first() && (results.getInt(1) == 1);
+ } finally {
+ results.close();
+ }
+ } finally {
+ statement.close();
+ }
} finally {
connection.close();
}
} catch (SQLException e) {
return false;
}
}
}
diff --git a/src/test/java/com/wesabe/bouncer/servlets/tests/HealthServletTest.java b/src/test/java/com/wesabe/bouncer/servlets/tests/HealthServletTest.java
index eda8de3..5f2e0d6 100644
--- a/src/test/java/com/wesabe/bouncer/servlets/tests/HealthServletTest.java
+++ b/src/test/java/com/wesabe/bouncer/servlets/tests/HealthServletTest.java
@@ -1,186 +1,189 @@
package com.wesabe.bouncer.servlets.tests;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import net.spy.memcached.MemcachedClientIF;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import com.google.common.collect.ImmutableMap;
import com.wesabe.bouncer.servlets.HealthServlet;
@RunWith(Enclosed.class)
public class HealthServletTest {
private static abstract class Context {
protected DataSource dataSource;
protected MemcachedClientIF memcached;
protected HealthServlet servlet;
protected HttpServletRequest request;
protected HttpServletResponse response;
protected Connection connection;
protected PreparedStatement query;
protected ResultSet results;
protected Map<SocketAddress, Map<String, String>> stats;
public void setup() throws Exception {
this.results = mock(ResultSet.class);
this.query = mock(PreparedStatement.class);
when(query.executeQuery()).thenReturn(results);
this.connection = mock(Connection.class);
when(connection.prepareStatement(anyString())).thenReturn(query);
this.dataSource = mock(DataSource.class);
when(dataSource.getConnection()).thenReturn(connection);
this.memcached = mock(MemcachedClientIF.class);
this.servlet = new HealthServlet(dataSource, memcached);
this.request = mock(HttpServletRequest.class);
when(request.getMethod()).thenReturn("GET");
this.response = mock(HttpServletResponse.class);
}
}
public static class Handling_A_Health_Request_When_Healthy extends Context {
@Before
@Override
public void setup() throws Exception {
super.setup();
when(results.first()).thenReturn(true);
when(results.getInt(anyInt())).thenReturn(1);
this.stats = ImmutableMap.of((SocketAddress) new InetSocketAddress("example", 11211), (Map<String, String>) ImmutableMap.of("one", "two"));
when(memcached.getStats()).thenReturn(stats);
}
@Test
public void itReturns200OK() throws Exception {
servlet.service(request, response);
verify(response).sendError(200);
}
@Test
public void itChecksMemcacheForLiveness() throws Exception {
servlet.service(request, response);
verify(memcached).getStats();
}
@Test
public void itChecksTheDatabaseForLiveness() throws Exception {
servlet.service(request, response);
InOrder inOrder = inOrder(dataSource, connection, query, results);
inOrder.verify(dataSource).getConnection();
inOrder.verify(connection).prepareStatement("SELECT 1");
inOrder.verify(query).executeQuery();
inOrder.verify(results).first();
inOrder.verify(results).getInt(1);
+ inOrder.verify(results).close();
+ inOrder.verify(query).close();
+ inOrder.verify(connection).close();
}
}
public static class Handling_A_Health_Request_When_Memcached_Is_Down extends Context {
@Before
@Override
public void setup() throws Exception {
super.setup();
when(results.first()).thenReturn(true);
when(results.getInt(anyInt())).thenReturn(1);
this.stats = ImmutableMap.of();
when(memcached.getStats()).thenReturn(stats);
}
@Test
public void itReturns500() throws Exception {
servlet.service(request, response);
verify(response).sendError(500);
}
@Test
public void itChecksMemcacheForLiveness() throws Exception {
servlet.service(request, response);
verify(memcached).getStats();
}
}
public static class Handling_A_Health_Request_When_Database_Is_Down extends Context {
@Before
@Override
public void setup() throws Exception {
super.setup();
when(dataSource.getConnection()).thenThrow(new SQLException("AUGH FIRE"));
}
@Test
public void itReturns500() throws Exception {
servlet.service(request, response);
verify(response).sendError(500);
}
}
public static class Handling_A_Health_Request_When_Database_Is_Not_Returning_Results extends Context {
@Before
@Override
public void setup() throws Exception {
super.setup();
when(results.first()).thenReturn(false);
}
@Test
public void itReturns500() throws Exception {
servlet.service(request, response);
verify(response).sendError(500);
}
}
public static class Handling_A_Health_Request_When_Database_Is_Returning_Bad_Results extends Context {
@Before
@Override
public void setup() throws Exception {
super.setup();
when(results.first()).thenReturn(true);
when(results.getInt(anyInt())).thenReturn(2);
}
@Test
public void itReturns500() throws Exception {
servlet.service(request, response);
verify(response).sendError(500);
}
}
}
| false | false | null | null |
diff --git a/common/plugins/com.liferay.ide.core/src/com/liferay/ide/core/LiferayCore.java b/common/plugins/com.liferay.ide.core/src/com/liferay/ide/core/LiferayCore.java
index 52958ffff..bfe87dcf9 100644
--- a/common/plugins/com.liferay.ide.core/src/com/liferay/ide/core/LiferayCore.java
+++ b/common/plugins/com.liferay.ide.core/src/com/liferay/ide/core/LiferayCore.java
@@ -1,212 +1,227 @@
/*******************************************************************************
* Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*******************************************************************************/
package com.liferay.ide.core;
import com.liferay.ide.core.util.CoreUtil;
import org.eclipse.core.net.proxy.IProxyService;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Plugin;
import org.eclipse.core.runtime.Status;
import org.osgi.framework.BundleContext;
import org.osgi.util.tracker.ServiceTracker;
/**
*
* @author Gregory Amerson
*/
public class LiferayCore extends Plugin
{
private static LiferayProjectAdapterReader adapterReader;
// The shared instance
private static LiferayCore plugin;
// The plugin ID
public static final String PLUGIN_ID = "com.liferay.ide.core"; //$NON-NLS-1$
private static LiferayProjectProviderReader providerReader;
public static ILiferayProject create( Object adaptable )
{
ILiferayProject project = null;
final ILiferayProjectProvider[] providers = getProviders( adaptable.getClass() );
if( ! CoreUtil.isNullOrEmpty( providers ) )
{
ILiferayProjectProvider currentProvider = null;
for( ILiferayProjectProvider provider : providers )
{
if ( currentProvider == null || provider.getPriority() > currentProvider.getPriority() )
{
final ILiferayProject lrp = provider.provide( adaptable );
if( lrp != null )
{
currentProvider = provider;
project = lrp;
}
}
}
}
if( project == null )
{
- LiferayCore.logError( "No liferay project providers registered for type: " + adaptable.getClass() ); //$NON-NLS-1$
+ LiferayCore.logInfo( "No liferay project providers registered for type: " + adaptable.getClass() ); //$NON-NLS-1$
}
return project;
}
public static IStatus createErrorStatus( Exception e )
{
return createErrorStatus( PLUGIN_ID, e );
}
public static IStatus createErrorStatus( String msg )
{
return createErrorStatus( PLUGIN_ID, msg );
}
public static IStatus createErrorStatus( String pluginId, String msg )
{
return new Status( IStatus.ERROR, pluginId, msg );
}
public static IStatus createErrorStatus( String pluginId, String msg, Throwable e )
{
return new Status( IStatus.ERROR, pluginId, msg, e );
}
public static IStatus createErrorStatus( String pluginId, Throwable t )
{
return new Status( IStatus.ERROR, pluginId, t.getMessage(), t );
}
+ public static IStatus createInfoStatus( String msg )
+ {
+ return createInfoStatus( PLUGIN_ID, msg );
+ }
+
+ public static IStatus createInfoStatus( String pluginId, String msg )
+ {
+ return new Status( IStatus.INFO, pluginId, msg );
+ }
+
public static IStatus createWarningStatus( String message )
{
return new Status( IStatus.WARNING, PLUGIN_ID, message );
}
public static IStatus createWarningStatus( String message, String id )
{
return new Status( IStatus.WARNING, id, message );
}
public static IStatus createWarningStatus( String message, String id, Exception e )
{
return new Status( IStatus.WARNING, id, message, e );
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static LiferayCore getDefault()
{
return plugin;
}
public static synchronized ILiferayProjectAdapter[] getProjectAdapters()
{
if( adapterReader == null )
{
adapterReader = new LiferayProjectAdapterReader();
}
return adapterReader.getExtensions().toArray( new ILiferayProjectAdapter[0] );
}
public static synchronized ILiferayProjectProvider[] getProviders( Class<?> type )
{
if( providerReader == null )
{
providerReader = new LiferayProjectProviderReader();
}
return providerReader.getProviders( type );
}
public static IProxyService getProxyService()
{
final ServiceTracker<Object, Object> proxyTracker =
new ServiceTracker<Object, Object>(
getDefault().getBundle().getBundleContext(), IProxyService.class.getName(), null );
proxyTracker.open();
final IProxyService proxyService = (IProxyService) proxyTracker.getService();
proxyTracker.close();
return proxyService;
}
public static void logError( IStatus status )
{
getDefault().getLog().log( status );
}
public static void logError( String msg )
{
logError( createErrorStatus( msg ) );
}
public static void logError( String msg, Throwable t )
{
getDefault().getLog().log( createErrorStatus( PLUGIN_ID, msg, t ) );
}
public static void logError( Throwable t )
{
getDefault().getLog().log( new Status( IStatus.ERROR, PLUGIN_ID, t.getMessage(), t ) );
}
+ public static void logInfo( String msg )
+ {
+ logError( createInfoStatus( msg ) );
+ }
+
public static void logWarning( Throwable t )
{
getDefault().getLog().log( new Status( IStatus.WARNING, PLUGIN_ID, t.getMessage(), t ) );
}
/**
* The constructor
*/
public LiferayCore()
{
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext )
*/
public void start( BundleContext context ) throws Exception
{
super.start( context );
plugin = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext )
*/
public void stop( BundleContext context ) throws Exception
{
plugin = null;
super.stop( context );
}
}
diff --git a/maven/plugins/com.liferay.ide.maven.core/src/com/liferay/ide/maven/core/MavenUtil.java b/maven/plugins/com.liferay.ide.maven.core/src/com/liferay/ide/maven/core/MavenUtil.java
index e582d82e4..0e48cf4bb 100644
--- a/maven/plugins/com.liferay.ide.maven.core/src/com/liferay/ide/maven/core/MavenUtil.java
+++ b/maven/plugins/com.liferay.ide.maven.core/src/com/liferay/ide/maven/core/MavenUtil.java
@@ -1,315 +1,315 @@
/*******************************************************************************
* Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
*******************************************************************************/
package com.liferay.ide.maven.core;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.apache.maven.execution.MavenExecutionRequest;
import org.apache.maven.lifecycle.MavenExecutionPlan;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.m2e.core.MavenPlugin;
import org.eclipse.m2e.core.embedder.IMaven;
import org.eclipse.m2e.core.embedder.IMavenExecutionContext;
import org.eclipse.m2e.core.internal.IMavenConstants;
import org.eclipse.m2e.core.project.IMavenProjectFacade;
import org.eclipse.m2e.core.project.IMavenProjectRegistry;
import org.eclipse.m2e.core.project.ResolverConfiguration;
import org.eclipse.m2e.wtp.ProjectUtils;
/**
* @author Gregory Amerson
*/
@SuppressWarnings( "restriction" )
public class MavenUtil
{
public static IStatus executeMojoGoal( final IMavenProjectFacade projectFacade,
- final IMavenExecutionContext context,
- final String goal,
- final IProgressMonitor monitor ) throws CoreException
+ final IMavenExecutionContext context,
+ final String goal,
+ final IProgressMonitor monitor ) throws CoreException
{
IStatus retval = null;
final IMaven maven = MavenPlugin.getMaven();
final List<String> goals = Collections.singletonList( goal );
final MavenExecutionPlan plan = maven.calculateExecutionPlan( projectFacade.getMavenProject(), goals, true, monitor );
// context.getExecutionRequest().setOffline( true );
// context.getExecutionRequest().setRecursive( false );
final MojoExecution liferayMojoExecution =
getExecution( plan, ILiferayMavenConstants.LIFERAY_MAVEN_PLUGIN_ARTIFACT_ID );
if( liferayMojoExecution != null )
{
ResolverConfiguration configuration = projectFacade.getResolverConfiguration();
configuration.setResolveWorkspaceProjects( true );
maven.execute( projectFacade.getMavenProject(), liferayMojoExecution, monitor );
}
List<Throwable> exceptions = context.getSession().getResult().getExceptions();
if( exceptions.size() == 1 )
{
retval = LiferayMavenCore.createErrorStatus( exceptions.get( 0 ) );
}
else if( exceptions.size() > 1 )
{
List<IStatus> statues = new ArrayList<IStatus>();
for( Throwable t : exceptions )
{
statues.add( LiferayMavenCore.createErrorStatus( t ) );
}
final IStatus firstStatus = statues.get( 0 );
retval =
new MultiStatus(
LiferayMavenCore.PLUGIN_ID, IStatus.ERROR, statues.toArray( new IStatus[0] ),
firstStatus.getMessage(), firstStatus.getException() );
}
return retval == null ? Status.OK_STATUS : retval;
}
public static MojoExecution getExecution( MavenExecutionPlan plan, String artifactId )
{
if( plan != null )
{
for( MojoExecution execution : plan.getMojoExecutions() )
{
if( artifactId.equals( execution.getArtifactId() ) )
{
return execution;
}
}
}
return null;
}
public static IFolder getGeneratedThemeResourcesFolder( MavenProject mavenProject, IProject project )
{
IPath m2eLiferayFolder = getM2eLiferayFolder( mavenProject, project );
return project.getFolder( m2eLiferayFolder ).getFolder( ILiferayMavenConstants.THEME_RESOURCES_FOLDER );
}
public static Plugin getLiferayMavenPlugin( MavenProject mavenProject )
{
Plugin retval = null;
if( mavenProject != null )
{
retval = mavenProject.getPlugin( ILiferayMavenConstants.LIFERAY_MAVEN_PLUGIN_KEY );
}
return retval;
}
public static Xpp3Dom getLiferayMavenPluginConfig( MavenProject mavenProject )
{
Xpp3Dom retval = null;
if( mavenProject != null )
{
final Plugin plugin = mavenProject.getPlugin( ILiferayMavenConstants.LIFERAY_MAVEN_PLUGIN_KEY );
if( plugin != null )
{
retval = (Xpp3Dom) plugin.getConfiguration();
}
}
return retval;
}
public static String getLiferayMavenPluginConfig( MavenProject mavenProject, String childElement )
{
String retval = null;
Xpp3Dom liferayMavenPluginConfig = getLiferayMavenPluginConfig( mavenProject );
if( liferayMavenPluginConfig != null )
{
final Xpp3Dom childNode = liferayMavenPluginConfig.getChild( childElement );
if( childNode != null )
{
retval = childNode.getValue();
}
}
return retval;
}
public static String getLiferayMavenPluginType( MavenProject mavenProject )
{
String pluginType = getLiferayMavenPluginConfig( mavenProject,
ILiferayMavenConstants.PLUGIN_CONFIG_PLUGIN_TYPE );
if( pluginType == null )
{
// check for EXT
pluginType = ILiferayMavenConstants.DEFAULT_PLUGIN_TYPE;
}
return pluginType;
}
public static IPath getM2eLiferayFolder( MavenProject mavenProject, IProject project )
{
String buildOutputDir = mavenProject.getBuild().getDirectory();
String relativeBuildOutputDir = ProjectUtils.getRelativePath( project, buildOutputDir );
return new Path( relativeBuildOutputDir ).append( ILiferayMavenConstants.M2E_LIFERAY_FOLDER );
}
public static IMavenProjectFacade getProjectFacade( final IProject project )
{
return getProjectFacade( project, new NullProgressMonitor() );
}
public static IMavenProjectFacade getProjectFacade( final IProject project, final IProgressMonitor monitor )
{
final IMavenProjectRegistry projectManager = MavenPlugin.getMavenProjectRegistry();
final IFile pomResource = project.getFile( IMavenConstants.POM_FILE_NAME );
IMavenProjectFacade projectFacade = projectManager.create( project, monitor );
if( projectFacade == null || projectFacade.isStale() )
{
try
{
projectManager.refresh( Collections.singleton( pomResource ), monitor );
}
catch( CoreException e )
{
LiferayMavenCore.logError( e );
}
projectFacade = projectManager.create( project, monitor );
if( projectFacade == null )
{
// error marker should have been created
}
}
return projectFacade;
}
public static String getVersion( String version )
{
DefaultArtifactVersion v = new DefaultArtifactVersion( version );
return v.getMajorVersion() + "." + v.getMinorVersion() + "." + v.getIncrementalVersion(); //$NON-NLS-1$ //$NON-NLS-2$
}
public static boolean isMavenProject( IProject project ) throws CoreException
{
- return project != null &&
+ return project != null && project.exists() &&
( project.hasNature( IMavenConstants.NATURE_ID ) || project.getFile( IMavenConstants.POM_FILE_NAME ).exists() );
}
public static boolean isPomFile( IFile pomFile )
{
return pomFile != null && pomFile.exists() && IMavenConstants.POM_FILE_NAME.equals( pomFile.getName() ) &&
pomFile.getParent() instanceof IProject;
}
public static boolean loadParentHierarchy( final IMaven maven,
final IMavenProjectFacade facade,
final IMavenExecutionContext context,
final IProgressMonitor monitor ) throws CoreException
{
boolean loadedParent = false;
MavenProject mavenProject = facade.getMavenProject();
try
{
if( mavenProject.getModel().getParent() == null || mavenProject.getParent() != null )
{
// If the method is called without error, we can assume the project has been fully loaded
// No need to continue.
return false;
}
}
catch( IllegalStateException e )
{
// The parent can not be loaded properly
}
MavenExecutionRequest request = null;
while( mavenProject != null && mavenProject.getModel().getParent() != null )
{
if( monitor.isCanceled() )
{
break;
}
if( request == null )
{
request = context.getExecutionRequest();
}
MavenProject parentProject = maven.resolveParentProject( mavenProject, monitor );
if( parentProject != null )
{
mavenProject.setParent( parentProject );
loadedParent = true;
}
mavenProject = parentProject;
}
return loadedParent;
}
public static void setConfigValue( Xpp3Dom configuration, String childName, Object value )
{
Xpp3Dom childNode = configuration.getChild( childName );
if( childNode == null )
{
childNode = new Xpp3Dom( childName );
configuration.addChild( childNode );
}
childNode.setValue( ( value == null ) ? null : value.toString() );
}
}
| false | false | null | null |
diff --git a/src/de/lemo/dms/db/hibernate/HibernateDBHandler.java b/src/de/lemo/dms/db/hibernate/HibernateDBHandler.java
index 18c29436..03a9037f 100644
--- a/src/de/lemo/dms/db/hibernate/HibernateDBHandler.java
+++ b/src/de/lemo/dms/db/hibernate/HibernateDBHandler.java
@@ -1,139 +1,139 @@
package de.lemo.dms.db.hibernate;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import de.lemo.dms.core.ServerConfigurationHardCoded;
import de.lemo.dms.db.DBConfigObject;
import de.lemo.dms.db.EQueryType;
import de.lemo.dms.db.IDBHandler;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
* Implementation of the IDBHandler interface for Hibernate.
*
*
* @author s.schwarzrock
*
*/
public class HibernateDBHandler implements IDBHandler{
static Session mining_session;
private DBConfigObject currentConfig;
private static Logger logger = ServerConfigurationHardCoded.getInstance().getLogger();
@Override
/**
* Saves a list of generic objects to the database.
*
*/
public void saveToDB(List<Collection<?>> data) {
try{
Transaction tx = mining_session.beginTransaction();
Long i = 0L;
boolean isNewTable = true;
//Iterate through all object-lists
for ( Iterator<Collection<?>> iter = data.iterator(); iter.hasNext();)
{
//Iterate through all objects of a mapping-class
Collection<?> l = iter.next();
isNewTable = true;
for ( Iterator<?> iter2 = l.iterator(); iter2.hasNext();) {
Object o = iter2.next();
if(isNewTable)
{
System.out.println("Writing "+l.size()+" elements of "+o.getClass().getName()+" to the database.");
isNewTable = false;
}
mining_session.saveOrUpdate(o);
i++;
if ( i % 60 == 0 ) {
//flush a batch of inserts and release memory:
mining_session.flush();
mining_session.clear();
}
}
}
tx.commit();
mining_session.clear();
}catch(Exception e)
{
System.out.println(e.getMessage());
}
}
@Override
/**
* Save a single object to the database.
*/
public void saveToDB(Object data) {
Transaction tx = mining_session.beginTransaction();
mining_session.saveOrUpdate(data);
tx.commit();
mining_session.clear();
// TODO Auto-generated method stub
}
@Override
/**
* Opens a connection to the database.
*
*/
public void getConnection(DBConfigObject dbConf) {
try
{
if(mining_session == null)
mining_session = de.lemo.dms.db.hibernate.HibernateUtil.getSessionFactoryMining(dbConf).openSession();
}catch(HibernateException he)
{
System.out.println(he.getMessage());
}
}
@Override
/**
* Closes the database connection.
*/
public void closeConnection() {
try{
mining_session.close();
}catch(HibernateException he)
{logger.info(he.getMessage());}
}
@Override
/**
* Performs a Hibernate query.
*/
public List<?> performQuery(EQueryType queryType, String query) {
List<?> l = null;
try {
if(queryType == EQueryType.SQL)
l = mining_session.createSQLQuery(query).list();
else if(queryType == EQueryType.HQL)
l = mining_session.createQuery(query).list();
}catch(HibernateException he)
{
- System.out.println("Exception: "+ he.getMessage());
+ he.printStackTrace();
}
return l;
}
}
diff --git a/src/de/lemo/dms/processing/QCourseActivity.java b/src/de/lemo/dms/processing/QCourseActivity.java
index 21247641..17d7e9cc 100644
--- a/src/de/lemo/dms/processing/QCourseActivity.java
+++ b/src/de/lemo/dms/processing/QCourseActivity.java
@@ -1,130 +1,131 @@
package de.lemo.dms.processing;
+import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import de.lemo.dms.core.ServerConfigurationHardCoded;
import de.lemo.dms.db.EQueryType;
import de.lemo.dms.db.IDBHandler;
import de.lemo.dms.db.miningDBclass.CourseUserMining;
import de.lemo.dms.db.miningDBclass.ResourceLogMining;
import de.lemo.dms.processing.parameter.Interval;
import de.lemo.dms.processing.parameter.Parameter;
import de.lemo.dms.processing.parameter.ParameterMetaData;
import de.lemo.dms.processing.resulttype.ResultList;
@Path("courseactivity")
public class QCourseActivity extends Question{
@Override
protected List<ParameterMetaData<?>> createParamMetaData() {
List<ParameterMetaData<?>> parameters = new LinkedList<ParameterMetaData<?>>();
IDBHandler dbHandler = ServerConfigurationHardCoded.getInstance().getDBHandler();
dbHandler.getConnection(ServerConfigurationHardCoded.getInstance().getMiningDBConfig());
List<?> latest = dbHandler.performQuery(EQueryType.SQL, "Select max(timestamp) from resource_log");
Long now = System.currentTimeMillis()/1000;
if(latest.size() > 0)
- now = (Long)latest.get(0);
+ now = ((BigInteger)latest.get(0)).longValue();
Collections.<ParameterMetaData<?>> addAll( parameters,
Parameter.create("course_ids","Courses","List of courses."),
Parameter.create("role_ids", "Roles","List of roles."),
Interval.create(Long.class, "starttime", "Start time", "", 0L, now, 0L),
Interval.create(Long.class, "endtime", "End time", "", 0L, now, now),
Parameter.create("resolution", "Resolution", "")
);
return parameters;
}
@GET
public ResultList compute(@QueryParam("course_ids") List<Long> courses, @QueryParam("role_ids") List<Long> roles,
@QueryParam("starttime") Long starttime, @QueryParam("endtime") Long endtime, @QueryParam("resolution") int resolution) {
List<Long> list = new ArrayList<Long>();
//Check arguments
if(starttime < endtime && resolution > 0)
{
if(courses == null)
courses = new ArrayList<Long>();
if(roles == null)
roles = new ArrayList<Long>();
//Set up db-connection
IDBHandler dbHandler = ServerConfigurationHardCoded.getInstance().getDBHandler();
dbHandler.getConnection(ServerConfigurationHardCoded.getInstance().getMiningDBConfig());
//Calculate size of time intervalls
double intervall = (endtime - starttime) / (resolution);
//Create and initialize array for results
Long[] resArr = new Long[resolution];
for(int i = 0; i < resArr.length; i++)
resArr[i] = 0L;
//Create WHERE clause for course_ids
String cou = "";
for(int i = 0; i < courses.size(); i++)
if(i == 0)
cou += "course in ("+courses.get(i);
else
cou += "," + courses.get(i);
if(cou != "")
cou += ") AND";
String rol = "";
List<CourseUserMining> users = new ArrayList<CourseUserMining>();
//Retrieve user-ids of users with specified roles in the courses
if(roles.size() > 0)
{
for(int i = 0; i < roles.size(); i++)
if(i == 0)
rol += "role in ("+roles.get(i);
else
rol += "," + roles.get(i);
if(rol != "")
rol += ")";
String query ="from CourseUserMining where "+ cou +" "+rol;
users = (List<CourseUserMining>)dbHandler.performQuery(EQueryType.HQL, query);
}
//Create WHERE clause for user_ids
String use = "";
for(int i = 0; i < users.size(); i++)
if(i == 0)
use += "user in ("+users.get(i).getUser().getId();
else
use += "," + users.get(i).getUser().getId();
if(use != "")
use += ") AND";
String query = "from ResourceLogMining x where "+ cou + " " + use + " x.timestamp between '" + starttime + "' AND '" + endtime +"' order by x.timestamp asc";
List<ResourceLogMining> resource_logs = (List<ResourceLogMining>)dbHandler.performQuery(EQueryType.HQL, query);
for(int i = 0 ; i < resource_logs.size(); i++)
{
Integer pos = new Double((resource_logs.get(i).getTimestamp() - starttime) / intervall).intValue();
if(pos>resolution-1)
pos = resolution-1;
else
resArr[pos] = resArr[pos] + 1;
}
Collections.addAll(list, resArr);
}
return new ResultList(list);
}
}
| false | false | null | null |
diff --git a/src/com/modcrafting/diablodrops/listeners/TomeListener.java b/src/com/modcrafting/diablodrops/listeners/TomeListener.java
index c148d84..85c737b 100644
--- a/src/com/modcrafting/diablodrops/listeners/TomeListener.java
+++ b/src/com/modcrafting/diablodrops/listeners/TomeListener.java
@@ -1,145 +1,147 @@
package com.modcrafting.diablodrops.listeners;
import java.util.Iterator;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.Event.Result;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.ItemMeta;
import com.modcrafting.diablodrops.DiabloDrops;
import com.modcrafting.diablodrops.events.IdentifyItemEvent;
import com.modcrafting.diablodrops.items.IdentifyTome;
public class TomeListener implements Listener
{
private final DiabloDrops plugin;
public TomeListener(final DiabloDrops plugin)
{
this.plugin = plugin;
}
public ChatColor findColor(final String s)
{
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++)
if ((c[i] == new Character((char) 167)) && ((i + 1) < c.length))
return ChatColor.getByChar(c[i + 1]);
return null;
}
@EventHandler
public void onCraftItem(final CraftItemEvent e)
{
ItemStack item = e.getCurrentItem();
if (item.getType().equals(Material.WRITTEN_BOOK))
{
if (e.isShiftClick())
{
e.setCancelled(true);
}
e.setCurrentItem(new IdentifyTome());
}
}
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.LOWEST)
public void onRightClick(final PlayerInteractEvent e)
{
if ((e.getAction().equals(Action.RIGHT_CLICK_AIR) || e.getAction()
.equals(Action.RIGHT_CLICK_BLOCK))
&& e.getPlayer().getItemInHand().getType()
.equals(Material.WRITTEN_BOOK))
{
ItemStack inh = e.getPlayer().getItemInHand();
BookMeta b = (BookMeta) inh.getItemMeta();
if (b == null)
return;
- if (b.getTitle().contains("Identity Tome")
- && b.getAuthor().endsWith("AAAA"))
+ if (!b.hasTitle() || !b.hasAuthor())
+ return;
+ if (b.getTitle().equalsIgnoreCase(
+ ChatColor.DARK_AQUA + "Identity Tome"))
{
Player p = e.getPlayer();
PlayerInventory pi = p.getInventory();
p.updateInventory();
Iterator<ItemStack> itis = pi.iterator();
while (itis.hasNext())
{
ItemStack tool = itis.next();
if ((tool == null)
|| !plugin.getDropAPI().canBeItem(tool.getType()))
{
continue;
}
ItemMeta meta;
if (tool.hasItemMeta())
meta = tool.getItemMeta();
else
meta = plugin.getServer().getItemFactory()
.getItemMeta(tool.getType());
String name;
if (meta.hasDisplayName())
name = meta.getDisplayName();
else
name = tool.getType().name();
if ((ChatColor.getLastColors(name) == null || (!ChatColor
.getLastColors(name).equalsIgnoreCase(
ChatColor.MAGIC.name()) && !ChatColor
.getLastColors(name).equalsIgnoreCase(
ChatColor.MAGIC.toString()))
&& (!name.contains(ChatColor.MAGIC.name()) && !name
.contains(ChatColor.MAGIC.toString()))))
{
continue;
}
IdentifyItemEvent iie = new IdentifyItemEvent(tool);
plugin.getServer().getPluginManager().callEvent(iie);
if (iie.isCancelled())
{
p.sendMessage(ChatColor.RED
+ "You are unable to identify right now.");
p.closeInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
return;
}
pi.setItemInHand(null);
ItemStack item = plugin.getDropAPI().getItem(tool);
while ((item == null)
|| !item.hasItemMeta()
|| !item.getItemMeta().hasDisplayName()
|| item.getItemMeta().getDisplayName()
.contains(ChatColor.MAGIC.toString()))
{
item = plugin.getDropAPI().getItem(tool);
}
pi.removeItem(tool);
pi.addItem(item);
p.sendMessage(ChatColor.GREEN
+ "You have identified an item!");
p.updateInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
p.closeInventory();
return;
}
p.sendMessage(ChatColor.RED + "You have no items to identify.");
p.closeInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
return;
}
}
}
}
| true | true | public void onRightClick(final PlayerInteractEvent e)
{
if ((e.getAction().equals(Action.RIGHT_CLICK_AIR) || e.getAction()
.equals(Action.RIGHT_CLICK_BLOCK))
&& e.getPlayer().getItemInHand().getType()
.equals(Material.WRITTEN_BOOK))
{
ItemStack inh = e.getPlayer().getItemInHand();
BookMeta b = (BookMeta) inh.getItemMeta();
if (b == null)
return;
if (b.getTitle().contains("Identity Tome")
&& b.getAuthor().endsWith("AAAA"))
{
Player p = e.getPlayer();
PlayerInventory pi = p.getInventory();
p.updateInventory();
Iterator<ItemStack> itis = pi.iterator();
while (itis.hasNext())
{
ItemStack tool = itis.next();
if ((tool == null)
|| !plugin.getDropAPI().canBeItem(tool.getType()))
{
continue;
}
ItemMeta meta;
if (tool.hasItemMeta())
meta = tool.getItemMeta();
else
meta = plugin.getServer().getItemFactory()
.getItemMeta(tool.getType());
String name;
if (meta.hasDisplayName())
name = meta.getDisplayName();
else
name = tool.getType().name();
if ((ChatColor.getLastColors(name) == null || (!ChatColor
.getLastColors(name).equalsIgnoreCase(
ChatColor.MAGIC.name()) && !ChatColor
.getLastColors(name).equalsIgnoreCase(
ChatColor.MAGIC.toString()))
&& (!name.contains(ChatColor.MAGIC.name()) && !name
.contains(ChatColor.MAGIC.toString()))))
{
continue;
}
IdentifyItemEvent iie = new IdentifyItemEvent(tool);
plugin.getServer().getPluginManager().callEvent(iie);
if (iie.isCancelled())
{
p.sendMessage(ChatColor.RED
+ "You are unable to identify right now.");
p.closeInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
return;
}
pi.setItemInHand(null);
ItemStack item = plugin.getDropAPI().getItem(tool);
while ((item == null)
|| !item.hasItemMeta()
|| !item.getItemMeta().hasDisplayName()
|| item.getItemMeta().getDisplayName()
.contains(ChatColor.MAGIC.toString()))
{
item = plugin.getDropAPI().getItem(tool);
}
pi.removeItem(tool);
pi.addItem(item);
p.sendMessage(ChatColor.GREEN
+ "You have identified an item!");
p.updateInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
p.closeInventory();
return;
}
p.sendMessage(ChatColor.RED + "You have no items to identify.");
p.closeInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
return;
}
}
}
| public void onRightClick(final PlayerInteractEvent e)
{
if ((e.getAction().equals(Action.RIGHT_CLICK_AIR) || e.getAction()
.equals(Action.RIGHT_CLICK_BLOCK))
&& e.getPlayer().getItemInHand().getType()
.equals(Material.WRITTEN_BOOK))
{
ItemStack inh = e.getPlayer().getItemInHand();
BookMeta b = (BookMeta) inh.getItemMeta();
if (b == null)
return;
if (!b.hasTitle() || !b.hasAuthor())
return;
if (b.getTitle().equalsIgnoreCase(
ChatColor.DARK_AQUA + "Identity Tome"))
{
Player p = e.getPlayer();
PlayerInventory pi = p.getInventory();
p.updateInventory();
Iterator<ItemStack> itis = pi.iterator();
while (itis.hasNext())
{
ItemStack tool = itis.next();
if ((tool == null)
|| !plugin.getDropAPI().canBeItem(tool.getType()))
{
continue;
}
ItemMeta meta;
if (tool.hasItemMeta())
meta = tool.getItemMeta();
else
meta = plugin.getServer().getItemFactory()
.getItemMeta(tool.getType());
String name;
if (meta.hasDisplayName())
name = meta.getDisplayName();
else
name = tool.getType().name();
if ((ChatColor.getLastColors(name) == null || (!ChatColor
.getLastColors(name).equalsIgnoreCase(
ChatColor.MAGIC.name()) && !ChatColor
.getLastColors(name).equalsIgnoreCase(
ChatColor.MAGIC.toString()))
&& (!name.contains(ChatColor.MAGIC.name()) && !name
.contains(ChatColor.MAGIC.toString()))))
{
continue;
}
IdentifyItemEvent iie = new IdentifyItemEvent(tool);
plugin.getServer().getPluginManager().callEvent(iie);
if (iie.isCancelled())
{
p.sendMessage(ChatColor.RED
+ "You are unable to identify right now.");
p.closeInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
return;
}
pi.setItemInHand(null);
ItemStack item = plugin.getDropAPI().getItem(tool);
while ((item == null)
|| !item.hasItemMeta()
|| !item.getItemMeta().hasDisplayName()
|| item.getItemMeta().getDisplayName()
.contains(ChatColor.MAGIC.toString()))
{
item = plugin.getDropAPI().getItem(tool);
}
pi.removeItem(tool);
pi.addItem(item);
p.sendMessage(ChatColor.GREEN
+ "You have identified an item!");
p.updateInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
p.closeInventory();
return;
}
p.sendMessage(ChatColor.RED + "You have no items to identify.");
p.closeInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
return;
}
}
}
|
diff --git a/android/src/fq/router2/life_cycle/ManagerProcess.java b/android/src/fq/router2/life_cycle/ManagerProcess.java
index 06e524d..524b173 100644
--- a/android/src/fq/router2/life_cycle/ManagerProcess.java
+++ b/android/src/fq/router2/life_cycle/ManagerProcess.java
@@ -1,76 +1,76 @@
package fq.router2.life_cycle;
import fq.router2.utils.IOUtils;
import fq.router2.utils.LogUtils;
import fq.router2.utils.ShellUtils;
import java.io.File;
public class ManagerProcess {
public static void kill() throws Exception {
try {
if ("run-needs-su".equals(getRunMode())) {
ShellUtils.execute(
ShellUtils.pythonEnv(), Deployer.PYTHON_LAUNCHER.getAbsolutePath(),
Deployer.MANAGER_MAIN_PY.getAbsolutePath(), "clean");
} else {
ShellUtils.sudo(
ShellUtils.pythonEnv(), Deployer.PYTHON_LAUNCHER.getAbsolutePath(),
Deployer.MANAGER_MAIN_PY.getAbsolutePath(), "clean");
}
} catch (Exception e) {
LogUtils.e("failed to clean", e);
}
LogUtils.i("killall python");
ShellUtils.sudo("/data/data/fq.router2/busybox", "killall", "python");
for (int i = 0; i < 10; i++) {
if (exists()) {
Thread.sleep(3000);
} else {
LogUtils.i("killall python done cleanly");
return;
}
}
LogUtils.e("killall python by force");
ShellUtils.sudo("/data/data/fq.router2/busybox", "killall", "-KILL", "python");
}
public static boolean exists() {
try {
if (ShellUtils.sudo("/data/data/fq.router2/busybox", "killall", "-0", "python").contains(
"no process killed")) {
return false;
} else {
return true;
}
} catch (Exception e) {
return false;
}
}
public static String getRunMode() throws Exception {
File runModeCacheFile = new File("/data/data/fq.router2/etc/run-mode");
if (runModeCacheFile.exists()) {
return IOUtils.readFromFile(runModeCacheFile);
}
// S4 will fail this test
try {
String output = ShellUtils.sudo(ShellUtils.pythonEnv(), Deployer.PYTHON_LAUNCHER +
" -c \"import subprocess; print(subprocess.check_output(['" +
ShellUtils.BUSYBOX_FILE.getCanonicalPath() + "', 'echo', 'hello']))\"").trim();
LogUtils.i("get run mode: " + output);
- if ("hello".equals(output)) {
+ if (output.contains("hello")) {
IOUtils.writeToFile(runModeCacheFile, "run-normally");
return "run-normally";
} else {
IOUtils.writeToFile(runModeCacheFile, "run-needs-su");
return "run-needs-su";
}
} catch (Exception e) {
LogUtils.e("failed to test subprocess", e);
IOUtils.writeToFile(runModeCacheFile, "run-needs-su");
return "run-needs-su";
}
}
}
| true | false | null | null |
diff --git a/android/src/main/java/no/kantega/android/afp/utils/FmtUtil.java b/android/src/main/java/no/kantega/android/afp/utils/FmtUtil.java
index 620cddf..61e23a1 100644
--- a/android/src/main/java/no/kantega/android/afp/utils/FmtUtil.java
+++ b/android/src/main/java/no/kantega/android/afp/utils/FmtUtil.java
@@ -1,139 +1,133 @@
package no.kantega.android.afp.utils;
-import java.math.RoundingMode;
-import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* This class handles formatting and validation of input and output values
*/
public class FmtUtil {
/**
* Convert the given date to string using the given format
*
* @param format Date format to use when converting
* @param date Date to convert
* @return The date
*/
public static String dateToString(String format, Date date) {
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
return simpleDateFormat.format(date);
}
/**
* Format currency according to the default locale
*
* @param number Number to format
* @return Formatted currency
*/
public static String currency(double number) {
return currency(number, Locale.getDefault());
}
/**
* Format currency according to the given locale
*
* @param number Number to format
* @param locale Locale to use when formatting
* @return Formatted currency
*/
public static String currency(double number, Locale locale) {
final NumberFormat nf = NumberFormat.getCurrencyInstance(locale);
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
return nf.format(number);
}
/**
* Format currency without prefix using the default locale
*
* @param number Number to format
* @return Formatted currency
*/
public static String currencyWithoutPrefix(double number) {
return currencyWithoutPrefix(number, Locale.getDefault());
}
/**
* Format currency according to the given locale
*
* @param number Number to format
* @param locale Locale to use when formatting
* @return Formatted currency
*/
public static String currencyWithoutPrefix(double number, Locale locale) {
- NumberFormat df = DecimalFormat.getInstance(locale);
- df.setMinimumFractionDigits(2);
- df.setMaximumFractionDigits(2);
- df.setRoundingMode(RoundingMode.HALF_UP);
- return df.format(number);
+ return currency(number, locale).replaceFirst("^[^\\d]+", "");
}
/**
* Trim useless data from the given transaction text
*
* @param text Text to trim
* @return Trimmed text
*/
public static String trimTransactionText(String text) {
final String pattern = "(^\\d{16}\\s)?" +
"(\\d{2}\\.\\d{2}\\s)?" +
"([A-Z]{3}\\s\\d+,\\d+\\s)?" +
"(TIL\\:\\s)?" +
"(BETNR:\\s*\\d*)?";
if (text != null) {
String out = text.trim();
out = out.replaceAll(pattern, "").trim();
return out;
} else {
return "";
}
}
/**
* Convert the given string to date using the given format
*
* @param format Format to use when converting
* @param date Date to convert
* @return The date
*/
public static Date stringToDate(String format, String date) {
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
try {
return simpleDateFormat.parse(date);
} catch (ParseException e) {
return null;
}
}
/**
* Check if given string is a number with optional decimals
*
* @param s String to check
* @return True if string contains one or more numbers
*/
public static boolean isNumber(String s) {
return s != null && s.matches("^\\d+([,\\.]\\d+)?$");
}
/**
* Get first word in string split by space
*
* @param s String
* @return First word
*/
public static String firstWord(String s) {
if (s != null) {
final String[] words = s.split(" ");
if (words.length > 0) {
return words[0];
}
}
return "";
}
}
| false | false | null | null |
diff --git a/de.uni_koeln.ub.drc.ui/src/de/uni_koeln/ub/drc/ui/views/CheckView.java b/de.uni_koeln.ub.drc.ui/src/de/uni_koeln/ub/drc/ui/views/CheckView.java
index a5b6b2c..3c9a2c9 100644
--- a/de.uni_koeln.ub.drc.ui/src/de/uni_koeln/ub/drc/ui/views/CheckView.java
+++ b/de.uni_koeln.ub.drc.ui/src/de/uni_koeln/ub/drc/ui/views/CheckView.java
@@ -1,210 +1,210 @@
/**************************************************************************************************
* Copyright (c) 2010 Fabian Steeg. All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 which accompanies this
* distribution, and is available at http://www.eclipse.org/legal/epl-v10.html
* <p/>
* Contributors: Fabian Steeg - initial API and implementation
*************************************************************************************************/
package de.uni_koeln.ub.drc.ui.views;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.e4.ui.services.IServiceConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import de.uni_koeln.ub.drc.data.Box;
import de.uni_koeln.ub.drc.data.Index;
import de.uni_koeln.ub.drc.data.Page;
import de.uni_koeln.ub.drc.data.Word;
/**
* View containing the scanned page used to check the original word while editing.
* @author Fabian Steeg (fsteeg)
*/
public final class CheckView {
private Composite parent;
private Label imageLabel;
private boolean imageLoaded = false;
private ScrolledComposite scrolledComposite;
private ImageData image;
private Text suggestions;
private Job job;
private Button check;
@Inject public CheckView(final Composite parent) {
this.parent = parent;
scrolledComposite = new ScrolledComposite(parent, SWT.V_SCROLL | SWT.BORDER);
imageLabel = new Label(scrolledComposite, SWT.BORDER);
scrolledComposite.setContent(imageLabel);
scrolledComposite.setExpandVertical(true);
scrolledComposite.setExpandHorizontal(true);
// scrolledComposite.setMinSize(imageLabel.computeSize(SWT.MAX, SWT.MAX));
scrolledComposite.setMinSize(new Point(900, 1440)); // IMG_SIZE
addSuggestions();
GridLayoutFactory.fillDefaults().generateLayout(parent);
}
private void addSuggestions() {
Composite bottom = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout(2, false);
bottom.setLayout(layout);
check = new Button(bottom, SWT.CHECK);
check.setToolTipText("Suggest corrections");
- check.setSelection(true);
+ check.setSelection(false);
suggestions = new Text(bottom, SWT.WRAP);
suggestions.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
}
@Inject public void setSelection(
@Optional @Named( IServiceConstants.ACTIVE_SELECTION ) final List<Page> pages) {
if (pages != null && pages.size() > 0) {
Page page = pages.get(0);
try {
updateImage(page);
} catch (MalformedURLException e) {
handle(e);
} catch (IOException e) {
handle(e);
}
} else {
return;
}
}
private void handle(Exception e) {
MessageDialog.openError(parent.getShell(), "Could not load scan",
"Could not load the image file for the current page");
e.printStackTrace();
}
@Inject public void setSelection(@Optional @Named( IServiceConstants.ACTIVE_SELECTION ) final Text word) {
if (imageLoaded && word != null) {
markPosition(word);
if (job != null) {
/* If a word is selected while we had a Job running for the previous word, cancel that: */
job.cancel();
}
if (word == null) {
suggestions.setText("No word selected");
} else if (!check.getSelection()) {
suggestions.setText("Edit suggestions disabled");
} else {
findEditSuggestions((Word)word.getData());
job.setPriority(Job.DECORATE);
job.schedule();
}
}
}
private void findEditSuggestions(final Word word) {
suggestions.setText("Finding edit suggestions...");
job = new Job("Edit suggestions search job") {
protected IStatus run(final IProgressMonitor monitor) {
final boolean complete = word.prepSuggestions();
suggestions.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
if (!complete) {
suggestions.setText("Finding edit suggestions...");
} else {
final String s = "Suggestions for " + word.original() + ": "
+ word.suggestions().mkString(", ");
if (!suggestions.isDisposed()) {
suggestions.setText(s);
}
}
}
});
return Status.OK_STATUS;
}
@Override
protected void canceling() {
word.cancelled_$eq(true);
suggestions.setText("Finding edit suggestions...");
};
};
}
private void updateImage(final Page page) throws IOException {
Image loadedImage = loadImage(page);
image = loadedImage.getImageData();
imageLabel.setImage(loadedImage);
imageLoaded = true;
}
private Image reloadImage() {
Display display = parent.getDisplay();
Image newImage = new Image(display, image);
return newImage;
}
private Image loadImage(final Page page) throws IOException {
Display display = parent.getDisplay();
Image newImage = null;
InputStream in = new ByteArrayInputStream(Index.loadImageFor(page)); // TODO image as lazy def in page, fetched on demand?
newImage = new Image(display, in); //new ZipFile(new File(page.zip().get().getName())).getInputStream(page.image().get()));
return newImage;
}
private void markPosition(final Text text) {
imageLabel.getImage().dispose();
Word word = (Word) text.getData();
Box box = word.position();
Rectangle rect = new Rectangle(box.x() - 10, box.y() - 4, box.width() + 20, box.height() + 12); // IMG_SIZE
System.out.println("Current word: " + word);
Image image = reloadImage();
GC gc = new GC(image);
drawBoxArea(rect, gc);
drawBoxBorder(rect, gc);
imageLabel.setImage(image);
gc.dispose();
scrolledComposite.setOrigin(new Point(rect.x - 10, rect.y - 10)); // IMG_SIZE
}
private void drawBoxBorder(final Rectangle rect, final GC gc) {
gc.setAlpha(200);
gc.setLineWidth(1);
gc.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_DARK_GREEN));
gc.drawRectangle(rect);
}
private void drawBoxArea(final Rectangle rect, final GC gc) {
gc.setAlpha(50);
gc.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_GREEN));
gc.fillRectangle(rect);
}
private void clearMarker() {
imageLabel.setImage(reloadImage());
}
}
diff --git a/de.uni_koeln.ub.drc.ui/src/de/uni_koeln/ub/drc/ui/views/EditComposite.java b/de.uni_koeln.ub.drc.ui/src/de/uni_koeln/ub/drc/ui/views/EditComposite.java
index fde072d..7edc3d1 100644
--- a/de.uni_koeln.ub.drc.ui/src/de/uni_koeln/ub/drc/ui/views/EditComposite.java
+++ b/de.uni_koeln.ub.drc.ui/src/de/uni_koeln/ub/drc/ui/views/EditComposite.java
@@ -1,197 +1,201 @@
/**************************************************************************************************
* Copyright (c) 2010 Fabian Steeg. All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 which accompanies this
* distribution, and is available at http://www.eclipse.org/legal/epl-v10.html
* <p/>
* Contributors: Fabian Steeg - initial API and implementation
*************************************************************************************************/
package de.uni_koeln.ub.drc.ui.views;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.e4.ui.model.application.ui.MDirtyable;
import org.eclipse.e4.ui.services.IServiceConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import scala.collection.JavaConversions;
+import de.uni_koeln.ub.drc.data.Modification;
import de.uni_koeln.ub.drc.data.Page;
import de.uni_koeln.ub.drc.data.Word;
+import de.uni_koeln.ub.drc.ui.DrcUiActivator;
/**
* Composite holding the edit area. Used by the {@link EditView}.
* @author Fabian Steeg (fsteeg)
*/
public final class EditComposite extends Composite {
private MDirtyable dirtyable;
private Composite parent;
private Page page;
private boolean commitChanges = false;
private List<Text> words;
private List<Composite> lines = new ArrayList<Composite>();
IEclipseContext context;
@Inject
public EditComposite(final MDirtyable dirtyable, final Composite parent, final int style) {
super(parent, style);
this.parent = parent;
this.dirtyable = dirtyable;
parent.getShell().setBackgroundMode(SWT.INHERIT_DEFAULT);
GridLayout layout = new GridLayout(1, false);
this.setLayout(layout);
commitChanges = true;
addWrapOnResizeListener(parent);
}
/**
* @return The text widgets representing the words in the current page
*/
public List<Text> getWords() {
return words;
}
/**
* @param page Update the content of this composite with the given page
*/
public void update(final Page page) {
this.page = page;
updatePage(parent);
}
Page getPage() {
return page;
}
private void addWrapOnResizeListener(final Composite parent) {
parent.addControlListener(new ControlListener() {
@Override
public void controlResized(final ControlEvent e) {
for (Composite line : lines) {
if (!line.isDisposed()) {
setLineLayout(line);
}
}
layout();
}
@Override
public void controlMoved(final ControlEvent e) {}
});
}
private void updatePage(final Composite parent) {
words = addTextFrom(page, this);
}
private List<Text> addTextFrom(final Page page, final Composite c) {
if (lines != null) {
for (Composite line : lines) {
line.dispose();
}
}
List<Text> list = new ArrayList<Text>();
this.page = page;
Composite lineComposite = new Composite(c, SWT.NONE);
setLineLayout(lineComposite);
lines.add(lineComposite);
for (Word word : JavaConversions.asIterable(page.words())) {
if (word.original().equals(Page.ParagraphMarker())) {
lineComposite = new Composite(c, SWT.NONE);
setLineLayout(lineComposite);
lines.add(lineComposite);
} else {
Text text = new Text(lineComposite, SWT.NONE);
text.setText(word.history().top().form());
if (word.isPossibleError()) {
text.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_DARK_GRAY));
}
text.setData(word);
addListeners(text);
text.setEditable(!word.isLocked());
list.add(text);
}
}
this.layout();
return list;
}
private void setLineLayout(final Composite lineComposite) {
RowLayout layout = new RowLayout();
GridData data = new GridData();
data.widthHint = lineComposite.computeSize(parent.getSize().x, parent.getSize().y).x - 20;
lineComposite.setLayoutData(data);
lineComposite.setLayout(layout);
}
private void addListeners(final Text text) {
addFocusListener(text);
addModifyListener(text);
}
private Text prev;
private int active = SWT.COLOR_DARK_GREEN;
private int dubious = SWT.COLOR_RED;
private void addModifyListener(final Text text) {
text.addModifyListener(new ModifyListener() {
public void modifyText(final ModifyEvent e) {
/* Reset any warning color during editing (we check when focus is lost, see below): */
text.setForeground(text.getDisplay().getSystemColor(active));
if (commitChanges) {
dirtyable.setDirty(true);
}
}
});
}
private void addFocusListener(final Text text) {
text.addFocusListener(new FocusListener() {
public void focusLost(final FocusEvent e) {
prev = text; // remember so we can clear only when new focus gained, not when lost
context.modify(IServiceConstants.ACTIVE_SELECTION, null);
checkWordValidity(text);
}
private void checkWordValidity(final Text text) {
String current = text.getText();
Word word = (Word) text.getData();
String reference = word.history().top().form();
if (current.length() != reference.length()
|| (current.contains(" ") && !reference.contains(" "))) {
if(!MessageDialog.openQuestion(text.getShell(), "Questionable Edit Operation",
"Your recent edit operation changed a word in a dubious way (e.g. by adding a blank into "
+ "what should be a single word or by changing the length of a word) - are you sure?")){
text.setForeground(text.getDisplay().getSystemColor(dubious));
+ } else {
+ word.history().push(new Modification(current, DrcUiActivator.instance().currentUser().id()));
}
}
}
public void focusGained(final FocusEvent e) {
text.clearSelection(); // use only our persistent marking below
context.modify(IServiceConstants.ACTIVE_SELECTION, text);
text.setToolTipText(((Word) text.getData()).formattedHistory());
if (prev != null && !prev.isDisposed()
&& !prev.getForeground().equals(text.getDisplay().getSystemColor(dubious))) {
prev.setForeground(text.getDisplay().getSystemColor(SWT.COLOR_BLACK));
}
text.setForeground(text.getDisplay().getSystemColor(active));
}
});
}
}
| false | false | null | null |
diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/experimental/SkeletonModelGpuSkinningTest.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/experimental/SkeletonModelGpuSkinningTest.java
index ec86c81ba..f75cfafb3 100644
--- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/experimental/SkeletonModelGpuSkinningTest.java
+++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/experimental/SkeletonModelGpuSkinningTest.java
@@ -1,240 +1,240 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.graphics.g3d.experimental;
import com.badlogic.gdx.Application.ApplicationType;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.FPSLogger;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g3d.AnimatedModelNode;
import com.badlogic.gdx.graphics.g3d.lights.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.lights.LightManager;
import com.badlogic.gdx.graphics.g3d.lights.LightManager.LightQuality;
import com.badlogic.gdx.graphics.g3d.lights.PointLight;
import com.badlogic.gdx.graphics.g3d.loaders.ModelLoaderRegistry;
import com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dLoader;
import com.badlogic.gdx.graphics.g3d.loaders.g3d.chunks.G3dExporter;
import com.badlogic.gdx.graphics.g3d.loaders.ogre.OgreXmlLoader;
import com.badlogic.gdx.graphics.g3d.materials.BlendingAttribute;
import com.badlogic.gdx.graphics.g3d.materials.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.materials.GpuSkinningAttribute;
import com.badlogic.gdx.graphics.g3d.materials.Material;
import com.badlogic.gdx.graphics.g3d.materials.MaterialAttribute;
import com.badlogic.gdx.graphics.g3d.materials.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.model.skeleton.SkeletonAnimation;
import com.badlogic.gdx.graphics.g3d.model.skeleton.SkeletonModel;
import com.badlogic.gdx.graphics.g3d.model.skeleton.SkeletonModelGpuSkinned;
import com.badlogic.gdx.graphics.g3d.test.PrototypeRendererGL20;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Matrix3;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.collision.BoundingBox;
public class SkeletonModelGpuSkinningTest implements ApplicationListener {
static final int LIGHTS_NUM = 4;
static final float LIGHT_INTESITY = 3f;
static final boolean useGpuSkinning = true;
LightManager lightManager;
PerspectiveCamController camController;
PerspectiveCamera cam;
private Texture texture;
FPSLogger logger = new FPSLogger();
private Matrix4 modelMatrix = new Matrix4();
final private Matrix3 normalMatrix = new Matrix3();
float timer;
private PrototypeRendererGL20 protoRenderer;
private SkeletonModel model;
private int currAnimIdx;
final static int gridSize = 4;
private AnimatedModelNode[][] animInstance = new AnimatedModelNode[gridSize][gridSize];
public void render () {
logger.log();
final float delta = Gdx.graphics.getDeltaTime();
camController.update(delta);
timer += delta;
for (int i = 0; i < 1 && i < lightManager.pointLights.size; i++) {
final Vector3 v = lightManager.pointLights.get(i).position;
v.set(animInstance[0][0].getSortCenter());
v.x += MathUtils.sin(timer);
v.z += MathUtils.cos(timer);
}
Gdx.gl.glEnable(GL10.GL_CULL_FACE);
Gdx.gl.glFrontFace(GL10.GL_CW);
Gdx.gl.glCullFace(GL10.GL_FRONT);
Gdx.gl.glEnable(GL10.GL_DEPTH_TEST);
Gdx.gl.glDepthMask(true);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT
| (Gdx.graphics.getBufferFormat().coverageSampling ? GL20.GL_COVERAGE_BUFFER_BIT_NV : 0));
protoRenderer.begin();
for (int i = 0; i < gridSize; i++) {
for (int j = 0; j < gridSize; j++) {
AnimatedModelNode instance = animInstance[i][j];
instance.time += MathUtils.clamp(delta, 0, 0.1f)*0.5f;
if (instance.time > model.getAnimations()[currAnimIdx].totalDuration) {
instance.time = 0;
}
instance.matrix.val[12] = -i * 2 + 8;
instance.matrix.val[14] = -j * 2 - 4;
protoRenderer.draw(model, instance);
}
}
protoRenderer.end();
}
public void create () {
lightManager = new LightManager(LIGHTS_NUM, LightQuality.FRAGMENT);
for (int i = 0; i < LIGHTS_NUM; i++) {
PointLight l = new PointLight();
l.position.set(MathUtils.random(6) - 3, 1 + MathUtils.random(6), MathUtils.random(6) - 3);
l.color.r = MathUtils.random();
l.color.b = MathUtils.random();
l.color.g = MathUtils.random();
l.intensity = LIGHT_INTESITY;
lightManager.addLigth(l);
}
lightManager.dirLight = new DirectionalLight();
lightManager.dirLight.color.set(0.1f, 0.1f, 0.1f, 1);
lightManager.dirLight.direction.set(-.4f, -1, 0.03f).nor();
lightManager.ambientLight.set(.01f, 0.01f, 0.03f, 0f);
cam = new PerspectiveCamera(45, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.near = 0.1f;
cam.far = 64f;
cam.position.set(2, 2.75f, 1f);
cam.update();
camController = new PerspectiveCamController(cam);
Gdx.input.setInputProcessor(camController);
texture = new Texture(Gdx.files.internal("data/models/robot.jpg"), Format.RGB565, true);
texture.setFilter(TextureFilter.MipMapLinearNearest, TextureFilter.Linear);
- //String fileName = "data/models/robot-mesh.xml.g3d";
+ String fileName = "data/models/robot-mesh.xml.g3d";
- String fileName = "data/models/cube.dae";
+// String fileName = "data/models/cube.dae";
if (!fileName.endsWith(".g3d") && Gdx.app.getType() == ApplicationType.Desktop) {
model = ModelLoaderRegistry.loadSkeletonModel(Gdx.files.internal(fileName));
if(model == null){
model = new OgreXmlLoader().load(Gdx.files.internal(fileName),
Gdx.files.internal(fileName.replace("mesh.xml", "skeleton.xml")));
}
G3dExporter.export(model, Gdx.files.absolute(fileName + ".g3d"));
model = G3dLoader.loadSkeletonModel(Gdx.files.absolute(fileName + ".g3d"));
}
else
{
model = ModelLoaderRegistry.loadSkeletonModel(Gdx.files.internal(fileName));
}
if(useGpuSkinning){
model = SkeletonModelGpuSkinned.CreateFromSkeletonModel(model);
}
protoRenderer = new PrototypeRendererGL20(lightManager);
protoRenderer.cam = cam;
MaterialAttribute c1 = new ColorAttribute(new Color(0.75f, 0.75f, 0.75f, 0.3f), ColorAttribute.diffuse);
MaterialAttribute c2 = new ColorAttribute(new Color(0.35f, 0.35f, 0.35f, 0.35f), ColorAttribute.specular);
MaterialAttribute c3 = new ColorAttribute(new Color(0.2f, 1f, 0.15f, 1.0f), ColorAttribute.rim);
MaterialAttribute c4 = new ColorAttribute(new Color(0.0f, 0.0f, 0.0f, 0.35f), ColorAttribute.fog);
MaterialAttribute b = new BlendingAttribute(BlendingAttribute.translucent);
BoundingBox box = new BoundingBox();
for (int i = 0; i < gridSize; i++) {
for (int j = 0; j < gridSize; j++) {
AnimatedModelNode instance = new AnimatedModelNode();
SkeletonAnimation[] animations = model.getAnimations();
SkeletonAnimation sa = animations[(i+j*gridSize)%animations.length];
instance.animation = sa.name;
instance.time = MathUtils.random(sa.totalDuration);
instance.looping = true;
model.getBoundingBox(box);
instance.matrix.trn(-1.75f, 0f, -5.5f);
- instance.matrix.scale(0.4f, 0.4f, 0.4f);
+ instance.matrix.scale(0.01f, 0.01f, 0.01f);
box.mul(instance.matrix);
instance.radius = (box.getDimensions().len() / 2);
animInstance[i][j] = instance;
}
}
MaterialAttribute t1 = new TextureAttribute(texture, 0, TextureAttribute.diffuseTexture);
GpuSkinningAttribute gpuAttribute = new GpuSkinningAttribute(model.skeleton);
Material material = new Material("s", t1, gpuAttribute);
model.setMaterial(material);
}
public void resize (int width, int height) {
}
public void pause () {
}
public void dispose () {
model.dispose();
texture.dispose();
}
public void resume () {
}
public static void main (String[] argv) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.title = "Hybrid Light";
config.width = 800;
config.height = 480;
config.samples = 8;
config.vSyncEnabled = true;
config.useGL20 = true;
new LwjglApplication(new SkeletonModelGpuSkinningTest(), config);
}
}
diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/OgreXmlLoader.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/OgreXmlLoader.java
index 9747050f3..9823a9a1f 100644
--- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/OgreXmlLoader.java
+++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/OgreXmlLoader.java
@@ -1,535 +1,537 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.graphics.g3d.loaders.ogre;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.loaders.ogre.mesh.BaseGeometry;
import com.badlogic.gdx.graphics.g3d.loaders.ogre.mesh.Boneassignments;
import com.badlogic.gdx.graphics.g3d.loaders.ogre.mesh.ColourDiffuse;
import com.badlogic.gdx.graphics.g3d.loaders.ogre.mesh.Face;
import com.badlogic.gdx.graphics.g3d.loaders.ogre.mesh.Geometry;
import com.badlogic.gdx.graphics.g3d.loaders.ogre.mesh.Mesh;
import com.badlogic.gdx.graphics.g3d.loaders.ogre.mesh.Submesh;
import com.badlogic.gdx.graphics.g3d.loaders.ogre.mesh.Submeshname;
import com.badlogic.gdx.graphics.g3d.loaders.ogre.mesh.Texcoord;
import com.badlogic.gdx.graphics.g3d.loaders.ogre.mesh.Vertex;
import com.badlogic.gdx.graphics.g3d.loaders.ogre.mesh.Vertexboneassignment;
import com.badlogic.gdx.graphics.g3d.loaders.ogre.mesh.Vertexbuffer;
import com.badlogic.gdx.graphics.g3d.loaders.ogre.skeleton.Animation;
import com.badlogic.gdx.graphics.g3d.loaders.ogre.skeleton.Bone;
import com.badlogic.gdx.graphics.g3d.loaders.ogre.skeleton.Boneparent;
import com.badlogic.gdx.graphics.g3d.loaders.ogre.skeleton.Keyframe;
import com.badlogic.gdx.graphics.g3d.loaders.ogre.skeleton.Track;
import com.badlogic.gdx.graphics.g3d.model.SubMesh;
import com.badlogic.gdx.graphics.g3d.model.skeleton.Skeleton;
import com.badlogic.gdx.graphics.g3d.model.skeleton.SkeletonAnimation;
import com.badlogic.gdx.graphics.g3d.model.skeleton.SkeletonJoint;
import com.badlogic.gdx.graphics.g3d.model.skeleton.SkeletonKeyframe;
import com.badlogic.gdx.graphics.g3d.model.skeleton.SkeletonModel;
import com.badlogic.gdx.graphics.g3d.model.skeleton.SkeletonSubMesh;
import com.badlogic.gdx.graphics.g3d.model.still.StillModel;
import com.badlogic.gdx.graphics.g3d.model.still.StillSubMesh;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.FloatArray;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.IntArray;
public class OgreXmlLoader {
public SubMesh[] loadMeshes (FileHandle file) {
InputStream in = null;
try {
in = file.read();
return loadMesh(in);
} catch (Throwable t) {
throw new GdxRuntimeException("Couldn't load file '" + file.name() + "'", t);
} finally {
if (in != null) try {
in.close();
} catch (Exception e) {
}
}
}
public SubMesh[] loadMesh (InputStream in) {
try {
Mesh ogreMesh = loadOgreMesh(in);
SubMesh[] meshes = generateSubMeshes(ogreMesh);
return meshes;
} catch (Throwable t) {
throw new GdxRuntimeException("Couldn't load meshes", t);
}
}
public SkeletonModel load (FileHandle mesh, FileHandle skeleton) {
SubMesh[] meshes = loadMeshes(mesh);
return new SkeletonModel(loadSkeleton(skeleton), meshes);
}
public StillModel load (FileHandle mesh) {
SubMesh[] meshes = loadMeshes(mesh);
return new StillModel(meshes);
}
private SubMesh[] generateSubMeshes (Mesh ogreMesh) {
List<Submesh> ogreSubmeshes = ogreMesh.getSubmeshes().getSubmesh();
SubMesh[] submeshes = new SubMesh[ogreSubmeshes.size()];
for (int i = 0; i < ogreSubmeshes.size(); i++) {
Submesh ogreSubmesh = ogreSubmeshes.get(i);
boolean usesTriangleList = false;
if (ogreSubmesh.use32Bitindexes) throw new GdxRuntimeException("submesh '" + i + "' uses 32-bit indices");
if (ogreSubmesh.getOperationtype().equals("triangle_list")) {
usesTriangleList = true;
}
short[] indices = new short[ogreSubmesh.getFaces().count * (usesTriangleList ? 3 : 1)];
for (int j = 0, idx = 0; j < ogreSubmesh.getFaces().count; j++) {
Face face = ogreSubmesh.getFaces().getFace().get(j);
indices[idx++] = face.v1;
if (usesTriangleList || j == 0) {
indices[idx++] = face.v2;
indices[idx++] = face.v3;
}
}
List<VertexAttribute> attributes = new ArrayList<VertexAttribute>();
IntArray offsets = new IntArray();
int offset = 0;
BaseGeometry geom;
if (ogreSubmesh.useSharedVertices) {
geom = ogreMesh.getSharedgeometry();
} else {
geom = ogreSubmesh.getGeometry();
}
for (int j = 0; j < geom.getVertexbuffer().size(); j++) {
Vertexbuffer buffer = geom.getVertexbuffer().get(j);
offsets.add(offset);
if (buffer.positions) {
attributes.add(new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE));
offset += 3;
}
if (buffer.normals) {
attributes.add(new VertexAttribute(Usage.Normal, 3, ShaderProgram.NORMAL_ATTRIBUTE));
offset += 3;
}
if (buffer.tangents) {
attributes.add(new VertexAttribute(Usage.Generic, buffer.tangentDimensions, ShaderProgram.TANGENT_ATTRIBUTE));
offset += buffer.tangentDimensions;
}
if (buffer.binormals) {
attributes.add(new VertexAttribute(Usage.Generic, 3, ShaderProgram.BINORMAL_ATTRIBUTE));
offset += 3;
}
if (buffer.coloursDiffuse) {
attributes.add(new VertexAttribute(Usage.ColorPacked, 4, ShaderProgram.COLOR_ATTRIBUTE));
offset += 4;
}
for (int k = 0; k < buffer.textureCoords; k++) {
try {
int numTexCoords = 0;
switch (k) {
case 0:
numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions0());
break;
case 1:
numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions1());
break;
case 2:
numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions2());
break;
case 3:
numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions3());
break;
case 4:
numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions4());
break;
case 5:
numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions5());
break;
case 6:
numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions6());
break;
case 7:
numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions7());
break;
}
attributes
.add(new VertexAttribute(Usage.TextureCoordinates, numTexCoords, ShaderProgram.TEXCOORD_ATTRIBUTE + k));
offset += numTexCoords;
} catch (NumberFormatException e) {
throw new GdxRuntimeException("Can't process texture coords with dimensions != 1, 2, 3, 4 (e.g. float1)");
}
}
}
VertexAttributes attribs = new VertexAttributes(attributes.toArray(new VertexAttribute[0]));
int vertexSize = offset;
float[] vertices = new float[geom.getVertexCount() * offset];
for (int j = 0; j < geom.getVertexbuffer().size(); j++) {
Vertexbuffer buffer = geom.getVertexbuffer().get(j);
offset = offsets.get(j);
int idx = offset;
for (int k = 0; k < buffer.getVertex().size(); k++) {
Vertex v = buffer.getVertex().get(k);
if (v.getPosition() != null) {
vertices[idx++] = v.getPosition().x;
vertices[idx++] = v.getPosition().y;
vertices[idx++] = v.getPosition().z;
}
if (v.getNormal() != null) {
vertices[idx++] = v.getNormal().x;
vertices[idx++] = v.getNormal().y;
vertices[idx++] = v.getNormal().z;
}
if (v.getTangent() != null) {
vertices[idx++] = v.getTangent().x;
vertices[idx++] = v.getTangent().y;
vertices[idx++] = v.getTangent().z;
if (buffer.tangentDimensions == 4) vertices[idx++] = v.getTangent().w;
}
if (v.getBinormal() != null) {
vertices[idx++] = v.getBinormal().x;
vertices[idx++] = v.getBinormal().y;
vertices[idx++] = v.getBinormal().z;
}
if (v.getColourDiffuse() != null) {
float color = getColor(v.getColourDiffuse());
vertices[idx++] = color;
}
if (v.getTexcoord() != null) {
for (int l = 0; l < v.getTexcoord().size(); l++) {
Texcoord texCoord = v.getTexcoord().get(l);
int numTexCoords = 0;
switch (l) {
case 0:
numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions0());
break;
case 1:
numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions1());
break;
case 2:
numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions2());
break;
case 3:
numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions3());
break;
case 4:
numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions4());
break;
case 5:
numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions5());
break;
case 6:
numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions6());
break;
case 7:
numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions7());
break;
}
if (numTexCoords == 1) {
vertices[idx++] = texCoord.u;
}
if (numTexCoords == 2) {
vertices[idx++] = texCoord.u;
vertices[idx++] = texCoord.v;
}
if (numTexCoords == 3) {
vertices[idx++] = texCoord.u;
vertices[idx++] = texCoord.v;
vertices[idx++] = texCoord.w;
}
if (numTexCoords == 4) {
vertices[idx++] = texCoord.u;
vertices[idx++] = texCoord.v;
vertices[idx++] = texCoord.w;
vertices[idx++] = texCoord.x;
}
}
}
offset += vertexSize;
idx = offset;
}
}
com.badlogic.gdx.graphics.Mesh mesh = new com.badlogic.gdx.graphics.Mesh(false, vertices.length / vertexSize,
indices.length, attribs);
mesh.setIndices(indices);
mesh.setVertices(vertices);
String meshName = "";
- List<Submeshname> names = ogreMesh.getSubmeshnames().getSubmeshname();
- for(int n = 0; n < names.size(); ++n) {
- if(Integer.parseInt(names.get(n).getIndex()) == i)
- meshName = names.get(n).getName();
+ if(ogreMesh.getSubmeshnames() != null) {
+ List<Submeshname> names = ogreMesh.getSubmeshnames().getSubmeshname();
+ for(int n = 0; n < names.size(); ++n) {
+ if(Integer.parseInt(names.get(n).getIndex()) == i)
+ meshName = names.get(n).getName();
+ }
}
SubMesh subMesh;
Boneassignments boneAssigments = (ogreSubmesh.getBoneassignments() != null)? ogreSubmesh.getBoneassignments() : ogreMesh.getBoneassignments();
if (boneAssigments != null) {
subMesh = new SkeletonSubMesh(meshName, mesh, GL10.GL_TRIANGLES);
} else {
subMesh = new StillSubMesh(meshName, mesh, GL10.GL_TRIANGLES);
}
// FIXME ? subMesh.materialName = ogreSubmesh.material;
if (boneAssigments != null) {
SkeletonSubMesh subSkelMesh = (SkeletonSubMesh) subMesh;
subSkelMesh.setVertices(vertices);
subSkelMesh.setIndices(indices);
subSkelMesh.skinnedVertices = new float[vertices.length];
System.arraycopy(subSkelMesh.vertices, 0, subSkelMesh.skinnedVertices, 0, subSkelMesh.vertices.length);
loadBones(boneAssigments, subSkelMesh);
}
if (ogreSubmesh.getOperationtype().equals("triangle_list")) subMesh.primitiveType = GL10.GL_TRIANGLES;
if (ogreSubmesh.getOperationtype().equals("triangle_fan")) subMesh.primitiveType = GL10.GL_TRIANGLE_FAN;
if (ogreSubmesh.getOperationtype().equals("triangle_strip")) subMesh.primitiveType = GL10.GL_TRIANGLE_STRIP;
submeshes[i] = subMesh;
}
return submeshes;
}
private void loadBones (Boneassignments boneAssigments, SkeletonSubMesh subMesh) {
Array<IntArray> boneAssignments = new Array<IntArray>();
Array<FloatArray> boneWeights = new Array<FloatArray>();
for (int j = 0; j < subMesh.getMesh().getNumVertices(); j++) {
boneAssignments.add(new IntArray(4));
boneWeights.add(new FloatArray(4));
}
List<Vertexboneassignment> vertexboneassignment = boneAssigments.getVertexboneassignment();
for (int j = 0; j < vertexboneassignment.size(); j++) {
Vertexboneassignment assignment = vertexboneassignment.get(j);
int boneIndex = assignment.boneindex;
int vertexIndex = assignment.vertexindex;
float weight = assignment.weight;
boneAssignments.get(vertexIndex).add(boneIndex);
boneWeights.get(vertexIndex).add(weight);
}
subMesh.boneAssignments = new int[boneAssignments.size][];
subMesh.boneWeights = new float[boneWeights.size][];
for (int j = 0; j < boneAssignments.size; j++) {
subMesh.boneAssignments[j] = new int[boneAssignments.get(j).size];
subMesh.boneWeights[j] = new float[boneWeights.get(j).size];
for (int k = 0; k < boneAssignments.get(j).size; k++) {
subMesh.boneAssignments[j][k] = boneAssignments.get(j).get(k);
}
for (int k = 0; k < boneWeights.get(j).size; k++) {
subMesh.boneWeights[j][k] = boneWeights.get(j).get(k);
}
}
}
Color color = new Color();
private float getColor (ColourDiffuse colourDiffuse) {
String[] tokens = colourDiffuse.getValue().split(" ");
if (tokens.length == 3)
color.set(Float.valueOf(tokens[0]), Float.valueOf(tokens[1]), Float.valueOf(tokens[2]), 1);
else
color.set(Float.valueOf(tokens[0]), Float.valueOf(tokens[1]), Float.valueOf(tokens[2]), Float.valueOf(tokens[3]));
return color.toFloatBits();
}
private Mesh loadOgreMesh (InputStream in) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(Mesh.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
long start = System.nanoTime();
Mesh mesh = (Mesh)unmarshaller.unmarshal(in);
System.out.println("took: " + (System.nanoTime() - start) / 1000000000.0f);
return mesh;
}
public Skeleton loadSkeleton (FileHandle file) {
InputStream in = null;
try {
in = file.read();
return loadSkeleton(in);
} catch (Throwable t) {
throw new GdxRuntimeException("Couldn't load file '" + file.name() + "'", t);
} finally {
if (in != null) try {
in.close();
} catch (Exception e) {
}
}
}
public Skeleton loadSkeleton (InputStream in) {
try {
com.badlogic.gdx.graphics.g3d.loaders.ogre.skeleton.Skeleton ogreSkel = loadOgreSkeleton(in);
return generateSkeleton(ogreSkel);
} catch (Throwable t) {
throw new GdxRuntimeException("Couldn't load model", t);
}
}
private Skeleton generateSkeleton (com.badlogic.gdx.graphics.g3d.loaders.ogre.skeleton.Skeleton ogreSkel) {
List<Bone> bones = ogreSkel.getBones().getBone();
List<SkeletonJoint> joints = new ArrayList<SkeletonJoint>();
Map<String, SkeletonJoint> nameToJoint = new HashMap<String, SkeletonJoint>();
for (int i = 0; i < bones.size(); i++) {
Bone bone = bones.get(i);
SkeletonJoint joint = new SkeletonJoint();
joint.name = bone.name;
joint.position.set(bone.position.x, bone.position.y, bone.position.z);
joint.rotation.setFromAxis(bone.rotation.axis.x, bone.rotation.axis.y, bone.rotation.axis.z, MathUtils.radiansToDegrees
* bone.rotation.angle);
if (bone.scale != null) {
if (bone.scale.factor == 0)
joint.scale.set(bone.scale.x, bone.scale.y, bone.scale.z);
else
joint.scale.set(bone.scale.factor, bone.scale.factor, bone.scale.factor);
}
joints.add(joint);
nameToJoint.put(joint.name, joint);
}
List<Boneparent> hierarchy = ogreSkel.getBonehierarchy().getBoneparent();
for (int i = 0; i < hierarchy.size(); i++) {
Boneparent link = hierarchy.get(i);
SkeletonJoint joint = nameToJoint.get(link.getBone());
SkeletonJoint parent = nameToJoint.get(link.getParent());
parent.children.add(joint);
joint.parent = parent;
}
Skeleton skel = new Skeleton();
for (int i = 0; i < joints.size(); i++) {
SkeletonJoint joint = joints.get(i);
if (joint.parent == null) skel.hierarchy.add(joint);
}
skel.buildFromHierarchy();
List<Animation> animations = ogreSkel.getAnimations().getAnimation();
for (int i = 0; i < animations.size(); i++) {
Animation animation = animations.get(i);
SkeletonKeyframe[][] perJointkeyFrames = new SkeletonKeyframe[skel.bindPoseJoints.size][];
List<Track> tracks = animation.getTracks().getTrack();
if (tracks.size() != perJointkeyFrames.length)
throw new IllegalArgumentException("Number of tracks does not equal number of joints");
Matrix4 rotation = new Matrix4();
Matrix4 transform = new Matrix4();
for (int j = 0; j < tracks.size(); j++) {
Track track = tracks.get(j);
String jointName = track.getBone();
int jointIndex = skel.namesToIndices.get(jointName);
if (perJointkeyFrames[jointIndex] != null)
throw new IllegalArgumentException("Track for bone " + jointName + " in animation " + animation.name
+ " already defined!");
SkeletonKeyframe[] jointKeyFrames = new SkeletonKeyframe[track.getKeyframes().getKeyframe().size()];
perJointkeyFrames[jointIndex] = jointKeyFrames;
for (int k = 0; k < track.getKeyframes().getKeyframe().size(); k++) {
Keyframe keyFrame = track.getKeyframes().getKeyframe().get(k);
SkeletonKeyframe jointKeyframe = new SkeletonKeyframe();
jointKeyframe.timeStamp = keyFrame.time;
jointKeyframe.position.set(keyFrame.translate.x, keyFrame.translate.y, keyFrame.translate.z);
if (keyFrame.scale != null) {
if (keyFrame.scale.factor == 0)
jointKeyframe.scale.set(keyFrame.scale.x, keyFrame.scale.y, keyFrame.scale.z);
else
jointKeyframe.scale.set(keyFrame.scale.factor, keyFrame.scale.factor, keyFrame.scale.factor);
}
jointKeyframe.rotation
.setFromAxis(keyFrame.rotate.axis.x, keyFrame.rotate.axis.y, keyFrame.rotate.axis.z,
MathUtils.radiansToDegrees * keyFrame.rotate.angle).nor();
jointKeyframe.parentIndex = skel.bindPoseJoints.get(jointIndex).parentIndex;
jointKeyFrames[k] = jointKeyframe;
rotation.set(jointKeyframe.rotation);
rotation.trn(jointKeyframe.position);
transform.set(skel.sceneMatrices.get(jointIndex));
transform.mul(rotation);
if (jointKeyframe.parentIndex != -1) {
rotation.set(skel.offsetMatrices.get(jointKeyframe.parentIndex)).mul(transform);
transform.set(rotation);
}
transform.getTranslation(jointKeyframe.position);
transform.getRotation(jointKeyframe.rotation);
jointKeyframe.rotation.x *= -1;
jointKeyframe.rotation.y *= -1;
jointKeyframe.rotation.z *= -1;
}
}
for (int j = 0; j < perJointkeyFrames.length; j++) {
if (perJointkeyFrames[j] == null) throw new IllegalArgumentException("No track for bone " + skel.jointNames.get(j));
}
skel.animations.put(animation.name, new SkeletonAnimation(animation.name, animation.length, perJointkeyFrames));
}
return skel;
}
private com.badlogic.gdx.graphics.g3d.loaders.ogre.skeleton.Skeleton loadOgreSkeleton (InputStream in) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(com.badlogic.gdx.graphics.g3d.loaders.ogre.skeleton.Skeleton.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
long start = System.nanoTime();
com.badlogic.gdx.graphics.g3d.loaders.ogre.skeleton.Skeleton skel = (com.badlogic.gdx.graphics.g3d.loaders.ogre.skeleton.Skeleton)unmarshaller
.unmarshal(in);
System.out.println("took: " + (System.nanoTime() - start) / 1000000000.0f);
return skel;
}
}
diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/SkeletonModelViewer.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/SkeletonModelViewer.java
index 3051afdcc..bc3ccf05b 100644
--- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/SkeletonModelViewer.java
+++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/SkeletonModelViewer.java
@@ -1,189 +1,189 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.graphics.g3d.test;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g3d.loaders.ogre.OgreXmlLoader;
import com.badlogic.gdx.graphics.g3d.materials.Material;
import com.badlogic.gdx.graphics.g3d.materials.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.model.skeleton.SkeletonAnimation;
import com.badlogic.gdx.graphics.g3d.model.skeleton.SkeletonModel;
import com.badlogic.gdx.graphics.g3d.model.skeleton.SkeletonSubMesh;
import com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer10;
import com.badlogic.gdx.math.collision.BoundingBox;
import com.badlogic.gdx.utils.GdxRuntimeException;
public class SkeletonModelViewer implements ApplicationListener {
PerspectiveCamera cam;
SkeletonModel model;
Texture texture = null;
boolean hasNormals = false;
BoundingBox bounds = new BoundingBox();
ImmediateModeRenderer10 renderer;
float angle = 0;
String fileName;
String textureFileName;
SkeletonAnimation anim;
float animTime = 0;
SpriteBatch batch;
BitmapFont font;
public SkeletonModelViewer (String fileName, String textureFileName) {
this.fileName = fileName;
this.textureFileName = textureFileName;
}
@Override
public void create () {
if (fileName.endsWith(".xml")) {
model = new OgreXmlLoader().load(Gdx.files.internal(fileName),
Gdx.files.internal(fileName.replace("mesh.xml", "skeleton.xml")));
} else
throw new GdxRuntimeException("Unknown file format '" + fileName + "'");
if (textureFileName != null) texture = new Texture(Gdx.files.internal(textureFileName));
hasNormals = hasNormals();
Material material = new Material("material", new TextureAttribute(texture, 0, "s_tex"));
model.setMaterial(material);
anim = (SkeletonAnimation)model.getAnimations()[0];
model.getBoundingBox(bounds);
float len = bounds.getDimensions().len();
System.out.println("bounds: " + bounds);
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(bounds.getCenter().cpy().add(len, len, len));
cam.lookAt(bounds.getCenter().x, bounds.getCenter().y, bounds.getCenter().z);
cam.near = 0.1f;
cam.far = 1000;
renderer = new ImmediateModeRenderer10();
batch = new SpriteBatch();
font = new BitmapFont();
}
private boolean hasNormals () {
for (SkeletonSubMesh mesh : model.subMeshes) {
if (mesh.mesh.getVertexAttribute(Usage.Normal) == null) return false;
}
return true;
}
@Override
public void resume () {
}
float[] lightColor = {1, 1, 1, 0};
float[] lightPosition = {2, 5, 10, 0};
@Override
public void render () {
Gdx.gl.glClearColor(0.2f, 0.2f, 0.2f, 1.0f);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
Gdx.gl.glEnable(GL10.GL_DEPTH_TEST);
cam.update();
cam.apply(Gdx.gl10);
drawAxes();
if (hasNormals) {
Gdx.gl.glEnable(GL10.GL_LIGHTING);
Gdx.gl.glEnable(GL10.GL_COLOR_MATERIAL);
Gdx.gl.glEnable(GL10.GL_LIGHT0);
Gdx.gl10.glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, lightColor, 0);
Gdx.gl10.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, lightPosition, 0);
}
if (texture != null) {
Gdx.gl.glEnable(GL10.GL_TEXTURE_2D);
Gdx.gl.glEnable(GL10.GL_BLEND);
Gdx.gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
}
angle += 45 * Gdx.graphics.getDeltaTime();
Gdx.gl10.glRotatef(angle, 0, 1, 0);
- animTime += Gdx.graphics.getDeltaTime();
+ animTime += Gdx.graphics.getDeltaTime() / 10;
if (animTime > anim.totalDuration) {
animTime = 0;
}
model.setAnimation(anim.name, animTime, false);
model.render();
if (texture != null) {
Gdx.gl.glDisable(GL10.GL_TEXTURE_2D);
}
if (hasNormals) {
Gdx.gl.glDisable(GL10.GL_LIGHTING);
}
batch.begin();
font.draw(batch, "fps: " + Gdx.graphics.getFramesPerSecond(), 20, 30);
batch.end();
}
private void drawAxes () {
float len = bounds.getDimensions().len();
renderer.begin(GL10.GL_LINES);
renderer.color(1, 0, 0, 1);
renderer.vertex(0, 0, 0);
renderer.color(1, 0, 0, 1);
renderer.vertex(len, 0, 0);
renderer.color(0, 1, 0, 1);
renderer.vertex(0, 0, 0);
renderer.color(0, 1, 0, 1);
renderer.vertex(0, len, 0);
renderer.color(0, 0, 1, 1);
renderer.vertex(0, 0, 0);
renderer.color(0, 0, 1, 1);
renderer.vertex(0, 0, len);
renderer.end();
Gdx.gl10.glColor4f(1, 1, 1, 1);
}
@Override
public void resize (int width, int height) {
}
@Override
public void pause () {
}
@Override
public void dispose () {
}
public static void main (String[] argv) {
// if(argv.length != 1 && argv.length != 2) {
// System.out.println("KeyframedModelViewer <filename> ?<texture-filename>");
// System.exit(-1);
// }
new LwjglApplication(new SkeletonModelViewer("data/models/robot-mesh.xml", "data/models/robot.jpg"), "SkeletonModel Viewer", 800, 480,
false);
}
}
| false | false | null | null |
diff --git a/web/src/org/openmrs/module/sdmxhdintegration/web/controller/MessageUploadFormController.java b/web/src/org/openmrs/module/sdmxhdintegration/web/controller/MessageUploadFormController.java
index 3d6088f..88a8523 100644
--- a/web/src/org/openmrs/module/sdmxhdintegration/web/controller/MessageUploadFormController.java
+++ b/web/src/org/openmrs/module/sdmxhdintegration/web/controller/MessageUploadFormController.java
@@ -1,152 +1,152 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.module.sdmxhdintegration.web.controller;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jembi.sdmxhd.dsd.DSD;
import org.jembi.sdmxhd.dsd.KeyFamily;
import org.openmrs.api.AdministrationService;
import org.openmrs.api.context.Context;
import org.openmrs.module.reporting.report.definition.service.ReportDefinitionService;
import org.openmrs.module.sdmxhdintegration.KeyFamilyMapping;
import org.openmrs.module.sdmxhdintegration.SDMXHDMessage;
import org.openmrs.module.sdmxhdintegration.SDMXHDMessageValidator;
import org.openmrs.module.sdmxhdintegration.SDMXHDService;
import org.openmrs.web.WebConstants;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
@Controller
@SessionAttributes("sdmxhdMessage")
@RequestMapping("/module/sdmxhdintegration/messageUpload")
public class MessageUploadFormController {
private static Log log = LogFactory.getLog(MessageUploadFormController.class);
@RequestMapping(method=RequestMethod.GET)
public void showForm(@RequestParam(value = "sdmxhdmessageid", required = false) Integer sdmxMessageId, ModelMap model) {
if (sdmxMessageId != null) {
SDMXHDService sdmxhdService = (SDMXHDService) Context.getService(SDMXHDService.class);
SDMXHDMessage sdmxhdMessage = sdmxhdService.getSDMXHDMessage(sdmxMessageId);
model.addAttribute("sdmxhdMessage", sdmxhdMessage);
} else {
model.addAttribute("sdmxhdMessage", new SDMXHDMessage());
}
}
@RequestMapping(method=RequestMethod.POST)
public String handleSubmission(HttpServletRequest request,
@ModelAttribute("sdmxhdMessage") SDMXHDMessage sdmxhdMessage,
BindingResult result,
SessionStatus status) throws IllegalStateException {
DefaultMultipartHttpServletRequest req = (DefaultMultipartHttpServletRequest) request;
MultipartFile file = req.getFile("sdmxhdMessage");
File destFile = null;
if (!(file.getSize() <= 0)) {
AdministrationService as = Context.getAdministrationService();
String dir = as.getGlobalProperty("sdmxhdintegration.messageUploadDir");
String filename = file.getOriginalFilename();
- filename = "[" + (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")).format(new Date()) + "]" + filename;
+ filename = "_" + (new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss")).format(new Date()) + "_" + filename;
destFile = new File(dir + File.separator + filename);
destFile.mkdirs();
try {
file.transferTo(destFile);
}
catch (IOException e) {
HttpSession session = request.getSession();
session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Could not save file. Make sure you have setup the upload directory using the configuration page and that the directory is readable by the tomcat user.");
return "/module/sdmxhdintegration/messageUpload";
}
sdmxhdMessage.setSdmxhdZipFileName(filename);
}
new SDMXHDMessageValidator().validate(sdmxhdMessage, result);
if (result.hasErrors()) {
log.error("SDMXHDMessage object failed validation");
if (destFile != null) {
destFile.delete();
}
return "/module/sdmxhdintegration/messageUpload";
}
SDMXHDService sdmxhdService = Context.getService(SDMXHDService.class);
ReportDefinitionService rds = Context.getService(ReportDefinitionService.class);
sdmxhdService.saveSDMXHDMessage(sdmxhdMessage);
// delete all existing mappings and reports
List<KeyFamilyMapping> allKeyFamilyMappingsForMsg = sdmxhdService.getKeyFamilyMappingBySDMXHDMessage(sdmxhdMessage);
for (Iterator<KeyFamilyMapping> iterator = allKeyFamilyMappingsForMsg.iterator(); iterator.hasNext();) {
KeyFamilyMapping kfm = iterator.next();
Integer reportDefinitionId = kfm.getReportDefinitionId();
sdmxhdService.purgeKeyFamilyMapping(kfm);
if (reportDefinitionId != null) {
rds.purgeDefinition(rds.getDefinition(reportDefinitionId));
}
}
// create initial keyFamilyMappings
try {
DSD dsd = sdmxhdService.getSDMXHDDataSetDefinition(sdmxhdMessage);
List<KeyFamily> keyFamilies = dsd.getKeyFamilies();
for (Iterator<KeyFamily> iterator = keyFamilies.iterator(); iterator.hasNext();) {
KeyFamily keyFamily = iterator.next();
KeyFamilyMapping kfm = new KeyFamilyMapping();
kfm.setKeyFamilyId(keyFamily.getId());
kfm.setSdmxhdMessage(sdmxhdMessage);
sdmxhdService.saveKeyFamilyMapping(kfm);
}
}
catch (Exception e) {
log.error("Error parsing SDMX-HD Message: " + e, e);
if (destFile != null) {
destFile.delete();
}
sdmxhdService.purgeSDMXHDMessage(sdmxhdMessage);
result.rejectValue("sdmxhdZipFileName", "upload.file.rejected", "This file is not a valid zip file or it does not contain a valid SDMX-HD DataSetDefinition");
return "/module/sdmxhdintegration/messageUpload";
}
return "redirect:viewSDMXHDMessages.list";
}
}
| true | true | public String handleSubmission(HttpServletRequest request,
@ModelAttribute("sdmxhdMessage") SDMXHDMessage sdmxhdMessage,
BindingResult result,
SessionStatus status) throws IllegalStateException {
DefaultMultipartHttpServletRequest req = (DefaultMultipartHttpServletRequest) request;
MultipartFile file = req.getFile("sdmxhdMessage");
File destFile = null;
if (!(file.getSize() <= 0)) {
AdministrationService as = Context.getAdministrationService();
String dir = as.getGlobalProperty("sdmxhdintegration.messageUploadDir");
String filename = file.getOriginalFilename();
filename = "[" + (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")).format(new Date()) + "]" + filename;
destFile = new File(dir + File.separator + filename);
destFile.mkdirs();
try {
file.transferTo(destFile);
}
catch (IOException e) {
HttpSession session = request.getSession();
session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Could not save file. Make sure you have setup the upload directory using the configuration page and that the directory is readable by the tomcat user.");
return "/module/sdmxhdintegration/messageUpload";
}
sdmxhdMessage.setSdmxhdZipFileName(filename);
}
new SDMXHDMessageValidator().validate(sdmxhdMessage, result);
if (result.hasErrors()) {
log.error("SDMXHDMessage object failed validation");
if (destFile != null) {
destFile.delete();
}
return "/module/sdmxhdintegration/messageUpload";
}
SDMXHDService sdmxhdService = Context.getService(SDMXHDService.class);
ReportDefinitionService rds = Context.getService(ReportDefinitionService.class);
sdmxhdService.saveSDMXHDMessage(sdmxhdMessage);
// delete all existing mappings and reports
List<KeyFamilyMapping> allKeyFamilyMappingsForMsg = sdmxhdService.getKeyFamilyMappingBySDMXHDMessage(sdmxhdMessage);
for (Iterator<KeyFamilyMapping> iterator = allKeyFamilyMappingsForMsg.iterator(); iterator.hasNext();) {
KeyFamilyMapping kfm = iterator.next();
Integer reportDefinitionId = kfm.getReportDefinitionId();
sdmxhdService.purgeKeyFamilyMapping(kfm);
if (reportDefinitionId != null) {
rds.purgeDefinition(rds.getDefinition(reportDefinitionId));
}
}
// create initial keyFamilyMappings
try {
DSD dsd = sdmxhdService.getSDMXHDDataSetDefinition(sdmxhdMessage);
List<KeyFamily> keyFamilies = dsd.getKeyFamilies();
for (Iterator<KeyFamily> iterator = keyFamilies.iterator(); iterator.hasNext();) {
KeyFamily keyFamily = iterator.next();
KeyFamilyMapping kfm = new KeyFamilyMapping();
kfm.setKeyFamilyId(keyFamily.getId());
kfm.setSdmxhdMessage(sdmxhdMessage);
sdmxhdService.saveKeyFamilyMapping(kfm);
}
}
catch (Exception e) {
log.error("Error parsing SDMX-HD Message: " + e, e);
if (destFile != null) {
destFile.delete();
}
sdmxhdService.purgeSDMXHDMessage(sdmxhdMessage);
result.rejectValue("sdmxhdZipFileName", "upload.file.rejected", "This file is not a valid zip file or it does not contain a valid SDMX-HD DataSetDefinition");
return "/module/sdmxhdintegration/messageUpload";
}
return "redirect:viewSDMXHDMessages.list";
}
| public String handleSubmission(HttpServletRequest request,
@ModelAttribute("sdmxhdMessage") SDMXHDMessage sdmxhdMessage,
BindingResult result,
SessionStatus status) throws IllegalStateException {
DefaultMultipartHttpServletRequest req = (DefaultMultipartHttpServletRequest) request;
MultipartFile file = req.getFile("sdmxhdMessage");
File destFile = null;
if (!(file.getSize() <= 0)) {
AdministrationService as = Context.getAdministrationService();
String dir = as.getGlobalProperty("sdmxhdintegration.messageUploadDir");
String filename = file.getOriginalFilename();
filename = "_" + (new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss")).format(new Date()) + "_" + filename;
destFile = new File(dir + File.separator + filename);
destFile.mkdirs();
try {
file.transferTo(destFile);
}
catch (IOException e) {
HttpSession session = request.getSession();
session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Could not save file. Make sure you have setup the upload directory using the configuration page and that the directory is readable by the tomcat user.");
return "/module/sdmxhdintegration/messageUpload";
}
sdmxhdMessage.setSdmxhdZipFileName(filename);
}
new SDMXHDMessageValidator().validate(sdmxhdMessage, result);
if (result.hasErrors()) {
log.error("SDMXHDMessage object failed validation");
if (destFile != null) {
destFile.delete();
}
return "/module/sdmxhdintegration/messageUpload";
}
SDMXHDService sdmxhdService = Context.getService(SDMXHDService.class);
ReportDefinitionService rds = Context.getService(ReportDefinitionService.class);
sdmxhdService.saveSDMXHDMessage(sdmxhdMessage);
// delete all existing mappings and reports
List<KeyFamilyMapping> allKeyFamilyMappingsForMsg = sdmxhdService.getKeyFamilyMappingBySDMXHDMessage(sdmxhdMessage);
for (Iterator<KeyFamilyMapping> iterator = allKeyFamilyMappingsForMsg.iterator(); iterator.hasNext();) {
KeyFamilyMapping kfm = iterator.next();
Integer reportDefinitionId = kfm.getReportDefinitionId();
sdmxhdService.purgeKeyFamilyMapping(kfm);
if (reportDefinitionId != null) {
rds.purgeDefinition(rds.getDefinition(reportDefinitionId));
}
}
// create initial keyFamilyMappings
try {
DSD dsd = sdmxhdService.getSDMXHDDataSetDefinition(sdmxhdMessage);
List<KeyFamily> keyFamilies = dsd.getKeyFamilies();
for (Iterator<KeyFamily> iterator = keyFamilies.iterator(); iterator.hasNext();) {
KeyFamily keyFamily = iterator.next();
KeyFamilyMapping kfm = new KeyFamilyMapping();
kfm.setKeyFamilyId(keyFamily.getId());
kfm.setSdmxhdMessage(sdmxhdMessage);
sdmxhdService.saveKeyFamilyMapping(kfm);
}
}
catch (Exception e) {
log.error("Error parsing SDMX-HD Message: " + e, e);
if (destFile != null) {
destFile.delete();
}
sdmxhdService.purgeSDMXHDMessage(sdmxhdMessage);
result.rejectValue("sdmxhdZipFileName", "upload.file.rejected", "This file is not a valid zip file or it does not contain a valid SDMX-HD DataSetDefinition");
return "/module/sdmxhdintegration/messageUpload";
}
return "redirect:viewSDMXHDMessages.list";
}
|
diff --git a/plugins/generator/src/main/java/org/richfaces/cdk/apt/processors/AttributesProcessorImpl.java b/plugins/generator/src/main/java/org/richfaces/cdk/apt/processors/AttributesProcessorImpl.java
index 8236790..fb2c8a0 100644
--- a/plugins/generator/src/main/java/org/richfaces/cdk/apt/processors/AttributesProcessorImpl.java
+++ b/plugins/generator/src/main/java/org/richfaces/cdk/apt/processors/AttributesProcessorImpl.java
@@ -1,241 +1,245 @@
package org.richfaces.cdk.apt.processors;
import java.io.FileNotFoundException;
import java.util.Collection;
import java.util.Set;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import org.richfaces.cdk.CdkException;
import org.richfaces.cdk.Logger;
import org.richfaces.cdk.annotations.Attribute;
import org.richfaces.cdk.annotations.Signature;
import org.richfaces.cdk.apt.SourceUtils;
import org.richfaces.cdk.apt.SourceUtils.BeanProperty;
import org.richfaces.cdk.apt.SourceUtils.SuperTypeVisitor;
import org.richfaces.cdk.model.BeanModelBase;
import org.richfaces.cdk.model.ClassName;
import org.richfaces.cdk.model.MethodSignature;
import org.richfaces.cdk.model.PropertyBase;
import org.richfaces.cdk.util.JavaUtils;
import org.richfaces.cdk.xmlconfig.CdkEntityResolver;
import org.richfaces.cdk.xmlconfig.FragmentParser;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
import com.google.inject.Provider;
/**
* <p class="changed_added_4_0">
* </p>
*
* @author [email protected]
*
*/
public class AttributesProcessorImpl implements AttributesProcessor {
private static final ClassName SIGNATURE_NONE_CLASS_NAME = ClassName.get(Signature.NONE.class);
private static final ClassName STRING_TYPE = ClassName.get(String.class);
@Inject
private Logger log;
private final DescriptionProcessor descriptionProcessor;
private final Provider<SourceUtils> utilsProvider;
private final FragmentParser parser;
/**
* <p class="changed_added_4_0">
* </p>
*
* @param descriptionProcessor
* @param utilsProvider
* @param parser
*/
@Inject
public AttributesProcessorImpl(DescriptionProcessor descriptionProcessor, Provider<SourceUtils> utilsProvider,
FragmentParser parser) {
this.descriptionProcessor = descriptionProcessor;
this.utilsProvider = utilsProvider;
this.parser = parser;
}
protected void processAttribute(SourceUtils.BeanProperty beanProperty, PropertyBase attribute) {
attribute.setType(beanProperty.getType());
AnnotationMirror attributeAnnotarion = beanProperty.getAnnotationMirror(Attribute.class);
if (attributeAnnotarion == null) {
attribute.setGenerate(!beanProperty.isExists());
attribute.setDescription(beanProperty.getDocComment());
attribute.setHidden(true);
if (attribute.getType().isPrimitive()) {
String value = getPimitiveDefaultValue(attribute.getType().getName());
if (value != null) {
attribute.setDefaultValue(value);
}
}
} else {
SourceUtils utils = utilsProvider.get();
utils.setModelProperty(attribute, attributeAnnotarion, "hidden");
utils.setModelProperty(attribute, attributeAnnotarion, "literal");
utils.setModelProperty(attribute, attributeAnnotarion, "passThrough");
utils.setModelProperty(attribute, attributeAnnotarion, "required");
utils.setModelProperty(attribute, attributeAnnotarion, "readOnly");
- utils.setModelProperty(attribute, attributeAnnotarion, "generate");
+ if (!utils.isDefaultValue(attributeAnnotarion, "generate")) {
+ attribute.setGenerate(utils.getAnnotationValue(attributeAnnotarion, "generate", boolean.class));
+ } else {
+ attribute.setGenerate(!beanProperty.isExists());
+ }
descriptionProcessor.processDescription(attribute, beanProperty.getAnnotation(Attribute.class).description(), beanProperty
.getDocComment());
setDefaultValue(attribute, attributeAnnotarion);
utils.setModelProperty(attribute, attributeAnnotarion, "suggestedValue");
// MethodExpression call signature.
attribute.setSignature(getSignature(attributeAnnotarion));
for (AnnotationMirror event : utils.getAnnotationValues(attributeAnnotarion, "events", AnnotationMirror.class)){
setBehaviorEvent(attribute, event);
}
}
}
private void setDefaultValue(PropertyBase attribute, AnnotationMirror attributeAnnotarion) {
SourceUtils utils = utilsProvider.get();
String defaultValue;
// TODO - move to model validator.
if (utils.isDefaultValue(attributeAnnotarion, "defaultValue")) {
if (attribute.getType().isPrimitive()) {
String pimitiveDefaultValue = getPimitiveDefaultValue(attribute.getType().getName());
attribute.setDefaultValue(pimitiveDefaultValue);
}
} else {
defaultValue = utils.getAnnotationValue(attributeAnnotarion, "defaultValue", String.class);
if (STRING_TYPE.equals(attribute.getType())) {
defaultValue = JavaUtils.getEscapedString(defaultValue);
}
attribute.setDefaultValue(defaultValue);
}
}
private String getPimitiveDefaultValue(String typeName) {
if (isInstace(boolean.class, typeName)) {
return "false";
} else if (isInstace(int.class, typeName)) {
return "Integer.MIN_VALUE";
} else if (isInstace(long.class, typeName)) {
return "Long.MIN_VALUE";
} else if (isInstace(byte.class, typeName)) {
return "Byte.MIN_VALUE";
} else if (isInstace(short.class, typeName)) {
return "Short.MIN_VALUE";
} else if (isInstace(float.class, typeName)) {
return "Float.MIN_VALUE";
} else if (isInstace(double.class, typeName)) {
return "Double.MIN_VALUE";
} else if (isInstace(char.class, typeName)) {
return "Character.MIN_VALUE";
}
return null;
}
private boolean isInstace(Class<?> byteClass, String typeName) {
return byteClass.getSimpleName().equals(typeName);
}
private MethodSignature getSignature(AnnotationMirror attributeAnnotarion) {
SourceUtils utils = utilsProvider.get();
if (!utils.isDefaultValue(attributeAnnotarion, "signature")) {
AnnotationMirror signatureAnnotation =
utils.getAnnotationValue(attributeAnnotarion, "signature", AnnotationMirror.class);
ClassName returnType = utils.getAnnotationValue(signatureAnnotation, "returnType", ClassName.class);
if (!SIGNATURE_NONE_CLASS_NAME.equals(returnType)) {
MethodSignature methodSignature = new MethodSignature();
methodSignature.setParameters(utils.getAnnotationValues(signatureAnnotation, "parameters",
ClassName.class));
methodSignature.setReturnType(returnType);
return methodSignature;
}
}
return null;
}
private void setBehaviorEvent(PropertyBase attribute, AnnotationMirror eventMirror) {
if (null != eventMirror) {
SourceUtils utils = utilsProvider.get();
org.richfaces.cdk.model.EventName event = new org.richfaces.cdk.model.EventName();
utils.setModelProperty(event, eventMirror, "name", "value");
utils.setModelProperty(event, eventMirror, "defaultEvent");
attribute.getEventNames().add(event);
}
}
@Override
public void processType(final BeanModelBase component, TypeElement element) throws CdkException {
log.debug("AttributesProcessorImpl.processType");
log.debug(" -> component = " + component);
log.debug(" -> typeElement = " + element);
log.debug(" -- Process XML files with standard attributes definitions.");
log.debug(" -> sourceUtils.visitSupertypes...");
SourceUtils sourceUtils = getSourceUtils();
sourceUtils.visitSupertypes(element, new SuperTypeVisitor() {
@Override
public void visit(TypeMirror type) {
String uri = type.toString() + ".xml";
try {
log.debug(" -> visit - " + type.toString());
component.getAttributes().addAll(parseProperties(uri));
} catch (CdkException e) {
log.error(e);
} catch (FileNotFoundException e) {
log.debug("No properties description found at " + uri);
}
}
});
log.debug(" -- Process Java files.");
Set<BeanProperty> properties = Sets.newHashSet();
properties.addAll(sourceUtils.getBeanPropertiesAnnotatedWith(Attribute.class, element));
properties.addAll(sourceUtils.getAbstractBeanProperties(element));
for (BeanProperty beanProperty : properties) {
processAttribute(beanProperty, component.getOrCreateAttribute(beanProperty.getName()));
}
}
private Collection<? extends PropertyBase> parseProperties(String uri) throws FileNotFoundException {
return parser.parseProperties(CdkEntityResolver.URN_ATTRIBUTES + uri);
}
private SourceUtils getSourceUtils() {
return utilsProvider.get();
}
@Override
public void processXmlFragment(BeanModelBase component, String... attributesConfig) {
// Process all files from @Jsf.. attributes property.
for (String attributes : attributesConfig) {
try {
component.getAttributes().addAll(parseProperties(attributes));
} catch (CdkException e) {
log.error(e);
} catch (FileNotFoundException e) {
log.debug("No properties description found at " + attributes);
}
}
}
}
diff --git a/plugins/generator/src/main/java/org/richfaces/cdk/model/validator/ValidatorImpl.java b/plugins/generator/src/main/java/org/richfaces/cdk/model/validator/ValidatorImpl.java
index 4c128c7..a013e0c 100644
--- a/plugins/generator/src/main/java/org/richfaces/cdk/model/validator/ValidatorImpl.java
+++ b/plugins/generator/src/main/java/org/richfaces/cdk/model/validator/ValidatorImpl.java
@@ -1,402 +1,404 @@
/*
* $Id$
*
* License Agreement.
*
* Rich Faces - Natural Ajax for Java Server Faces (JSF)
*
* Copyright (C) 2007 Exadel, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.richfaces.cdk.model.validator;
import java.util.Collection;
import java.util.HashSet;
import java.util.NoSuchElementException;
import javax.faces.view.facelets.BehaviorHandler;
import javax.faces.view.facelets.ComponentHandler;
import javax.faces.view.facelets.ConverterHandler;
import javax.xml.validation.ValidatorHandler;
import org.richfaces.cdk.CdkException;
import org.richfaces.cdk.Logger;
import org.richfaces.cdk.ModelValidator;
import org.richfaces.cdk.NamingConventions;
import org.richfaces.cdk.apt.SourceUtils;
import org.richfaces.cdk.model.BehaviorModel;
import org.richfaces.cdk.model.ClassName;
import org.richfaces.cdk.model.ComponentLibrary;
import org.richfaces.cdk.model.ComponentModel;
import org.richfaces.cdk.model.DescriptionGroup;
import org.richfaces.cdk.model.EventModel;
import org.richfaces.cdk.model.FacesComponent;
import org.richfaces.cdk.model.FacesId;
import org.richfaces.cdk.model.FacetModel;
import org.richfaces.cdk.model.InvalidNameException;
import org.richfaces.cdk.model.PropertyBase;
import org.richfaces.cdk.model.RenderKitModel;
import org.richfaces.cdk.model.RendererModel;
import org.richfaces.cdk.model.TagModel;
import org.richfaces.cdk.model.Taglib;
import org.richfaces.cdk.util.Strings;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
+import com.google.inject.Provider;
/**
* <p class="changed_added_4_0">
* </p>
*
* @author [email protected]
*
*/
public class ValidatorImpl implements ModelValidator {
public static final ClassName DEFAULT_COMPONENT_HANDLER = new ClassName(ComponentHandler.class);
public static final ClassName DEFAULT_VALIDATOR_HANDLER = new ClassName(ValidatorHandler.class);
public static final ClassName DEFAULT_CONVERTER_HANDLER = new ClassName(ConverterHandler.class);
public static final ClassName DEFAULT_BEHAVIOR_HANDLER = new ClassName(BehaviorHandler.class);
/**
* <p class="changed_added_4_0">
* </p>
*
* @author [email protected]
*
*/
interface NamingConventionsCallback {
FacesId inferType(ClassName targetClass);
ClassName inferClass(FacesId id);
}
@Inject
private Logger log;
private final NamingConventions namingConventions;
- private final SourceUtils sourceUtils;
+ private final Provider<SourceUtils> sourceUtilsProvider;
@Inject
- public ValidatorImpl(NamingConventions namingConventions, SourceUtils sourceUtils) {
+ public ValidatorImpl(NamingConventions namingConventions, Provider<SourceUtils> sourceUtilsProvider) {
this.namingConventions = namingConventions;
- this.sourceUtils = sourceUtils;
+ this.sourceUtilsProvider = sourceUtilsProvider;
}
/*
* (non-Javadoc)
*
* @see org.richfaces.cdk.ValidatorModel#verify(org.richfaces.cdk.model.ComponentLibrary)
*/
@Override
public void verify(ComponentLibrary library) throws CdkException {
verifyComponents(library);
verifyEvents(library);
verifyBehaviors(library);
verifyRenderers(library);
verifyTaglib(library);
}
protected void verifyEvents(ComponentLibrary library) {
for (EventModel event : library.getEvents()) {
ClassName listenerInterface = event.getListenerInterface();
if (null == listenerInterface) {
// TODO - infer listener interface name.
}
+ SourceUtils sourceUtils = sourceUtilsProvider.get();
event.setGenerateListener(null == sourceUtils.asTypeElement(listenerInterface));
String methodName = event.getListenerMethod();
if (null == methodName) {
// TODO infer listener method name.
methodName="process";
event.setListenerMethod(methodName);
}
ClassName sourceInterface = event.getSourceInterface();
if (null == sourceInterface) {
// TODO - infer source interface.
}
event.setGenerateSource(null == sourceUtils.asTypeElement(sourceInterface));
// Propagate event to corresponding components.
for (ComponentModel component : library.getComponents()) {
for (EventModel componentEvent : component.getEvents()) {
if (event.getType().equals(componentEvent.getType())) {
componentEvent.merge(event);
}
}
}
}
}
protected void verifyTaglib(ComponentLibrary library) {
Taglib taglib = library.getTaglib();
if (null == taglib) {
// Oops, create taglib model
taglib = new Taglib();
library.setTaglib(taglib);
}
// Verify URI
String uri = taglib.getUri();
if (null == uri) {
// infer default value.
uri = namingConventions.inferTaglibUri(library);
taglib.setUri(uri);
// log.error("No uri defined for taglib");
}
String shortName = taglib.getShortName();
if (null == shortName) {
shortName = namingConventions.inferTaglibName(uri);
taglib.setShortName(shortName);
// log.error("No short defined for taglib");
}
}
/**
* <p class="changed_added_4_0">
* Verify all behaviors in the library.
* </p>
*
* @param library
*/
protected void verifyBehaviors(ComponentLibrary library) {
for (BehaviorModel behavior : library.getBehaviors()) {
verifyTypes(behavior, new NamingConventionsCallback() {
@Override
public FacesId inferType(ClassName targetClass) {
// TODO Auto-generated method stub
return namingConventions.inferBehaviorType(targetClass);
}
@Override
public ClassName inferClass(FacesId id) {
// TODO Auto-generated method stub
return namingConventions.inferBehaviorClass(id);
}
});
for (TagModel tag : behavior.getTags()) {
verifyTag(tag, behavior.getId(), DEFAULT_BEHAVIOR_HANDLER);
}
}
}
protected void verifyRenderers(ComponentLibrary library) {
for (RenderKitModel renderKit : library.getRenderKits()) {
// Check render kit name and class.
for (RendererModel renderer : renderKit.getRenderers()) {
vefifyRenderer(library, renderer);
}
}
}
protected void vefifyRenderer(ComponentLibrary library, RendererModel renderer) {
// Check type.
// Check family.
// Check generated class.
// Check superclass.
// Check component type.
}
protected void verifyComponents(ComponentLibrary library) throws CdkException {
// Verify types and classes. Do it first to be sure what all all values are set before second stage.
for (ComponentModel component : library.getComponents()) {
verifyComponentType(component);
}
// Verify component attributes
HashSet<ComponentModel> verified = Sets.newHashSet();
for (ComponentModel component : library.getComponents()) {
verifyComponentAttributes(library, component, verified);
}
}
/**
* <p class="changed_added_4_0">
* </p>
*
* @param library
* @param component
* @param verified
*/
protected void verifyComponentAttributes(ComponentLibrary library, final ComponentModel component,
Collection<ComponentModel> verified) {
// There is potential StackOverflow, so we process only components which have not been
// verified before.
if (!verified.contains(component)) {
// Propagate attributes from parent component, if any.
verified.add(component);
if (null != component.getBaseClass()) {
try {
// Step one, lookup for parent.
ComponentModel parentComponent =
Iterables.find(library.getComponents(), new Predicate<ComponentModel>() {
@Override
public boolean apply(ComponentModel input) {
return component.getBaseClass().equals(input.getTargetClass());
}
});
// To be sure what all properties for parent component were propagated.
verifyComponentAttributes(library, parentComponent, verified);
for (PropertyBase parentAttribute : parentComponent.getAttributes()) {
PropertyBase attribute = component.getOrCreateAttribute(parentAttribute.getName());
attribute.merge(parentAttribute);
// TODO Check generate status. Attribute should not be generated if the parent component
// represents
// concrete class.
attribute.setGenerate(false);
}
} catch (NoSuchElementException e) {
// No parent component in the library
}
} // Check attributes.
for (PropertyBase attribute : component.getAttributes()) {
verifyAttribute(attribute, component.isGenerate());
}
// compact(component.getAttributes());
// Check renderers.
// Check Tag
for (TagModel tag : component.getTags()) {
verifyTag(tag, component.getId(), DEFAULT_COMPONENT_HANDLER);
}
verifyDescription(component);
for (FacetModel facet : component.getFacets()) {
verifyDescription(facet);
}
}
}
protected void verifyTag(TagModel tag, FacesId id, ClassName handler) {
if (Strings.isEmpty(tag.getName())) {
String defaultTagName = namingConventions.inferTagName(id);
tag.setName(defaultTagName);
}
if (tag.isGenerate()) {
if (null == tag.getBaseClass()) {
// TODO - choose default handler class by tag type.
tag.setBaseClass(handler);
}
if (null == tag.getTargetClass()) {
namingConventions.inferTagHandlerClass(id, tag.getType().toString());// TODO - get markup somethere.
}
}
// TODO - copy component description to tag, if it has no description.
}
/**
* <p class="changed_added_4_0">
* </p>
*
* @param component
* @throws InvalidNameException
*/
protected void verifyComponentType(ComponentModel component) throws InvalidNameException {
// Check JsfComponent type.
if (verifyTypes(component, new NamingConventionsCallback() {
@Override
public FacesId inferType(ClassName targetClass) {
return namingConventions.inferComponentType(targetClass);
}
@Override
public ClassName inferClass(FacesId id) {
return namingConventions.inferUIComponentClass(id);
}
}) && null == component.getFamily()) {
// Check family.
component.setFamily(namingConventions.inferUIComponentFamily(component.getId()));
}
}
protected boolean verifyTypes(FacesComponent component, NamingConventionsCallback callback) {
// Check JsfComponent type.
if (null == component.getId()) {
if (null != component.getTargetClass()) {
component.setId(callback.inferType(component.getTargetClass()));
} else if (null != component.getBaseClass()) {
component.setId(callback.inferType(component.getBaseClass()));
} else {
// No clue for component type, log error and return.
log.error("No type information available for component: " + component);
return false;
}
}
// Check classes.
if (component.isGenerate()) {
if (null == component.getBaseClass()) {
log.error("Base class for generated component is not set :" + component.getId());
// return;
} else if (null == component.getTargetClass()) {
component.setTargetClass(callback.inferClass(component.getId()));
}
} else if (null == component.getTargetClass()) {
if (null != component.getBaseClass()) {
component.setTargetClass(component.getBaseClass());
} else {
log.error("No class information available for component: " + component);
return false;
}
}
return true;
}
protected void verifyAttribute(PropertyBase attribute, boolean generatedComponent) {
// Check name.
if (Strings.isEmpty(attribute.getName())) {
log.error("No name for attribute " + attribute);
return;
}
if (attribute.getName().contains(".") || Character.isDigit(attribute.getName().charAt(0))
|| attribute.getName().contains(" ")) {
log.error("Invalid attribute name [" + attribute.getName() + "]");
return;
}
// Check type
if (null == attribute.getType()) {
log.error("Unknown type of attribute [" + attribute.getName() + "]");
return;
}
// Check binding properties.
if ("javax.faces.el.MethodBinding".equals(attribute.getType().getName())) {
attribute.setBinding(true);
attribute.setBindingAttribute(true);
} else if ("javax.el.MethodExpression".equals(attribute.getType().getName())) {
attribute.setBindingAttribute(true);
}
//if(attribute.isBindingAttribute() && attribute.getSignature().isEmpty() && !attribute.isHidden()) {
// log.error("Signature for method expression attribute "+attribute.getName()+" has not been set");
//}
// Check "generate" flag.
if (generatedComponent) {
// TODO Attribute should be only generated if it does not exist or abstract in the base class.
// Step one - check base class
} else {
attribute.setGenerate(false);
}
verifyDescription(attribute);
}
protected void verifyDescription(DescriptionGroup element) {
}
}
| false | false | null | null |
diff --git a/weather/src/main/java/de/luho/weather/WeatherApp.java b/weather/src/main/java/de/luho/weather/WeatherApp.java
index 1f17fbe..1f2b90d 100644
--- a/weather/src/main/java/de/luho/weather/WeatherApp.java
+++ b/weather/src/main/java/de/luho/weather/WeatherApp.java
@@ -1,57 +1,57 @@
package de.luho.weather;
import java.util.Date;
import de.luho.weather.db.WeatherDatabase;
import de.luho.weather.google.GoogleWeatherClient;
import de.luho.weather.google.GoogleWeatherParser;
import de.luho.weather.google.GoogleWeatherService;
public class WeatherApp {
private WeatherService service;
private WeatherFormatter formatter;
private WeatherStore store;
public String getAndStoreForecastForCity(String city) {
Forecast forecast = service.getForecastForCity(city);
String formatted = formatter.format(forecast);
- //store.save(forecast);
+ store.save(forecast);
return formatted;
}
public String getPastForecast(String city, Date date) {
if (new Date().before(date)) {
throw new IllegalArgumentException("Date should be in the past.");
}
Forecast past = store.find(city, date);
String formatted = formatter.format(past);
return formatted;
}
public void setWeatherService(WeatherService service) {
this.service = service;
}
public void setWeatherFormatter(WeatherFormatter formatter) {
this.formatter = formatter;
}
public void setWeatherStore(WeatherStore store) {
this.store = store;
}
public static void main(String[] args) {
GoogleWeatherService service = new GoogleWeatherService();
service.setGoogleWeatherClient(new GoogleWeatherClient());
service.setGoogleWeatherParser(new GoogleWeatherParser());
WeatherApp wapp = new WeatherApp();
wapp.setWeatherService(service);
wapp.setWeatherFormatter(new ConsoleWeatherFormatter());
wapp.setWeatherStore(new WeatherDatabase());
String forecast = wapp.getAndStoreForecastForCity("München");
System.out.println(forecast);
}
}
| true | false | null | null |
diff --git a/core/src/java/liquibase/diff/DiffResult.java b/core/src/java/liquibase/diff/DiffResult.java
index 5dda6ce1..9fd21e7b 100644
--- a/core/src/java/liquibase/diff/DiffResult.java
+++ b/core/src/java/liquibase/diff/DiffResult.java
@@ -1,962 +1,970 @@
package liquibase.diff;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.RandomAccessFile;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import liquibase.change.*;
import liquibase.csv.CSVWriter;
import liquibase.database.Database;
import liquibase.database.structure.*;
import liquibase.exception.JDBCException;
import liquibase.log.LogFactory;
import liquibase.parser.LiquibaseSchemaResolver;
import liquibase.parser.xml.XMLChangeLogParser;
import liquibase.util.SqlUtil;
import liquibase.util.StringUtils;
import liquibase.xml.DefaultXmlWriter;
import liquibase.xml.XmlWriter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class DiffResult {
private Long baseId = new Date().getTime();
private int changeNumber = 1;
private Database baseDatabase;
private Database targetDatabase;
private DatabaseSnapshot baseSnapshot;
private DatabaseSnapshot targetSnapshot;
private DiffComparison productName;
private DiffComparison productVersion;
private SortedSet<Table> missingTables = new TreeSet<Table>();
private SortedSet<Table> unexpectedTables = new TreeSet<Table>();
private SortedSet<View> missingViews = new TreeSet<View>();
private SortedSet<View> unexpectedViews = new TreeSet<View>();
private SortedSet<Column> missingColumns = new TreeSet<Column>();
private SortedSet<Column> unexpectedColumns = new TreeSet<Column>();
private SortedSet<Column> changedColumns = new TreeSet<Column>();
private SortedSet<ForeignKey> missingForeignKeys = new TreeSet<ForeignKey>();
private SortedSet<ForeignKey> unexpectedForeignKeys = new TreeSet<ForeignKey>();
private SortedSet<Index> missingIndexes = new TreeSet<Index>();
private SortedSet<Index> unexpectedIndexes = new TreeSet<Index>();
private SortedSet<PrimaryKey> missingPrimaryKeys = new TreeSet<PrimaryKey>();
private SortedSet<PrimaryKey> unexpectedPrimaryKeys = new TreeSet<PrimaryKey>();
private SortedSet<UniqueConstraint> missingUniqueConstraints = new TreeSet<UniqueConstraint>();
private SortedSet<UniqueConstraint> unexpectedUniqueConstraints = new TreeSet<UniqueConstraint>();
private SortedSet<Sequence> missingSequences = new TreeSet<Sequence>();
private SortedSet<Sequence> unexpectedSequences = new TreeSet<Sequence>();
private boolean diffData = false;
private String dataDir = null;
private String changeSetContext;
private String changeSetAuthor;
public DiffResult(DatabaseSnapshot baseDatabase, DatabaseSnapshot targetDatabase) {
this.baseDatabase = baseDatabase.getDatabase();
this.targetDatabase = targetDatabase.getDatabase();
this.baseSnapshot = baseDatabase;
this.targetSnapshot = targetDatabase;
}
public DiffComparison getProductName() {
return productName;
}
public void setProductName(DiffComparison productName) {
this.productName = productName;
}
public DiffComparison getProductVersion() {
return productVersion;
}
public void setProductVersion(DiffComparison product) {
this.productVersion = product;
}
public void addMissingTable(Table table) {
missingTables.add(table);
}
public SortedSet<Table> getMissingTables() {
return missingTables;
}
public void addUnexpectedTable(Table table) {
unexpectedTables.add(table);
}
public SortedSet<Table> getUnexpectedTables() {
return unexpectedTables;
}
public void addMissingView(View viewName) {
missingViews.add(viewName);
}
public SortedSet<View> getMissingViews() {
return missingViews;
}
public void addUnexpectedView(View viewName) {
unexpectedViews.add(viewName);
}
public SortedSet<View> getUnexpectedViews() {
return unexpectedViews;
}
public void addMissingColumn(Column columnName) {
missingColumns.add(columnName);
}
public SortedSet<Column> getMissingColumns() {
return missingColumns;
}
public void addUnexpectedColumn(Column columnName) {
unexpectedColumns.add(columnName);
}
public SortedSet<Column> getUnexpectedColumns() {
return unexpectedColumns;
}
public void addChangedColumn(Column columnName) {
changedColumns.add(columnName);
}
public SortedSet<Column> getChangedColumns() {
return changedColumns;
}
public void addMissingForeignKey(ForeignKey fkName) {
missingForeignKeys.add(fkName);
}
public SortedSet<ForeignKey> getMissingForeignKeys() {
return missingForeignKeys;
}
public void addUnexpectedForeignKey(ForeignKey fkName) {
unexpectedForeignKeys.add(fkName);
}
public SortedSet<ForeignKey> getUnexpectedForeignKeys() {
return unexpectedForeignKeys;
}
public void addMissingIndex(Index fkName) {
missingIndexes.add(fkName);
}
public SortedSet<Index> getMissingIndexes() {
return missingIndexes;
}
public void addUnexpectedIndex(Index fkName) {
unexpectedIndexes.add(fkName);
}
public SortedSet<Index> getUnexpectedIndexes() {
return unexpectedIndexes;
}
public void addMissingPrimaryKey(PrimaryKey primaryKey) {
missingPrimaryKeys.add(primaryKey);
}
public SortedSet<PrimaryKey> getMissingPrimaryKeys() {
return missingPrimaryKeys;
}
public void addUnexpectedPrimaryKey(PrimaryKey primaryKey) {
unexpectedPrimaryKeys.add(primaryKey);
}
public SortedSet<PrimaryKey> getUnexpectedPrimaryKeys() {
return unexpectedPrimaryKeys;
}
public void addMissingSequence(Sequence sequence) {
missingSequences.add(sequence);
}
public SortedSet<Sequence> getMissingSequences() {
return missingSequences;
}
public void addUnexpectedSequence(Sequence sequence) {
unexpectedSequences.add(sequence);
}
public SortedSet<Sequence> getUnexpectedSequences() {
return unexpectedSequences;
}
public void addMissingUniqueConstraint(UniqueConstraint uniqueConstraint) {
missingUniqueConstraints.add(uniqueConstraint);
}
public SortedSet<UniqueConstraint> getMissingUniqueConstraints() {
return this.missingUniqueConstraints;
}
public void addUnexpectedUniqueConstraint(UniqueConstraint uniqueConstraint) {
unexpectedUniqueConstraints.add(uniqueConstraint);
}
public SortedSet<UniqueConstraint> getUnexpectedUniqueConstraints() {
return unexpectedUniqueConstraints;
}
public boolean shouldDiffData() {
return diffData;
}
public void setDiffData(boolean diffData) {
this.diffData = diffData;
}
public String getDataDir() {
return dataDir;
}
public void setDataDir(String dataDir) {
this.dataDir = dataDir;
}
public String getChangeSetContext() {
return changeSetContext;
}
public void setChangeSetContext(String changeSetContext) {
this.changeSetContext = changeSetContext;
}
public void printResult(PrintStream out) throws JDBCException {
out.println("Base Database: " + targetDatabase.getConnectionUsername() + " " + targetDatabase.getConnectionURL());
out.println("Target Database: " + baseDatabase.getConnectionUsername() + " " + baseDatabase.getConnectionURL());
printComparision("Product Name", productName, out);
printComparision("Product Version", productVersion, out);
printSetComparison("Missing Tables", getMissingTables(), out);
printSetComparison("Unexpected Tables", getUnexpectedTables(), out);
printSetComparison("Missing Views", getMissingViews(), out);
printSetComparison("Unexpected Views", getUnexpectedViews(), out);
printSetComparison("Missing Columns", getMissingColumns(), out);
printSetComparison("Unexpected Columns", getUnexpectedColumns(), out);
printColumnComparison(getChangedColumns(), out);
printSetComparison("Missing Foreign Keys", getMissingForeignKeys(), out);
printSetComparison("Unexpected Foreign Keys", getUnexpectedForeignKeys(), out);
printSetComparison("Missing Primary Keys", getMissingPrimaryKeys(), out);
printSetComparison("Unexpected Primary Keys", getUnexpectedPrimaryKeys(), out);
printSetComparison("Missing Unique Constraints", getMissingUniqueConstraints(), out);
printSetComparison("Unexpected Unique Constraints", getUnexpectedUniqueConstraints(), out);
printSetComparison("Missing Indexes", getMissingIndexes(), out);
printSetComparison("Unexpected Indexes", getUnexpectedIndexes(), out);
printSetComparison("Missing Sequences", getMissingSequences(), out);
printSetComparison("Unexpected Sequences", getUnexpectedSequences(), out);
}
private void printSetComparison(String title, SortedSet<?> objects, PrintStream out) {
out.print(title + ": ");
if (objects.size() == 0) {
out.println("NONE");
} else {
out.println();
for (Object object : objects) {
out.println(" " + object);
}
}
}
private void printColumnComparison(SortedSet<Column> changedColumns, PrintStream out) {
out.print("Changed Columns: ");
if (changedColumns.size() == 0) {
out.println("NONE");
} else {
out.println();
for (Column column : changedColumns) {
out.println(" " + column);
Column baseColumn = baseSnapshot.getColumn(column);
if (baseColumn != null) {
if (baseColumn.isDataTypeDifferent(column)) {
out.println(" from " + baseColumn.getDataTypeString(baseDatabase) + " to " + targetSnapshot.getColumn(column).getDataTypeString(targetDatabase));
}
if (baseColumn.isNullabilityDifferent(column)) {
Boolean nowNullable = targetSnapshot.getColumn(column).isNullable();
if (nowNullable == null) {
nowNullable = Boolean.TRUE;
}
if (nowNullable) {
out.println(" now nullable");
} else {
out.println(" now not null");
}
}
}
}
}
}
private void printComparision(String title, DiffComparison comparison, PrintStream out) {
out.print(title + ":");
if (comparison.areTheSame()) {
out.println(" EQUAL");
} else {
out.println();
out.println(" Base: '" + comparison.getBaseVersion() + "'");
out.println(" Target: '" + comparison.getTargetVersion() + "'");
}
}
public void printChangeLog(String changeLogFile, Database targetDatabase) throws ParserConfigurationException, IOException, JDBCException {
this.printChangeLog(changeLogFile, targetDatabase, new DefaultXmlWriter());
}
public void printChangeLog(PrintStream out, Database targetDatabase) throws ParserConfigurationException, IOException, JDBCException {
this.printChangeLog(out, targetDatabase, new DefaultXmlWriter());
}
public void printChangeLog(String changeLogFile, Database targetDatabase, XmlWriter xmlWriter) throws ParserConfigurationException, IOException, JDBCException {
File file = new File(changeLogFile);
if (!file.exists()) {
LogFactory.getLogger().info(file + " does not exist, creating");
FileOutputStream stream = new FileOutputStream(file);
printChangeLog(new PrintStream(stream), targetDatabase, xmlWriter);
stream.close();
} else {
LogFactory.getLogger().info(file + " exists, appending");
ByteArrayOutputStream out = new ByteArrayOutputStream();
printChangeLog(new PrintStream(out), targetDatabase, xmlWriter);
String xml = new String(out.toByteArray());
xml = xml.replaceFirst("(?ms).*<databaseChangeLog[^>]*>", "");
xml = xml.replaceFirst("</databaseChangeLog>", "");
xml = xml.trim();
String lineSeparator = System.getProperty("line.separator");
BufferedReader fileReader = new BufferedReader(new FileReader(file));
String line;
long offset = 0;
while ((line = fileReader.readLine()) != null) {
int index = line.indexOf("</databaseChangeLog>");
if (index >= 0) {
offset += index;
} else {
offset += line.getBytes().length;
offset += lineSeparator.getBytes().length;
}
}
fileReader.close();
fileReader = new BufferedReader(new FileReader(file));
fileReader.skip(offset);
fileReader.close();
// System.out.println("resulting XML: " + xml.trim());
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
randomAccessFile.seek(offset);
randomAccessFile.writeBytes(" " + xml + lineSeparator);
randomAccessFile.writeBytes("</databaseChangeLog>" + lineSeparator);
randomAccessFile.close();
// BufferedWriter fileWriter = new BufferedWriter(new FileWriter(file));
// fileWriter.append(xml);
// fileWriter.close();
}
}
/**
* Prints changeLog that would bring the base database to be the same as the target database
*/
public void printChangeLog(PrintStream out, Database targetDatabase, XmlWriter xmlWriter) throws ParserConfigurationException, IOException, JDBCException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
documentBuilder.setEntityResolver(new LiquibaseSchemaResolver());
Document doc = documentBuilder.newDocument();
Element changeLogElement = doc.createElement("databaseChangeLog");
changeLogElement.setAttribute("xmlns", "http://www.liquibase.org/xml/ns/dbchangelog/" + XMLChangeLogParser.getSchemaVersion());
changeLogElement.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
changeLogElement.setAttribute("xsi:schemaLocation", "http://www.liquibase.org/xml/ns/dbchangelog/" + XMLChangeLogParser.getSchemaVersion() + " http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-" + XMLChangeLogParser.getSchemaVersion() + ".xsd");
doc.appendChild(changeLogElement);
List<Change> changes = new ArrayList<Change>();
addUnexpectedViewChanges(changes);
addMissingTableChanges(changes, targetDatabase);
addMissingColumnChanges(changes, targetDatabase);
addChangedColumnChanges(changes);
addMissingPrimaryKeyChanges(changes);
addUnexpectedPrimaryKeyChanges(changes);
addMissingUniqueConstraintChanges(changes);
addUnexpectedUniqueConstraintChanges(changes);
addMissingIndexChanges(changes);
addUnexpectedIndexChanges(changes);
if (diffData) {
addInsertDataChanges(changes, dataDir);
}
addMissingForeignKeyChanges(changes);
addUnexpectedForeignKeyChanges(changes);
addUnexpectedColumnChanges(changes);
addMissingSequenceChanges(changes);
addUnexpectedSequenceChanges(changes);
addMissingViewChanges(changes);
addUnexpectedTableChanges(changes);
for (Change change : changes) {
Element changeSet = doc.createElement("changeSet");
changeSet.setAttribute("author", getChangeSetAuthor());
changeSet.setAttribute("id", generateId());
if (getChangeSetContext() != null) {
changeSet.setAttribute("context", getChangeSetContext());
}
changeSet.appendChild(change.createNode(doc));
doc.getDocumentElement().appendChild(changeSet);
}
xmlWriter.write(doc, out);
out.flush();
}
private String getChangeSetAuthor() {
if (changeSetAuthor != null) {
return changeSetAuthor;
}
String author = System.getProperty("user.name");
if (StringUtils.trimToNull(author) == null) {
return "diff-generated";
} else {
return author + " (generated)";
}
}
public void setChangeSetAuthor(String changeSetAuthor) {
this.changeSetAuthor = changeSetAuthor;
}
private String generateId() {
return baseId.toString() + "-" + changeNumber++;
}
private void addUnexpectedIndexChanges(List<Change> changes) {
for (Index index : getUnexpectedIndexes()) {
DropIndexChange change = new DropIndexChange();
change.setTableName(index.getTable().getName());
change.setSchemaName(index.getTable().getSchema());
change.setIndexName(index.getName());
changes.add(change);
}
}
private void addMissingIndexChanges(List<Change> changes) {
for (Index index : getMissingIndexes()) {
CreateIndexChange change = new CreateIndexChange();
change.setTableName(index.getTable().getName());
change.setSchemaName(index.getTable().getSchema());
change.setIndexName(index.getName());
change.setUnique(index.isUnique());
for (String columnName : index.getColumns()) {
ColumnConfig column = new ColumnConfig();
column.setName(columnName);
change.addColumn(column);
}
changes.add(change);
}
}
private void addUnexpectedPrimaryKeyChanges(List<Change> changes) {
for (PrimaryKey pk : getUnexpectedPrimaryKeys()) {
if (!getUnexpectedTables().contains(pk.getTable())) {
DropPrimaryKeyChange change = new DropPrimaryKeyChange();
change.setTableName(pk.getTable().getName());
change.setSchemaName(pk.getTable().getSchema());
change.setConstraintName(pk.getName());
changes.add(change);
}
}
}
private void addMissingPrimaryKeyChanges(List<Change> changes) {
for (PrimaryKey pk : getMissingPrimaryKeys()) {
AddPrimaryKeyChange change = new AddPrimaryKeyChange();
change.setTableName(pk.getTable().getName());
change.setSchemaName(pk.getTable().getSchema());
change.setConstraintName(pk.getName());
change.setColumnNames(pk.getColumnNames());
changes.add(change);
}
}
private void addUnexpectedUniqueConstraintChanges(List<Change> changes) {
for (UniqueConstraint uc : getUnexpectedUniqueConstraints()) {
if (!getUnexpectedTables().contains(uc.getTable())) {
DropUniqueConstraintChange change = new DropUniqueConstraintChange();
change.setTableName(uc.getTable().getName());
change.setSchemaName(uc.getTable().getSchema());
change.setConstraintName(uc.getName());
changes.add(change);
}
}
}
private void addMissingUniqueConstraintChanges(List<Change> changes) {
for (UniqueConstraint uc : getMissingUniqueConstraints()) {
AddUniqueConstraintChange change = new AddUniqueConstraintChange();
change.setTableName(uc.getTable().getName());
change.setSchemaName(uc.getTable().getSchema());
change.setConstraintName(uc.getName());
change.setColumnNames(uc.getColumnNames());
changes.add(change);
}
}
private void addUnexpectedForeignKeyChanges(List<Change> changes) {
for (ForeignKey fk : getUnexpectedForeignKeys()) {
DropForeignKeyConstraintChange change = new DropForeignKeyConstraintChange();
change.setConstraintName(fk.getName());
change.setBaseTableName(fk.getForeignKeyTable().getName());
change.setBaseTableSchemaName(fk.getForeignKeyTable().getSchema());
changes.add(change);
}
}
private void addMissingForeignKeyChanges(List<Change> changes) {
for (ForeignKey fk : getMissingForeignKeys()) {
AddForeignKeyConstraintChange change = new AddForeignKeyConstraintChange();
change.setConstraintName(fk.getName());
change.setReferencedTableName(fk.getPrimaryKeyTable().getName());
change.setReferencedTableSchemaName(fk.getPrimaryKeyTable().getSchema());
change.setReferencedColumnNames(fk.getPrimaryKeyColumns());
change.setBaseTableName(fk.getForeignKeyTable().getName());
change.setBaseTableSchemaName(fk.getForeignKeyTable().getSchema());
change.setBaseColumnNames(fk.getForeignKeyColumns());
change.setDeferrable(fk.isDeferrable());
change.setInitiallyDeferred(fk.isInitiallyDeferred());
change.setUpdateRule(fk.getUpdateRule());
change.setDeleteRule(fk.getDeleteRule());
changes.add(change);
}
}
private void addUnexpectedSequenceChanges(List<Change> changes) {
for (Sequence sequence : getUnexpectedSequences()) {
DropSequenceChange change = new DropSequenceChange();
change.setSequenceName(sequence.getName());
change.setSchemaName(sequence.getSchema());
changes.add(change);
}
}
private void addMissingSequenceChanges(List<Change> changes) {
for (Sequence sequence : getMissingSequences()) {
CreateSequenceChange change = new CreateSequenceChange();
change.setSequenceName(sequence.getName());
change.setSchemaName(sequence.getSchema());
changes.add(change);
}
}
private void addUnexpectedColumnChanges(List<Change> changes) {
for (Column column : getUnexpectedColumns()) {
if (!shouldModifyColumn(column)) {
continue;
}
DropColumnChange change = new DropColumnChange();
change.setTableName(column.getTable().getName());
change.setSchemaName(column.getTable().getName());
change.setColumnName(column.getName());
changes.add(change);
}
}
private void addMissingViewChanges(List<Change> changes) {
for (View view : getMissingViews()) {
CreateViewChange change = new CreateViewChange();
change.setViewName(view.getName());
change.setSchemaName(view.getSchema());
String selectQuery = view.getDefinition();
if (selectQuery == null) {
selectQuery = "COULD NOT DETERMINE VIEW QUERY";
}
change.setSelectQuery(selectQuery);
changes.add(change);
}
}
private void addChangedColumnChanges(List<Change> changes) {
for (Column column : getChangedColumns()) {
if (!shouldModifyColumn(column)) {
continue;
}
boolean foundDifference = false;
Column baseColumn = baseSnapshot.getColumn(column);
if (column.isDataTypeDifferent(baseColumn)) {
ColumnConfig columnConfig = new ColumnConfig();
columnConfig.setName(column.getName());
columnConfig.setType(baseColumn.getDataTypeString(targetDatabase));
ModifyColumnChange change = new ModifyColumnChange();
change.setTableName(column.getTable().getName());
change.setSchemaName(column.getTable().getSchema());
change.addColumn(columnConfig);
changes.add(change);
foundDifference = true;
}
if (column.isNullabilityDifferent(baseColumn)) {
if (baseColumn.isNullable() == null || baseColumn.isNullable()) {
DropNotNullConstraintChange change = new DropNotNullConstraintChange();
change.setTableName(column.getTable().getName());
change.setSchemaName(column.getTable().getSchema());
change.setColumnName(column.getName());
change.setColumnDataType(baseColumn.getDataTypeString(targetDatabase));
changes.add(change);
foundDifference = true;
} else {
AddNotNullConstraintChange change = new AddNotNullConstraintChange();
change.setTableName(column.getTable().getName());
change.setSchemaName(column.getTable().getSchema());
change.setColumnName(column.getName());
change.setColumnDataType(baseColumn.getDataTypeString(targetDatabase));
changes.add(change);
foundDifference = true;
}
}
if (!foundDifference) {
throw new RuntimeException("Unknown difference");
}
}
}
private boolean shouldModifyColumn(Column column) {
return column.getView() == null
&& !baseDatabase.isLiquibaseTable(column.getTable().getName());
}
private void addUnexpectedViewChanges(List<Change> changes) {
for (View view : getUnexpectedViews()) {
DropViewChange change = new DropViewChange();
change.setViewName(view.getName());
change.setSchemaName(view.getSchema());
changes.add(change);
}
}
private void addMissingColumnChanges(List<Change> changes, Database database) {
for (Column column : getMissingColumns()) {
if (!shouldModifyColumn(column)) {
continue;
}
AddColumnChange change = new AddColumnChange();
change.setTableName(column.getTable().getName());
change.setSchemaName(column.getTable().getSchema());
ColumnConfig columnConfig = new ColumnConfig();
columnConfig.setName(column.getName());
String dataType = column.getDataTypeString(database);
columnConfig.setType(dataType);
String defaultValueString = database.convertJavaObjectToString(column.getDefaultValue());
if(defaultValueString !=null) {
defaultValueString = defaultValueString.replaceFirst("'","").replaceAll("'$", "");
}
columnConfig.setDefaultValue(defaultValueString);
if (column.getRemarks() != null) {
columnConfig.setRemarks(column.getRemarks());
}
+ if (column.isNullable() != null && !column.isNullable()) {
+ ConstraintsConfig constraintsConfig = columnConfig.getConstraints();
+ if (constraintsConfig == null) {
+ constraintsConfig = new ConstraintsConfig();
+ columnConfig.setConstraints(constraintsConfig);
+ }
+ constraintsConfig.setNullable(false);
+ }
change.addColumn(columnConfig);
changes.add(change);
}
}
private void addMissingTableChanges(List<Change> changes, Database database) {
for (Table missingTable : getMissingTables()) {
if (baseDatabase.isLiquibaseTable(missingTable.getName())) {
continue;
}
CreateTableChange change = new CreateTableChange();
change.setTableName(missingTable.getName());
change.setSchemaName(missingTable.getSchema());
if (missingTable.getRemarks() != null) {
change.setRemarks(missingTable.getRemarks());
}
for (Column column : missingTable.getColumns()) {
ColumnConfig columnConfig = new ColumnConfig();
columnConfig.setName(column.getName());
columnConfig.setType(column.getDataTypeString(database));
ConstraintsConfig constraintsConfig = null;
if (column.isPrimaryKey()) {
PrimaryKey primaryKey = null;
for (PrimaryKey pk : getMissingPrimaryKeys()) {
if (pk.getTable().getName().equalsIgnoreCase(missingTable.getName())) {
primaryKey = pk;
}
}
if (primaryKey == null || primaryKey.getColumnNamesAsList().size() == 1) {
constraintsConfig = new ConstraintsConfig();
constraintsConfig.setPrimaryKey(true);
if (primaryKey != null) {
constraintsConfig.setPrimaryKeyName(primaryKey.getName());
getMissingPrimaryKeys().remove(primaryKey);
}
}
}
if (column.isAutoIncrement()) {
columnConfig.setAutoIncrement(true);
}
if (column.isNullable() != null && !column.isNullable()) {
if (constraintsConfig == null) {
constraintsConfig = new ConstraintsConfig();
}
constraintsConfig.setNullable(false);
}
if (constraintsConfig != null) {
columnConfig.setConstraints(constraintsConfig);
}
Object defaultValue = column.getDefaultValue();
if (defaultValue == null) {
//do nothing
} else if (column.isAutoIncrement()) {
//do nothing
} else if (defaultValue instanceof Date) {
columnConfig.setDefaultValueDate((Date) defaultValue);
} else if (defaultValue instanceof Boolean) {
columnConfig.setDefaultValueBoolean(((Boolean) defaultValue));
} else if (defaultValue instanceof Number) {
columnConfig.setDefaultValueNumeric(((Number) defaultValue));
} else {
columnConfig.setDefaultValue(defaultValue.toString());
}
if (column.getRemarks() != null) {
columnConfig.setRemarks(column.getRemarks());
}
change.addColumn(columnConfig);
}
changes.add(change);
}
}
private void addUnexpectedTableChanges(List<Change> changes) {
for (Table unexpectedTable : getUnexpectedTables()) {
DropTableChange change = new DropTableChange();
change.setTableName(unexpectedTable.getName());
change.setSchemaName(unexpectedTable.getSchema());
changes.add(change);
}
}
private void addInsertDataChanges(List<Change> changes, String dataDir) throws JDBCException, IOException {
try {
String schema = baseSnapshot.getSchema();
Statement stmt = baseSnapshot.getDatabase().getConnection().createStatement();
for (Table table : baseSnapshot.getTables()) {
ResultSet rs = stmt.executeQuery("SELECT * FROM " + baseSnapshot.getDatabase().escapeTableName(schema, table.getName()));
ResultSetMetaData columnData = rs.getMetaData();
int columnCount = columnData.getColumnCount();
// if dataDir is not null, print out a csv file and use loadData tag
if (dataDir != null) {
String fileName = table.getName() + ".csv";
if (dataDir != null) {
fileName = dataDir + "/" + fileName;
}
File parentDir = new File(dataDir);
if (!parentDir.exists()) {
parentDir.mkdirs();
}
if (!parentDir.isDirectory()) {
throw new RuntimeException(parentDir + " is not a directory");
}
CSVWriter outputFile = new CSVWriter(new FileWriter(fileName));
outputFile.writeAll(rs, true);
outputFile.flush();
outputFile.close();
LoadDataChange change = new LoadDataChange();
change.setFile(fileName);
change.setEncoding("UTF-8");
change.setSchemaName(schema);
change.setTableName(table.getName());
for (int col = 1; col <= columnCount; col++) {
String colName = columnData.getColumnName(col);
int dataType = columnData.getColumnType(col);
String typeString = "STRING";
if (SqlUtil.isNumeric(dataType)) {
typeString = "NUMERIC";
} else if (SqlUtil.isBoolean(dataType)) {
typeString = "BOOLEAN";
} else if (SqlUtil.isDate(dataType)) {
typeString = "DATE";
}
LoadDataColumnConfig columnConfig = new LoadDataColumnConfig();
columnConfig.setHeader(colName);
columnConfig.setType(typeString);
change.addColumn(columnConfig);
}
changes.add(change);
} else { // if dataDir is null, build and use insert tags
// loop over all rows
while (rs.next()) {
InsertDataChange change = new InsertDataChange();
change.setSchemaName(schema);
change.setTableName(table.getName());
// loop over all columns for this row
for (int col = 1; col <= columnCount; col++) {
ColumnConfig column = new ColumnConfig();
column.setName(columnData.getColumnName(col));
// set the value for this column
int dataType = columnData.getColumnType(col);
if (SqlUtil.isNumeric(dataType)) {
String columnValue = rs.getString(col);
if (columnValue == null) {
column.setValueNumeric((Number) null);
} else {
// its some sort of non-null number
if (dataType == Types.DOUBLE ||
dataType == Types.NUMERIC ||
dataType == Types.DECIMAL) {
column.setValueNumeric(new Double(columnValue));
} else if (dataType == Types.FLOAT ||
dataType == Types.REAL) {
column.setValueNumeric(new Float(columnValue));
} else {
// its an integer type of column
column.setValueNumeric(new Integer(columnValue));
}
}
} else if (SqlUtil.isBoolean(dataType)) {
column.setValueBoolean(rs.getBoolean(col));
} else if (SqlUtil.isDate(dataType)) {
column.setValueDate(rs.getDate(col));
} else { //string
column.setValue(rs.getString(col));
}
change.addColumn(column);
}
// for each row, add a new change
// (there will be one group per table)
changes.add(change);
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| true | false | null | null |
diff --git a/src/main/java/org/nuxeo/isbn/ISBNQuery.java b/src/main/java/org/nuxeo/isbn/ISBNQuery.java
index 95ee3c7..488298a 100644
--- a/src/main/java/org/nuxeo/isbn/ISBNQuery.java
+++ b/src/main/java/org/nuxeo/isbn/ISBNQuery.java
@@ -1,98 +1,98 @@
/*
- * (C) Copyright ${year} Nuxeo SA (http://nuxeo.com/) and contributors.
+ * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
- * http://www.gnu.org/licenses/lgpl.html
+ * http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* ldoguin
*/
package org.nuxeo.isbn;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import org.nuxeo.ecm.automation.core.Constants;
import org.nuxeo.ecm.automation.core.annotations.Operation;
import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
import org.nuxeo.ecm.automation.core.collectors.DocumentModelCollector;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.model.PropertyException;
import sun.net.www.protocol.http.HttpURLConnection;
/**
* @author ldoguin
*/
@Operation(id = ISBNQuery.ID, category = Constants.CAT_DOCUMENT, label = "ISBNQuery", description = "")
public class ISBNQuery {
public static final String ID = "ISBNQuery";
public static final String QUERY_ISBN_URL = "http://openlibrary.org/api/books?bibkeys=%s&format=json";
@OperationMethod(collector = DocumentModelCollector.class)
public DocumentModel run(DocumentModel input) throws MalformedURLException,
PropertyException, ClientException, JSONException {
String isbn = input.getProperty("isbn:isbn").getValue(String.class);
isbn = "ISBN:".concat(isbn);
String query = String.format(QUERY_ISBN_URL, isbn);
URL url = new URL(query);
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
StringBuffer sb = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
JSONObject jso = new JSONObject(sb.toString());
JSONObject metadata = jso.getJSONObject(isbn);
String bib_key = metadata.getString("bib_key");
if (bib_key != null) {
input.setPropertyValue("isbn:bib_key", bib_key);
}
String info_url = metadata.getString("info_url");
if (bib_key != null) {
input.setPropertyValue("isbn:info_url", info_url);
}
String preview = metadata.getString("preview");
if (bib_key != null) {
input.setPropertyValue("isbn:preview", preview);
}
String preview_url = metadata.getString("preview_url");
if (bib_key != null) {
input.setPropertyValue("isbn:preview_url", preview_url);
}
String thumbnail_url = metadata.getString("thumbnail_url");
if (bib_key != null) {
input.setPropertyValue("isbn:thumbnail_url", thumbnail_url);
}
in.close();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return input;
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/nuxeo/isbn/test/TestISBNQuery.java b/src/test/java/org/nuxeo/isbn/test/TestISBNQuery.java
index 909a753..0168c3e 100644
--- a/src/test/java/org/nuxeo/isbn/test/TestISBNQuery.java
+++ b/src/test/java/org/nuxeo/isbn/test/TestISBNQuery.java
@@ -1,65 +1,82 @@
+/*
+ * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and others.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the GNU Lesser General Public License
+ * (LGPL) version 2.1 which accompanies this distribution, and is available at
+ * http://www.gnu.org/licenses/lgpl-2.1.html
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * Contributors:
+ * ldoguin
+ */
+
package org.nuxeo.isbn.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.nuxeo.ecm.automation.AutomationService;
import org.nuxeo.ecm.automation.OperationContext;
import org.nuxeo.ecm.automation.OperationType;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.test.CoreFeature;
import org.nuxeo.isbn.ISBNQuery;
import org.nuxeo.runtime.test.runner.Deploy;
import org.nuxeo.runtime.test.runner.Features;
import org.nuxeo.runtime.test.runner.FeaturesRunner;
import com.google.inject.Inject;
@RunWith(FeaturesRunner.class)
@Features(CoreFeature.class)
@Deploy({ "nuxeo-book-isbn", "org.nuxeo.ecm.automation.core" })
public class TestISBNQuery {
@Inject
AutomationService automationService;
@Inject
CoreSession coreSession;
public static final String ISBN_TEST = "0201558025";
@Test
public void testISBNQuery() throws Exception {
assertNotNull(automationService);
OperationType opType = automationService.getOperation(ISBNQuery.ID);
assertNotNull(opType);
assertNotNull(coreSession);
DocumentModel bookDocument = coreSession.createDocumentModel("/", ISBN_TEST, "Book");
bookDocument.setPropertyValue("isbn:isbn", ISBN_TEST);
bookDocument = coreSession.createDocument(bookDocument);
OperationContext ctx = new OperationContext();
ctx.setInput(bookDocument);
Map<String, Object> parameters = new HashMap<String, Object>();
Object result = automationService.run(ctx, ISBNQuery.ID, parameters);
assertNotNull(result);
if (result instanceof DocumentModel) {
bookDocument = (DocumentModel) result;
String bib_key = bookDocument.getProperty("isbn:bib_key").getValue(String.class);
assertEquals("ISBN:0201558025",bib_key);
} else {
fail("result should be a DocumentModel instead of" + result.getClass());
}
}
}
| false | false | null | null |
diff --git a/navit/navit/android/src/org/navitproject/navit/NavitVehicle.java b/navit/navit/android/src/org/navitproject/navit/NavitVehicle.java
index 552bbb4c..e2004a8f 100644
--- a/navit/navit/android/src/org/navitproject/navit/NavitVehicle.java
+++ b/navit/navit/android/src/org/navitproject/navit/NavitVehicle.java
@@ -1,109 +1,109 @@
/**
* Navit, a modular navigation system.
* Copyright (C) 2005-2008 Navit Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
package org.navitproject.navit;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
public class NavitVehicle {
private static LocationManager sLocationManager = null;
private int vehicle_callbackid;
private String preciseProvider;
private String fastProvider;
private static NavitLocationListener preciseLocationListener = null;
private static NavitLocationListener fastLocationListener = null;
public native void VehicleCallback(int id, Location location);
private class NavitLocationListener implements LocationListener {
public boolean precise = false;
public void onLocationChanged(Location location) {
// Disable the fast provider if still active
if (precise && fastProvider != null) {
sLocationManager.removeUpdates(fastLocationListener);
fastProvider = null;
}
VehicleCallback(vehicle_callbackid, location);
}
public void onProviderDisabled(String provider){}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
NavitVehicle (Context context, int callbackid) {
sLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
preciseLocationListener = new NavitLocationListener();
preciseLocationListener.precise = true;
fastLocationListener = new NavitLocationListener();
/* Use 2 LocationProviders, one precise (usually GPS), and one
not so precise, but possible faster. The fast provider is
disabled when the precise provider gets its first fix. */
// Selection criteria for the precise provider
Criteria highCriteria = new Criteria();
highCriteria.setAccuracy(Criteria.ACCURACY_FINE);
highCriteria.setAltitudeRequired(true);
highCriteria.setBearingRequired(true);
highCriteria.setCostAllowed(true);
highCriteria.setPowerRequirement(Criteria.POWER_HIGH);
// Selection criteria for the fast provider
Criteria lowCriteria = new Criteria();
lowCriteria.setAccuracy(Criteria.ACCURACY_COARSE);
lowCriteria.setAltitudeRequired(false);
lowCriteria.setBearingRequired(false);
lowCriteria.setCostAllowed(true);
lowCriteria.setPowerRequirement(Criteria.POWER_HIGH);
Log.e("NavitVehicle", "Providers " + sLocationManager.getAllProviders());
preciseProvider = sLocationManager.getBestProvider(highCriteria, false);
Log.e("NavitVehicle", "Precise Provider " + preciseProvider);
fastProvider = sLocationManager.getBestProvider(lowCriteria, false);
Log.e("NavitVehicle", "Fast Provider " + fastProvider);
vehicle_callbackid=callbackid;
sLocationManager.requestLocationUpdates(preciseProvider, 0, 0, preciseLocationListener);
// If the 2 providers are the same, only activate one listener
if (fastProvider == null || preciseProvider.compareTo(fastProvider) == 0) {
fastProvider = null;
} else {
sLocationManager.requestLocationUpdates(fastProvider, 0, 0, fastLocationListener);
}
}
public static void removeListener() {
if (sLocationManager != null) {
if (preciseLocationListener != null) sLocationManager.removeUpdates(preciseLocationListener);
- if (fastLocationListener != null) sLocationManager.removeUpdates(preciseLocationListener);
+ if (fastLocationListener != null) sLocationManager.removeUpdates(fastLocationListener);
}
}
}
| true | false | null | null |
diff --git a/src/main/java/nl/topicus/onderwijs/dashboard/modules/topicus/VocusStatusRetriever.java b/src/main/java/nl/topicus/onderwijs/dashboard/modules/topicus/VocusStatusRetriever.java
index a91e0f7..8ce01a9 100644
--- a/src/main/java/nl/topicus/onderwijs/dashboard/modules/topicus/VocusStatusRetriever.java
+++ b/src/main/java/nl/topicus/onderwijs/dashboard/modules/topicus/VocusStatusRetriever.java
@@ -1,181 +1,182 @@
package nl.topicus.onderwijs.dashboard.modules.topicus;
import static nl.topicus.onderwijs.dashboard.modules.topicus.RetrieverUtils.getStatuspage;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;
import nl.topicus.onderwijs.dashboard.datasources.ApplicationVersion;
import nl.topicus.onderwijs.dashboard.datasources.NumberOfServers;
import nl.topicus.onderwijs.dashboard.datasources.NumberOfServersOffline;
import nl.topicus.onderwijs.dashboard.datasources.NumberOfUsers;
import nl.topicus.onderwijs.dashboard.datasources.Uptime;
import nl.topicus.onderwijs.dashboard.modules.Project;
import nl.topicus.onderwijs.dashboard.modules.Projects;
import nl.topicus.onderwijs.dashboard.modules.Repository;
import org.apache.wicket.util.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class VocusStatusRetriever implements Retriever,
TopicusApplicationStatusProvider {
private static final Logger log = LoggerFactory
.getLogger(VocusStatusRetriever.class);
private Map<Project, List<String>> configuration = new HashMap<Project, List<String>>();
private Map<Project, TopicusApplicationStatus> statusses = new HashMap<Project, TopicusApplicationStatus>();
public VocusStatusRetriever() {
configuration.put(Projects.ATVO, Arrays.asList(
"https://start.vocuslis.nl/app/status",
"https://start2.vocuslis.nl/app/status",
"https://start3.atvo.nl/app/status"));
- configuration.put(Projects.IRIS, Arrays
- .asList("https://www.irisplus.nl/irisplus-prod/app/status"));
+ // configuration.put(Projects.IRIS, Arrays
+ // .asList("https://www.irisplus.nl/irisplus-prod/app/status"),
+ // );
for (Project project : configuration.keySet()) {
statusses.put(project, new TopicusApplicationStatus());
}
}
@Override
public TopicusApplicationStatus getStatus(Project project) {
return statusses.get(project);
}
@Override
public void onConfigure(Repository repository) {
for (Project project : configuration.keySet()) {
repository.addDataSourceForProject(project, NumberOfUsers.class,
new NumberOfUsersImpl(project, this));
repository.addDataSourceForProject(project, NumberOfServers.class,
new NumberOfServersImpl(project, this));
repository.addDataSourceForProject(project,
NumberOfServersOffline.class,
new NumberOfServersOfflineImpl(project, this));
repository.addDataSourceForProject(project, Uptime.class,
new UptimeImpl(project, this));
repository.addDataSourceForProject(project,
ApplicationVersion.class, new ApplicationVersionImpl(
project, this));
}
}
@Override
public void refreshData() {
HashMap<Project, TopicusApplicationStatus> newStatusses = new HashMap<Project, TopicusApplicationStatus>();
for (Project project : configuration.keySet()) {
TopicusApplicationStatus status = getProjectData(project);
newStatusses.put(project, status);
}
statusses = newStatusses;
}
private TopicusApplicationStatus getProjectData(Project project) {
List<String> urls = configuration.get(project);
if (urls == null || urls.isEmpty()) {
TopicusApplicationStatus status = new TopicusApplicationStatus();
status.setVersion("n/a");
return status;
}
int numberOfOfflineServers = 0;
TopicusApplicationStatus status = new TopicusApplicationStatus();
status.setNumberOfServers(urls.size());
for (String statusUrl : urls) {
try {
StatusPageResponse statuspage = getStatuspage(statusUrl);
if (statuspage.isOffline()) {
numberOfOfflineServers++;
continue;
}
String page = statuspage.getPageContent();
Source source = new Source(page);
source.fullSequentialParse();
List<Element> tableHeaders = source
.getAllElements(HTMLElementName.TH);
for (Element tableHeader : tableHeaders) {
String contents = tableHeader.getContent().toString();
if ("Applicatie".equals(contents)) {
getApplicationVersion(status, tableHeader);
} else if ("Sessions/Requests".equals(contents)) {
getNumberOfUsers(status, tableHeader);
}
}
List<Element> tdHeaders = source
.getAllElements(HTMLElementName.TD);
for (Element td : tdHeaders) {
String contents = td.getContent().toString();
if ("Starttijd".equals(contents)) {
getStartTime(status, td);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
status.setNumberOfServersOnline(status.getNumberOfServers()
- numberOfOfflineServers);
log.info("Application status: {}->{}", project, status);
return status;
}
private Integer getNumberOfUsers(TopicusApplicationStatus status,
Element tableHeader) {
Element sessiesCell = tableHeader.getParentElement().getParentElement()
.getContent().getFirstElement("class", "value_column", true);
int currentNumberOfUsers = status.getNumberOfUsers();
Integer numberOfUsersOnServer = Integer.valueOf(sessiesCell
.getContent().getTextExtractor().toString());
status.setNumberOfUsers(currentNumberOfUsers + numberOfUsersOnServer);
return numberOfUsersOnServer;
}
private void getApplicationVersion(TopicusApplicationStatus status,
Element tableHeader) {
Element versieCell = tableHeader.getParentElement().getParentElement()
.getContent().getFirstElement("class", "value_column", true);
status.setVersion(versieCell.getContent().getTextExtractor().toString());
}
/*
* <tr><td class="name_column">Starttijd</td><td
* class="value_column"><span>10-10-2010 03:51:22</span></td></tr>
*/
private void getStartTime(TopicusApplicationStatus status, Element td) {
Element starttijdCell = td.getParentElement().getFirstElement("class",
"value_column", true);
String starttijdText = starttijdCell.getTextExtractor().toString();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
Date starttime;
try {
starttime = sdf.parse(starttijdText);
Date now = new Date();
status.setUptime(Duration.milliseconds(
now.getTime() - starttime.getTime()).getMilliseconds());
} catch (ParseException e) {
log.error("Unable to parse starttime " + starttijdText
+ " according to format dd-MM-yyyy hh:mm:ss", e);
}
}
public static void main(String[] args) {
VocusStatusRetriever retriever = new VocusStatusRetriever();
retriever.getProjectData(Projects.ATVO);
}
}
| true | false | null | null |
diff --git a/src/com/redhat/ceylon/compiler/java/codegen/MethodDefinitionBuilder.java b/src/com/redhat/ceylon/compiler/java/codegen/MethodDefinitionBuilder.java
index 104003123..6c38483ec 100755
--- a/src/com/redhat/ceylon/compiler/java/codegen/MethodDefinitionBuilder.java
+++ b/src/com/redhat/ceylon/compiler/java/codegen/MethodDefinitionBuilder.java
@@ -1,405 +1,423 @@
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License,
* along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.java.codegen;
import static com.sun.tools.javac.code.Flags.ABSTRACT;
import static com.sun.tools.javac.code.Flags.FINAL;
import static com.sun.tools.javac.code.Flags.PUBLIC;
import static com.sun.tools.javac.code.Flags.STATIC;
import static com.sun.tools.javac.code.TypeTags.VOID;
import com.redhat.ceylon.compiler.java.util.Util;
import com.redhat.ceylon.compiler.typechecker.model.Annotation;
import com.redhat.ceylon.compiler.typechecker.model.FunctionalParameter;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
+import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.ProducedTypedReference;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCBlock;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.tree.JCTree.JCTypeParameter;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Name;
/**
* Builder for Java Methods. With special pre-definied builders
* for normal methods, constructors, getters and setters.
*
* @author Tako Schotanus
*/
public class MethodDefinitionBuilder {
private final AbstractTransformer gen;
private final String name;
private long modifiers;
private boolean isOverride;
private boolean isAbstract;
private JCExpression resultTypeExpr;
private List<JCAnnotation> resultTypeAnnos;
private final ListBuffer<JCAnnotation> annotations = ListBuffer.lb();
private final ListBuffer<JCTypeParameter> typeParams = ListBuffer.lb();
private final ListBuffer<JCExpression> typeParamAnnotations = ListBuffer.lb();
private final ListBuffer<ParameterDefinitionBuilder> params = ListBuffer.lb();
private ListBuffer<JCStatement> body = ListBuffer.lb();
private boolean ignoreAnnotations;
private boolean noAnnotations = false;
private boolean built = false;
public static MethodDefinitionBuilder method(AbstractTransformer gen, boolean isMember, String name) {
return new MethodDefinitionBuilder(gen, false, isMember ? Naming.getErasedMethodName(name) : Naming.getMethodName(name));
}
public static MethodDefinitionBuilder method2(AbstractTransformer gen, String name) {
return new MethodDefinitionBuilder(gen, false, name);
}
public static MethodDefinitionBuilder callable(AbstractTransformer gen) {
return systemMethod(gen, "$call");
}
public static MethodDefinitionBuilder systemMethod(AbstractTransformer gen, String name) {
MethodDefinitionBuilder builder = new MethodDefinitionBuilder(gen, true, name);
return builder;
}
public static MethodDefinitionBuilder constructor(AbstractTransformer gen) {
return new MethodDefinitionBuilder(gen, false, null);
}
public static MethodDefinitionBuilder main(AbstractTransformer gen) {
MethodDefinitionBuilder mdb = new MethodDefinitionBuilder(gen, false, "main")
.modifiers(PUBLIC | STATIC);
ParameterDefinitionBuilder pdb = ParameterDefinitionBuilder.instance(mdb.gen, "args");
pdb.type(gen.make().TypeArray(gen.make().Type(gen.syms().stringType)), List.<JCAnnotation>nil());
return mdb.parameter(pdb);
}
private MethodDefinitionBuilder(AbstractTransformer gen, boolean ignoreAnnotations, String name) {
this.gen = gen;
this.name = name;
this.ignoreAnnotations = ignoreAnnotations;
resultTypeExpr = makeVoidType();
}
private ListBuffer<JCAnnotation> getAnnotations() {
ListBuffer<JCAnnotation> result = ListBuffer.lb();
if (!noAnnotations) {
if (!ignoreAnnotations) {
result.appendList(this.annotations);
}
if (isOverride) {
result.appendList(gen.makeAtOverride());
}
if (ignoreAnnotations) {
result.appendList(gen.makeAtIgnore());
} else {
if (resultTypeAnnos != null) {
result.appendList(resultTypeAnnos);
}
if(!typeParamAnnotations.isEmpty()) {
result.appendList(gen.makeAtTypeParameters(typeParamAnnotations.toList()));
}
}
}
return result;
}
public JCTree.JCMethodDecl build() {
if (built) {
throw new IllegalStateException();
}
built = true;
ListBuffer<JCVariableDecl> params = ListBuffer.lb();
for (ParameterDefinitionBuilder pdb : this.params) {
if (noAnnotations || ignoreAnnotations) {
pdb.noAnnotations();
}
params.append(pdb.build());
}
return gen.make().MethodDef(
gen.make().Modifiers(modifiers, getAnnotations().toList()),
makeName(name),
resultTypeExpr,
typeParams.toList(),
params.toList(),
List.<JCExpression> nil(),
makeBody(body),
null);
}
private Name makeName(String name) {
if (name != null) {
return gen.names().fromString(name);
} else {
return gen.names().init;
}
}
private JCBlock makeBody(ListBuffer<JCStatement> body2) {
return (!isAbstract && (body != null) && ((modifiers & ABSTRACT) == 0)) ? gen.make().Block(0, body.toList()) : null;
}
JCExpression makeVoidType() {
return gen.make().TypeIdent(VOID);
}
JCExpression makeResultType(TypedDeclaration typedDeclaration, ProducedType type, int flags) {
if (typedDeclaration == null
|| (!(typedDeclaration instanceof FunctionalParameter)
&& gen.isVoid(type))) {
if ((typedDeclaration instanceof Method)
&& ((Method)typedDeclaration).isDeclaredVoid()
&& !Strategy.useBoxedVoid((Method)typedDeclaration)) {
return makeVoidType();
} else {
return gen.makeJavaType(typedDeclaration, gen.typeFact().getVoidDeclaration().getType(), flags);
}
} else {
return gen.makeJavaType(typedDeclaration, type, flags);
}
}
/*
* Builder methods - they transform the inner state before doing the final construction
*/
public MethodDefinitionBuilder modifiers(long... modifiers) {
long mods = 0;
for (long mod : modifiers) {
mods |= mod;
}
this.modifiers = mods;
return this;
}
/**
* The class will be generated with the {@code @Ignore} annotation only
*/
public MethodDefinitionBuilder ignoreAnnotations() {
ignoreAnnotations = true;
return this;
}
public MethodDefinitionBuilder noAnnotations() {
return noAnnotations(true);
}
public MethodDefinitionBuilder noAnnotations(boolean noAnnotations) {
this.noAnnotations = noAnnotations;
return this;
}
public MethodDefinitionBuilder annotations(List<JCTree.JCAnnotation> annotations) {
this.annotations.appendList(annotations);
return this;
}
public MethodDefinitionBuilder typeParameter(Tree.TypeParameterDeclaration param) {
gen.at(param);
return typeParameter(gen.makeTypeParameter(param), gen.makeAtTypeParameter(param));
}
public MethodDefinitionBuilder typeParameter(TypeParameter param) {
return typeParameter(gen.makeTypeParameter(param), gen.makeAtTypeParameter(param));
}
public MethodDefinitionBuilder typeParameter(JCTypeParameter tp, JCAnnotation tpAnno) {
typeParams.append(tp);
typeParamAnnotations.append(tpAnno);
return this;
}
public MethodDefinitionBuilder parameters(List<ParameterDefinitionBuilder> pdbs) {
params.appendList(pdbs);
return this;
}
public MethodDefinitionBuilder parameter(ParameterDefinitionBuilder pdb) {
params.append(pdb);
return this;
}
public MethodDefinitionBuilder parameter(long modifiers, String name, TypedDeclaration decl, TypedDeclaration nonWideningDecl, ProducedType nonWideningType, int flags) {
return parameter(modifiers, name, name, decl, nonWideningDecl, nonWideningType, flags);
}
private MethodDefinitionBuilder parameter(long modifiers, String name, String aliasedName, TypedDeclaration decl, TypedDeclaration nonWideningDecl, ProducedType nonWideningType, int flags) {
ParameterDefinitionBuilder pdb = ParameterDefinitionBuilder.instance(gen, name);
pdb.modifiers(modifiers);
pdb.aliasName(aliasedName);
pdb.sequenced(decl instanceof Parameter && ((Parameter)decl).isSequenced());
pdb.defaulted(decl instanceof Parameter && ((Parameter)decl).isDefaulted());
pdb.type(paramType(nonWideningDecl, nonWideningType, flags), gen.makeJavaTypeAnnotations(decl));
return parameter(pdb);
}
private JCExpression paramType(TypedDeclaration nonWideningDecl,
ProducedType nonWideningType, int flags) {
if (gen.typeFact().isUnion(nonWideningType)
|| gen.typeFact().isIntersection(nonWideningType)) {
final TypeDeclaration refinedTypeDecl = ((TypedDeclaration)CodegenUtil.getTopmostRefinedDeclaration(nonWideningDecl)).getType().getDeclaration();
if (refinedTypeDecl instanceof TypeParameter
&& !refinedTypeDecl.getSatisfiedTypes().isEmpty()) {
nonWideningType = refinedTypeDecl.getSatisfiedTypes().get(0);
}
}
JCExpression type = gen.makeJavaType(nonWideningDecl, nonWideningType, flags);
return type;
}
public MethodDefinitionBuilder parameter(Parameter paramDecl, ProducedType paramType, int mods, int flags) {
String name = paramDecl.getName();
return parameter(mods, name, paramDecl, paramDecl, paramType, flags);
}
public MethodDefinitionBuilder parameter(Parameter param, int flags) {
String paramName = param.getName();
String aliasedName = paramName;
MethodOrValue mov = CodegenUtil.findMethodOrValueForParam(param);
int mods = 0;
if (!(mov instanceof Value) || !mov.isVariable() || mov.isCaptured()) {
mods |= FINAL;
}
if (mov instanceof Method
|| mov instanceof Value && mov.isVariable() && mov.isCaptured()) {
aliasedName = Naming.getAliasedParameterName(param);
}
return parameter(mods, paramName, aliasedName, param, param, param.getType(), flags);
}
public MethodDefinitionBuilder isOverride(boolean isOverride) {
this.isOverride = isOverride;
return this;
}
public MethodDefinitionBuilder isAbstract(boolean isAbstract) {
this.isAbstract = isAbstract;
return this;
}
public MethodDefinitionBuilder body(JCStatement statement) {
if (statement != null) {
this.body.append(statement);
}
return this;
}
public MethodDefinitionBuilder body(List<JCStatement> body) {
if (body != null) {
this.body.appendList(body);
}
return this;
}
MethodDefinitionBuilder noBody() {
this.body = null;
return this;
}
public MethodDefinitionBuilder block(JCBlock block) {
if (block != null) {
body.clear();
return body(block.getStatements());
} else {
return noBody();
}
}
public MethodDefinitionBuilder resultType(Method method, int flags) {
if (Decl.isMpl(method)) {
- return resultType(null, gen.makeJavaType(gen.functionalReturnType(method), flags));
+ //Create a String with the TypeInfo
+ StringBuilder sb = new StringBuilder();
+ //It's a bunch of nested callables (# of param lists - 1)
+ for (int i = 1; i < method.getParameterLists().size(); i++) {
+ sb.append("ceylon.language.Callable<");
+ }
+ //Then the return type as defined originally
+ sb.append(method.getType().getProducedTypeQualifiedName());
+ //And then the parameter types of each nested callable
+ for (int i = method.getParameterLists().size()-1; i>0; i--) {
+ ParameterList plist = method.getParameterLists().get(i);
+ for (Parameter p : plist.getParameters()) {
+ sb.append(',');
+ sb.append(p.getTypeDeclaration().getQualifiedNameString());
+ }
+ sb.append('>');
+ }
+ return resultType(gen.makeAtType(sb.toString()), gen.makeJavaType(gen.functionalReturnType(method), flags));
} else {
ProducedTypedReference typedRef = gen.getTypedReference(method);
ProducedTypedReference nonWideningTypedRef = gen.nonWideningTypeDecl(typedRef);
ProducedType nonWideningType = gen.nonWideningType(typedRef, nonWideningTypedRef);
return resultType(makeResultType(nonWideningTypedRef.getDeclaration(), nonWideningType, flags), method);
}
}
public MethodDefinitionBuilder resultTypeNonWidening(ProducedTypedReference typedRef, ProducedType returnType, int flags){
ProducedTypedReference nonWideningTypedRef = gen.nonWideningTypeDecl(typedRef);
returnType = gen.nonWideningType(typedRef, nonWideningTypedRef);
return resultType(makeResultType(nonWideningTypedRef.getDeclaration(), returnType, flags), typedRef.getDeclaration());
}
public MethodDefinitionBuilder resultType(TypedDeclaration resultType, ProducedType type, int flags) {
return resultType(makeResultType(resultType, type, flags), resultType);
}
public MethodDefinitionBuilder resultType(JCExpression resultType, TypedDeclaration typeDecl) {
return resultType(gen.makeJavaTypeAnnotations(typeDecl), resultType);
}
public MethodDefinitionBuilder resultType(List<JCAnnotation> resultTypeAnnos, JCExpression resultType) {
this.resultTypeAnnos = resultTypeAnnos;
this.resultTypeExpr = resultType;
return this;
}
public MethodDefinitionBuilder modelAnnotations(java.util.List<Annotation> annotations) {
annotations(gen.makeAtAnnotations(annotations));
return this;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getAnnotations()).append(' ');
sb.append(Flags.toString(this.modifiers)).append(' ');
sb.append(resultTypeExpr).append(' ');
sb.append(name).append('(');
int i = 0;
for (ParameterDefinitionBuilder param : params) {
sb.append(param);
if (i < params.count -1) {
sb.append(',');
}
}
sb.append(')');
return sb.toString();
}
}
| false | false | null | null |
diff --git a/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/groups/RepositoryGroupListPlexusResource.java b/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/groups/RepositoryGroupListPlexusResource.java
index 6706bc651..a66ada697 100644
--- a/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/groups/RepositoryGroupListPlexusResource.java
+++ b/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/groups/RepositoryGroupListPlexusResource.java
@@ -1,170 +1,172 @@
/**
* Sonatype Nexus (TM) Open Source Version.
* Copyright (c) 2008 Sonatype, Inc. All rights reserved.
* Includes the third-party code listed at http://nexus.sonatype.org/dev/attributions.html
* This program is licensed to you under Version 3 only of the GNU General Public License as published by the Free Software Foundation.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License Version 3 for more details.
* You should have received a copy of the GNU General Public License Version 3 along with this program.
* If not, see http://www.gnu.org/licenses/.
* Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc.
* "Sonatype" and "Sonatype Nexus" are trademarks of Sonatype, Inc.
*/
package org.sonatype.nexus.rest.groups;
import java.util.Collection;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.codehaus.enunciate.contract.jaxrs.ResourceMethodSignature;
import org.codehaus.plexus.component.annotations.Component;
import org.restlet.Context;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.resource.ResourceException;
import org.restlet.resource.Variant;
import org.sonatype.nexus.proxy.NoSuchRepositoryException;
import org.sonatype.nexus.proxy.repository.GroupRepository;
import org.sonatype.nexus.rest.NoSuchRepositoryAccessException;
import org.sonatype.nexus.rest.model.RepositoryGroupListResource;
import org.sonatype.nexus.rest.model.RepositoryGroupListResourceResponse;
import org.sonatype.nexus.rest.model.RepositoryGroupResource;
import org.sonatype.nexus.rest.model.RepositoryGroupResourceResponse;
import org.sonatype.plexus.rest.resource.PathProtectionDescriptor;
import org.sonatype.plexus.rest.resource.PlexusResource;
import org.sonatype.plexus.rest.resource.PlexusResourceException;
/**
* A resource list for RepositoryGroup list.
*
* @author cstamas
* @author tstevens
*/
@Component( role = PlexusResource.class, hint = "RepositoryGroupListPlexusResource" )
@Path( RepositoryGroupListPlexusResource.RESOURCE_URI )
@Produces( { "application/xml", "application/json" } )
@Consumes( { "application/xml", "application/json" } )
public class RepositoryGroupListPlexusResource
extends AbstractRepositoryGroupPlexusResource
{
public static final String RESOURCE_URI = "/repo_groups";
public RepositoryGroupListPlexusResource()
{
this.setModifiable( true );
}
@Override
public Object getPayloadInstance()
{
return new RepositoryGroupResourceResponse();
}
@Override
public String getResourceUri()
{
return RESOURCE_URI;
}
@Override
public PathProtectionDescriptor getResourceProtection()
{
return new PathProtectionDescriptor( getResourceUri(), "authcBasic,perms[nexus:repogroups]" );
}
/**
* Get the list of repository groups defined in nexus.
*/
@Override
@GET
@ResourceMethodSignature( output = RepositoryGroupListResourceResponse.class )
public Object get( Context context, Request request, Response response, Variant variant )
throws ResourceException
{
RepositoryGroupListResourceResponse result = new RepositoryGroupListResourceResponse();
Collection<GroupRepository> groups = getRepositoryRegistry().getRepositoriesWithFacet( GroupRepository.class );
try
{
for ( GroupRepository group : groups )
{
RepositoryGroupListResource resource = new RepositoryGroupListResource();
resource.setContentResourceURI( createRepositoryContentReference( request, group.getId() ).toString() );
resource.setResourceURI( createRepositoryGroupReference( request, group.getId() ).toString() );
resource.setId( group.getId() );
resource.setExposed( group.isExposed() );
+ resource.setUserManaged( group.isUserManaged() );
+
resource.setFormat( getRepositoryRegistry()
.getRepositoryWithFacet( group.getId(), GroupRepository.class ).getRepositoryContentClass()
.getId() );
resource.setName( group.getName() );
result.addData( resource );
}
}
catch ( NoSuchRepositoryAccessException e)
{
// access denied 403
getLogger().debug( "Blocking access to all repository groups, based on permissions." );
throw new ResourceException( Status.CLIENT_ERROR_FORBIDDEN );
}
catch ( NoSuchRepositoryException e )
{
getLogger().warn( "Cannot find a repository group or repository declared within a group!", e );
throw new ResourceException( Status.SERVER_ERROR_INTERNAL );
}
return result;
}
/**
* Add a new repository group to nexus.
*/
@Override
@POST
@ResourceMethodSignature( input = RepositoryGroupResourceResponse.class, output = RepositoryGroupResourceResponse.class )
public Object post( Context context, Request request, Response response, Object payload )
throws ResourceException
{
RepositoryGroupResourceResponse groupRequest = (RepositoryGroupResourceResponse) payload;
if ( groupRequest != null )
{
RepositoryGroupResource resource = groupRequest.getData();
createOrUpdateRepositoryGroup( resource, true );
try
{
RepositoryGroupResourceResponse result = new RepositoryGroupResourceResponse();
result.setData( buildGroupResource( request, resource.getId() ) );
return result;
}
catch ( NoSuchRepositoryException e )
{
throw new PlexusResourceException(
Status.CLIENT_ERROR_BAD_REQUEST,
"The group was somehow not found!",
getNexusErrorResponse( "repositories", "Group id not found!" ) );
}
}
return null;
}
}
| true | false | null | null |
diff --git a/semanticXWiki/src/main/java/com/objectsecurity/jena/Context.java b/semanticXWiki/src/main/java/com/objectsecurity/jena/Context.java
index 134ba4c..7a337e4 100644
--- a/semanticXWiki/src/main/java/com/objectsecurity/jena/Context.java
+++ b/semanticXWiki/src/main/java/com/objectsecurity/jena/Context.java
@@ -1,597 +1,597 @@
/**
* Semantic XWiki Extension
* Copyright (c) 2010, 2011, 2012, 2014 ObjectSecurity Ltd.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
* The research leading to these results has received funding
* from the European Union Seventh Framework Programme (FP7/2007-2013)
* under grant agreement No FP7-242474.
*
* The research leading to these results has received funding
* from the European Union Seventh Framework Programme (FP7/2007-2013)
* under grant agreement No FP7-608142.
*
* Partially funded by the European Space Agengy as part of contract
* 4000101353 / 10 / NL / SFe
*
* Written by Karel Gardas, <[email protected]>
*/
package com.objectsecurity.jena;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Vector;
import org.xwiki.bridge.event.DocumentDeletedEvent;
import org.xwiki.bridge.event.DocumentUpdatingEvent;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.observation.EventListener;
import org.xwiki.observation.ObservationManager;
import org.xwiki.observation.event.Event;
import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.SimpleSelector;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.sdb.SDBFactory;
import com.hp.hpl.jena.sdb.Store;
import com.hp.hpl.jena.sdb.store.StoreFactory;
import com.hp.hpl.jena.tdb.TDBFactory;
import com.objectsecurity.xwiki.util.DocumentUtil;
import com.objectsecurity.xwiki.util.SymbolMapper;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.web.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Context implements EventListener {
public enum Mode {
ADD,
MODIFY
}
enum BackendImpl {
UNKNOWN,
SDB,
TDB_DIRECTORY,
TDB_ASSEMBLER
}
private static Context INSTANCE = null;
private static final Logger logger = LoggerFactory.getLogger(Context.class);
//private OntModel model_;
private Model model_;
private static final String storeFileName = "sdb.ttl";
private static BackendImpl jena_backend_default = BackendImpl.SDB;
private static String jena_backend_db_default = "sdb.ttl";
private static final String SDB = "sdb";
private static final String TDB = "tdb";
private static final String ASSEMBLER = "assembler";
private static final String DIRECTORY = "directory";
private BackendImpl jena_backend = BackendImpl.UNKNOWN;
private String jena_backend_db = "";
private ComponentManager componentManager;
/**
* The observation manager that will be use to fire user creation events. Note: We can't have the OM as a
* requirement, since it would create an infinite initialization loop, causing a stack overflow error (this event
* listener would require an initialized OM and the OM requires a list of initialized event listeners)
*/
private ObservationManager observationManager;
// Private constructor prevents instantiation from other classes
private Context() {
// Initialize Rendering components and allow getting instances
//EmbeddableComponentManager componentManager = new EmbeddableComponentManager();
//componentManager.initialize(this.getClass().getClassLoader());
componentManager = Utils.getComponentManager();
ObservationManager om = this.getObservationManager();
logger.info("XWiki Context: registering observation listener.");
om.addListener(this);
}
public static Context getInstance() {
if (INSTANCE == null) {
INSTANCE = new Context();
}
return INSTANCE;
}
public void initJenaBackendFromEnv() {
String jback = System.getenv("JENA_BACKEND");
String backend_name = "";
String backend_family = "";
String backend_db_name = "";
if (jback != null && !jback.equals("")) {
StringTokenizer st = new StringTokenizer(jback, ":");
if (st.hasMoreTokens()) {
backend_name = st.nextToken();
}
if (st.hasMoreTokens() && backend_name.equals(TDB)) {
backend_family = st.nextToken();
}
if (st.hasMoreTokens()) {
backend_db_name = st.nextToken();
}
if (backend_name.equals(SDB)) {
jena_backend = BackendImpl.SDB;
jena_backend_db = backend_db_name;
}
else if (backend_name.equals(TDB) && backend_family.equals(DIRECTORY)) {
jena_backend = BackendImpl.TDB_DIRECTORY;
jena_backend_db = backend_db_name;
}
else if (backend_name.equals(TDB) && backend_family.equals(ASSEMBLER)) {
jena_backend = BackendImpl.TDB_ASSEMBLER;
jena_backend_db = backend_db_name;
}
else {
logger.info("UNKNOWN backend! => will use default option...");
jena_backend = jena_backend_default;
jena_backend_db = jena_backend_db_default;
}
logger.info("backend: " + jena_backend);
logger.info("backend param: " + backend_db_name);
}
else {
logger.info("default option!");
jena_backend = jena_backend_default;
jena_backend_db = jena_backend_db_default;
}
}
synchronized public Model getModel() {
if (model_ == null) {
this.initJenaBackendFromEnv();
logger.info("BACKEND: " + jena_backend);
logger.info("DB: " + jena_backend_db);
if (jena_backend == BackendImpl.SDB) {
Store store = StoreFactory.create(storeFileName);
model_ = SDBFactory.connectDefaultModel(store);
}
else if (jena_backend == BackendImpl.TDB_DIRECTORY) {
Dataset ds = TDBFactory.createDataset(jena_backend_db);
model_ = ds.getDefaultModel();
}
else if (jena_backend == BackendImpl.TDB_ASSEMBLER) {
Dataset ds = TDBFactory.assembleDataset(jena_backend_db);
model_ = ds.getDefaultModel();
}
else {
logger.error("ERROR: unknown Jena Backend!");
}
//Model m = SDBFactory.connectDefaultModel(store);
//Model m = SDBFactory.connectNamedModel(store, iri);
//model_ = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, m);
logger.info("Context: created ontology model: " + model_);
}
return model_;
}
synchronized public void begin() {
// if (this.getModel().supportsTransactions()) {
this.getModel().begin();
// }
}
synchronized public void commit() {
// if (this.getModel().supportsTransactions()) {
this.getModel().commit();
// }
}
synchronized public void abort() {
this.getModel().abort();
}
synchronized public String query(String str) {
// getModel is also initializer of model_ variable!
String outstr = "";
Model m = this.getModel();
Query query = QueryFactory.create(str) ;
QueryExecution qexec = QueryExecutionFactory.create(query, m) ;
try {
ResultSet results = qexec.execSelect() ;
ByteArrayOutputStream out = new ByteArrayOutputStream();
ResultSetFormatter.out(out, results, query);
outstr = out.toString();
// // fmt.printAll(System.out) ;
} finally {
qexec.close() ;
}
return outstr;
}
synchronized public Vector<Vector<PairNameLink>> query(String str, String[] header, String[] linksAttrs, String[] linksValuesRemapping) {
Vector<Vector<PairNameLink>> retval = new Vector<Vector<PairNameLink>>();
Model m = this.getModel();
Query query = QueryFactory.create(str) ;
QueryExecution qexec = QueryExecutionFactory.create(query, m);
HashMap<String, String> name_link_map = new HashMap<String, String>();
HashMap<String, String> link_value_remap = new HashMap<String, String>();
logger.debug("header len: " + header.length);
logger.debug("linksAttrs len: " + linksAttrs.length);
for (int i = 0; i<linksAttrs.length; i++) {
String tmp = linksAttrs[i];
String link = tmp.substring(0, tmp.indexOf(">"));
String name = tmp.substring(tmp.indexOf(">") + 1, tmp.length());
logger.debug("link: " + link);
logger.debug("name: " + name);
name_link_map.put(name, link);
}
for (int i = 0; i<linksValuesRemapping.length; i++) {
String tmp = linksValuesRemapping[i];
String res = tmp.substring(0, tmp.indexOf(">"));
String link = tmp.substring(tmp.indexOf(">") + 1, tmp.length());
logger.debug("resource: " + res);
logger.debug("link: " + link);
link_value_remap.put(res, link);
}
String[] variable_names;
try {
ResultSet results = qexec.execSelect() ;
logger.debug("result set hasNext?: " + results.hasNext());
for ( ; results.hasNext(); ) {
QuerySolution sol = results.next();
System.out.println(sol);
if (header.length != 0) {
variable_names = header;
}
else {
System.out.println("header.length == 0 -> generating variable names...");
Iterator<String> names = sol.varNames();
Vector<String> vec = new Vector<String>();
while (names.hasNext()) {
vec.add(names.next());
}
variable_names = vec.toArray(new String[0]);
}
Vector<PairNameLink> row = new Vector<PairNameLink>();
for (int i = 0; i < variable_names.length; i++) {
if (sol.contains(variable_names[i])) {
RDFNode x = sol.get(variable_names[i]);
String field = name_link_map.get(variable_names[i]);
PairNameLink pair = new PairNameLink();
RDFNode r = null;
if (field != null && !field.equals("")) {
r = sol.get(field);
}
if (x.isLiteral()) {
pair.name = x.asLiteral().toString();
}
else if (x.isResource()) {
pair.name = x.asResource().toString();
}
else {
pair.name = "<not literal type>";
}
logger.debug("pair.name: " + pair.name);
logger.debug("r: " + r);
if (r != null) {
if (r.isLiteral()) {
pair.link = r.asLiteral().toString();
}
else if (r.isResource()) {
pair.link = r.asResource().toString();
}
else {
pair.link = "<not literal type>";
}
logger.debug("pair.link: " + pair.link);
// need to process link if linksValuesRemapping is used
logger.debug("empty remap?: " + link_value_remap.isEmpty());
if (!link_value_remap.isEmpty()) {
Set<String> keys = link_value_remap.keySet();
logger.debug("keys: " + keys.toString());
for (Iterator<String> it = keys.iterator(); it.hasNext(); ) {
String key = it.next();
logger.debug("key: " + key);
logger.debug("link: " + pair.link);
if (pair.link.contains(key)) {
// link contains the resource URL which needs to be re-mapped
String tmp = pair.link.replace(key, link_value_remap.get(key));
logger.debug("remapping link : " + pair.link + " to " + tmp);
pair.link = tmp;
}
}
}
}
row.add(pair);
}
}
retval.add(row);
}
} finally { qexec.close() ; }
return retval;
}
synchronized public Vector<Vector<String>> query(String str, String[] header) {
Vector<Vector<String>> retval = new Vector<Vector<String>>();
Vector<Vector<PairNameLink>> tmp = query(str, header, new String[0], new String[0]);
Iterator<Vector<PairNameLink>> i = tmp.iterator();
while (i.hasNext()) {
Vector<PairNameLink> x = i.next();
Iterator<PairNameLink> j = x.iterator();
Vector<String> row = new Vector<String>();
while (j.hasNext()) {
row.add(j.next().name);
}
retval.add(row);
}
return retval;
}
synchronized public String query(String str, String[] header, boolean literalsAsLinks) {
// getModel is also initializer of model_ variable!
String retval = "";
for (int i = 0; i<header.length; i++) {
if (i == 0)
retval = retval + "|";
retval = retval + header[i];
//if (i < header.length - 1)
retval = retval + "|";
}
retval = retval + "\n";
Model m = this.getModel();
Query query = QueryFactory.create(str) ;
QueryExecution qexec = QueryExecutionFactory.create(query, m) ;
try {
ResultSet results = qexec.execSelect() ;
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// ResultSetFormatter.out(out, results, query);
// String outstr = out.toString();
// return outstr;
// // fmt.printAll(System.out) ;
for ( ; results.hasNext(); ) {
QuerySolution sol = results.next();
System.out.println(sol);
for (int i = 0; i < header.length; i++) {
if (i == 0)
retval = retval + "|";
if (sol.contains(header[i])) {
RDFNode x = sol.get(header[i]);
if (x.isLiteral()) {
if (literalsAsLinks)
retval = retval + "[[";
String lit = x.asLiteral().toString();
retval = retval + lit.replace(".", "\\.");
if (literalsAsLinks)
retval = retval + "]]";
}
}
//if (i < header.length - 1)
retval = retval + "|";
}
retval = retval + "\n";
}
} finally { qexec.close() ; }
return retval;
}
public String query(String str, String header, String literalsAsLinks) {
if (header == null || header.equals(""))
return this.query(str);
StringTokenizer st = new StringTokenizer(header, ",");
Vector<String >vec = new Vector<String>();
while(st.hasMoreElements()) {
vec.add(st.nextToken());
}
boolean links = false;
if ("true".equals(literalsAsLinks)) {
links = true;
}
return this.query(str, vec.toArray(new String[0]), links);
}
synchronized public String getPropertyTableForResource(String res, String literalsAsLinks) {
String tres = SymbolMapper.transform(res, SymbolMapper.MappingDirection.XWIKI_URL_TO_PHYSICAL_URL, SymbolMapper.MappingStrategy.SYMBOLIC_NAME_TRANSLATION);
String retval = "";
StmtIterator iter = this.getModel().listStatements(new SimpleSelector(this.getModel().createResource(tres), null, (RDFNode)null) {
public boolean selects(Statement s) {
return true;
}
});
if (iter.hasNext()) {
retval = "|property|value|\n";
}
boolean links = false;
if ("true".equals(literalsAsLinks))
links = true;
while (iter.hasNext()) {
Statement stmt = iter.next();
retval = retval + "|"
+ stmt.getPredicate().toString()
+ "|"
+ (links ? "[[" : "")
+ (links ? /* stmt.getLiteral().toString().replace(".", "\\.") */ SymbolMapper.transform(stmt.getLiteral().toString(), SymbolMapper.MappingDirection.XWIKI_URL_TO_PHYSICAL_URL, SymbolMapper.MappingStrategy.SYMBOLIC_NAME_TRANSLATION) : stmt.getLiteral().toString())
+ (links ? "]]" : "")
+ "|\n";
}
return retval;
}
synchronized public Vector<Vector<String>> getPropertyTableForResource(String res) {
logger.debug("Context: table for resource: " + res);
String tres = SymbolMapper.transform(res, SymbolMapper.MappingDirection.XWIKI_URL_TO_PHYSICAL_URL, SymbolMapper.MappingStrategy.SYMBOLIC_NAME_TRANSLATION);
logger.debug("Context: resource translated to: " + tres);
Vector<Vector<String>> retval = new Vector<Vector<String>>();
StmtIterator iter = this.getModel().listStatements(new SimpleSelector(this.getModel().createResource(tres), null, (RDFNode)null) {
public boolean selects(Statement s) {
return true;
}
});
while (iter.hasNext()) {
Statement stmt = iter.next();
Vector<String> row = new Vector<String>();
row.add(stmt.getPredicate().toString());
//row.add(stmt.getPredicate().getLocalName());
row.add(stmt.getLiteral().toString());
logger.debug("adding row: " + row.toString());
retval.add(row);
}
return retval;
}
synchronized public void setProperty(String resource, String property_prefix, String property_name, String property_value, Mode mode) {
// createProperty reuses existing property
Property property = this.getModel().createProperty(property_prefix, property_name);
this.setProperty(resource, property, property_value, mode);
}
synchronized public void setProperty(String resource, Property property, String property_value, Mode mode) {
logger.debug("Context: set property on resource: " + resource);
String tres = SymbolMapper.transform(resource, SymbolMapper.MappingDirection.XWIKI_URL_TO_PHYSICAL_URL, SymbolMapper.MappingStrategy.SYMBOLIC_NAME_TRANSLATION);
logger.debug("Context: resource translated to: " + tres);
Resource res = this.getModel().getResource(tres);
if (res == null)
res = this.getModel().createResource();
if (mode == Mode.MODIFY) {
this.removeProperty(resource, property);
}
res.addProperty(property, property_value);
}
public void removeProperty(String resource, String property_prefix, String property_name) {
Property property = this.getModel().createProperty(property_prefix, property_name);
this.removeProperty(resource, property);
}
public void removeProperty(String resource, Property property) {
String tres = SymbolMapper.transform(resource, SymbolMapper.MappingDirection.XWIKI_URL_TO_PHYSICAL_URL, SymbolMapper.MappingStrategy.SYMBOLIC_NAME_TRANSLATION);
Resource res = this.getModel().getResource(tres);
if (res == null)
res = this.getModel().createResource(resource);
logger.debug("removeAll properties: `" + property.toString() + "' on resource: `" + res.toString() + "'");
res.removeAll(property);
}
public String getProperty(String resource, String property_prefix, String property_name) {
Property property = this.getModel().createProperty(property_prefix, property_name);
return this.getProperty(resource, property);
}
public String getProperty(String resource, Property property) {
String tres = SymbolMapper.transform(resource, SymbolMapper.MappingDirection.XWIKI_URL_TO_PHYSICAL_URL, SymbolMapper.MappingStrategy.SYMBOLIC_NAME_TRANSLATION);
Resource res = this.getModel().getResource(tres);
if (res == null)
res = this.getModel().createResource(resource);
Statement p = res.getProperty(property);
return p != null ? p.getString() : null;
}
@Override
- public List<Event> getEvents() {
+ public List<Event> getEvents() {
logger.debug("XWiki Context: getEvents called");
return Arrays.<Event>asList(new DocumentDeletedEvent(), new DocumentUpdatingEvent());
}
@Override
- public String getName() {
+ public String getName() {
return "XWiki Semantics: Context interceptor code";
}
@Override
- public void onEvent(Event arg0, Object arg1, Object arg2) {
+ public void onEvent(Event arg0, Object arg1, Object arg2) {
// TODO Auto-generated method stub
logger.debug("XWiki: EVENT: " + arg0.toString() + ", arg1: " + arg1 + ", arg2: " + arg2);
logger.debug("XWiki: classes: " + arg0.getClass().getName() + ", arg1: " + arg1.getClass().getName() + ", arg2: " + arg2.getClass().getName());
XWikiDocument doc = (XWikiDocument)arg1;
//String res = doc.getURL("view", (XWikiContext)arg2);
String name = DocumentUtil.computeFullDocName(doc.getDocumentReference());
String tres = SymbolMapper.transform(name, SymbolMapper.MappingDirection.XWIKI_URL_TO_PHYSICAL_URL, SymbolMapper.MappingStrategy.SYMBOLIC_NAME_TRANSLATION);
logger.debug("tres: " + tres);
Resource res = this.getModel().getResource(tres);
res.removeProperties();
logger.debug("props after delete: " + this.query("SELECT ?prop WHERE { <" + tres + "> ?prop ?prop_value }", new String[] {"prop"}, false));
StmtIterator it = res.listProperties();
while (it.hasNext()) {
Statement st = it.next();
logger.debug("prop: " + st);
}
// //Query query = QueryFactory.create("SELECT ?prop WHERE { ?ref <http://www.objectsecurity.com/NextGenRE/XWikiPage_properties_for_deletion> ?prop }") ;
// Query query = QueryFactory.create("SELECT ?prop WHERE { <" + res + "> ?prop ?prop_value }");
// QueryExecution qexec = QueryExecutionFactory.create(query, this.getModel()) ;
// String[] header = new String[] {"prop" };
// this.begin();
// try {
// ResultSet results = qexec.execSelect() ;
// for ( ; results.hasNext(); ) {
// QuerySolution sol = results.next();
// System.out.println(sol);
// for (int i = 0; i < header.length; i++) {
// if (sol.contains(header[i])) {
// RDFNode x = sol.get(header[i]);
// if (x.isLiteral()) {
// String lit = x.asLiteral().toString();
// System.err.println("deleting property: " + lit);
// if (lit != null && !lit.equals("")) {
// int pos = lit.lastIndexOf('/');
// String prefix = lit.substring(0, pos + 1);
// String name = lit.substring(pos + 1);
// System.err.println("property prefix `" + prefix + "'");
// System.err.println("property name `" + name + "'");
// this.removeProperty(res, prefix, name);
// }
// }
// }
// }
// }
// } finally { qexec.close() ; }
// this.removeProperty(res, "http://www.objectsecurity.com/NextGenRE/", "XWikiPage_properties_for_deletion");
// this.commit();
// System.err.println("props after delete: " + this.query("SELECT ?prop WHERE { ?ref ?prop_name ?prop }", new String[] {"prop"}, false));
}
private ObservationManager getObservationManager() {
if (this.observationManager == null) {
try {
this.observationManager = componentManager.getInstance(ObservationManager.class);
} catch (ComponentLookupException e) {
throw new RuntimeException("Cound not retrieve an Observation Manager against the component manager");
}
}
return this.observationManager;
}
}
| false | false | null | null |
diff --git a/src/uk/me/parabola/imgfmt/app/BufferedWriteStrategy.java b/src/uk/me/parabola/imgfmt/app/BufferedWriteStrategy.java
index 42485b7f..3e60243c 100644
--- a/src/uk/me/parabola/imgfmt/app/BufferedWriteStrategy.java
+++ b/src/uk/me/parabola/imgfmt/app/BufferedWriteStrategy.java
@@ -1,155 +1,157 @@
/*
* Copyright (C) 2006 Steve Ratcliffe
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* Author: Steve Ratcliffe
* Create date: 07-Dec-2006
*/
package uk.me.parabola.imgfmt.app;
import uk.me.parabola.imgfmt.fs.ImgChannel;
import uk.me.parabola.log.Logger;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
/**
* A straight forward implementation that just keeps all the data in a buffer
* until the file needs to be written to disk.
*
* @author Steve Ratcliffe
*/
public class BufferedWriteStrategy implements WriteStrategy {
private static final Logger log = Logger.getLogger(BufferedWriteStrategy.class);
private static final int KBYTE = 1024;
private static final int INIT_SIZE = 16 * KBYTE;
private static final int GROW_SIZE = 128 * KBYTE;
private static final int GUARD_SIZE = KBYTE;
private final ImgChannel chan;
private ByteBuffer buf = ByteBuffer.allocate(INIT_SIZE);
- private int maxSize = INIT_SIZE;
+ private int bufferSize = INIT_SIZE;
+
+ private int maxSize;
public BufferedWriteStrategy(ImgChannel chan) {
this.chan = chan;
buf.order(ByteOrder.LITTLE_ENDIAN);
}
/**
* Called to write out any saved buffers. The strategy may write
* directly to the file in which case this would have nothing or
* little to do.
*/
public void sync() throws IOException {
buf.limit(maxSize);
buf.position(0);
log.debug("syncing to pos", chan.position(), ", size", buf.limit());
chan.write(buf);
}
/**
* Get the position. Needed because may not be reflected in the underlying
* file if being buffered.
*
* @return The logical position within the file.
*/
public int position() {
return buf.position();
}
/**
* Set the position of the file.
*
* @param pos The new position in the file.
*/
public void position(long pos) {
int cur = position();
if (cur > maxSize)
maxSize = cur;
buf.position((int) pos);
}
/**
* Called when the stream is closed. Any resources can be freed.
*/
public void close() throws IOException {
chan.close();
}
/**
* Write out a single byte.
*
* @param b The byte to write.
*/
public void put(byte b) {
checkSize();
buf.put(b);
}
/**
* Write out two bytes. Done in the correct byte order.
*
* @param c The value to write.
*/
public void putChar(char c) {
checkSize();
log.debug("char at pos ", position());
buf.putChar(c);
}
/**
* Write out 4 byte value.
*
* @param val The value to write.
*/
public void putInt(int val) {
checkSize();
buf.putInt(val);
}
/**
* Write out an arbitary length sequence of bytes.
*
* @param val The values to write.
*/
public void put(byte[] val) {
checkSize();
buf.put(val);
}
/**
* Write out part of a byte array.
*
* @param src The array to take bytes from.
* @param start The start position.
* @param length The number of bytes to write.
*/
public void put(byte[] src, int start, int length) {
checkSize();
log.debug("start+len", start, ",", length);
buf.put(src, start, length);
}
private void checkSize() {
- if (buf.position() > maxSize - GUARD_SIZE) {
- maxSize += GROW_SIZE;
- ByteBuffer newb = ByteBuffer.allocate(maxSize);
+ if (buf.position() > bufferSize - GUARD_SIZE) {
+ bufferSize += GROW_SIZE;
+ ByteBuffer newb = ByteBuffer.allocate(bufferSize);
newb.order(ByteOrder.LITTLE_ENDIAN);
buf.flip();
newb.put(buf);
buf = newb;
}
}
}
diff --git a/src/uk/me/parabola/imgfmt/sys/Dirent.java b/src/uk/me/parabola/imgfmt/sys/Dirent.java
index 4b08b051..20d374ba 100644
--- a/src/uk/me/parabola/imgfmt/sys/Dirent.java
+++ b/src/uk/me/parabola/imgfmt/sys/Dirent.java
@@ -1,241 +1,237 @@
/*
* Copyright (C) 2006 Steve Ratcliffe
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* Author: Steve Ratcliffe
* Create date: 30-Nov-2006
*/
package uk.me.parabola.imgfmt.sys;
import uk.me.parabola.imgfmt.fs.DirectoryEntry;
import uk.me.parabola.imgfmt.Utils;
import uk.me.parabola.log.Logger;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
/**
* An entry within a directory. This holds its name and a list
* of blocks that go to make up this file.
*
* A directory entry may take more than block in the file system.
*
* All documentation seems to point to the block numbers having to be
* contiguous, but seems strange so I shall experiment.
*
* @author Steve Ratcliffe
*/
class Dirent implements DirectoryEntry {
private static final Logger log = Logger.getLogger(Dirent.class);
// Constants.
private static final int MAX_FILE_LEN = 8;
private static final int MAX_EXT_LEN = 3;
// Filenames are a base+extension
private String name;
private String ext;
// The file size.
private int size;
private int blockSize;
// The block table holds all the blocks that belong to this file. The
// documentation suggests that block numbers are always contiguous.
//private int nBlockTables;
//private int nblocks;
//private char[] blockTable;
private BlockTable blockTable;
private boolean special;
Dirent(String name, int blockSize) {
int dot;
dot = name.indexOf('.');
if (dot >= 0) {
setName(name.substring(0, dot));
setExt(name.substring(dot+1));
} else
throw new IllegalArgumentException("Filename did not have dot");
this.blockSize = blockSize;
//blockTable = new char[(blockSize - BLOCKS_TABLE_START)/2];
//Arrays.fill(blockTable, (char) 0xffff);
blockTable = new BlockTable(blockSize);
}
/**
* Write this entry out to disk.
*
* @param file The file to write to.
* @throws IOException If writing fails for any reason.
*/
void sync(FileChannel file) throws IOException {
int ntables = blockTable.getNBlockTables();
ByteBuffer buf = ByteBuffer.allocate(blockSize * ntables);
buf.order(ByteOrder.LITTLE_ENDIAN);
for (int part = 0; part < ntables; part++) {
log.debug("position at part", part, "is", buf.position());
buf.put((byte) 1);
buf.put(Utils.toBytes(name, MAX_FILE_LEN, (byte) ' '));
buf.put(Utils.toBytes(ext, MAX_EXT_LEN, (byte) ' '));
// Size is only present in the first part
if (part == 0) {
log.debug("dirent " + name + '.' + ext + " size is going to " + size);
buf.putInt(size);
} else {
buf.putInt(0);
}
- // For an unknown reason, the 'sub-file part' must be three when it
- // the header block entry.
- if (special)
- buf.putChar((char) 0x03);
- else
- buf.putChar((char) part);
+ buf.put((byte) (special? 0x3: 0));
+ buf.putChar((char) part);
// Write out the allocation of blocks for this entry.
buf.position(blockSize * part + 0x20);
blockTable.writeTable(buf, part);
}
buf.flip();
file.write(buf);
}
/**
* Get the file name.
*
* @return The file name.
*/
public String getName() {
return name;
}
/**
* Get the file extension.
*
* @return The file extension.
*/
public String getExt() {
return ext;
}
/**
* Set the file name. It cannot be too long.
*
* @param name The file name.
*/
private void setName(String name) {
if (name.length() != MAX_FILE_LEN)
throw new IllegalArgumentException("File name is wrong size "
+ "was " + name.length() + ", should be " + MAX_FILE_LEN);
this.name = name;
}
/**
* Set the file extension. Can't be longer than three characters.
* @param ext The file extension.
*/
private void setExt(String ext) {
log.debug("ext len" + ext.length());
if (ext.length() != MAX_EXT_LEN)
throw new IllegalArgumentException("File extension is wrong size");
this.ext = ext;
}
/**
* Get the file size.
*
* @return The size of the file in bytes.
*/
public int getSize() {
return size;
}
void setSize(int size) {
log.debug("setting size " + getName() + getExt() + " to " + size);
this.size = size;
}
/**
* Add a complete block and count the full size of it towards the
* file size.
*
* @param n The block number.
*/
void addFullBlock(int n) {
// We do not currently deal with more than one directory inode block.
//if (nblocks >= 240)
// throw new FormatException("reached limit of file size");
//blockTable[nblocks++] = (char) n;
blockTable.addBlock(n);
size += blockSize;
}
/**
* Set for the first directory entry that covers the header and directory
* itself.
*
* @param special Set to true to mark as the special first entry.
*/
public void setSpecial(boolean special) {
this.special = special;
}
/**
* Add a block without increasing the size of the file.
*
* @param n The block number.
*/
void addBlock(int n) {
//log.debug("adding block " + n + ", at " + nblocks);
blockTable.addBlock(n);
//blockTable[nblocks++] = (char) n;
}
/**
* Converts from a logical block to a physical block. If the block does
* not exist then 0xffff will be returned.
*
* @param lblock The logical block in the file.
* @return The corresponding physical block in the filesystem.
*/
public int getPhysicalBlock(int lblock) {
//if (lblock >= blockTable.length)
// throw new IllegalArgumentException("can't deal with long files yet");
//
//int pblock = blockTable[lblock];
return blockTable.physFromLogical(lblock);
}
/**
* Get the number of block tables used by this directory entry.
*
* @return The Number of block tables.
*/
public int getNBlockTables() {
return blockTable.getNBlockTables();
}
}
| false | false | null | null |
diff --git a/src/main/java/org/rcsb/sequence/view/multiline/ProtModLegendDrawer.java b/src/main/java/org/rcsb/sequence/view/multiline/ProtModLegendDrawer.java
index 69fc870..1145db5 100644
--- a/src/main/java/org/rcsb/sequence/view/multiline/ProtModLegendDrawer.java
+++ b/src/main/java/org/rcsb/sequence/view/multiline/ProtModLegendDrawer.java
@@ -1,221 +1,225 @@
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
* Created on Aug 26, 2010
* Author: Jianjiong Gao
*
*/
package org.rcsb.sequence.view.multiline;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.font.FontRenderContext;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextLayout;
import java.awt.image.BufferedImage;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.biojava3.protmod.ModificationCategory;
import org.biojava3.protmod.ProteinModification;
import org.rcsb.sequence.util.AnnotationConstants;
public class ProtModLegendDrawer implements Drawer {
private Font font;
private final int imageWidth;
private int totalHeight;
private ImageMapData mapData = null;
private ProtModDrawerUtil modDrawerUtil;
private Map<ProteinModification, List<TextLayout>> multiLineText;
private static final int legendHeight = 25;
private static final int legendOffset = 50;
private static final int legendSpacing = 20;
+
+
+ private static final int some_factor = 6;
+
Set<ProteinModification> protmods;
String annotationName ;
public ProtModLegendDrawer(ProtModDrawerUtil modDrawerUtil, Font font,
final int imageWidth, Set<ProteinModification> protMods, String annotationName) {
this.modDrawerUtil = modDrawerUtil;
this.imageWidth = imageWidth;
this.font = font;
this.protmods = protMods;
this.annotationName = annotationName;
setMultiLineText();
}
public void draw(Graphics2D g2, int yOffset) {
if (modDrawerUtil==null)
return;
if ( protmods == null || protmods.size() < 1)
return;
int fontSize = font.getSize();
int oldBendOffset = modDrawerUtil.getCrosslinkLineBendOffset();
modDrawerUtil.setCrosslinkLineBendOffset(0);
int height = legendHeight;
Color c = g2.getColor();
g2.setColor(Color.black);
g2.setFont(font);
g2.drawString(annotationName + " Legend", legendOffset, yOffset+legendSpacing);
g2.setColor(c);
if ( multiLineText == null)
setMultiLineText();
for (ProteinModification mod : protmods ) {
List<TextLayout> textLayouts = multiLineText.get(mod);
float lineHeight = textLayouts.get(0).getAscent()
+ textLayouts.get(0).getDescent() + textLayouts.get(0).getLeading();
int yMid = yOffset + height + (int)lineHeight/2;
modDrawerUtil.drawProtMod(g2, mod, 2*fontSize,
yMid-fontSize/2, 3*fontSize, yMid+fontSize/2);
ModificationCategory cat = mod.getCategory();
if (cat.isCrossLink() && cat!=ModificationCategory.CROSS_LINK_1 &&
annotationName.equals(AnnotationConstants.proteinModification)) {
Point p1 = new Point(0, yMid);
Point p2 = new Point(5*fontSize, yMid);
List<Point> points = Arrays.asList(
p1,
p2);
modDrawerUtil.drawCrosslinks(g2, mod, points);
//xPos, xPos += counter * fontWidth, yMin, yMax, counter));
}
- height += drawMultiLineText(g2, textLayouts, 6*fontSize, yOffset+height);
+ height += drawMultiLineText(g2, textLayouts, some_factor*fontSize, yOffset+height) ;
}
if (height!=totalHeight)
System.err.println("inconsistent height for "+ annotationName + " legend : " + height + " total: " + totalHeight);
modDrawerUtil.setCrosslinkLineBendOffset(oldBendOffset);
}
private int drawMultiLineText(Graphics2D g2, List<TextLayout> textLayouts, int xOffset, int yOffset) {
int deltaY = 0;
Color c = g2.getColor();
g2.setColor(Color.black);
for (TextLayout textLayout : textLayouts) {
deltaY += textLayout.getAscent();
textLayout.draw(g2, xOffset, yOffset + deltaY);
deltaY += textLayout.getDescent() + textLayout.getLeading();
}
g2.setColor(c);
return deltaY;
}
private void setMultiLineText() {
BufferedImage tmpImage = new BufferedImage(imageWidth, 1, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g2 = tmpImage.createGraphics();
g2.setFont(font);
totalHeight = legendHeight;
- int xOffset = 6 * font.getSize();
+ int xOffset = some_factor * font.getSize();
if ( protmods == null) {
System.err.println("!! ProtModLegendDrawer: protMods == null");
protmods = new TreeSet<ProteinModification>();
}
multiLineText = new HashMap<ProteinModification,List<TextLayout>>(protmods.size());
for (ProteinModification mod : protmods) {
AttributedString attributedString = new AttributedString(mod.getDescription());
AttributedCharacterIterator characterIterator = attributedString.getIterator();
FontRenderContext fontRenderContext = g2.getFontRenderContext();
LineBreakMeasurer measurer = new LineBreakMeasurer(characterIterator,
fontRenderContext);
List<TextLayout> list = new ArrayList<TextLayout>();
multiLineText.put(mod, list);
//System.out.println(mod.getPdbccId() + " " + list);
while (measurer.getPosition() < characterIterator.getEndIndex()) {
- TextLayout textLayout = measurer.nextLayout(imageWidth - xOffset);
+ TextLayout textLayout = measurer.nextLayout(imageWidth - xOffset );
list.add(textLayout);
- totalHeight += textLayout.getAscent() + textLayout.getDescent() + textLayout.getLeading();
+ totalHeight += textLayout.getAscent() + textLayout.getDescent() + textLayout.getLeading() - 1;
}
}
}
public ImageMapData getHtmlMapData() {
if(mapData == null)
{
mapData = new ImageMapData(AnnotationConstants.proteinModification+ hashCode(), totalHeight)
{
private static final long serialVersionUID = 1L;
@Override
public void populateImageMapData() {
//int yOffset = 0;
//int height = totalHeight;
//for (ProteinModification mod : modDrawerUtil.getProtMods())
addImageMapDataEntry(new Entry(0, imageWidth, AnnotationConstants.proteinModification, null)); // for now
}
};
}
//System.out.println("ProtModLegendDrawer : mapData: " + mapData.getImageMapDataEntries());
return mapData;
}
public int getImageHeightPx() {
return totalHeight;
}
}
| false | false | null | null |
diff --git a/src/rapidgator_premium/cz/vity/freerapid/plugins/services/rapidgator_premium/RapidGatorFileRunner.java b/src/rapidgator_premium/cz/vity/freerapid/plugins/services/rapidgator_premium/RapidGatorFileRunner.java
index 53d02f28..3239006d 100644
--- a/src/rapidgator_premium/cz/vity/freerapid/plugins/services/rapidgator_premium/RapidGatorFileRunner.java
+++ b/src/rapidgator_premium/cz/vity/freerapid/plugins/services/rapidgator_premium/RapidGatorFileRunner.java
@@ -1,108 +1,108 @@
package cz.vity.freerapid.plugins.services.rapidgator_premium;
import cz.vity.freerapid.plugins.exceptions.*;
import cz.vity.freerapid.plugins.webclient.AbstractRunner;
import cz.vity.freerapid.plugins.webclient.FileState;
import cz.vity.freerapid.plugins.webclient.hoster.PremiumAccount;
import cz.vity.freerapid.plugins.webclient.utils.PlugUtils;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpMethod;
import java.util.logging.Logger;
import java.util.regex.Matcher;
/**
* Class which contains main code
*
* @author ntoskrnl
*/
class RapidGatorFileRunner extends AbstractRunner {
private final static Logger logger = Logger.getLogger(RapidGatorFileRunner.class.getName());
@Override
public void runCheck() throws Exception {
super.runCheck();
addCookie(new Cookie(".rapidgator.net", "lang", "en", "/", 86400, false));
final HttpMethod method = getGetMethod(fileURL);
if (makeRedirectedRequest(method)) {
checkProblems();
checkNameAndSize(getContentAsString());
} else {
checkProblems();
throw new ServiceConnectionProblemException();
}
}
private void checkNameAndSize(final String content) throws ErrorDuringDownloadingException {
final String filenameRegexRule = "Downloading:\\s*</strong>\\s*<a.+?>\\s*(\\S+)\\s*</a>\\s*</p>";
final String filesizeRegexRule = "File size:\\s*<strong>(.+?)</strong>";
final Matcher filenameMatcher = PlugUtils.matcher(filenameRegexRule, content);
if (filenameMatcher.find()) {
httpFile.setFileName(filenameMatcher.group(1));
} else {
throw new PluginImplementationException("File name not found");
}
final Matcher filesizeMatcher = PlugUtils.matcher(filesizeRegexRule, content);
if (filesizeMatcher.find()) {
- PlugUtils.getFileSizeFromString(filesizeMatcher.group(1));
+ httpFile.setFileSize(PlugUtils.getFileSizeFromString(filesizeMatcher.group(1)));
} else {
throw new PluginImplementationException("File size not found");
}
httpFile.setFileState(FileState.CHECKED_AND_EXISTING);
}
@Override
public void run() throws Exception {
super.run();
logger.info("Starting download in TASK " + fileURL);
addCookie(new Cookie(".rapidgator.net", "lang", "en", "/", 86400, false));
login();
HttpMethod method = getGetMethod(fileURL);
if (makeRedirectedRequest(method)) {
checkProblems();
checkNameAndSize(getContentAsString());
method = getMethodBuilder().setActionFromTextBetween("var premium_download_link = '", "';").toGetMethod();
if (!tryDownloadAndSaveFile(method)) {
checkProblems();
throw new ServiceConnectionProblemException("Error starting download");
}
} else {
checkProblems();
throw new ServiceConnectionProblemException();
}
}
private void checkProblems() throws ErrorDuringDownloadingException {
if (getContentAsString().contains("File not found")) {
throw new URLNotAvailableAnymoreException("File not found");
}
}
private void login() throws Exception {
synchronized (RapidGatorFileRunner.class) {
RapidGatorServiceImpl service = (RapidGatorServiceImpl) getPluginService();
PremiumAccount pa = service.getConfig();
if (!pa.isSet()) {
pa = service.showConfigDialog();
if (pa == null || !pa.isSet()) {
throw new BadLoginException("No RapidGator account login information!");
}
}
final HttpMethod method = getMethodBuilder()
- .setAction("http://rapidgator.net/auth/login")
+ .setAction("https://rapidgator.net/auth/login")
.setParameter("LoginForm[email]", pa.getUsername())
.setParameter("LoginForm[password]", pa.getPassword())
.setParameter("LoginForm[rememberMe]", "1")
.toPostMethod();
if (!makeRedirectedRequest(method)) {
throw new ServiceConnectionProblemException("Error posting login info");
}
if (getContentAsString().contains("Please fix the following input errors")) {
throw new BadLoginException("Invalid RapidGator account login information!");
}
}
}
}
\ No newline at end of file
diff --git a/src/rapidgator_premium/cz/vity/freerapid/plugins/services/rapidgator_premium/TestApp.java b/src/rapidgator_premium/cz/vity/freerapid/plugins/services/rapidgator_premium/TestApp.java
index 323b397f..29aab3a8 100644
--- a/src/rapidgator_premium/cz/vity/freerapid/plugins/services/rapidgator_premium/TestApp.java
+++ b/src/rapidgator_premium/cz/vity/freerapid/plugins/services/rapidgator_premium/TestApp.java
@@ -1,48 +1,48 @@
package cz.vity.freerapid.plugins.services.rapidgator_premium;
import cz.vity.freerapid.plugins.dev.PluginDevApplication;
import cz.vity.freerapid.plugins.webclient.ConnectionSettings;
import cz.vity.freerapid.plugins.webclient.hoster.PremiumAccount;
import cz.vity.freerapid.plugins.webclient.interfaces.HttpFile;
import org.jdesktop.application.Application;
import java.net.URL;
/**
* @author ntoskrnl
*/
public class TestApp extends PluginDevApplication {
@Override
protected void startup() {
final HttpFile httpFile = getHttpFile(); //creates new test instance of HttpFile
try {
//we set file URL
- httpFile.setNewURL(new URL("http://rapidgator.net/file/372677/Ajax-ManUtd.1st.part1.rar.html"));
+ httpFile.setNewURL(new URL("http://rapidgator.net/file/53570013/asd.txt.html"));
//the way we connect to the internet
final ConnectionSettings connectionSettings = new ConnectionSettings();// creates default connection
//connectionSettings.setProxy("localhost", 8081); //eg we can use local proxy to sniff HTTP communication
//then we tries to download
final RapidGatorServiceImpl service = new RapidGatorServiceImpl(); //instance of service - of our plugin
final PremiumAccount config = new PremiumAccount();
config.setUsername("***");
config.setPassword("***");
service.setConfig(config);
//runcheck makes the validation
testRun(service, httpFile, connectionSettings);//download file with service and its Runner
//all output goes to the console
} catch (Exception e) {//catch possible exception
e.printStackTrace(); //writes error output - stack trace to console
}
this.exit();//exit application
}
/**
* Main start method for running this application
* Called from IDE
*
* @param args arguments for application
*/
public static void main(String[] args) {
Application.launch(TestApp.class, args);//starts the application - calls startup() internally
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/sandbox-providers/trmk-enterprisecloud/src/main/java/org/jclouds/trmk/enterprisecloud/TerremarkEnterpriseCloudPropertiesBuilder.java b/sandbox-providers/trmk-enterprisecloud/src/main/java/org/jclouds/trmk/enterprisecloud/TerremarkEnterpriseCloudPropertiesBuilder.java
index 8c50bb1a92..cdf78549e2 100644
--- a/sandbox-providers/trmk-enterprisecloud/src/main/java/org/jclouds/trmk/enterprisecloud/TerremarkEnterpriseCloudPropertiesBuilder.java
+++ b/sandbox-providers/trmk-enterprisecloud/src/main/java/org/jclouds/trmk/enterprisecloud/TerremarkEnterpriseCloudPropertiesBuilder.java
@@ -1,47 +1,46 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.trmk.enterprisecloud;
import static org.jclouds.Constants.PROPERTY_API_VERSION;
import static org.jclouds.Constants.PROPERTY_ENDPOINT;
import java.util.Properties;
import org.jclouds.PropertiesBuilder;
/**
* Builds properties used in TerremarkEnterpriseCloud Clients
*
* @author Adrian Cole
*/
public class TerremarkEnterpriseCloudPropertiesBuilder extends PropertiesBuilder {
@Override
protected Properties defaultProperties() {
Properties properties = super.defaultProperties();
- // TODO replace with the actual rest url
- properties.setProperty(PROPERTY_ENDPOINT, "http://209.251.187.125/livespec");
+ properties.setProperty(PROPERTY_ENDPOINT, "https://services-beta.enterprisecloud.terremark.com/cloudapi");
properties.setProperty(PROPERTY_API_VERSION, "2011-07-01");
return properties;
}
public TerremarkEnterpriseCloudPropertiesBuilder(Properties properties) {
super(properties);
}
}
diff --git a/sandbox-providers/trmk-enterprisecloud/src/test/java/org/jclouds/trmk/enterprisecloud/features/BaseTerremarkEnterpriseCloudClientLiveTest.java b/sandbox-providers/trmk-enterprisecloud/src/test/java/org/jclouds/trmk/enterprisecloud/features/BaseTerremarkEnterpriseCloudClientLiveTest.java
index d51c6d13fc..27bc89286e 100644
--- a/sandbox-providers/trmk-enterprisecloud/src/test/java/org/jclouds/trmk/enterprisecloud/features/BaseTerremarkEnterpriseCloudClientLiveTest.java
+++ b/sandbox-providers/trmk-enterprisecloud/src/test/java/org/jclouds/trmk/enterprisecloud/features/BaseTerremarkEnterpriseCloudClientLiveTest.java
@@ -1,65 +1,67 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.trmk.enterprisecloud.features;
import java.util.Properties;
+import org.jclouds.compute.BaseVersionedServiceLiveTest;
import org.jclouds.logging.log4j.config.Log4JLoggingModule;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.RestContextFactory;
import org.jclouds.sshj.config.SshjSshClientModule;
import org.jclouds.trmk.enterprisecloud.TerremarkEnterpriseCloudAsyncClient;
import org.jclouds.trmk.enterprisecloud.TerremarkEnterpriseCloudClient;
import org.testng.annotations.AfterGroups;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Module;
/**
* Tests behavior of {@code TerremarkEnterpriseCloudClient}
*
* @author Adrian Cole
*/
@Test(groups = "live")
-public class BaseTerremarkEnterpriseCloudClientLiveTest {
+public class BaseTerremarkEnterpriseCloudClientLiveTest extends BaseVersionedServiceLiveTest {
protected RestContext<TerremarkEnterpriseCloudClient, TerremarkEnterpriseCloudAsyncClient> context;
protected Module module;
+ public BaseTerremarkEnterpriseCloudClientLiveTest() {
+ provider = "trmk-enterprisecloud";
+ }
+
@BeforeGroups(groups = { "live" })
public void setupClient() {
- // TODO organize this like other compute tests
- String identity = System.getProperty("test.trmk-enterprisecloud.identity", "[email protected]");
- String credential = System.getProperty("test.trmk-enterprisecloud.credential", "T3rr3m@rk");
-
- Properties props = new Properties();
+ setupCredentials();
+ Properties overrides = setupProperties();
- context = new RestContextFactory().createContext("trmk-enterprisecloud", identity, credential,
- ImmutableSet.<Module> of(new Log4JLoggingModule(), new SshjSshClientModule()), props);
+ context = new RestContextFactory().createContext(provider, identity, credential,
+ ImmutableSet.<Module> of(new Log4JLoggingModule(), new SshjSshClientModule()), overrides);
}
@AfterGroups(groups = "live")
protected void tearDown() {
if (context != null)
context.close();
}
}
diff --git a/sandbox-providers/trmk-enterprisecloud/src/test/java/org/jclouds/trmk/enterprisecloud/features/TaskClientLiveTest.java b/sandbox-providers/trmk-enterprisecloud/src/test/java/org/jclouds/trmk/enterprisecloud/features/TaskClientLiveTest.java
index 09cd937d64..775266d59c 100644
--- a/sandbox-providers/trmk-enterprisecloud/src/test/java/org/jclouds/trmk/enterprisecloud/features/TaskClientLiveTest.java
+++ b/sandbox-providers/trmk-enterprisecloud/src/test/java/org/jclouds/trmk/enterprisecloud/features/TaskClientLiveTest.java
@@ -1,59 +1,59 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.trmk.enterprisecloud.features;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.util.Set;
import org.jclouds.trmk.enterprisecloud.domain.Task;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;
/**
* Tests behavior of {@code TaskClient}
*
* @author Adrian Cole
*/
@Test(groups = "live", testName = "TaskClientLiveTest")
public class TaskClientLiveTest extends BaseTerremarkEnterpriseCloudClientLiveTest {
@BeforeGroups(groups = { "live" })
public void setupClient() {
super.setupClient();
client = context.getApi().getTaskClient();
}
private TaskClient client;
@Test
public void testGetTasks() {
// TODO: don't hard-code id
// TODO: docs say don't parse the href, yet no xml includes "identifier",
// I suspect we may need to change to URI args as opposed to long
- Set<Task> response = client.getTasksInEnvironment(1);
+ Set<Task> response = client.getTasksInEnvironment(77);
assert null != response;
assertTrue(response.size() >= 0);
for (Task task : response) {
assertEquals(client.getTask(task.getHref()), task);
assert task.getStatus() != Task.Status.UNRECOGNIZED : response;
}
}
}
| false | false | null | null |
diff --git a/src/nl/PAINt/OptiesPanel.java b/src/nl/PAINt/OptiesPanel.java
index 70bb9ef..f1c7a94 100644
--- a/src/nl/PAINt/OptiesPanel.java
+++ b/src/nl/PAINt/OptiesPanel.java
@@ -1,150 +1,141 @@
/**
* PAINt
*
* Created for the course intro Human-Computer Interaction at the
* Radboud Universiteit Nijmegen
*
* 2013
*/
package nl.PAINt;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.colorchooser.AbstractColorChooserPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* @author Luuk Scholten & Thom Wiggers
*
*/
-public class OptiesPanel extends JPanel implements ChangeListener {
+public class OptiesPanel extends JPanel {
/**
*
*/
private static final long serialVersionUID = -8647274997122730322L;
private CanvasPanel canvas;
private JColorChooser colorPicker;
/**
* @param canvas
*
*/
public OptiesPanel(CanvasPanel theCanvas) {
canvas = theCanvas;
setBackground(Color.black);
setPreferredSize(new Dimension(450, canvas.getHeight()));
this.setLayout(new GridLayout(3, 1));
+ initColorPicker();
+
+ }
+
+ private void initColorPicker() {
colorPicker = new JColorChooser();
- // colorPicker.getSelectionModel().addChangeListener(this);
PreviewPanel pp = new PreviewPanel();
colorPicker.getSelectionModel().addChangeListener(pp);
colorPicker.setPreviewPanel(pp);
boolean skipped = false;
for (AbstractColorChooserPanel panel : colorPicker.getChooserPanels()) {
if (!skipped) {
skipped = true;
continue;
} else
colorPicker.removeChooserPanel(panel);
}
this.add(colorPicker);
}
- /*
- * (non-Javadoc)
- *
- * @see
- * javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent
- * )
- */
- @Override
- public void stateChanged(ChangeEvent arg0) {
- canvas.setColor(colorPicker.getColor());
-
- }
-
- public class PreviewPanel extends JPanel implements ChangeListener,
+ protected class PreviewPanel extends JPanel implements ChangeListener,
ActionListener {
/**
*
*/
private static final long serialVersionUID = 3445719326561602037L;
private JLabel label;
private JPanel block;
public PreviewPanel() {
super();
this.setLayout(new GridLayout(0, 2));
setPreferredSize(new Dimension(400, 100));
setSize(getPreferredSize());
label = new JLabel("Huidige Kleur:");
label.setBackground(Color.blue);
label.setSize(getPreferredSize());
label.setVisible(true);
this.block = new JPanel();
block.setSize(80, 80);
block.setBackground(colorPicker.getColor());
JButton knopjeFill = new JButton("Gebruik als Fill");
knopjeFill.setActionCommand("FILL");
knopjeFill.addActionListener(this);
JButton knopjeLijn = new JButton("Gebruik als Lijn");
knopjeLijn.setActionCommand("LIJN");
knopjeLijn.addActionListener(this);
add(label);
add(block);
add(knopjeFill);
add(knopjeLijn);
}
/*
* (non-Javadoc)
*
* @see
* javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent
* )
*/
@Override
public void stateChanged(ChangeEvent e) {
block.setBackground(colorPicker.getColor());
}
/*
* (non-Javadoc)
*
* @see
* java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
@Override
public void actionPerformed(ActionEvent arg0) {
switch (arg0.getActionCommand()) {
case "FILL":
canvas.setColor(colorPicker.getColor());
break;
case "LIJN":
canvas.setLineColor(colorPicker.getColor());
break;
default:
throw new IllegalArgumentException("WAT");
}
}
}
}
diff --git a/src/nl/PAINt/shapes/Triangle.java b/src/nl/PAINt/shapes/Triangle.java
index 0ebb373..8868c0d 100644
--- a/src/nl/PAINt/shapes/Triangle.java
+++ b/src/nl/PAINt/shapes/Triangle.java
@@ -1,157 +1,157 @@
package nl.PAINt.shapes;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.geom.Rectangle2D;
public class Triangle implements Shape {
Point p1, p2, p3;
private boolean selected;
private Point lockedCorner;
private Color color;
private Color lineColor;
private boolean isFilled;
public Triangle(Point p1, Point p2, Point p3, boolean filled) {
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
this.selected = false;
this.isFilled = filled;
}
@Override
public void draw(Graphics2D g2d) {
int[] x = { p1.x, p2.x, p3.x };
int[] y = { p1.y, p2.y, p3.y };
Polygon p = new Polygon(x, y, 3);
if (isFilled) {
g2d.setPaint(color);
g2d.fill(p);
}
g2d.setPaint(lineColor);
g2d.setStroke(new BasicStroke(3.0f));
g2d.drawPolygon(p);
if (this.selected) {
this.drawSelectionBox(g2d);
}
}
private void drawSelectionBox(Graphics2D g2d) {
int[] x = { p1.x, p2.x, p3.x };
int[] y = { p1.y, p2.y, p3.y };
Polygon p = new Polygon(x, y, 3);
g2d.setPaint(Color.BLACK);
final float dash[] = { 7.0f };
g2d.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10.0f, dash, 0.0f));
g2d.drawPolygon(p);
- g2d.setPaint(color);
+ g2d.setPaint(Color.blue);
g2d.setStroke(new BasicStroke(0.0f));
Rectangle2D r2d = new Rectangle2D.Double(p1.x - 5, p1.y - 5, 10, 10);
g2d.fill(r2d);
r2d = new Rectangle2D.Double(p2.x - 5, p2.y - 5, 10, 10);
g2d.fill(r2d);
r2d = new Rectangle2D.Double(p3.x - 5, p3.y - 5, 10, 10);
g2d.fill(r2d);
}
public void setLastPoint(Point p) {
this.p3 = p;
}
public void setSecondPoint(Point p) {
this.p2 = p;
}
@Override
public boolean checkHit(Point point) {
int[] x = { p1.x, p2.x, p3.x };
int[] y = { p1.y, p2.y, p3.y };
Polygon p = new Polygon(x, y, 3);
return p.contains(point);
}
@Override
public void setSelectionBox(boolean bool) {
this.selected = bool;
}
@Override
public void move(double dx, double dy) {
int dxx = (int) dx;
int dyy = (int) dy;
this.p1 = movePoint(p1, dxx, dyy);
this.p2 = movePoint(p2, dxx, dyy);
this.p3 = movePoint(p3, dxx, dyy);
}
private Point movePoint(Point p, int dx, int dy) {
return new Point(p.x + dx, p.y + dy);
}
public void moveCorner(Point point) {
this.lockedCorner.x = point.x;
this.lockedCorner.y = point.y;
}
@Override
public boolean lockCorner(Point p) {
if (p.x >= p1.x - 5 && p.x <= p1.x + 5 && p.y >= p1.y - 5
&& p.y <= p1.y + 5) {
lockedCorner = p1;
return true;
}
if (p.x >= p2.x - 5 && p.x <= p2.x + 5 && p.y >= p2.y - 5
&& p.y <= p2.y + 5) {
lockedCorner = p2;
return true;
}
if (p.x >= p3.x - 5 && p.x <= p3.x + 5 && p.y >= p3.y - 5
&& p.y <= p3.y + 5) {
lockedCorner = p3;
return true;
}
return false;
}
@Override
public void unlockCorner() {
lockedCorner = null;
}
/*
* (non-Javadoc)
*
* @see nl.PAINt.shapes.Shape#setColor(java.awt.Color)
*/
@Override
public void setColor(Color color) {
this.color = color;
}
/*
* (non-Javadoc)
*
* @see nl.PAINt.shapes.Shape#setLineColor(java.awt.Color)
*/
@Override
public void setLineColor(Color color) {
this.lineColor = color;
}
}
| false | false | null | null |
diff --git a/src/java/simpledb/Join.java b/src/java/simpledb/Join.java
index f43c750..5876b79 100644
--- a/src/java/simpledb/Join.java
+++ b/src/java/simpledb/Join.java
@@ -1,181 +1,183 @@
package simpledb;
import java.util.*;
/**
* The Join operator implements the relational join operation.
*/
public class Join extends Operator {
private static final long serialVersionUID = 1L;
/**
* Constructor. Accepts to children to join and the predicate to join them
* on
*
* @param p
* The predicate to use to join the children
* @param child1
* Iterator for the left(outer) relation to join
* @param child2
* Iterator for the right(inner) relation to join
*/
JoinPredicate preHolder;
DbIterator[] holder;
Tuple hold;
int nullCounter;
public Join(JoinPredicate p, DbIterator child1, DbIterator child2) {
// some code goes here
preHolder=p;
holder=new DbIterator[2];
holder[0]=child1;
holder[1]=child2;
}
public JoinPredicate getJoinPredicate() {
// some code goes here
return preHolder;
}
/**
* @return
* the field name of join field1. Should be quantified by
* alias or table name.
* */
public String getJoinField1Name() {
// some code goes here
String result="";
TupleDesc td=holder[0].getTupleDesc();
int bound=td.numFields();
for(int i=0;i<bound;i++){
result+=td.getFieldName(i);
}
return result;
}
/**
* @return
* the field name of join field2. Should be quantified by
* alias or table name.
* */
public String getJoinField2Name() {
// some code goes here
String result="";
TupleDesc td=holder[1].getTupleDesc();
int bound=td.numFields();
for(int i=0;i<bound;i++){
result+=td.getFieldName(i);
}
return result;
}
/**
* @see simpledb.TupleDesc#merge(TupleDesc, TupleDesc) for possible
* implementation logic.
*/
public TupleDesc getTupleDesc() {
// some code goes here
return simpledb.TupleDesc.merge(holder[0].getTupleDesc(),holder[1].getTupleDesc());
}
public void open() throws DbException, NoSuchElementException,
TransactionAbortedException {
// some code goes here
holder[0].open();
holder[1].open();
hold=null;
super.open();
nullCounter=0;
}
public void close() {
// some code goes here
holder[0].close();
holder[1].close();
super.close();
}
public void rewind() throws DbException, TransactionAbortedException {
// some code goes here
holder[0].rewind();
holder[1].rewind();
hold=null;
nullCounter=0;
}
/**
* Returns the next tuple generated by the join, or null if there are no
* more tuples. Logically, this is the next tuple in r1 cross r2 that
* satisfies the join predicate. There are many possible implementations;
* the simplest is a nested loops join.
* <p>
* Note that the tuples returned from this particular implementation of Join
* are simply the concatenation of joining tuples from the left and right
* relation. Therefore, if an equality predicate is used there will be two
* copies of the join attribute in the results. (Removing such duplicate
* columns can be done with an additional projection operator if needed.)
* <p>
* For example, if one tuple is {1,2,3} and the other tuple is {1,5,6},
* joined on equality of the first column, then this returns {1,2,3,1,5,6}.
*
* @return The next matching tuple.
* @see JoinPredicate#filter
*/
protected Tuple fetchNext() throws TransactionAbortedException, DbException {
// some code goes here
Tuple x=hold;
if(x==null && holder[0].hasNext()){
x=holder[0].next();
holder[1].rewind();
}
-
+ if(x==null && !holder[0].hasNext()){
+ return null;
+ }
while(nullCounter<1){
while(holder[1].hasNext()){
Tuple y=holder[1].next();
if(preHolder.filter(x,y)){
Tuple result= new Tuple(getTupleDesc());
int bound=getTupleDesc().numFields();
int first=x.getTupleDesc().numFields();
int second=y.getTupleDesc().numFields();
for(int i=0;i<bound;i++){
if(i<first){
result.setField(i,x.getField(i));
} else {
result.setField(i,y.getField(i-first));
}
}
hold=x;
return result;
}
}
holder[1].rewind();
if(holder[0].hasNext()){
x=holder[0].next();
hold=x;
} else {
nullCounter++;
}
}
hold=null;
return null;
}
@Override
public DbIterator[] getChildren() {
// some code goes here
return holder;
}
@Override
public void setChildren(DbIterator[] children) {
// some code goes here
holder[0]=children[0];
holder[1]=children[1];
}
}
| true | false | null | null |
diff --git a/core/src/main/java/org/apache/hadoop/hbase/ipc/HBaseClient.java b/core/src/main/java/org/apache/hadoop/hbase/ipc/HBaseClient.java
index a935c21b3..7e1de8dec 100644
--- a/core/src/main/java/org/apache/hadoop/hbase/ipc/HBaseClient.java
+++ b/core/src/main/java/org/apache/hadoop/hbase/ipc/HBaseClient.java
@@ -1,878 +1,888 @@
/**
* Copyright 2010 The Apache Software Foundation
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.ipc;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.ObjectWritable;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableUtils;
import org.apache.hadoop.ipc.RemoteException;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.ReflectionUtils;
import javax.net.SocketFactory;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
/** A client for an IPC service. IPC calls take a single {@link Writable} as a
* parameter, and return a {@link Writable} as their value. A service runs on
* a port and is defined by a parameter class and a value class.
*
* <p>This is the org.apache.hadoop.ipc.Client renamed as HBaseClient and
* moved into this package so can access package-private methods.
*
* @see HBaseServer
*/
public class HBaseClient {
private static final Log LOG =
LogFactory.getLog("org.apache.hadoop.ipc.HBaseClient");
protected final Hashtable<ConnectionId, Connection> connections =
new Hashtable<ConnectionId, Connection>();
protected final Class<? extends Writable> valueClass; // class of call values
protected int counter; // counter for call ids
protected final AtomicBoolean running = new AtomicBoolean(true); // if client runs
final protected Configuration conf;
final protected int maxIdleTime; // connections will be culled if it was idle for
// maxIdleTime microsecs
final protected int maxRetries; //the max. no. of retries for socket connections
final protected long failureSleep; // Time to sleep before retry on failure.
protected final boolean tcpNoDelay; // if T then disable Nagle's Algorithm
protected final boolean tcpKeepAlive; // if T then use keepalives
protected final int pingInterval; // how often sends ping to the server in msecs
protected final SocketFactory socketFactory; // how to create sockets
private int refCount = 1;
final private static String PING_INTERVAL_NAME = "ipc.ping.interval";
final static int DEFAULT_PING_INTERVAL = 60000; // 1 min
final static int PING_CALL_ID = -1;
/**
* set the ping interval value in configuration
*
* @param conf Configuration
* @param pingInterval the ping interval
*/
@SuppressWarnings({"UnusedDeclaration"})
public static void setPingInterval(Configuration conf, int pingInterval) {
conf.setInt(PING_INTERVAL_NAME, pingInterval);
}
/**
* Get the ping interval from configuration;
* If not set in the configuration, return the default value.
*
* @param conf Configuration
* @return the ping interval
*/
static int getPingInterval(Configuration conf) {
return conf.getInt(PING_INTERVAL_NAME, DEFAULT_PING_INTERVAL);
}
/**
* Increment this client's reference count
*
*/
synchronized void incCount() {
refCount++;
}
/**
* Decrement this client's reference count
*
*/
synchronized void decCount() {
refCount--;
}
/**
* Return if this client has no reference
*
* @return true if this client has no reference; false otherwise
*/
synchronized boolean isZeroReference() {
return refCount==0;
}
/** A call waiting for a value. */
private class Call {
final int id; // call id
final Writable param; // parameter
Writable value; // value, null if error
IOException error; // exception, null if value
boolean done; // true when call is done
protected Call(Writable param) {
this.param = param;
synchronized (HBaseClient.this) {
this.id = counter++;
}
}
/** Indicate when the call is complete and the
* value or error are available. Notifies by default. */
protected synchronized void callComplete() {
this.done = true;
notify(); // notify caller
}
/** Set the exception when there is an error.
* Notify the caller the call is done.
*
* @param error exception thrown by the call; either local or remote
*/
public synchronized void setException(IOException error) {
this.error = error;
callComplete();
}
/** Set the return value when there is no error.
* Notify the caller the call is done.
*
* @param value return value of the call.
*/
public synchronized void setValue(Writable value) {
this.value = value;
callComplete();
}
}
/** Thread that reads responses and notifies callers. Each connection owns a
* socket connected to a remote address. Calls are multiplexed through this
* socket: responses may be delivered out of order. */
private class Connection extends Thread {
private ConnectionId remoteId;
private Socket socket = null; // connected socket
private DataInputStream in;
private DataOutputStream out;
// currently active calls
private final Hashtable<Integer, Call> calls = new Hashtable<Integer, Call>();
private final AtomicLong lastActivity = new AtomicLong();// last I/O activity time
protected final AtomicBoolean shouldCloseConnection = new AtomicBoolean(); // indicate if the connection is closed
private IOException closeException; // close reason
public Connection(InetSocketAddress address) throws IOException {
this(new ConnectionId(address, null));
}
public Connection(ConnectionId remoteId) throws IOException {
if (remoteId.getAddress().isUnresolved()) {
throw new UnknownHostException("unknown host: " +
remoteId.getAddress().getHostName());
}
this.remoteId = remoteId;
UserGroupInformation ticket = remoteId.getTicket();
this.setName("IPC Client (" + socketFactory.hashCode() +") connection to " +
remoteId.getAddress().toString() +
((ticket==null)?" from an unknown user": (" from " + ticket.getUserName())));
this.setDaemon(true);
}
/** Update lastActivity with the current time. */
private void touch() {
lastActivity.set(System.currentTimeMillis());
}
/**
* Add a call to this connection's call queue and notify
* a listener; synchronized.
* Returns false if called during shutdown.
* @param call to add
* @return true if the call was added.
*/
protected synchronized boolean addCall(Call call) {
if (shouldCloseConnection.get())
return false;
calls.put(call.id, call);
notify();
return true;
}
/** This class sends a ping to the remote side when timeout on
* reading. If no failure is detected, it retries until at least
* a byte is read.
*/
private class PingInputStream extends FilterInputStream {
/* constructor */
protected PingInputStream(InputStream in) {
super(in);
}
/* Process timeout exception
* if the connection is not going to be closed, send a ping.
* otherwise, throw the timeout exception.
*/
private void handleTimeout(SocketTimeoutException e) throws IOException {
if (shouldCloseConnection.get() || !running.get()) {
throw e;
}
sendPing();
}
/** Read a byte from the stream.
* Send a ping if timeout on read. Retries if no failure is detected
* until a byte is read.
* @throws IOException for any IO problem other than socket timeout
*/
@Override
public int read() throws IOException {
do {
try {
return super.read();
} catch (SocketTimeoutException e) {
handleTimeout(e);
}
} while (true);
}
/** Read bytes into a buffer starting from offset <code>off</code>
* Send a ping if timeout on read. Retries if no failure is detected
* until a byte is read.
*
* @return the total number of bytes read; -1 if the connection is closed.
*/
@Override
public int read(byte[] buf, int off, int len) throws IOException {
do {
try {
return super.read(buf, off, len);
} catch (SocketTimeoutException e) {
handleTimeout(e);
}
} while (true);
}
}
/** Connect to the server and set up the I/O streams. It then sends
* a header to the server and starts
* the connection thread that waits for responses.
* @throws java.io.IOException e
*/
protected synchronized void setupIOstreams() throws IOException {
if (socket != null || shouldCloseConnection.get()) {
return;
}
short ioFailures = 0;
short timeoutFailures = 0;
try {
if (LOG.isDebugEnabled()) {
LOG.debug("Connecting to "+remoteId.getAddress());
}
while (true) {
try {
this.socket = socketFactory.createSocket();
this.socket.setTcpNoDelay(tcpNoDelay);
this.socket.setKeepAlive(tcpKeepAlive);
// connection time out is 20s
NetUtils.connect(this.socket, remoteId.getAddress(), 20000);
this.socket.setSoTimeout(pingInterval);
break;
} catch (SocketTimeoutException toe) {
handleConnectionFailure(timeoutFailures++, maxRetries, toe);
} catch (IOException ie) {
handleConnectionFailure(ioFailures++, maxRetries, ie);
}
}
this.in = new DataInputStream(new BufferedInputStream
(new PingInputStream(NetUtils.getInputStream(socket))));
this.out = new DataOutputStream
(new BufferedOutputStream(NetUtils.getOutputStream(socket)));
writeHeader();
// update last activity time
touch();
// start the receiver thread after the socket connection has been set up
start();
} catch (IOException e) {
markClosed(e);
close();
throw e;
}
}
/* Handle connection failures
*
* If the current number of retries is equal to the max number of retries,
* stop retrying and throw the exception; Otherwise backoff N seconds and
* try connecting again.
*
* This Method is only called from inside setupIOstreams(), which is
* synchronized. Hence the sleep is synchronized; the locks will be retained.
*
* @param curRetries current number of retries
* @param maxRetries max number of retries allowed
* @param ioe failure reason
* @throws IOException if max number of retries is reached
*/
private void handleConnectionFailure(
int curRetries, int maxRetries, IOException ioe) throws IOException {
// close the current connection
try {
socket.close();
} catch (IOException e) {
LOG.warn("Not able to close a socket", e);
}
// set socket to null so that the next call to setupIOstreams
// can start the process of connect all over again.
socket = null;
// throw the exception if the maximum number of retries is reached
if (curRetries >= maxRetries) {
throw ioe;
}
// otherwise back off and retry
try {
Thread.sleep(failureSleep);
} catch (InterruptedException ignored) {}
LOG.info("Retrying connect to server: " + remoteId.getAddress() +
" after sleeping " + failureSleep + "ms. Already tried " + curRetries +
" time(s).");
}
/* Write the header for each connection
* Out is not synchronized because only the first thread does this.
*/
private void writeHeader() throws IOException {
out.write(HBaseServer.HEADER.array());
out.write(HBaseServer.CURRENT_VERSION);
//When there are more fields we can have ConnectionHeader Writable.
DataOutputBuffer buf = new DataOutputBuffer();
ObjectWritable.writeObject(buf, remoteId.getTicket(),
UserGroupInformation.class, conf);
int bufLen = buf.getLength();
out.writeInt(bufLen);
out.write(buf.getData(), 0, bufLen);
}
/* wait till someone signals us to start reading RPC response or
* it is idle too long, it is marked as to be closed,
* or the client is marked as not running.
*
* Return true if it is time to read a response; false otherwise.
*/
@SuppressWarnings({"ThrowableInstanceNeverThrown"})
private synchronized boolean waitForWork() {
if (calls.isEmpty() && !shouldCloseConnection.get() && running.get()) {
long timeout = maxIdleTime-
(System.currentTimeMillis()-lastActivity.get());
if (timeout>0) {
try {
wait(timeout);
} catch (InterruptedException ignored) {}
}
}
if (!calls.isEmpty() && !shouldCloseConnection.get() && running.get()) {
return true;
} else if (shouldCloseConnection.get()) {
return false;
} else if (calls.isEmpty()) { // idle connection closed or stopped
markClosed(null);
return false;
} else { // get stopped but there are still pending requests
markClosed((IOException)new IOException().initCause(
new InterruptedException()));
return false;
}
}
public InetSocketAddress getRemoteAddress() {
return remoteId.getAddress();
}
/* Send a ping to the server if the time elapsed
* since last I/O activity is equal to or greater than the ping interval
*/
protected synchronized void sendPing() throws IOException {
long curTime = System.currentTimeMillis();
if ( curTime - lastActivity.get() >= pingInterval) {
lastActivity.set(curTime);
//noinspection SynchronizeOnNonFinalField
synchronized (this.out) {
out.writeInt(PING_CALL_ID);
out.flush();
}
}
}
@Override
public void run() {
if (LOG.isDebugEnabled())
LOG.debug(getName() + ": starting, having connections "
+ connections.size());
while (waitForWork()) {//wait here for work - read or close connection
receiveResponse();
}
close();
if (LOG.isDebugEnabled())
LOG.debug(getName() + ": stopped, remaining connections "
+ connections.size());
}
/* Initiates a call by sending the parameter to the remote server.
* Note: this is not called from the Connection thread, but by other
* threads.
*/
protected void sendParam(Call call) {
if (shouldCloseConnection.get()) {
return;
}
DataOutputBuffer d=null;
try {
//noinspection SynchronizeOnNonFinalField
synchronized (this.out) { // FindBugs IS2_INCONSISTENT_SYNC
if (LOG.isDebugEnabled())
LOG.debug(getName() + " sending #" + call.id);
//for serializing the
//data to be written
d = new DataOutputBuffer();
d.writeInt(call.id);
call.param.write(d);
byte[] data = d.getData();
int dataLength = d.getLength();
out.writeInt(dataLength); //first put the data length
out.write(data, 0, dataLength);//write the data
out.flush();
}
} catch(IOException e) {
markClosed(e);
} finally {
//the buffer is just an in-memory buffer, but it is still polite to
// close early
IOUtils.closeStream(d);
}
}
/* Receive a response.
* Because only one receiver, so no synchronization on in.
*/
private void receiveResponse() {
if (shouldCloseConnection.get()) {
return;
}
touch();
try {
int id = in.readInt(); // try to read an id
if (LOG.isDebugEnabled())
LOG.debug(getName() + " got value #" + id);
- Call call = calls.remove(id);
+ Call call = calls.get(id);
boolean isError = in.readBoolean(); // read if error
if (isError) {
//noinspection ThrowableInstanceNeverThrown
call.setException(new RemoteException( WritableUtils.readString(in),
WritableUtils.readString(in)));
} else {
Writable value = ReflectionUtils.newInstance(valueClass, conf);
value.readFields(in); // read value
call.setValue(value);
+ calls.remove(id);
}
} catch (IOException e) {
markClosed(e);
}
}
private synchronized void markClosed(IOException e) {
if (shouldCloseConnection.compareAndSet(false, true)) {
closeException = e;
notifyAll();
}
}
/** Close the connection. */
private synchronized void close() {
if (!shouldCloseConnection.get()) {
LOG.error("The connection is not in the closed state");
return;
}
// release the resources
// first thing to do;take the connection out of the connection list
synchronized (connections) {
if (connections.get(remoteId) == this) {
connections.remove(remoteId);
}
}
// close the streams and therefore the socket
IOUtils.closeStream(out);
IOUtils.closeStream(in);
// clean up all calls
if (closeException == null) {
if (!calls.isEmpty()) {
LOG.warn(
"A connection is closed for no cause and calls are not empty");
// clean up calls anyway
closeException = new IOException("Unexpected closed connection");
cleanupCalls();
}
} else {
// log the info
if (LOG.isDebugEnabled()) {
LOG.debug("closing ipc connection to " + remoteId.address + ": " +
closeException.getMessage(),closeException);
}
// cleanup calls
cleanupCalls();
}
if (LOG.isDebugEnabled())
LOG.debug(getName() + ": closed");
}
/* Cleanup all calls and mark them as done */
private void cleanupCalls() {
Iterator<Entry<Integer, Call>> itor = calls.entrySet().iterator() ;
while (itor.hasNext()) {
Call c = itor.next().getValue();
c.setException(closeException); // local exception
itor.remove();
}
}
}
/** Call implementation used for parallel calls. */
private class ParallelCall extends Call {
private final ParallelResults results;
protected final int index;
public ParallelCall(Writable param, ParallelResults results, int index) {
super(param);
this.results = results;
this.index = index;
}
/** Deliver result to result collector. */
@Override
protected void callComplete() {
results.callComplete(this);
}
}
/** Result collector for parallel calls. */
private static class ParallelResults {
protected final Writable[] values;
protected int size;
protected int count;
public ParallelResults(int size) {
this.values = new Writable[size];
this.size = size;
}
/*
* Collect a result.
*/
synchronized void callComplete(ParallelCall call) {
// FindBugs IS2_INCONSISTENT_SYNC
values[call.index] = call.value; // store the value
count++; // count it
if (count == size) // if all values are in
notify(); // then notify waiting caller
}
}
/**
* Construct an IPC client whose values are of the given {@link Writable}
* class.
* @param valueClass value class
* @param conf configuration
* @param factory socket factory
*/
public HBaseClient(Class<? extends Writable> valueClass, Configuration conf,
SocketFactory factory) {
this.valueClass = valueClass;
this.maxIdleTime =
conf.getInt("hbase.ipc.client.connection.maxidletime", 10000); //10s
this.maxRetries = conf.getInt("hbase.ipc.client.connect.max.retries", 0);
this.failureSleep = conf.getInt("hbase.client.pause", 2000);
this.tcpNoDelay = conf.getBoolean("hbase.ipc.client.tcpnodelay", false);
this.tcpKeepAlive = conf.getBoolean("hbase.ipc.client.tcpkeepalive", true);
this.pingInterval = getPingInterval(conf);
if (LOG.isDebugEnabled()) {
LOG.debug("The ping interval is" + this.pingInterval + "ms.");
}
this.conf = conf;
this.socketFactory = factory;
}
/**
* Construct an IPC client with the default SocketFactory
* @param valueClass value class
* @param conf configuration
*/
public HBaseClient(Class<? extends Writable> valueClass, Configuration conf) {
this(valueClass, conf, NetUtils.getDefaultSocketFactory(conf));
}
/** Return the socket factory of this client
*
* @return this client's socket factory
*/
SocketFactory getSocketFactory() {
return socketFactory;
}
/** Stop all threads related to this client. No further calls may be made
* using this client. */
public void stop() {
if (LOG.isDebugEnabled()) {
LOG.debug("Stopping client");
}
if (!running.compareAndSet(true, false)) {
return;
}
// wake up all connections
synchronized (connections) {
for (Connection conn : connections.values()) {
conn.interrupt();
}
}
// wait until all connections are closed
while (!connections.isEmpty()) {
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
}
}
/** Make a call, passing <code>param</code>, to the IPC server running at
* <code>address</code>, returning the value. Throws exceptions if there are
* network problems or if the remote code threw an exception.
* @param param writable parameter
* @param address network address
* @return Writable
* @throws IOException e
*/
public Writable call(Writable param, InetSocketAddress address)
throws IOException {
return call(param, address, null);
}
public Writable call(Writable param, InetSocketAddress addr,
UserGroupInformation ticket)
throws IOException {
Call call = new Call(param);
Connection connection = getConnection(addr, ticket, call);
connection.sendParam(call); // send the parameter
+ boolean interrupted = false;
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized (call) {
while (!call.done) {
try {
call.wait(); // wait for the result
- } catch (InterruptedException ignored) {}
+ } catch (InterruptedException ignored) {
+ // save the fact that we were interrupted
+ interrupted = true;
+ }
+ }
+
+ if (interrupted) {
+ // set the interrupt flag now that we are done waiting
+ Thread.currentThread().interrupt();
}
if (call.error != null) {
if (call.error instanceof RemoteException) {
call.error.fillInStackTrace();
throw call.error;
}
// local exception
throw wrapException(addr, call.error);
}
return call.value;
}
}
/**
* Take an IOException and the address we were trying to connect to
* and return an IOException with the input exception as the cause.
* The new exception provides the stack trace of the place where
* the exception is thrown and some extra diagnostics information.
* If the exception is ConnectException or SocketTimeoutException,
* return a new one of the same type; Otherwise return an IOException.
*
* @param addr target address
* @param exception the relevant exception
* @return an exception to throw
*/
@SuppressWarnings({"ThrowableInstanceNeverThrown"})
private IOException wrapException(InetSocketAddress addr,
IOException exception) {
if (exception instanceof ConnectException) {
//connection refused; include the host:port in the error
return (ConnectException)new ConnectException(
"Call to " + addr + " failed on connection exception: " + exception)
.initCause(exception);
} else if (exception instanceof SocketTimeoutException) {
return (SocketTimeoutException)new SocketTimeoutException(
"Call to " + addr + " failed on socket timeout exception: "
+ exception).initCause(exception);
} else {
return (IOException)new IOException(
"Call to " + addr + " failed on local exception: " + exception)
.initCause(exception);
}
}
/** Makes a set of calls in parallel. Each parameter is sent to the
* corresponding address. When all values are available, or have timed out
* or errored, the collected results are returned in an array. The array
* contains nulls for calls that timed out or errored.
* @param params writable parameters
* @param addresses socket addresses
* @return Writable[]
* @throws IOException e
*/
public Writable[] call(Writable[] params, InetSocketAddress[] addresses)
throws IOException {
if (addresses.length == 0) return new Writable[0];
ParallelResults results = new ParallelResults(params.length);
// TODO this synchronization block doesnt make any sense, we should possibly fix it
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized (results) {
for (int i = 0; i < params.length; i++) {
ParallelCall call = new ParallelCall(params[i], results, i);
try {
Connection connection = getConnection(addresses[i], null, call);
connection.sendParam(call); // send each parameter
} catch (IOException e) {
// log errors
LOG.info("Calling "+addresses[i]+" caught: " +
e.getMessage(),e);
results.size--; // wait for one fewer result
}
}
while (results.count != results.size) {
try {
results.wait(); // wait for all results
} catch (InterruptedException ignored) {}
}
return results.values;
}
}
/* Get a connection from the pool, or create a new one and add it to the
* pool. Connections to a given host/port are reused. */
private Connection getConnection(InetSocketAddress addr,
UserGroupInformation ticket,
Call call)
throws IOException {
if (!running.get()) {
// the client is stopped
throw new IOException("The client is stopped");
}
Connection connection;
/* we could avoid this allocation for each RPC by having a
* connectionsId object and with set() method. We need to manage the
* refs for keys in HashMap properly. For now its ok.
*/
ConnectionId remoteId = new ConnectionId(addr, ticket);
do {
synchronized (connections) {
connection = connections.get(remoteId);
if (connection == null) {
connection = new Connection(remoteId);
connections.put(remoteId, connection);
}
}
} while (!connection.addCall(call));
//we don't invoke the method below inside "synchronized (connections)"
//block above. The reason for that is if the server happens to be slow,
//it will take longer to establish a connection and that will slow the
//entire system down.
connection.setupIOstreams();
return connection;
}
/**
* This class holds the address and the user ticket. The client connections
* to servers are uniquely identified by <remoteAddress, ticket>
*/
private static class ConnectionId {
final InetSocketAddress address;
final UserGroupInformation ticket;
ConnectionId(InetSocketAddress address, UserGroupInformation ticket) {
this.address = address;
this.ticket = ticket;
}
InetSocketAddress getAddress() {
return address;
}
UserGroupInformation getTicket() {
return ticket;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ConnectionId) {
ConnectionId id = (ConnectionId) obj;
return address.equals(id.address) && ticket == id.ticket;
//Note : ticket is a ref comparision.
}
return false;
}
@Override
public int hashCode() {
return address.hashCode() ^ System.identityHashCode(ticket);
}
}
}
| false | false | null | null |
diff --git a/msv/test/batch/verifier/SchemaVerifySuite.java b/msv/test/batch/verifier/SchemaVerifySuite.java
index 578d7547..77e0444a 100644
--- a/msv/test/batch/verifier/SchemaVerifySuite.java
+++ b/msv/test/batch/verifier/SchemaVerifySuite.java
@@ -1,138 +1,143 @@
/*
* @(#)$Id$
*
* Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
*
* This software is the proprietary information of Sun Microsystems, Inc.
* Use is subject to license terms.
*
*/
package batch.verifier;
import batch.*;
import junit.framework.*;
import org.xml.sax.*;
import java.io.*;
import com.sun.msv.verifier.*;
import com.sun.msv.verifier.identity.IDConstraintChecker;
import com.sun.msv.verifier.util.VerificationErrorHandlerImpl;
import com.sun.msv.verifier.regexp.REDocumentDeclaration;
import com.sun.msv.reader.util.GrammarLoader;
import com.sun.msv.reader.util.IgnoreController;
import com.sun.msv.reader.dtd.DTDReader;
import com.sun.msv.grammar.trex.*;
import com.sun.msv.grammar.relax.*;
import com.sun.msv.grammar.*;
/**
* loads a schema and creates test case for every test instances.
*
* @author <a href="mailto:[email protected]">Kohsuke KAWAGUCHI</a>
*/
class SchemaVerifySuite extends batch.SchemaSuite {
SchemaVerifySuite( BatchVerifyTester parent, String schemaFileName ) {
super(parent,schemaFileName);
}
protected void createInstanceTestCase( String pathName, String fileName, TestSuite suite ) {
suite.addTest( new VerifyCase( fileName ) );
}
/** set by testLoadSchema method */
protected REDocumentDeclaration docDecl;
protected void runTest() throws Exception {
final String pathName = parent.dir + File.separatorChar + schemaFileName;
InputSource is = new InputSource(pathName);
is.setSystemId(pathName);
// load grammar
if( pathName.endsWith(".e"+parent.ext) ) {
- Grammar g = parent.loader.load( is, new IgnoreController(), parent.factory );
+ Grammar g = null;
+ try {
+ g = parent.loader.load( is, new ThrowErrorController(), parent.factory );
+ } catch( Error e ) {
+ System.out.println("schema:"+e.getMessage());
+ }
if( g!=null )
fail("unexpected result");
} else {
Grammar g = parent.loader.load( is, new ThrowErrorController(), parent.factory );
if( g==null )
fail("unexpected result"); // unexpected result
{// ensure that the serialization works
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(g);
oos.flush();
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream(bos.toByteArray()));
g = (Grammar)ois.readObject();
}
docDecl = new REDocumentDeclaration(g);
}
}
public static boolean xor( boolean a, boolean b ) {
return (a && !b) || (!a && b);
}
/** verifies one file */
class VerifyCase extends TestCase {
/** instance file name to be tested. */
public final String fileName;
public VerifyCase( String fileName ) {
super("testVerify("+fileName+")");
this.fileName = fileName;
}
protected void runTest() throws Exception {
if( docDecl==null )
fail("docDecl==null");
try {
ValidityViolation vv=null;
try {
XMLReader r =parent.factory.newSAXParser().getXMLReader();
Verifier v;
if( parent.target.equals("xsd") )
v = new IDConstraintChecker( docDecl, new VerificationErrorHandlerImpl() );
else
v = new Verifier( docDecl, new VerificationErrorHandlerImpl() );
r.setContentHandler(v);
r.parse( new InputSource(parent.dir+File.separatorChar+fileName) );
assert( v.isValid() );
} catch( ValidityViolation _vv ) {
vv = _vv;
}
// if(vv!=null) parent.report(vv);
final boolean supposedToBeValid = (fileName.indexOf(".v")!=-1);
if( xor( supposedToBeValid , vv==null ) ) {
if( vv!=null ) fail( vv.getMessage() );
else fail( "should be invalid" );
}
if( vv!=null )
System.out.println(vv.getMessage());
}
catch( SAXException se )
{
if( se.getException()!=null )
throw se.getException();
else
throw se;
}
}
}
}
| true | false | null | null |
diff --git a/databus-core/src/main/java/com/inmobi/databus/utils/CalendarHelper.java b/databus-core/src/main/java/com/inmobi/databus/utils/CalendarHelper.java
index d6afefdd..2ab4a042 100644
--- a/databus-core/src/main/java/com/inmobi/databus/utils/CalendarHelper.java
+++ b/databus-core/src/main/java/com/inmobi/databus/utils/CalendarHelper.java
@@ -1,166 +1,166 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.inmobi.databus.utils;
import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.apache.hadoop.fs.Path;
import org.apache.log4j.Logger;
public class CalendarHelper {
static Logger logger = Logger.getLogger(CalendarHelper.class);
static String minDirFormatStr = "yyyy" + File.separator + "MM" +
File.separator + "dd" + File.separator + "HH" + File.separator +"mm";
static final ThreadLocal<DateFormat> minDirFormat =
new ThreadLocal<DateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(minDirFormatStr);
}
};
// TODO - all date/time should be returned in a common time zone GMT
public static Date getDateFromStreamDir(Path streamDirPrefix, Path dir) {
String pathStr = dir.toString();
int startIndex = streamDirPrefix.toString().length() + 1;
/* logger.debug("StartIndex [" + startIndex + "] PathStr [" + pathStr
+"] endIndex [" + (startIndex + minDirFormatStr.length()) + "] length ["
+ pathStr.length() +"]");
*/
String dirString = pathStr.substring(startIndex,
startIndex + minDirFormatStr.length());
try {
return minDirFormat.get().parse(dirString);
} catch (ParseException e) {
logger.warn("Could not get date from directory passed", e);
}
return null;
}
public static Calendar getDate(String year, String month, String day) {
return new GregorianCalendar(new Integer(year).intValue(), new Integer(
month).intValue() - 1, new Integer(day).intValue());
}
public static Calendar getDate(Integer year, Integer month, Integer day) {
return new GregorianCalendar(year.intValue(), month.intValue() - 1,
day.intValue());
}
public static Calendar getDateHour(String year, String month, String day,
String hour) {
return new GregorianCalendar(new Integer(year).intValue(), new Integer(
month).intValue() - 1, new Integer(day).intValue(),
new Integer(hour).intValue(), new Integer(0));
}
public static Calendar getDateHourMinute(Integer year, Integer month,
Integer day, Integer hour, Integer minute) {
return new GregorianCalendar(year.intValue(), month.intValue() - 1,
day.intValue(), hour.intValue(), minute.intValue());
}
public static String getCurrentMinute() {
Calendar calendar;
calendar = new GregorianCalendar();
String minute = Integer.toString(calendar.get(Calendar.MINUTE));
return minute;
}
public static String getCurrentHour() {
Calendar calendar;
calendar = new GregorianCalendar();
String hour = Integer.toString(calendar.get(Calendar.HOUR_OF_DAY));
return hour;
}
public static Calendar getNowTime() {
return new GregorianCalendar();
}
private static String getCurrentDayTimeAsString(boolean includeMinute) {
return getDayTimeAsString(new GregorianCalendar(), includeMinute,
includeMinute);
}
private static String getDayTimeAsString(Calendar calendar,
boolean includeHour,
boolean includeMinute) {
String minute = null;
String hour = null;
String fileNameInnYYMMDDHRMNFormat = null;
String year = Integer.toString(calendar.get(Calendar.YEAR));
String month = Integer.toString(calendar.get(Calendar.MONTH) + 1);
String day = Integer.toString(calendar.get(Calendar.DAY_OF_MONTH));
if (includeHour || includeMinute) {
hour = Integer.toString(calendar.get(Calendar.HOUR_OF_DAY));
}
if (includeMinute) {
minute = Integer.toString(calendar.get(Calendar.MINUTE));
}
- if (includeHour) {
- fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day + "-" + hour;
- } else if (includeMinute) {
+ if (includeMinute) {
fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day + "-" + hour
+ "-" + minute;
+ } else if (includeHour) {
+ fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day + "-" + hour;
} else {
fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day;
}
logger.debug("getCurrentDayTimeAsString :: ["
+ fileNameInnYYMMDDHRMNFormat + "]");
return fileNameInnYYMMDDHRMNFormat;
}
public static String getCurrentDayTimeAsString() {
return getCurrentDayTimeAsString(true);
}
public static String getCurrentDayHourAsString() {
return getDayTimeAsString(new GregorianCalendar(), true, false);
}
public static String getCurrentDateAsString() {
return getCurrentDayTimeAsString(false);
}
public static String getDateAsString(Calendar calendar) {
return getDayTimeAsString(calendar, false, false);
}
public static String getDateTimeAsString(Calendar calendar) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
return format.format(calendar.getTime());
}
public static Calendar getDateTime(String dateTime) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
Calendar calendar = new GregorianCalendar();
try {
calendar.setTime(format.parse(dateTime));
} catch(Exception e){
}
return calendar;
}
}
| false | true | private static String getDayTimeAsString(Calendar calendar,
boolean includeHour,
boolean includeMinute) {
String minute = null;
String hour = null;
String fileNameInnYYMMDDHRMNFormat = null;
String year = Integer.toString(calendar.get(Calendar.YEAR));
String month = Integer.toString(calendar.get(Calendar.MONTH) + 1);
String day = Integer.toString(calendar.get(Calendar.DAY_OF_MONTH));
if (includeHour || includeMinute) {
hour = Integer.toString(calendar.get(Calendar.HOUR_OF_DAY));
}
if (includeMinute) {
minute = Integer.toString(calendar.get(Calendar.MINUTE));
}
if (includeHour) {
fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day + "-" + hour;
} else if (includeMinute) {
fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day + "-" + hour
+ "-" + minute;
} else {
fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day;
}
logger.debug("getCurrentDayTimeAsString :: ["
+ fileNameInnYYMMDDHRMNFormat + "]");
return fileNameInnYYMMDDHRMNFormat;
}
| private static String getDayTimeAsString(Calendar calendar,
boolean includeHour,
boolean includeMinute) {
String minute = null;
String hour = null;
String fileNameInnYYMMDDHRMNFormat = null;
String year = Integer.toString(calendar.get(Calendar.YEAR));
String month = Integer.toString(calendar.get(Calendar.MONTH) + 1);
String day = Integer.toString(calendar.get(Calendar.DAY_OF_MONTH));
if (includeHour || includeMinute) {
hour = Integer.toString(calendar.get(Calendar.HOUR_OF_DAY));
}
if (includeMinute) {
minute = Integer.toString(calendar.get(Calendar.MINUTE));
}
if (includeMinute) {
fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day + "-" + hour
+ "-" + minute;
} else if (includeHour) {
fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day + "-" + hour;
} else {
fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day;
}
logger.debug("getCurrentDayTimeAsString :: ["
+ fileNameInnYYMMDDHRMNFormat + "]");
return fileNameInnYYMMDDHRMNFormat;
}
|
diff --git a/ini/trakem2/utils/Utils.java b/ini/trakem2/utils/Utils.java
index 6de440a0..c5550241 100644
--- a/ini/trakem2/utils/Utils.java
+++ b/ini/trakem2/utils/Utils.java
@@ -1,1127 +1,1130 @@
/**
TrakEM2 plugin for ImageJ(C).
-Copyright (C) 2005,2006 Albert Cardona and Rodney Douglas.
+Copyright (C) 2005,2006,2007,2008 Albert Cardona and Rodney Douglas.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation (http://www.gnu.org/licenses/gpl.txt )
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
You may contact Albert Cardona at acardona at ini.phys.ethz.ch
Institute of Neuroinformatics, University of Zurich / ETH, Switzerland.
*/
package ini.trakem2.utils;
import ini.trakem2.ControlWindow;
import ini.trakem2.display.YesNoDialog;
import ini.trakem2.display.Layer;
import ini.trakem2.display.LayerSet;
import ini.trakem2.persistence.Loader;
import ini.trakem2.imaging.FloatProcessorT2;
import ij.IJ;
import ij.ImagePlus;
import ij.Menus;
import ij.WindowManager;
import ij.gui.GenericDialog;
import ij.gui.YesNoCancelDialog;
import ij.gui.Roi;
import ij.gui.ShapeRoi;
import ij.process.*;
import ij.io.*;
import ij.process.ImageProcessor;
import ij.process.ImageConverter;
import java.awt.Checkbox;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Component;
import java.awt.MenuBar;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Area;
import java.awt.Rectangle;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.*;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.MouseEvent;
import java.awt.Event;
import javax.swing.SwingUtilities;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
import java.util.Calendar;
import javax.vecmath.Point3f;
import javax.vecmath.Vector3f;
/** Utils class: stores generic widely used methods. In particular, those for logging text messages (for debugging) and also some math and memory utilities.
*
*
*/
public class Utils implements ij.plugin.PlugIn {
static public String version = "0.5u 2008-06-01";
static public boolean debug = false;
static public boolean debug_mouse = false;
static public boolean debug_sql = false;
static public boolean debug_event = false;
static public boolean debug_clip = false; //clip for repainting
static public boolean debug_thing = false;
/** The error to use in floating-point or double floating point literal comparisons. */
static public final double FL_ERROR = 0.0000001;
static public void debug(String msg) {
if (debug) IJ.log(msg);
}
static public void debugMouse(String msg) {
if (debug_mouse) IJ.log(msg);
}
/** Avoid waiting on the AWT thread repainting ImageJ's log window. */
static private class LogDispatcher extends Thread {
private final StringBuffer cache = new StringBuffer();
private boolean loading = false;
private boolean go = true;
public LogDispatcher() {
super("T2-Log-Dispatcher");
setPriority(Thread.NORM_PRIORITY);
try { setDaemon(true); } catch (Exception e) { e.printStackTrace(); }
start();
}
public final void quit() {
go = false;
synchronized (this) { notify(); }
}
public final void log(final String msg) {
try {
synchronized (cache) {
loading = true; // no need to synch, variable setting is atomic
if (0 != cache.length()) cache.append('\n');
cache.append(msg);
loading = false;
}
Thread.yield();
if (loading) return;
} catch (Exception e) {
e.printStackTrace();
}
try {
synchronized (this) { notify(); }
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
while (go) {
try {
synchronized (this) { wait(); }
synchronized (cache) {
if (0 != cache.length()) IJ.log(cache.toString());
cache.setLength(0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
static private LogDispatcher logger = new LogDispatcher();
/** Avoid waiting on the AWT thread repainting ImageJ's status bar.
Waits 100 ms before printing the status message; if too many status messages are being sent, the last one overrides all. */
static private final class StatusDispatcher extends Thread {
private String msg = null;
private boolean loading = false;
private boolean go = true;
private double progress = -1;
public StatusDispatcher() {
super("T2-Status-Dispatcher");
setPriority(Thread.NORM_PRIORITY);
try { setDaemon(true); } catch (Exception e) { e.printStackTrace(); }
start();
}
public final void quit() {
go = false;
synchronized (this) { notify(); }
}
public final void showStatus(final String msg) {
try {
synchronized (this) {
this.msg = msg;
notify();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public final void showProgress(final double progress) {
try {
synchronized (this) {
this.progress = progress;
notify();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
while (go) {
try {
// first part ensures it gets printed even if the notify was issued while not waiting
synchronized (this) {
if (null != msg) {
IJ.showStatus(msg);
msg = null;
}
if (-1 != progress) {
IJ.showProgress(progress);
progress = -1;
}
wait();
}
// allow some time for overwriting of messages
Thread.sleep(100);
/* // should not be needed
// print the msg if necessary
synchronized (this) {
if (null != msg) {
IJ.showStatus(msg);
msg = null;
}
}
*/
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
static private StatusDispatcher status = new StatusDispatcher();
/** Initialize house keeping threads. */
static public void setup(final ControlWindow master) { // the ControlWindow acts as a switch: nobody cna controls this because the CW constructor is private
if (null == status) status = new StatusDispatcher();
if (null == logger) logger = new LogDispatcher();
}
/** Destroy house keeping threads. */
static public void destroy(final ControlWindow master) {
if (null != status) { status.quit(); status = null; }
if (null != logger) { logger.quit(); logger = null; }
}
/** Intended for the user to see. */
static public void log(final String msg) {
if (ControlWindow.isGUIEnabled() && null != logger) {
logger.log(msg);
} else {
System.out.println(msg);
}
}
/** Print in all printable places: log window, System.out.println, and status bar.*/
static public void logAll(final String msg) {
if (!ControlWindow.isGUIEnabled()) {
System.out.println(msg);
return;
}
System.out.println(msg);
if (null != logger) logger.log(msg);
if (null != status) status.showStatus(msg);
}
/** Intended for developers: prints to terminal. */
static public void log2(String msg) {
System.out.println(msg);
}
static public void setDebug(boolean debug) {
Utils.debug = debug;
}
static public void setDebugMouse(boolean debug_mouse) {
Utils.debug_mouse = debug_mouse;
}
static public void setDebugSQL(boolean debug_sql) {
Utils.debug_sql = debug_sql;
}
+ /** Adjusting so that 0 is 3 o'clock, PI+PI/2 is 12 o'clock, PI is 9 o'clock, and PI/2 is 6 o'clock (why atan2 doesn't output angles this way? I remember I had the same problem for Pipe.java in the A_3D_editing plugin)
+ Using schemata in JavaAngles.ai as reference */
static public double fixAtan2Angle(double angle) {
- //Adjusting so that 0 is 3 o'clock, PI+PI/2 is 12 o'clock, PI is 9 o'clock, and PI/2 is 6 o'clock (why atan2 doesn't output angles this way? I remember I has the same problem for Pipe.java in the A_3D_editing plugin)
- //Using schemata in JavaAngles.ai as reference
double a = angle;
//fix too large angles
if (angle > 2*Math.PI) {
a = angle - 2*Math.PI;
}
//fix signs and shity oriented angle values given by atan2
if (a > 0.0 && a <= Math.PI/2) {
a = Math.PI/2 - a;
} else if (a <= 0.0 && a >= -Math.PI) {
a = Math.PI/2 - a; // minus because angle is negative
} else if (a > Math.PI/2 && a <= Math.PI ) {
a = Math.PI + Math.PI + (Math.PI/2 - a);
}
return a;
}
static public int count = 0;
/** Find out which method from which class called the method where the printCaller is used; for debugging purposes.*/
static public void printCaller(Object called_object) {
StackTraceElement[] elems = new Exception().getStackTrace();
if (elems.length < 3) {
log2("Stack trace too short! No useful info");
} else {
log2( "#### START TRACE ####\nObject " + called_object.getClass().getName() + " called at: " + elems[1].getFileName() + " " + elems[1].getLineNumber() + ": " + elems[1].getMethodName() + "()\n by: " + elems[2].getClassName() + " " + elems[2].getLineNumber() + ": " + elems[2].getMethodName() + "()");
log2("==== END ====");
}
}
static public void printCaller(Object called_object, int lines) {
StackTraceElement[] elems = new Exception().getStackTrace();
if (elems.length < 3) {
log2("Stack trace too short! No useful info");
} else {
log2( "#### START TRACE ####\nObject " + called_object.getClass().getName() + " called at: " + elems[1].getFileName() + " " + elems[1].getLineNumber() + ": " + elems[1].getMethodName() + "()\n by: " + elems[2].getClassName() + " " + elems[2].getLineNumber() + ": " + elems[2].getMethodName() + "()");
for (int i=3; i<lines+2 && i<elems.length; i++) {
log2("\tby: " + elems[i].getClassName() + " " + elems[i].getLineNumber() + ": " + elems[i].getMethodName() + "()");
}
log2("==== END ====");
}
}
static public String caller(Object called) {
StackTraceElement[] elems = new Exception().getStackTrace();
if (elems.length < 3) {
log2("Stack trace too short! No useful info");
return null;
} else {
return elems[2].getClassName();
}
}
/**Restore ImageJ's MenuBar*/
static public void restoreMenuBar() {
MenuBar menu_bar = Menus.getMenuBar();
final int n_menus = menu_bar.getMenuCount();
for (int i=0; i<n_menus;i++) {
Menu menu = menu_bar.getMenu(i);
restoreMenu(menu);
}
//make sure there isn't a null menu bar
//WindowManager.getCurrentWindow().setMenuBar(menu_bar);
}
static private void restoreMenu(final Menu menu) {
final int n_menuitems = menu.getItemCount();
for (int i=0; i<n_menuitems; i++) {
MenuItem menu_item = menu.getItem(i);
if (menu_item instanceof Menu) {
restoreMenu((Menu)menu_item);
}
menu_item.setEnabled(true);
}
}
static public void showMessage(String msg) {
if (!ControlWindow.isGUIEnabled()) System.out.println(msg);
else IJ.showMessage(msg);
}
/** Runs the showMessage in a separate Thread. */
static public void showMessageT(final String msg) {
new Thread() {
public void run() {
setPriority(Thread.NORM_PRIORITY);
Utils.showMessage(msg);
}
}.start();
}
static public final void showStatus(final String msg, final boolean focus) {
if (null == IJ.getInstance() || !ControlWindow.isGUIEnabled() || null == status) {
System.out.println(msg);
return;
}
if (focus) IJ.getInstance().toFront();
status.showStatus(msg);
}
static public final void showStatus(final String msg) {
showStatus(msg, true);
}
static private double last_progress = 0;
static private int last_percent = 0;
static public final void showProgress(final double p) {
//IJ.showProgress(p); // never happens, can't repaint even though they are different threads
if (null == IJ.getInstance() || !ControlWindow.isGUIEnabled() || null == status) {
if (0 == p) {
last_progress = 0; // reset
last_percent = 0;
return;
}
// don't show intervals smaller than 1%:
if (last_progress + 0.01 > p ) {
int percent = (int)(p * 100);
if (last_percent != percent) {
System.out.println(percent + " %");
last_percent = percent;
}
}
last_progress = p;
return;
}
status.showProgress(p);
}
static public void debugDialog() {
// note: all this could nicely be done using reflection, so adding another boolean variable would be automatically added here (filtering by the prefix "debug").
GenericDialog gd = new GenericDialog("Debug:");
gd.addCheckbox("debug", debug);
gd.addCheckbox("debug mouse", debug_mouse);
gd.addCheckbox("debug sql", debug_sql);
gd.addCheckbox("debug event", debug_event);
gd.addCheckbox("debug clip", debug_clip);
gd.addCheckbox("debug thing", debug_thing);
gd.showDialog();
if (gd.wasCanceled()) {
return;
}
debug = gd.getNextBoolean();
debug_mouse = gd.getNextBoolean();
debug_sql = gd.getNextBoolean();
debug_event = gd.getNextBoolean();
debug_clip = gd.getNextBoolean();
debug_thing = gd.getNextBoolean();
}
/** Scan the WindowManager for open stacks.*/
static public ImagePlus[] findOpenStacks() {
ImagePlus[] imp = scanWindowManager("stacks");
if (null == imp) return null;
return imp;
}
/** Scan the WindowManager for non-stack images*/
static public ImagePlus[] findOpenImages() {
ImagePlus[] imp = scanWindowManager("images");
if (null == imp) return null;
return imp;
}
/** Scan the WindowManager for all open images, including stacks.*/
static public ImagePlus[] findAllOpenImages() {
return scanWindowManager("all");
}
static private ImagePlus[] scanWindowManager(String type) {
// check if any stacks are opened within ImageJ
int[] all_ids = WindowManager.getIDList();
if (null == all_ids) return null;
ImagePlus[] imp = new ImagePlus[all_ids.length];
int next = 0;
for (int i=0; i < all_ids.length; i++) {
ImagePlus image = WindowManager.getImage(all_ids[i]);
if (type.equals("stacks")) {
if (image.getStackSize() <= 1) {
continue;
}
} else if (type.equals("images")) {
if (image.getStackSize() > 1) {
continue;
}
}
// add:
imp[next] = image;
next++;
}
// resize the array if necessary
if (next != all_ids.length) {
ImagePlus[] imp2 = new ImagePlus[next];
System.arraycopy(imp, 0, imp2, 0, next);
imp = imp2;
}
// return what has been found:
if (0 == next) return null;
return imp;
}
/**The path of the directory from which images have been recently loaded.*/
static public String last_dir = ij.Prefs.getString(ij.Prefs.DIR_IMAGE);
/**The path of the last opened file.*/
static public String last_file = null;
static public String cutNumber(double d, int n_decimals) {
return cutNumber(d, n_decimals, false);
}
/** remove_trailing_zeros will leave at least one zero after the comma if appropriate. */
static public String cutNumber(final double d, final int n_decimals, final boolean remove_trailing_zeros) {
String num = new Double(d).toString();
int i_e = num.indexOf("E-");
if (-1 != i_e) {
final int exp = Integer.parseInt(num.substring(i_e+2));
if (n_decimals < exp) {
final StringBuffer sb = new StringBuffer("0.");
int count = n_decimals;
while (count > 0) {
sb.append('0');
count--;
}
return sb.toString(); // returns 0.000... as many zeros as desired n_decimals
}
// else move comma
StringBuffer sb = new StringBuffer("0.");
int count = exp -1;
while (count > 0) {
sb.append('0');
count--;
}
sb.append(num.charAt(0)); // the single number before the comma
// up to here there are 'exp' number of decimals appended
int i_end = 2 + n_decimals - exp;
if (i_end > i_e) i_end = i_e; // there arent' that ,any, so cut
sb.append(num.substring(2, i_end)); // all numbers after the comma
return sb.toString();
}
// else, there is no scientific notation to worry about
int i_dot = num.indexOf('.');
StringBuffer sb = new StringBuffer(num.substring(0, i_dot+1));
for (int i=i_dot+1; i < (n_decimals + i_dot + 1) && i < num.length(); i++) {
sb.append(num.charAt(i));
}
// remove zeros from the end
if (remove_trailing_zeros) {
for (int i=sb.length()-1; i>i_dot+1; i--) { // leep at least one zero after the comma
if ('0' == sb.charAt(i)) {
sb.setLength(i);
} else {
break;
}
}
}
return sb.toString();
}
static public boolean check(String msg) {
YesNoCancelDialog dialog = new YesNoCancelDialog(IJ.getInstance(), "Execute?", msg);
if (dialog.yesPressed()) {
return true;
}
return false;
}
static public boolean checkYN(String msg) {
YesNoDialog yn = new YesNoDialog(IJ.getInstance(), "Execute?", msg);
if (yn.yesPressed()) return true;
return false;
}
static public String d2s(double d, int n_decimals) {
return IJ.d2s(d, n_decimals);
}
// from utilities.c in my CurveMorphing C module ... from C! Java is a low level language with the disadvantages of the high level languages ...
/** Returns the angle in radians of the given polar coordinates, correcting the Math.atan2 output. */
static public double getAngle(double x, double y) {
// calculate angle
double a = Math.atan2(x, y);
// fix too large angles (beats me why are they ever generated)
if (a > 2 * Math.PI) {
a = a - 2 * Math.PI;
}
// fix atan2 output scheme to match my mental scheme
if (a >= 0.0 && a <= Math.PI/2) {
a = Math.PI/2 - a;
} else if (a < 0 && a >= -Math.PI) {
a = Math.PI/2 -a;
} else if (a > Math.PI/2 && a <= Math.PI) {
a = Math.PI + Math.PI + Math.PI/2 - a;
}
// return
return a;
}
static public String[] getHexRGBColor(Color color) {
int c = color.getRGB();
String r = Integer.toHexString(((c&0x00FF0000)>>16));
if (1 == r.length()) r = "0" + r;
String g = Integer.toHexString(((c&0x0000FF00)>>8));
if (1 == g.length()) g = "0" + g;
String b = Integer.toHexString((c&0x000000FF));
if (1 == b.length()) b = "0" + b;
return new String[]{r, g, b};
}
static public Color getRGBColorFromHex(String hex) {
if (hex.length() < 6) return null;
return new Color(Integer.parseInt(hex.substring(0, 2), 16), // parse in hexadecimal radix
Integer.parseInt(hex.substring(2, 4), 16),
Integer.parseInt(hex.substring(4, 6), 16));
}
static public final int[] get4Ints(int hex) {
return new int[]{((hex&0xFF000000)>>24),
((hex&0x00FF0000)>>16),
((hex&0x0000FF00)>> 8),
hex&0x000000FF };
}
public void run(String arg) {
IJ.showMessage("TrakEM2", "TrakEM2 " + Utils.version + "\nCopyright Albert Cardona & Rodney Douglas\nInstitute for Neuroinformatics, Univ. Zurich / ETH\nUniversity of California Los Angeles");
}
static public File chooseFile(String name, String extension) {
return Utils.chooseFile(null, name, extension);
}
/** Select a file from the file system, for saving purposes. Prompts for overwritting if the file exists, unless the ControlWindow.isGUIEnabled() returns false (i.e. there is no GUI). */
static public File chooseFile(String default_dir, String name, String extension) {
// using ImageJ's JFileChooser or internal FileDialog, according to user preferences.
String user = System.getProperty("user.name");
String name2 = null;
if (null != name && null != extension) name2 = name + extension;
else if (null != name) name2 = name;
else if (null != extension) name2 = "untitled" + extension;
if (null != default_dir) {
OpenDialog.setDefaultDirectory(default_dir);
}
SaveDialog sd = new SaveDialog("Save",
//(user.startsWith("albert") || user.endsWith("cardona")) ?
// "/home/" + user + "/temp" :
OpenDialog.getDefaultDirectory(),
name2,
extension);
String filename = sd.getFileName();
if (null == filename || filename.toLowerCase().startsWith("null")) return null;
File f = new File(sd.getDirectory() + "/" + filename);
if (f.exists() && ControlWindow.isGUIEnabled()) {
YesNoCancelDialog d = new YesNoCancelDialog(IJ.getInstance(), "Overwrite?", "File " + filename + " exists! Overwrite?");
if (d.cancelPressed()) {
return null;
} else if (!d.yesPressed()) {
return chooseFile(name, extension);
}
// else if yes pressed, overwrite.
}
return f;
}
/** Returns null or the selected directory and file. */
static public String[] selectFile(String title_msg) {
OpenDialog od = new OpenDialog("Select file", OpenDialog.getDefaultDirectory(), null);
String file = od.getFileName();
if (null == file || file.toLowerCase().startsWith("null")) return null;
String dir = od.getDirectory();
File f = null;
if (null != dir) {
dir = dir.replace('\\', '/');
if (!dir.endsWith("/")) dir += "/";
f = new File(dir + "/" + file); // I'd use File.separator, but in Windows it fails
}
if (null == dir || !f.exists()) {
Utils.log2("No proper file selected.");
return null;
}
return new String[]{dir, file};
}
static public boolean saveToFile(File f, String contents) {
if (null == f) return false;
try {
/*
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f), contents.length()));
*/
OutputStreamWriter dos = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(f), contents.length()), "8859_1"); // encoding in Latin 1 (for macosx not to mess around
//dos.writeBytes(contents);
dos.write(contents, 0, contents.length());
dos.flush();
} catch (Exception e) {
IJError.print(e);
Utils.showMessage("ERROR: Most likely did NOT save your file.");
return false;
}
return true;
}
static public boolean saveToFile(String name, String extension, String contents) {
if (null == contents) {
Utils.log2("Utils.saveToFile: contents is null");
return false;
}
// save the file
File f = Utils.chooseFile(name, extension);
return Utils.saveToFile(f, contents);
}
/** Converts sequences of spaces into single space, and trims the ends. */
static public String cleanString(String s) {
s = s.trim();
while (-1 != s.indexOf("\u0020\u0020")) { // \u0020 equals a single space
s = s.replaceAll("\u0020\u0020", "\u0020");
}
return s;
}
static public final String openTextFile(final String path) {
if (null == path || !new File(path).exists()) return null;
final StringBuffer sb = new StringBuffer();
BufferedReader r = null;
try {
r = new BufferedReader(new FileReader(path));
while (true) {
String s = r.readLine();
if (null == s) break;
sb.append(s).append('\n'); // I am sure the reading can be done better
}
} catch (Exception e) {
IJError.print(e);
if (null != r) try { r.close(); } catch (IOException ioe) { ioe.printStackTrace(); }
return null;
}
return sb.toString();
}
/** Returns the file found at path as an array of lines, or null if not found. */
static public final String[] openTextFileLines(final String path) {
if (null == path || !new File(path).exists()) return null;
final ArrayList al = new ArrayList();
try {
BufferedReader r = new BufferedReader(new FileReader(path));
while (true) {
String s = r.readLine();
if (null == s) break;
al.add(s);
}
r.close();
} catch (Exception e) {
IJError.print(e);
return null;
}
final String[] sal = new String[al.size()];
al.toArray(sal);
return sal;
}
static public final char[] openTextFileChars(final String path) {
File f = null;
if (null == path || !(f = new File(path)).exists()) {
Utils.log("File not found: " + path);
return null;
}
final char[] src = new char[(int)f.length()]; // assumes file is small enough to fit in integer range!
try {
BufferedReader r = new BufferedReader(new FileReader(path));
r.read(src, 0, src.length);
r.close();
} catch (Exception e) {
IJError.print(e);
return null;
}
return src;
}
/** The cosinus between two vectors (in polar coordinates), by means of the dot product. */
static public final double getCos(final double x1, final double y1, final double x2, final double y2) {
return (x1 * x2 + y1 * y2) / (Math.sqrt(x1*x1 + y1*y1) * Math.sqrt(x2*x2 + y2*y2));
}
static public final String removeExtension(final String path) {
final int i_dot = path.lastIndexOf('.');
if (-1 == i_dot || i_dot + 4 != path.length()) return path;
else return path.substring(0, i_dot);
}
/** A helper for GenericDialog checkboxes to control other the enabled state of other GUI elements in the same dialog. */
static public final void addEnablerListener(final Checkbox master, final Component[] enable, final Component[] disable) {
master.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
if (ie.getStateChange() == ItemEvent.SELECTED) {
process(enable, true);
process(disable, false);
} else {
process(enable, false);
process(disable, true);
}
}
private void process(final Component[] c, final boolean state) {
if (null == c) return;
for (int i=0; i<c.length; i++) c[i].setEnabled(state);
}
});
}
static private int n_CPUs = 0;
+ /** This method is obsolete: there's Runtime.getRuntime().availableProcessors() */
+ /*
static public final int getCPUCount() {
if (0 != n_CPUs) return n_CPUs;
if (IJ.isWindows()) return 1; // no clue
// POSIX systems, attempt to count CPUs from /proc/stat
try {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("cat /proc/stat");
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
n_CPUs = 0;
// valid cores will print as cpu0, cpu1. cpu2 ...
while ((line = br.readLine()) != null) {
if (0 == line.indexOf("cpu") && line.length() > 3 && Character.isDigit(line.charAt(3))) {
n_CPUs++;
}
}
// fix possible errors
if (0 == n_CPUs) n_CPUs = 1;
return n_CPUs;
} catch (Exception e) {
Utils.log(e.toString()); // just one line
return 1;
}
}
+ */
static public final boolean wrongImageJVersion() {
boolean b = IJ.versionLessThan("1.37g");
if (b) Utils.showMessage("TrakEM2 requires ImageJ 1.37g or above.");
return b;
}
static public final boolean java3d = isJava3DInstalled();
static private final boolean isJava3DInstalled() {
try {
Class p3f = Class.forName("javax.vecmath.Point3f");
} catch (ClassNotFoundException cnfe) {
return false;
}
return true;
}
static public final void addLayerRangeChoices(final Layer selected, final GenericDialog gd) {
Utils.addLayerRangeChoices(selected, selected, gd);
}
static public final void addLayerRangeChoices(final Layer first, final Layer last, final GenericDialog gd) {
final String[] layers = new String[first.getParent().size()];
final ArrayList al_layer_titles = new ArrayList();
int i = 0;
for (Iterator it = first.getParent().getLayers().iterator(); it.hasNext(); ) {
layers[i] = first.getProject().findLayerThing((Layer)it.next()).toString();
al_layer_titles.add(layers[i]);
i++;
}
final int i_first = first.getParent().indexOf(first);
final int i_last = last.getParent().indexOf(last);
gd.addChoice("Start: ", layers, layers[i_first]);
final Vector v = gd.getChoices();
final Choice cstart = (Choice)v.get(v.size()-1);
gd.addChoice("End: ", layers, layers[i_last]);
final Choice cend = (Choice)v.get(v.size()-1);
cstart.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
int index = al_layer_titles.indexOf(ie.getItem());
if (index > cend.getSelectedIndex()) cend.select(index);
}
});
cend.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
int index = al_layer_titles.indexOf(ie.getItem());
if (index < cstart.getSelectedIndex()) cstart.select(index);
}
});
}
static public final void addLayerChoice(final String label, final Layer selected, final GenericDialog gd) {
final String[] layers = new String[selected.getParent().size()];
final ArrayList al_layer_titles = new ArrayList();
int i = 0;
for (Iterator it = selected.getParent().getLayers().iterator(); it.hasNext(); ) {
layers[i] = selected.getProject().findLayerThing((Layer)it.next()).toString();
al_layer_titles.add(layers[i]);
i++;
}
final int i_layer = selected.getParent().indexOf(selected);
gd.addChoice(label, layers, layers[i_layer]);
}
/** Converts the ImageProcessor to an ImageProcessor of the given type, or the same if of equal type. */
static final public ImageProcessor convertTo(final ImageProcessor ip, final int type, final boolean scaling) {
switch (type) {
case ImagePlus.GRAY8:
return ip.convertToByte(scaling);
case ImagePlus.GRAY16:
return ip.convertToShort(scaling);
case ImagePlus.GRAY32:
return ip.convertToFloat();
case ImagePlus.COLOR_RGB:
return ip.convertToRGB();
case ImagePlus.COLOR_256:
ImagePlus imp = new ImagePlus("", ip.convertToRGB());
new ImageConverter(imp).convertRGBtoIndexedColor(256);
return imp.getProcessor();
default:
return null;
}
}
/** Will make a new double[] array, then fit in it as many points from the given array as possible according to the desired new length. If the new length is shorter that a.length, it will shrink and crop from the end; if larger, the extra spaces will be set with zeros. */
static public final double[] copy(final double[] a, final int new_length) {
final double[] b = new double[new_length];
final int len = a.length > new_length ? new_length : a.length;
System.arraycopy(a, 0, b, 0, len);
return b;
}
/** Reverse in place an array of doubles. */
static public final void reverse(final double[] a) {
for (int left=0, right=a.length-1; left<right; left++, right--) {
double tmp = a[left];
a[left] = a[right];
a[right] = tmp;
}
}
/** OS-agnostic diagnosis of whether the click was for the contextual popup menu. */
static public final boolean isPopupTrigger(final MouseEvent me) {
return me.isPopupTrigger() || MouseEvent.BUTTON2 == me.getButton() || 0 != (me.getModifiers() & Event.META_MASK);
}
/** Repaint the given Component on the swing repaint thread (aka "SwingUtilities.invokeLater"). */
static public final void updateComponent(final Component c) {
//c.invalidate();
//c.validate();
// ALL that was needed: to put it into the swing repaint queue ... couldn't they JUST SAY SO
SwingUtilities.invokeLater(new Runnable() {
public void run() {
c.repaint();
}
});
}
static public final Point2D.Double transform(final AffineTransform affine, final double x, final double y) {
final Point2D.Double pSrc = new Point2D.Double(x, y);
if (affine.isIdentity()) return pSrc;
final Point2D.Double pDst = new Point2D.Double();
affine.transform(pSrc, pDst);
return pDst;
}
static public final Point2D.Double inverseTransform(final AffineTransform affine, final double x, final double y) {
final Point2D.Double pSrc = new Point2D.Double(x, y);
if (affine.isIdentity()) return pSrc;
final Point2D.Double pDst = new Point2D.Double();
try {
affine.createInverse().transform(pSrc, pDst);
} catch (NoninvertibleTransformException nite) {
IJError.print(nite);
}
return pDst;
}
/** Returns the time as HH:MM:SS */
static public final String now() {
/* Java time management is retarded. */
final Calendar c = Calendar.getInstance();
final int hour = c.get(Calendar.HOUR_OF_DAY);
final int min = c.get(Calendar.MINUTE);
final int sec = c.get(Calendar.SECOND);
final StringBuffer sb = new StringBuffer();
if (hour < 10) sb.append('0');
sb.append(hour).append(':');
if (min < 10) sb.append('0');
sb.append(min).append(':');
if (sec < 10) sb.append(0);
return sb.append(sec).toString();
}
static public final void sleep(final long miliseconds) {
try { Thread.currentThread().sleep(miliseconds); } catch (Exception e) { e.printStackTrace(); }
}
/** Mix colors visually: red + green = yellow, etc.*/
static public final Color mix(Color c1, Color c2) {
final float[] b = Color.RGBtoHSB(c1.getRed(), c1.getGreen(), c1.getBlue(), new float[3]);
final float[] c = Color.RGBtoHSB(c2.getRed(), c2.getGreen(), c2.getBlue(), new float[3]);
final float[] a = new float[3];
// find to which side the hue values are closer, since hue space is a a circle
// hue values all between 0 and 1
float h1 = b[0];
float h2 = c[0];
if (h1 < h2) {
float tmp = h1;
h1 = h2;
h2 = tmp;
}
float d1 = h2 - h1;
float d2 = 1 + h1 - h2;
if (d1 < d2) {
a[0] = h1 + d1 / 2;
} else {
a[0] = h2 + d2 / 2;
if (a[0] > 1) a[0] -= 1;
}
for (int i=1; i<3; i++) a[i] = (b[i] + c[i]) / 2; // only Saturation and Brightness can be averaged
return Color.getHSBColor(a[0], a[1], a[2]);
}
/** Test whether the areas intersect each other. */
static public final boolean intersects(final Area a1, final Area a2) {
final Area b = new Area(a1);
b.intersect(a2);
final java.awt.Rectangle r = b.getBounds();
return 0 != r.width && 0 != r.height;
}
/** 1 A, 2 B, 3 C --- 26 - z, 27 AA, 28 AB, 29 AC --- 26*27 AAA */
static public final String getCharacter(int i) {
i--;
int k = i / 26;
char c = (char)((i % 26) + 65); // 65 is 'A'
if (0 == k) return Character.toString(c);
return new StringBuffer().append(getCharacter(k)).append(c).toString();
}
static private Field shape_field = null;
static public final Shape getShape(final ShapeRoi roi) {
try {
if (null == shape_field) {
shape_field = ShapeRoi.class.getDeclaredField("shape");
shape_field.setAccessible(true);
}
return (Shape)shape_field.get((ShapeRoi)roi);
} catch (Exception e) {
IJError.print(e);
}
return null;
}
static public final Area getArea(final Roi roi) {
if (null == roi) return null;
ShapeRoi sroi = new ShapeRoi(roi);
AffineTransform at = new AffineTransform();
Rectangle bounds = sroi.getBounds();
at.translate(bounds.x, bounds.y);
Area area = new Area(getShape(sroi));
return area.createTransformedArea(at);
}
/** Returns the approximated area of the given Area object. */
static public final double measureArea(Area area, final Loader loader) {
double sum = 0;
try {
Rectangle bounds = area.getBounds();
double scale = 1;
if (bounds.width > 2048 || bounds.height > 2048) {
scale = 2048.0 / bounds.width;
}
if (0 == scale) {
Utils.log("Can't measure: area too large, out of scale range for approximation.");
return sum;
}
AffineTransform at = new AffineTransform();
at.translate(-bounds.x, -bounds.y);
at.scale(scale, scale);
area = area.createTransformedArea(at);
bounds = area.getBounds();
if (0 == bounds.width || 0 == bounds.height) {
Utils.log("Can't measure: area too large, approximates zero.");
return sum;
}
if (null != loader) loader.releaseToFit(bounds.width * bounds.height * 3);
BufferedImage bi = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_BYTE_INDEXED);
Graphics2D g = bi.createGraphics();
g.setColor(Color.white);
g.fill(area);
final byte[] pixels = ((DataBufferByte)bi.getRaster().getDataBuffer()).getData(); // buffer.getData();
for (int i=pixels.length-1; i>-1; i--) {
//if (255 == (pixels[i]&0xff)) sum++;
if (0 != pixels[i]) sum++;
}
bi.flush();
g.dispose();
if (1 != scale) sum = sum / (scale * scale);
} catch (Throwable e) {
IJError.print(e);
}
return sum;
}
- /** Compute the are of the triangle defined by 3 points in 3D space, returning half of the length of the vector resulting from the cross product of vectors p1p2 and p1p3. */
+ /** Compute the area of the triangle defined by 3 points in 3D space, returning half of the length of the vector resulting from the cross product of vectors p1p2 and p1p3. */
static public final double measureArea(final Point3f p1, final Point3f p2, final Point3f p3) {
final Vector3f v = new Vector3f();
v.cross(new Vector3f(p2.x - p1.x, p2.y - p1.y, p2.z - p1.z),
new Vector3f(p3.x - p1.x, p3.y - p1.y, p3.z - p1.z));
return 0.5 * Math.abs(v.x * v.x + v.y * v.y + v.z * v.z);
}
/** A method that circumvents the findMinAndMax when creating a float processor from an existing processor. Ignores color calibrations and does no scaling at all. */
static public final FloatProcessor fastConvertToFloat(final ByteProcessor ip) {
final byte[] pix = (byte[])ip.getPixels();
final float[] data = new float[pix.length];
for (int i=0; i<pix.length; i++) data[i] = pix[i]&0xff;
final FloatProcessor fp = new FloatProcessorT2(ip.getWidth(), ip.getHeight(), data, ip.getColorModel(), ip.getMin(), ip.getMax());
return fp;
}
/** A method that circumvents the findMinAndMax when creating a float processor from an existing processor. Ignores color calibrations and does no scaling at all. */
static public final FloatProcessor fastConvertToFloat(final ShortProcessor ip) {
final short[] pix = (short[])ip.getPixels();
final float[] data = new float[pix.length];
for (int i=0; i<pix.length; i++) data[i] = pix[i]&0xffff;
final FloatProcessor fp = new FloatProcessorT2(ip.getWidth(), ip.getHeight(), data, ip.getColorModel(), ip.getMin(), ip.getMax());
return fp;
}
/** A method that circumvents the findMinAndMax when creating a float processor from an existing processor. Ignores color calibrations and does no scaling at all. */
static public final FloatProcessor fastConvertToFloat(final ImageProcessor ip, final int type) {
switch (type) {
case ImagePlus.GRAY16: return fastConvertToFloat((ShortProcessor)ip);
case ImagePlus.GRAY32: return (FloatProcessor)ip;
case ImagePlus.GRAY8:
case ImagePlus.COLOR_256: return fastConvertToFloat((ByteProcessor)ip);
case ImagePlus.COLOR_RGB: return (FloatProcessor)ip.convertToFloat(); // SLOW
}
return null;
}
static public final FloatProcessor fastConvertToFloat(final ImageProcessor ip) {
if (ip instanceof ByteProcessor) return fastConvertToFloat((ByteProcessor)ip);
if (ip instanceof ShortProcessor) return fastConvertToFloat((ShortProcessor)ip);
return (FloatProcessor)ip.convertToFloat();
}
}
| false | false | null | null |
diff --git a/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java b/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java
index 75a3cf6d5..f879ad86c 100644
--- a/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java
+++ b/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java
@@ -1,404 +1,404 @@
/*
* Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved.
* Copyright (c) 2010 JogAmp Community. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
* INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN
* MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR
* ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR
* ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR
* DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
* DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
* ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF
* SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
*/
package jogamp.newt.driver.macosx;
import javax.media.nativewindow.AbstractGraphicsConfiguration;
import javax.media.nativewindow.GraphicsConfigurationFactory;
import javax.media.nativewindow.NativeWindow;
import javax.media.nativewindow.NativeWindowException;
import javax.media.nativewindow.SurfaceChangeable;
import javax.media.nativewindow.util.Insets;
import javax.media.nativewindow.util.InsetsImmutable;
import javax.media.nativewindow.util.Point;
import javax.media.nativewindow.util.PointImmutable;
import jogamp.newt.WindowImpl;
import jogamp.newt.driver.DriverClearFocus;
import jogamp.newt.driver.DriverUpdatePosition;
import com.jogamp.newt.event.KeyEvent;
public class MacWindow extends WindowImpl implements SurfaceChangeable, DriverClearFocus, DriverUpdatePosition {
static {
MacDisplay.initSingleton();
}
public MacWindow() {
}
@Override
protected void createNativeImpl() {
final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(getScreen().getDisplay().getGraphicsDevice()).chooseGraphicsConfiguration(
capsRequested, capsRequested, capabilitiesChooser, getScreen().getGraphicsScreen());
if (null == cfg) {
throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this);
}
setGraphicsConfiguration(cfg);
reconfigureWindowImpl(x, y, width, height, getReconfigureFlags(FLAG_CHANGE_VISIBILITY, true));
if (0 == getWindowHandle()) {
throw new NativeWindowException("Error creating window");
}
}
@Override
protected void closeNativeImpl() {
try {
if(DEBUG_IMPLEMENTATION) { System.err.println("MacWindow.CloseAction "+Thread.currentThread().getName()); }
if (getWindowHandle() != 0) {
close0(getWindowHandle());
}
} catch (Throwable t) {
if(DEBUG_IMPLEMENTATION) {
Exception e = new Exception("Warning: closeNative failed - "+Thread.currentThread().getName(), t);
e.printStackTrace();
}
} finally {
setWindowHandle(0);
surfaceHandle = 0;
sscSurfaceHandle = 0;
isOffscreenInstance = false;
}
}
@Override
protected int lockSurfaceImpl() {
if(!isOffscreenInstance) {
return lockSurface0(getWindowHandle()) ? LOCK_SUCCESS : LOCK_SURFACE_NOT_READY;
}
return LOCK_SUCCESS;
}
@Override
protected void unlockSurfaceImpl() {
if(!isOffscreenInstance) {
unlockSurface0(getWindowHandle());
}
}
@Override
public final long getSurfaceHandle() {
return 0 != sscSurfaceHandle ? sscSurfaceHandle : surfaceHandle;
}
public void setSurfaceHandle(long surfaceHandle) {
if(DEBUG_IMPLEMENTATION) {
System.err.println("MacWindow.setSurfaceHandle(): 0x"+Long.toHexString(surfaceHandle));
}
sscSurfaceHandle = surfaceHandle;
if (isNativeValid()) {
if (0 != sscSurfaceHandle) {
orderOut0( 0!=getParentWindowHandle() ? getParentWindowHandle() : getWindowHandle() );
} /** this is done by recreation!
else if (isVisible()){
orderFront0( 0!=getParentWindowHandle() ? getParentWindowHandle() : getWindowHandle() );
} */
}
}
public void surfaceSizeChanged(int width, int height) {
sizeChanged(false, width, height, false);
}
@Override
protected void setTitleImpl(final String title) {
setTitle0(getWindowHandle(), title);
}
protected void requestFocusImpl(boolean force) {
if(!isOffscreenInstance) {
requestFocus0(getWindowHandle(), force);
} else {
focusChanged(false, true);
}
}
public final void clearFocus() {
if(DEBUG_IMPLEMENTATION) {
System.err.println("MacWindow: clearFocus() - requestFocusParent, isOffscreenInstance "+isOffscreenInstance);
}
if(!isOffscreenInstance) {
requestFocusParent0(getWindowHandle());
} else {
focusChanged(false, false);
}
}
public void updatePosition() {
final Point pS = getTopLevelLocationOnScreen(getX(), getY());
if(DEBUG_IMPLEMENTATION) {
System.err.println("MacWindow: updatePosition() - isOffscreenInstance "+isOffscreenInstance+", new abs pos: pS "+pS);
}
if( !isOffscreenInstance ) {
setFrameTopLeftPoint0(getParentWindowHandle(), getWindowHandle(), pS.getX(), pS.getY());
} // else no offscreen position
// no native event (fullscreen, some reparenting)
super.positionChanged(true, getX(), getY());
}
protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) {
final Point pS = getTopLevelLocationOnScreen(x, y);
isOffscreenInstance = 0 != sscSurfaceHandle || isOffscreenInstance(this, this.getParent());
if(DEBUG_IMPLEMENTATION) {
System.err.println("MacWindow reconfig: "+x+"/"+y+" -> "+pS+" - "+width+"x"+height+
", offscreenInstance "+isOffscreenInstance+
", "+getReconfigureFlagsAsString(null, flags));
}
if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) && 0 == ( FLAG_IS_VISIBLE & flags) ) {
if ( !isOffscreenInstance ) {
orderOut0(getWindowHandle());
}
// no native event ..
visibleChanged(true, false);
}
if( 0 == getWindowHandle() && 0 != ( FLAG_IS_VISIBLE & flags) ||
0 != ( FLAG_CHANGE_DECORATION & flags) ||
0 != ( FLAG_CHANGE_PARENTING & flags) ||
0 != ( FLAG_CHANGE_FULLSCREEN & flags) ) {
createWindow(isOffscreenInstance, 0 != getWindowHandle(), pS, width, height, 0 != ( FLAG_IS_FULLSCREEN & flags));
if(isVisible()) { flags |= FLAG_CHANGE_VISIBILITY; }
}
if(x>=0 && y>=0) {
if( !isOffscreenInstance ) {
setFrameTopLeftPoint0(getParentWindowHandle(), getWindowHandle(), pS.getX(), pS.getY());
} // else no offscreen position
// no native event (fullscreen, some reparenting)
super.positionChanged(true, x, y);
}
if(width>0 && height>0) {
if( !isOffscreenInstance ) {
setContentSize0(getWindowHandle(), width, height);
} // else offscreen size is realized via recreation
// no native event (fullscreen, some reparenting)
sizeChanged(true, width, height, false); // incl. validation (incl. repositioning)
}
if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) && 0 != ( FLAG_IS_VISIBLE & flags) ) {
if( !isOffscreenInstance ) {
orderFront0(getWindowHandle());
}
// no native event ..
visibleChanged(true, true);
}
if( !isOffscreenInstance ) {
setAlwaysOnTop0(getWindowHandle(), 0 != ( FLAG_IS_ALWAYSONTOP & flags));
}
return true;
}
protected Point getLocationOnScreenImpl(int x, int y) {
Point p = new Point(x, y);
// min val is 0
p.setX(Math.max(p.getX(), 0));
p.setY(Math.max(p.getY(), 0));
final NativeWindow parent = getParent();
if( null != parent && 0 != parent.getWindowHandle() ) {
p.translate(parent.getLocationOnScreen(null));
}
return p;
}
private Point getTopLevelLocationOnScreen(int x, int y) {
final InsetsImmutable _insets = getInsets(); // zero if undecorated
// client position -> top-level window position
x -= _insets.getLeftWidth() ;
y -= _insets.getTopHeight() ;
return getLocationOnScreenImpl(x, y);
}
protected void updateInsetsImpl(Insets insets) {
// nop - using event driven insetsChange(..)
}
@Override
protected void sizeChanged(boolean defer, int newWidth, int newHeight, boolean force) {
if(width != newWidth || height != newHeight) {
final Point p0S = getTopLevelLocationOnScreen(x, y);
setFrameTopLeftPoint0(getParentWindowHandle(), getWindowHandle(), p0S.getX(), p0S.getY());
}
super.sizeChanged(defer, newWidth, newHeight, force);
}
@Override
protected void positionChanged(boolean defer, int newX, int newY) {
// passed coordinates are in screen position of the client area
if(getWindowHandle()!=0) {
// screen position -> window position
Point absPos = new Point(newX, newY);
final NativeWindow parent = getParent();
if(null != parent) {
absPos.translate( parent.getLocationOnScreen(null).scale(-1, -1) );
}
super.positionChanged(defer, absPos.getX(), absPos.getY());
}
}
@Override
protected boolean setPointerVisibleImpl(final boolean pointerVisible) {
if( !isOffscreenInstance ) {
- return setPointerVisible0(getWindowHandle(), pointerVisible);
+ return setPointerVisible0(getWindowHandle(), hasFocus(), pointerVisible);
} // else may need offscreen solution ? FIXME
return false;
}
@Override
protected boolean confinePointerImpl(final boolean confine) {
if( !isOffscreenInstance ) {
return confinePointer0(getWindowHandle(), confine);
} // else may need offscreen solution ? FIXME
return false;
}
@Override
protected void warpPointerImpl(final int x, final int y) {
if( !isOffscreenInstance ) {
warpPointer0(getWindowHandle(), x, y);
} // else may need offscreen solution ? FIXME
}
@Override
public void sendKeyEvent(int eventType, int modifiers, int keyCode, char keyChar) {
// Note that we send the key char for the key code on this
// platform -- we do not get any useful key codes out of the system
final int keyCode2 = MacKeyUtil.validateKeyCode(keyCode, keyChar);
if(DEBUG_IMPLEMENTATION) System.err.println("MacWindow.sendKeyEvent "+Thread.currentThread().getName()+" char: 0x"+Integer.toHexString(keyChar)+", code 0x"+Integer.toHexString(keyCode)+" -> 0x"+Integer.toHexString(keyCode2));
// only deliver keyChar on key Typed events, harmonizing platform behavior
keyChar = KeyEvent.EVENT_KEY_TYPED == eventType ? keyChar : (char)-1;
super.sendKeyEvent(eventType, modifiers, keyCode2, keyChar);
}
@Override
public void enqueueKeyEvent(boolean wait, int eventType, int modifiers, int keyCode, char keyChar) {
// Note that we send the key char for the key code on this
// platform -- we do not get any useful key codes out of the system
final int keyCode2 = MacKeyUtil.validateKeyCode(keyCode, keyChar);
if(DEBUG_IMPLEMENTATION) System.err.println("MacWindow.enqueueKeyEvent "+Thread.currentThread().getName()+" char: 0x"+Integer.toHexString(keyChar)+", code 0x"+Integer.toHexString(keyCode)+" -> 0x"+Integer.toHexString(keyCode2));
// only deliver keyChar on key Typed events, harmonizing platform behavior
keyChar = KeyEvent.EVENT_KEY_TYPED == eventType ? keyChar : (char)-1;
super.enqueueKeyEvent(wait, eventType, modifiers, keyCode2, keyChar);
}
//----------------------------------------------------------------------
// Internals only
//
private void createWindow(final boolean offscreenInstance, final boolean recreate,
final PointImmutable pS, final int width, final int height,
final boolean fullscreen) {
if(0!=getWindowHandle() && !recreate) {
return;
}
try {
if(0!=getWindowHandle()) {
// save the view .. close the window
surfaceHandle = changeContentView0(getParentWindowHandle(), getWindowHandle(), 0);
if(recreate && 0==surfaceHandle) {
throw new NativeWindowException("Internal Error - recreate, window but no view");
}
orderOut0(getWindowHandle());
close0(getWindowHandle());
setWindowHandle(0);
} else {
surfaceHandle = 0;
}
setWindowHandle(createWindow0(getParentWindowHandle(),
pS.getX(), pS.getY(), width, height,
(getGraphicsConfiguration().getChosenCapabilities().isBackgroundOpaque() && !offscreenInstance),
fullscreen,
((isUndecorated() || offscreenInstance) ?
NSBorderlessWindowMask :
NSTitledWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask),
NSBackingStoreBuffered,
getScreen().getIndex(), surfaceHandle));
if (getWindowHandle() == 0) {
throw new NativeWindowException("Could create native window "+Thread.currentThread().getName()+" "+this);
}
surfaceHandle = contentView0(getWindowHandle());
if( offscreenInstance ) {
orderOut0(0!=getParentWindowHandle() ? getParentWindowHandle() : getWindowHandle());
} else {
setTitle0(getWindowHandle(), getTitle());
}
} catch (Exception ie) {
ie.printStackTrace();
}
}
protected static native boolean initIDs0();
private native long createWindow0(long parentWindowHandle, int x, int y, int w, int h,
boolean opaque, boolean fullscreen, int windowStyle,
int backingStoreType,
int screen_idx, long view);
private native boolean lockSurface0(long window);
private native void unlockSurface0(long window);
private native void requestFocus0(long window, boolean force);
private native void requestFocusParent0(long window);
/** in case of a child window, it actually only issues orderBack(..) */
private native void orderOut0(long window);
private native void orderFront0(long window);
private native void close0(long window);
private native void setTitle0(long window, String title);
private native long contentView0(long window);
private native long changeContentView0(long parentWindowOrViewHandle, long window, long view);
private native void setContentSize0(long window, int w, int h);
private native void setFrameTopLeftPoint0(long parentWindowHandle, long window, int x, int y);
private native void setAlwaysOnTop0(long window, boolean atop);
private static native Object getLocationOnScreen0(long windowHandle, int src_x, int src_y);
- private static native boolean setPointerVisible0(long windowHandle, boolean visible);
+ private static native boolean setPointerVisible0(long windowHandle, boolean hasFocus, boolean visible);
private static native boolean confinePointer0(long windowHandle, boolean confine);
private static native void warpPointer0(long windowHandle, int x, int y);
// Window styles
private static final int NSBorderlessWindowMask = 0;
private static final int NSTitledWindowMask = 1 << 0;
private static final int NSClosableWindowMask = 1 << 1;
private static final int NSMiniaturizableWindowMask = 1 << 2;
private static final int NSResizableWindowMask = 1 << 3;
// Window backing store types
private static final int NSBackingStoreRetained = 0;
private static final int NSBackingStoreNonretained = 1;
private static final int NSBackingStoreBuffered = 2;
private volatile long surfaceHandle = 0;
private long sscSurfaceHandle = 0;
private boolean isOffscreenInstance = false;
}
| false | false | null | null |
diff --git a/src/main/java/com/googlecode/mgwt/ui/client/widget/HeaderList.java b/src/main/java/com/googlecode/mgwt/ui/client/widget/HeaderList.java
index 027de5a2..445d742d 100644
--- a/src/main/java/com/googlecode/mgwt/ui/client/widget/HeaderList.java
+++ b/src/main/java/com/googlecode/mgwt/ui/client/widget/HeaderList.java
@@ -1,349 +1,349 @@
/*
* Copyright 2012 Daniel Kurka
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.googlecode.mgwt.ui.client.widget;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gwt.dom.client.Document;
import com.google.gwt.event.logical.shared.HasSelectionHandlers;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Widget;
import com.googlecode.mgwt.collection.shared.LightArrayInt;
import com.googlecode.mgwt.dom.client.event.touch.TouchCancelEvent;
import com.googlecode.mgwt.dom.client.event.touch.TouchEndEvent;
import com.googlecode.mgwt.dom.client.event.touch.TouchHandler;
import com.googlecode.mgwt.dom.client.event.touch.TouchMoveEvent;
import com.googlecode.mgwt.dom.client.event.touch.TouchStartEvent;
import com.googlecode.mgwt.ui.client.MGWT;
import com.googlecode.mgwt.ui.client.MGWTStyle;
import com.googlecode.mgwt.ui.client.theme.base.GroupingList;
import com.googlecode.mgwt.ui.client.theme.base.ListCss;
import com.googlecode.mgwt.ui.client.util.CssUtil;
import com.googlecode.mgwt.ui.client.widget.GroupingCellList.CellGroup;
import com.googlecode.mgwt.ui.client.widget.event.scroll.ScrollAnimationMoveEvent;
import com.googlecode.mgwt.ui.client.widget.event.scroll.ScrollMoveEvent;
import com.googlecode.mgwt.ui.client.widget.event.scroll.ScrollRefreshEvent;
import com.googlecode.mgwt.ui.client.widget.touch.TouchWidget;
/**
- * This widget uses a {@link GroupingCellList} to render children withing
- * groups. On top of that it provides a fast selection through a bar on the
- * right by displaying symbols for group names.
+ * This widget uses a {@link GroupingCellList} to render children within groups.
+ * On top of that it provides a fast selection through a bar on the right by
+ * displaying symbols for group names.
*
* It also animates a header group so that the user can always see which group
* he is currently scrolling in.
*
* @author Daniel Kurka
*
* @param <G> type of the group
* @param <T> type of the children
*/
public class HeaderList<G, T> extends Composite {
private static class SelectionBar<G, T> extends TouchWidget implements TouchHandler, HasSelectionHandlers<Integer> {
private int selectedIndex;
private int renderedEntries;
private final GroupingList css;
public SelectionBar(GroupingList css) {
this.css = css;
setElement(Document.get().createULElement());
addStyleName(css.selectionBar());
selectedIndex = 0;
mapping = new HashMap<Integer, Integer>();
addTouchHandler(this);
}
@Override
public void onTouchStart(TouchStartEvent event) {
calculateSelection(event.getTouches().get(0).getPageY());
addStyleName(css.selectionBarActive());
}
@Override
public void onTouchMove(TouchMoveEvent event) {
calculateSelection(event.getTouches().get(0).getPageY());
if (MGWT.getOsDetection().isAndroid()) {
event.preventDefault();
}
}
@Override
public void onTouchEnd(TouchEndEvent event) {
removeStyleName(css.selectionBarActive());
}
@Override
public void onTouchCanceled(TouchCancelEvent event) {
removeStyleName(css.selectionBarActive());
}
protected void calculateSelection(int y) {
int absoluteTop = getElement().getAbsoluteTop();
int absoluteBottom = getElement().getAbsoluteBottom();
int normalized_y = y - absoluteTop;
int height = absoluteBottom - absoluteTop;
int index = (normalized_y * renderedEntries) / height;
if (index != selectedIndex) {
SelectionEvent.fire(this, mapping.get(index));
}
selectedIndex = index;
}
@Override
public HandlerRegistration addSelectionHandler(SelectionHandler<Integer> handler) {
return addHandler(handler, SelectionEvent.getType());
}
public void render(List<CellGroup<G, T>> list) {
mapping.clear();
StringBuffer buffer = new StringBuffer();
renderedEntries = 0;
int target = 0;
for (CellGroup<?, ?> cellGroup : list) {
buffer.append("<li>" + cellGroup.getKey() + "</li>");
mapping.put(renderedEntries, target);
if (!cellGroup.getMember().isEmpty()) {
target++;
}
renderedEntries++;
}
getElement().setInnerHTML(buffer.toString());
}
private Map<Integer, Integer> mapping;
}
private static class MovingHeader extends Widget {
public MovingHeader(ListCss listCss, GroupingList css) {
setElement(DOM.createDiv());
addStyleName(listCss.listHeadElement());
addStyleName(css.movingHeader());
}
public void setHTML(String string) {
getElement().setInnerHTML(string);
}
}
private FlowPanel main;
private ScrollPanel scrollPanel;
private MovingHeader movingHeader;
private LightArrayInt pagesY;
private int currentPage;
private final GroupingCellList<G, T> cellList;
private boolean needReset = false;
private int lastPage = -1;
private SelectionBar<G, T> selectionBar;
private List<CellGroup<G, T>> list;
private boolean headerVisible = true;
/**
* Construct a HeaderList
*
* @param cellList the cell list that renders its children inside this
* widget.
*/
public HeaderList(GroupingCellList<G, T> cellList) {
this(cellList, MGWTStyle.getTheme().getMGWTClientBundle().getGroupingList());
}
/**
* Construct a cell list with a given cell list and css
*
* @param cellList the cell list that renders its children inside this
* widget
* @param css the css to use
*/
public HeaderList(GroupingCellList<G, T> cellList, GroupingList css) {
this.cellList = cellList;
css.ensureInjected();
main = new FlowPanel();
initWidget(main);
main.addStyleName(css.groupingHeaderList());
currentPage = 0;
selectionBar = new SelectionBar<G, T>(css);
main.add(selectionBar);
scrollPanel = new ScrollPanel();
scrollPanel.addStyleName(MGWTStyle.getTheme().getMGWTClientBundle().getLayoutCss().fillPanelExpandChild());
scrollPanel.setWidget(cellList);
scrollPanel.setSnapSelector(cellList.getHeaderSelector());
scrollPanel.setShowScrollBarX(false);
main.add(scrollPanel);
movingHeader = new MovingHeader(cellList.getListCss(), css);
main.add(movingHeader);
scrollPanel.addScrollRefreshHandler(new ScrollRefreshEvent.Handler() {
@Override
public void onScrollRefresh(ScrollRefreshEvent event) {
pagesY = scrollPanel.getPagesY();
}
});
selectionBar.addSelectionHandler(new SelectionHandler<Integer>() {
@Override
public void onSelection(SelectionEvent<Integer> event) {
scrollPanel.scrollToPage(0, event.getSelectedItem(), 0);
currentPage = event.getSelectedItem();
updateCurrentPage(scrollPanel.getY());
updateHeaderPositionAndTitle(scrollPanel.getY());
}
});
scrollPanel.addScrollMoveHandler(new ScrollMoveEvent.Handler() {
@Override
public void onScrollMove(ScrollMoveEvent event) {
updateCurrentPage(scrollPanel.getY());
updateHeaderPositionAndTitle(scrollPanel.getY());
}
});
scrollPanel.addScrollAnimationMoveHandler(new ScrollAnimationMoveEvent.Handler() {
@Override
public void onScrollAnimationMove(ScrollAnimationMoveEvent event) {
updateCurrentPage(scrollPanel.getY());
updateHeaderPositionAndTitle(scrollPanel.getY());
}
});
}
public void render(List<CellGroup<G, T>> list) {
this.list = list;
selectionBar.render(list);
cellList.renderGroup(list);
scrollPanel.refresh();
}
private void updateCurrentPage(int y) {
int i;
for (i = 0; i < pagesY.length(); i++) {
int page_start = pagesY.get(i);
if (page_start < y) {
break;
}
}
currentPage = i - 1;
if (currentPage < 0)
currentPage = 0;
if (currentPage > pagesY.length() - 1) {
currentPage = pagesY.length() - 1;
}
}
private void updateHeaderPositionAndTitle(int y) {
int headerHeight = movingHeader.getOffsetHeight();
if (lastPage != currentPage) {
lastPage = currentPage;
int modelIndex = cellList.getMapping().get(currentPage);
movingHeader.setHTML(cellList.renderGroupHeader(list.get(modelIndex).getGroup()));
}
if (y > 0) {
if (headerVisible) {
headerVisible = false;
movingHeader.setVisible(false);
}
return;
} else {
if (!headerVisible) {
headerVisible = true;
movingHeader.setVisible(true);
}
}
if (currentPage + 1 < pagesY.length()) {
int nextHeader = pagesY.get(currentPage + 1);
if (nextHeader + headerHeight - y > 0) {
int move = -(nextHeader + headerHeight - y);
CssUtil.translate(movingHeader.getElement(), 0, move);
needReset = true;
} else {
if (needReset) {
needReset = false;
CssUtil.translate(movingHeader.getElement(), 0, 0);
}
}
}
}
}
| true | false | null | null |
diff --git a/nexus/nexus-test-harness/nexus-simple-memory-realm/src/test/java/org/sonatype/jsecurity/realms/simple/SimpleRealmTest.java b/nexus/nexus-test-harness/nexus-simple-memory-realm/src/test/java/org/sonatype/jsecurity/realms/simple/SimpleRealmTest.java
index 143ad31f6..75789b7db 100644
--- a/nexus/nexus-test-harness/nexus-simple-memory-realm/src/test/java/org/sonatype/jsecurity/realms/simple/SimpleRealmTest.java
+++ b/nexus/nexus-test-harness/nexus-simple-memory-realm/src/test/java/org/sonatype/jsecurity/realms/simple/SimpleRealmTest.java
@@ -1,173 +1,175 @@
/**
* Sonatype Nexus (TM) Open Source Version.
* Copyright (c) 2008 Sonatype, Inc. All rights reserved.
* Includes the third-party code listed at http://nexus.sonatype.org/dev/attributions.html
* This program is licensed to you under Version 3 only of the GNU General Public License as published by the Free Software Foundation.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License Version 3 for more details.
* You should have received a copy of the GNU General Public License Version 3 along with this program.
* If not, see http://www.gnu.org/licenses/.
* Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc.
* "Sonatype" and "Sonatype Nexus" are trademarks of Sonatype, Inc.
*/
package org.sonatype.jsecurity.realms.simple;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import junit.framework.Assert;
import org.codehaus.plexus.util.IOUtil;
import org.jsecurity.authc.AuthenticationException;
import org.jsecurity.authc.AuthenticationInfo;
import org.jsecurity.authc.AuthenticationToken;
import org.jsecurity.authc.UsernamePasswordToken;
import org.jsecurity.subject.PrincipalCollection;
import org.jsecurity.subject.SimplePrincipalCollection;
import org.sonatype.jsecurity.realms.PlexusSecurity;
import org.sonatype.nexus.AbstractNexusTestCase;
public class SimpleRealmTest
extends AbstractNexusTestCase
{
// Realm Tests
/**
* Test authentication with a valid user and password.
*
* @throws Exception
*/
public void testValidAuthentication()
throws Exception
{
PlexusSecurity plexusSecurity = this.lookup( PlexusSecurity.class, "web" );
AuthenticationToken token = new UsernamePasswordToken( "admin-simple", "admin123" );
AuthenticationInfo authInfo = plexusSecurity.authenticate( token );
// check
Assert.assertNotNull( authInfo );
}
/**
* Test authentication with a valid user and invalid password.
*
* @throws Exception
*/
public void testInvalidPasswordAuthentication()
throws Exception
{
PlexusSecurity plexusSecurity = this.lookup( PlexusSecurity.class, "web" );
AuthenticationToken token = new UsernamePasswordToken( "admin-simple", "INVALID" );
try
{
AuthenticationInfo authInfo = plexusSecurity.authenticate( token );
}
catch ( AuthenticationException e )
{
// expected
}
}
/**
* Test authentication with a invalid user and password.
*
* @throws Exception
*/
public void testInvalidUserAuthentication()
throws Exception
{
PlexusSecurity plexusSecurity = this.lookup( PlexusSecurity.class, "web" );
AuthenticationToken token = new UsernamePasswordToken( "INVALID", "INVALID" );
try
{
AuthenticationInfo authInfo = plexusSecurity.authenticate( token );
}
catch ( AuthenticationException e )
{
// expected
}
}
//
/**
* Test authorization using the NexusMethodAuthorizingRealm. <BR/> Take a look a the security.xml in
* src/test/resources this maps the users in the UserStore to nexus roles/privileges
*
* @throws Exception
*/
public void testPrivileges()
throws Exception
{
PlexusSecurity plexusSecurity = this.lookup( PlexusSecurity.class, "web" );
PrincipalCollection principal = new SimplePrincipalCollection( "admin-simple", PlexusSecurity.class
.getSimpleName() );
// test one of the privleges that the admin user has
Assert.assertTrue( plexusSecurity.isPermitted( principal, "nexus:repositories:create" ) );// Repositories -
// (create,read)
}
/**
* Tests a valid privilege for an invalid user
* @throws Exception
*/
public void testPrivilegesInvalidUser()
throws Exception
{
PlexusSecurity plexusSecurity = this.lookup( PlexusSecurity.class, "web" );
PrincipalCollection principal = new SimplePrincipalCollection( "INVALID", PlexusSecurity.class
.getSimpleName() );
// test one of the privleges
Assert.assertFalse( plexusSecurity.isPermitted( principal, "nexus:repositories:create" ) );// Repositories -
// (create,read)
}
@Override
protected void setUp()
throws Exception
{
// call super
super.setUp();
// copy the tests nexus.xml and security.xml to the correct location
this.copyTestConfigToPlace();
}
private void copyTestConfigToPlace()
throws FileNotFoundException,
IOException
{
InputStream nexusConf = null;
InputStream securityConf = null;
OutputStream nexusOut = null;
OutputStream securityOut = null;
try
{
nexusConf = Thread.currentThread().getContextClassLoader().getResourceAsStream( "nexus.xml" );
nexusOut = new FileOutputStream( getNexusConfiguration() );
IOUtil.copy( nexusConf, nexusOut );
securityConf = Thread.currentThread().getContextClassLoader().getResourceAsStream( "security.xml" );
securityOut = new FileOutputStream( getNexusSecurityConfiguration() );
IOUtil.copy( securityConf, securityOut);
}
finally
{
IOUtil.close( nexusConf );
IOUtil.close( securityConf );
+ IOUtil.close( nexusOut );
+ IOUtil.close( securityOut );
}
}
}
| true | true | private void copyTestConfigToPlace()
throws FileNotFoundException,
IOException
{
InputStream nexusConf = null;
InputStream securityConf = null;
OutputStream nexusOut = null;
OutputStream securityOut = null;
try
{
nexusConf = Thread.currentThread().getContextClassLoader().getResourceAsStream( "nexus.xml" );
nexusOut = new FileOutputStream( getNexusConfiguration() );
IOUtil.copy( nexusConf, nexusOut );
securityConf = Thread.currentThread().getContextClassLoader().getResourceAsStream( "security.xml" );
securityOut = new FileOutputStream( getNexusSecurityConfiguration() );
IOUtil.copy( securityConf, securityOut);
}
finally
{
IOUtil.close( nexusConf );
IOUtil.close( securityConf );
}
}
| private void copyTestConfigToPlace()
throws FileNotFoundException,
IOException
{
InputStream nexusConf = null;
InputStream securityConf = null;
OutputStream nexusOut = null;
OutputStream securityOut = null;
try
{
nexusConf = Thread.currentThread().getContextClassLoader().getResourceAsStream( "nexus.xml" );
nexusOut = new FileOutputStream( getNexusConfiguration() );
IOUtil.copy( nexusConf, nexusOut );
securityConf = Thread.currentThread().getContextClassLoader().getResourceAsStream( "security.xml" );
securityOut = new FileOutputStream( getNexusSecurityConfiguration() );
IOUtil.copy( securityConf, securityOut);
}
finally
{
IOUtil.close( nexusConf );
IOUtil.close( securityConf );
IOUtil.close( nexusOut );
IOUtil.close( securityOut );
}
}
|
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrServer.java b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrServer.java
index fe328612d..5c5ed4061 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrServer.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrServer.java
@@ -1,696 +1,700 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.client.solrj.impl;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.ClientParamBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.solr.client.solrj.ResponseParser;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.request.RequestWriter;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.client.solrj.util.ClientUtils;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.ContentStream;
import org.apache.solr.common.util.NamedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpSolrServer extends SolrServer {
private static final String UTF_8 = "UTF-8";
private static final String DEFAULT_PATH = "/select";
private static final long serialVersionUID = -946812319974801896L;
/**
* User-Agent String.
*/
public static final String AGENT = "Solr[" + HttpSolrServer.class.getName()
+ "] 1.0";
private static Logger log = LoggerFactory.getLogger(HttpSolrServer.class);
/**
* The URL of the Solr server.
*/
protected String baseUrl;
/**
* Default value: null / empty.
* <p/>
* Parameters that are added to every request regardless. This may be a place
* to add something like an authentication token.
*/
protected ModifiableSolrParams invariantParams;
/**
* Default response parser is BinaryResponseParser
* <p/>
* This parser represents the default Response Parser chosen to parse the
* response if the parser were not specified as part of the request.
*
* @see org.apache.solr.client.solrj.impl.BinaryResponseParser
*/
protected ResponseParser parser;
/**
* The RequestWriter used to write all requests to Solr
*
* @see org.apache.solr.client.solrj.request.RequestWriter
*/
protected RequestWriter requestWriter = new RequestWriter();
private final HttpClient httpClient;
/**
* This defaults to false under the assumption that if you are following a
* redirect to get to a Solr installation, something is misconfigured
* somewhere.
*/
private boolean followRedirects = false;
/**
* Maximum number of retries to attempt in the event of transient errors.
* Default: 0 (no) retries. No more than 1 recommended.
*/
private int maxRetries = 0;
private ThreadSafeClientConnManager ccm;
private boolean useMultiPartPost;
/**
* @param baseURL
* The URL of the Solr server. For example, "
* <code>http://localhost:8983/solr/</code>" if you are using the
* standard distribution Solr webapp on your local machine.
*/
public HttpSolrServer(String baseURL) {
this(baseURL, null, new BinaryResponseParser());
}
public HttpSolrServer(String baseURL, HttpClient client) {
this(baseURL, client, new BinaryResponseParser());
}
public HttpSolrServer(String baseURL, HttpClient client, ResponseParser parser) {
this.baseUrl = baseURL;
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
}
if (baseUrl.indexOf('?') >= 0) {
throw new RuntimeException(
"Invalid base url for solrj. The base URL must not contain parameters: "
+ baseUrl);
}
if (client != null) {
httpClient = client;
} else {
httpClient = createClient();
}
this.parser = parser;
}
private DefaultHttpClient createClient() {
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory
.getSocketFactory()));
schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory
.getSocketFactory()));
ccm = new ThreadSafeClientConnManager(schemeRegistry);
// Increase default max connection per route to 32
ccm.setDefaultMaxPerRoute(32);
// Increase max total connection to 128
ccm.setMaxTotal(128);
DefaultHttpClient httpClient = new DefaultHttpClient(ccm);
httpClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS,
followRedirects);
return httpClient;
}
/**
* Process the request. If
* {@link org.apache.solr.client.solrj.SolrRequest#getResponseParser()} is
* null, then use {@link #getParser()}
*
* @param request
* The {@link org.apache.solr.client.solrj.SolrRequest} to process
* @return The {@link org.apache.solr.common.util.NamedList} result
* @throws SolrServerException
* @throws IOException
*
* @see #request(org.apache.solr.client.solrj.SolrRequest,
* org.apache.solr.client.solrj.ResponseParser)
*/
@Override
public NamedList<Object> request(final SolrRequest request)
throws SolrServerException, IOException {
ResponseParser responseParser = request.getResponseParser();
if (responseParser == null) {
responseParser = parser;
}
return request(request, responseParser);
}
public NamedList<Object> request(final SolrRequest request,
final ResponseParser processor) throws SolrServerException, IOException {
HttpRequestBase method = null;
InputStream is = null;
SolrParams params = request.getParams();
Collection<ContentStream> streams = requestWriter.getContentStreams(request);
String path = requestWriter.getPath(request);
if (path == null || !path.startsWith("/")) {
path = DEFAULT_PATH;
}
ResponseParser parser = request.getResponseParser();
if (parser == null) {
parser = this.parser;
}
// The parser 'wt=' and 'version=' params are used instead of the original
// params
ModifiableSolrParams wparams = new ModifiableSolrParams(params);
wparams.set(CommonParams.WT, parser.getWriterType());
wparams.set(CommonParams.VERSION, parser.getVersion());
if (invariantParams != null) {
wparams.add(invariantParams);
}
params = wparams;
int tries = maxRetries + 1;
try {
while( tries-- > 0 ) {
// Note: since we aren't do intermittent time keeping
// ourselves, the potential non-timeout latency could be as
// much as tries-times (plus scheduling effects) the given
// timeAllowed.
try {
if( SolrRequest.METHOD.GET == request.getMethod() ) {
if( streams != null ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!" );
}
method = new HttpGet( baseUrl + path + ClientUtils.toQueryString( params, false ) );
}
else if( SolrRequest.METHOD.POST == request.getMethod() ) {
String url = baseUrl + path;
boolean isMultipart = ( streams != null && streams.size() > 1 );
LinkedList<NameValuePair> postParams = new LinkedList<NameValuePair>();
if (streams == null || isMultipart) {
HttpPost post = new HttpPost(url);
post.setHeader("Content-Charset", "UTF-8");
if (!this.useMultiPartPost && !isMultipart) {
post.addHeader("Content-Type",
"application/x-www-form-urlencoded; charset=UTF-8");
}
List<FormBodyPart> parts = new LinkedList<FormBodyPart>();
Iterator<String> iter = params.getParameterNamesIterator();
while (iter.hasNext()) {
String p = iter.next();
String[] vals = params.getParams(p);
if (vals != null) {
for (String v : vals) {
if (this.useMultiPartPost || isMultipart) {
parts.add(new FormBodyPart(p, new StringBody(v, Charset.forName("UTF-8"))));
} else {
postParams.add(new BasicNameValuePair(p, v));
}
}
}
}
if (isMultipart) {
for (ContentStream content : streams) {
- parts.add(new FormBodyPart(content.getName(), new InputStreamBody(content.getStream(), content.getName())));
+ parts.add(new FormBodyPart(content.getName(),
+ new InputStreamBody(
+ content.getStream(),
+ content.getContentType(),
+ content.getName())));
}
}
if (parts.size() > 0) {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(FormBodyPart p: parts) {
entity.addPart(p);
}
post.setEntity(entity);
} else {
//not using multipart
HttpEntity e;
post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8"));
}
method = post;
}
// It is has one stream, it is the post body, put the params in the URL
else {
String pstr = ClientUtils.toQueryString(params, false);
HttpPost post = new HttpPost(url + pstr);
// Single stream as body
// Using a loop just to get the first one
final ContentStream[] contentStream = new ContentStream[1];
for (ContentStream content : streams) {
contentStream[0] = content;
break;
}
if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) {
@Override
public Header getContentType() {
return new BasicHeader("Content-Type", contentStream[0].getContentType());
}
@Override
public boolean isRepeatable() {
return false;
}
});
} else {
post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) {
@Override
public Header getContentType() {
return new BasicHeader("Content-Type", contentStream[0].getContentType());
}
@Override
public boolean isRepeatable() {
return false;
}
});
}
method = post;
}
}
else {
throw new SolrServerException("Unsupported method: "+request.getMethod() );
}
}
catch( NoHttpResponseException r ) {
method = null;
if(is != null) {
is.close();
}
// If out of tries then just rethrow (as normal error).
if (tries < 1) {
throw r;
}
}
}
} catch (IOException ex) {
throw new SolrServerException("error reading streams", ex);
}
// TODO: move to a interceptor?
method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS,
followRedirects);
method.addHeader("User-Agent", AGENT);
InputStream respBody = null;
try {
// Execute the method.
final HttpResponse response = httpClient.execute(method);
int httpStatus = response.getStatusLine().getStatusCode();
// Read the contents
String charset = EntityUtils.getContentCharSet(response.getEntity());
respBody = response.getEntity().getContent();
// handle some http level checks before trying to parse the response
switch (httpStatus) {
case HttpStatus.SC_OK:
case HttpStatus.SC_BAD_REQUEST:
break;
case HttpStatus.SC_MOVED_PERMANENTLY:
case HttpStatus.SC_MOVED_TEMPORARILY:
if (!followRedirects) {
throw new SolrServerException("Server at " + getBaseURL()
+ " sent back a redirect (" + httpStatus + ").");
}
break;
case HttpStatus.SC_NOT_FOUND:
throw new SolrServerException("Server at " + getBaseURL()
+ " was not found (404).");
default:
throw new SolrException(SolrException.ErrorCode.getErrorCode(httpStatus), "Server at " + getBaseURL()
+ " returned non ok status:" + httpStatus + ", message:"
+ response.getStatusLine().getReasonPhrase());
}
NamedList<Object> rsp = processor.processResponse(respBody, charset);
if (httpStatus != HttpStatus.SC_OK) {
String reason = null;
try {
NamedList err = (NamedList) rsp.get("error");
if (err != null) {
reason = (String) err.get("msg");
// TODO? get the trace?
}
} catch (Exception ex) {}
if (reason == null) {
StringBuilder msg = new StringBuilder();
msg.append(response.getStatusLine().getReasonPhrase());
msg.append("\n\n");
msg.append("request: " + method.getURI());
reason = java.net.URLDecoder.decode(msg.toString(), UTF_8);
}
throw new SolrException(
SolrException.ErrorCode.getErrorCode(httpStatus), reason);
}
return rsp;
} catch (ConnectException e) {
throw new SolrServerException("Server refused connection at: "
+ getBaseURL(), e);
} catch (SocketTimeoutException e) {
throw new SolrServerException(
"Timeout occured while waiting response from server at: "
+ getBaseURL(), e);
} catch (IOException e) {
throw new SolrServerException(
"IOException occured when talking to server at: " + getBaseURL(), e);
} finally {
if (respBody != null) {
try {
respBody.close();
} catch (Throwable t) {} // ignore
}
}
}
// -------------------------------------------------------------------
// -------------------------------------------------------------------
/**
* Retrieve the default list of parameters are added to every request
* regardless.
*
* @see #invariantParams
*/
public ModifiableSolrParams getInvariantParams() {
return invariantParams;
}
public String getBaseURL() {
return baseUrl;
}
public void setBaseURL(String baseURL) {
this.baseUrl = baseURL;
}
public ResponseParser getParser() {
return parser;
}
/**
* Note: This setter method is <b>not thread-safe</b>.
*
* @param processor
* Default Response Parser chosen to parse the response if the parser
* were not specified as part of the request.
* @see org.apache.solr.client.solrj.SolrRequest#getResponseParser()
*/
public void setParser(ResponseParser processor) {
parser = processor;
}
public HttpClient getHttpClient() {
return httpClient;
}
/**
* HttpConnectionParams.setConnectionTimeout
*
* @param timeout
* Timeout in milliseconds
**/
public void setConnectionTimeout(int timeout) {
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), timeout);
}
/**
* Sets HttpConnectionParams.setSoTimeout (read timeout). This is desirable
* for queries, but probably not for indexing.
*
* @param timeout
* Timeout in milliseconds
**/
public void setSoTimeout(int timeout) {
HttpConnectionParams.setSoTimeout(httpClient.getParams(), timeout);
}
/**
* HttpClientParams.setRedirecting
*
* @see #followRedirects
*/
public void setFollowRedirects(boolean followRedirects) {
this.followRedirects = followRedirects;
new ClientParamBean(httpClient.getParams())
.setHandleRedirects(followRedirects);
}
private static class UseCompressionRequestInterceptor implements
HttpRequestInterceptor {
@Override
public void process(HttpRequest request, HttpContext context)
throws HttpException, IOException {
if (!request.containsHeader("Accept-Encoding")) {
request.addHeader("Accept-Encoding", "gzip, deflate");
}
}
}
private static class UseCompressionResponseInterceptor implements
HttpResponseInterceptor {
public void process(final HttpResponse response, final HttpContext context)
throws HttpException, IOException {
HttpEntity entity = response.getEntity();
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
response
.setEntity(new GzipDecompressingEntity(response.getEntity()));
return;
}
if (codecs[i].getName().equalsIgnoreCase("deflate")) {
response.setEntity(new DeflateDecompressingEntity(response
.getEntity()));
return;
}
}
}
}
}
private static class GzipDecompressingEntity extends HttpEntityWrapper {
public GzipDecompressingEntity(final HttpEntity entity) {
super(entity);
}
public InputStream getContent() throws IOException, IllegalStateException {
return new GZIPInputStream(wrappedEntity.getContent());
}
public long getContentLength() {
return -1;
}
}
private static class DeflateDecompressingEntity extends
GzipDecompressingEntity {
public DeflateDecompressingEntity(final HttpEntity entity) {
super(entity);
}
public InputStream getContent() throws IOException, IllegalStateException {
return new InflaterInputStream(wrappedEntity.getContent());
}
}
/**
* Allow server->client communication to be compressed. Currently gzip and
* deflate are supported. If the server supports compression the response will
* be compressed.
*/
public void setAllowCompression(boolean allowCompression) {
if (httpClient instanceof DefaultHttpClient) {
final DefaultHttpClient client = (DefaultHttpClient) httpClient;
client
.removeRequestInterceptorByClass(UseCompressionRequestInterceptor.class);
client
.removeResponseInterceptorByClass(UseCompressionResponseInterceptor.class);
if (allowCompression) {
client.addRequestInterceptor(new UseCompressionRequestInterceptor());
client.addResponseInterceptor(new UseCompressionResponseInterceptor());
}
} else {
throw new UnsupportedOperationException(
"HttpClient instance was not of type DefaultHttpClient");
}
}
/**
* Set maximum number of retries to attempt in the event of transient errors.
*
* @param maxRetries
* No more than 1 recommended
* @see #maxRetries
*/
public void setMaxRetries(int maxRetries) {
if (maxRetries > 1) {
log.warn("CommonsHttpSolrServer: maximum Retries " + maxRetries
+ " > 1. Maximum recommended retries is 1.");
}
this.maxRetries = maxRetries;
}
public void setRequestWriter(RequestWriter requestWriter) {
this.requestWriter = requestWriter;
}
/**
* Adds the documents supplied by the given iterator.
*
* @param docIterator
* the iterator which returns SolrInputDocument instances
*
* @return the response from the SolrServer
*/
public UpdateResponse add(Iterator<SolrInputDocument> docIterator)
throws SolrServerException, IOException {
UpdateRequest req = new UpdateRequest();
req.setDocIterator(docIterator);
return req.process(this);
}
/**
* Adds the beans supplied by the given iterator.
*
* @param beanIterator
* the iterator which returns Beans
*
* @return the response from the SolrServer
*/
public UpdateResponse addBeans(final Iterator<?> beanIterator)
throws SolrServerException, IOException {
UpdateRequest req = new UpdateRequest();
req.setDocIterator(new Iterator<SolrInputDocument>() {
public boolean hasNext() {
return beanIterator.hasNext();
}
public SolrInputDocument next() {
Object o = beanIterator.next();
if (o == null) return null;
return getBinder().toSolrInputDocument(o);
}
public void remove() {
beanIterator.remove();
}
});
return req.process(this);
}
public void shutdown() {
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
}
}
public void setDefaultMaxConnectionsPerHost(int max) {
if (ccm != null) {
ccm.setDefaultMaxPerRoute(max);
} else {
throw new UnsupportedOperationException(
"Client was created outside of HttpSolrServer");
}
}
/**
* Set the maximum number of connections that can be open at any given time.
*/
public void setMaxTotalConnections(int max) {
if (ccm != null) {
ccm.setMaxTotal(max);
} else {
throw new UnsupportedOperationException(
"Client was created outside of HttpSolrServer");
}
}
}
| true | true | public NamedList<Object> request(final SolrRequest request,
final ResponseParser processor) throws SolrServerException, IOException {
HttpRequestBase method = null;
InputStream is = null;
SolrParams params = request.getParams();
Collection<ContentStream> streams = requestWriter.getContentStreams(request);
String path = requestWriter.getPath(request);
if (path == null || !path.startsWith("/")) {
path = DEFAULT_PATH;
}
ResponseParser parser = request.getResponseParser();
if (parser == null) {
parser = this.parser;
}
// The parser 'wt=' and 'version=' params are used instead of the original
// params
ModifiableSolrParams wparams = new ModifiableSolrParams(params);
wparams.set(CommonParams.WT, parser.getWriterType());
wparams.set(CommonParams.VERSION, parser.getVersion());
if (invariantParams != null) {
wparams.add(invariantParams);
}
params = wparams;
int tries = maxRetries + 1;
try {
while( tries-- > 0 ) {
// Note: since we aren't do intermittent time keeping
// ourselves, the potential non-timeout latency could be as
// much as tries-times (plus scheduling effects) the given
// timeAllowed.
try {
if( SolrRequest.METHOD.GET == request.getMethod() ) {
if( streams != null ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!" );
}
method = new HttpGet( baseUrl + path + ClientUtils.toQueryString( params, false ) );
}
else if( SolrRequest.METHOD.POST == request.getMethod() ) {
String url = baseUrl + path;
boolean isMultipart = ( streams != null && streams.size() > 1 );
LinkedList<NameValuePair> postParams = new LinkedList<NameValuePair>();
if (streams == null || isMultipart) {
HttpPost post = new HttpPost(url);
post.setHeader("Content-Charset", "UTF-8");
if (!this.useMultiPartPost && !isMultipart) {
post.addHeader("Content-Type",
"application/x-www-form-urlencoded; charset=UTF-8");
}
List<FormBodyPart> parts = new LinkedList<FormBodyPart>();
Iterator<String> iter = params.getParameterNamesIterator();
while (iter.hasNext()) {
String p = iter.next();
String[] vals = params.getParams(p);
if (vals != null) {
for (String v : vals) {
if (this.useMultiPartPost || isMultipart) {
parts.add(new FormBodyPart(p, new StringBody(v, Charset.forName("UTF-8"))));
} else {
postParams.add(new BasicNameValuePair(p, v));
}
}
}
}
if (isMultipart) {
for (ContentStream content : streams) {
parts.add(new FormBodyPart(content.getName(), new InputStreamBody(content.getStream(), content.getName())));
}
}
if (parts.size() > 0) {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(FormBodyPart p: parts) {
entity.addPart(p);
}
post.setEntity(entity);
} else {
//not using multipart
HttpEntity e;
post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8"));
}
method = post;
}
// It is has one stream, it is the post body, put the params in the URL
else {
String pstr = ClientUtils.toQueryString(params, false);
HttpPost post = new HttpPost(url + pstr);
// Single stream as body
// Using a loop just to get the first one
final ContentStream[] contentStream = new ContentStream[1];
for (ContentStream content : streams) {
contentStream[0] = content;
break;
}
if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) {
@Override
public Header getContentType() {
return new BasicHeader("Content-Type", contentStream[0].getContentType());
}
@Override
public boolean isRepeatable() {
return false;
}
});
} else {
post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) {
@Override
public Header getContentType() {
return new BasicHeader("Content-Type", contentStream[0].getContentType());
}
@Override
public boolean isRepeatable() {
return false;
}
});
}
method = post;
}
}
else {
throw new SolrServerException("Unsupported method: "+request.getMethod() );
}
}
catch( NoHttpResponseException r ) {
method = null;
if(is != null) {
is.close();
}
// If out of tries then just rethrow (as normal error).
if (tries < 1) {
throw r;
}
}
}
} catch (IOException ex) {
throw new SolrServerException("error reading streams", ex);
}
// TODO: move to a interceptor?
method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS,
followRedirects);
method.addHeader("User-Agent", AGENT);
InputStream respBody = null;
try {
// Execute the method.
final HttpResponse response = httpClient.execute(method);
int httpStatus = response.getStatusLine().getStatusCode();
// Read the contents
String charset = EntityUtils.getContentCharSet(response.getEntity());
respBody = response.getEntity().getContent();
// handle some http level checks before trying to parse the response
switch (httpStatus) {
case HttpStatus.SC_OK:
case HttpStatus.SC_BAD_REQUEST:
break;
case HttpStatus.SC_MOVED_PERMANENTLY:
case HttpStatus.SC_MOVED_TEMPORARILY:
if (!followRedirects) {
throw new SolrServerException("Server at " + getBaseURL()
+ " sent back a redirect (" + httpStatus + ").");
}
break;
case HttpStatus.SC_NOT_FOUND:
throw new SolrServerException("Server at " + getBaseURL()
+ " was not found (404).");
default:
throw new SolrException(SolrException.ErrorCode.getErrorCode(httpStatus), "Server at " + getBaseURL()
+ " returned non ok status:" + httpStatus + ", message:"
+ response.getStatusLine().getReasonPhrase());
}
NamedList<Object> rsp = processor.processResponse(respBody, charset);
if (httpStatus != HttpStatus.SC_OK) {
String reason = null;
try {
NamedList err = (NamedList) rsp.get("error");
if (err != null) {
reason = (String) err.get("msg");
// TODO? get the trace?
}
} catch (Exception ex) {}
if (reason == null) {
StringBuilder msg = new StringBuilder();
msg.append(response.getStatusLine().getReasonPhrase());
msg.append("\n\n");
msg.append("request: " + method.getURI());
reason = java.net.URLDecoder.decode(msg.toString(), UTF_8);
}
throw new SolrException(
SolrException.ErrorCode.getErrorCode(httpStatus), reason);
}
return rsp;
} catch (ConnectException e) {
throw new SolrServerException("Server refused connection at: "
+ getBaseURL(), e);
} catch (SocketTimeoutException e) {
throw new SolrServerException(
"Timeout occured while waiting response from server at: "
+ getBaseURL(), e);
} catch (IOException e) {
throw new SolrServerException(
"IOException occured when talking to server at: " + getBaseURL(), e);
} finally {
if (respBody != null) {
try {
respBody.close();
} catch (Throwable t) {} // ignore
}
}
}
| public NamedList<Object> request(final SolrRequest request,
final ResponseParser processor) throws SolrServerException, IOException {
HttpRequestBase method = null;
InputStream is = null;
SolrParams params = request.getParams();
Collection<ContentStream> streams = requestWriter.getContentStreams(request);
String path = requestWriter.getPath(request);
if (path == null || !path.startsWith("/")) {
path = DEFAULT_PATH;
}
ResponseParser parser = request.getResponseParser();
if (parser == null) {
parser = this.parser;
}
// The parser 'wt=' and 'version=' params are used instead of the original
// params
ModifiableSolrParams wparams = new ModifiableSolrParams(params);
wparams.set(CommonParams.WT, parser.getWriterType());
wparams.set(CommonParams.VERSION, parser.getVersion());
if (invariantParams != null) {
wparams.add(invariantParams);
}
params = wparams;
int tries = maxRetries + 1;
try {
while( tries-- > 0 ) {
// Note: since we aren't do intermittent time keeping
// ourselves, the potential non-timeout latency could be as
// much as tries-times (plus scheduling effects) the given
// timeAllowed.
try {
if( SolrRequest.METHOD.GET == request.getMethod() ) {
if( streams != null ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!" );
}
method = new HttpGet( baseUrl + path + ClientUtils.toQueryString( params, false ) );
}
else if( SolrRequest.METHOD.POST == request.getMethod() ) {
String url = baseUrl + path;
boolean isMultipart = ( streams != null && streams.size() > 1 );
LinkedList<NameValuePair> postParams = new LinkedList<NameValuePair>();
if (streams == null || isMultipart) {
HttpPost post = new HttpPost(url);
post.setHeader("Content-Charset", "UTF-8");
if (!this.useMultiPartPost && !isMultipart) {
post.addHeader("Content-Type",
"application/x-www-form-urlencoded; charset=UTF-8");
}
List<FormBodyPart> parts = new LinkedList<FormBodyPart>();
Iterator<String> iter = params.getParameterNamesIterator();
while (iter.hasNext()) {
String p = iter.next();
String[] vals = params.getParams(p);
if (vals != null) {
for (String v : vals) {
if (this.useMultiPartPost || isMultipart) {
parts.add(new FormBodyPart(p, new StringBody(v, Charset.forName("UTF-8"))));
} else {
postParams.add(new BasicNameValuePair(p, v));
}
}
}
}
if (isMultipart) {
for (ContentStream content : streams) {
parts.add(new FormBodyPart(content.getName(),
new InputStreamBody(
content.getStream(),
content.getContentType(),
content.getName())));
}
}
if (parts.size() > 0) {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(FormBodyPart p: parts) {
entity.addPart(p);
}
post.setEntity(entity);
} else {
//not using multipart
HttpEntity e;
post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8"));
}
method = post;
}
// It is has one stream, it is the post body, put the params in the URL
else {
String pstr = ClientUtils.toQueryString(params, false);
HttpPost post = new HttpPost(url + pstr);
// Single stream as body
// Using a loop just to get the first one
final ContentStream[] contentStream = new ContentStream[1];
for (ContentStream content : streams) {
contentStream[0] = content;
break;
}
if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) {
@Override
public Header getContentType() {
return new BasicHeader("Content-Type", contentStream[0].getContentType());
}
@Override
public boolean isRepeatable() {
return false;
}
});
} else {
post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) {
@Override
public Header getContentType() {
return new BasicHeader("Content-Type", contentStream[0].getContentType());
}
@Override
public boolean isRepeatable() {
return false;
}
});
}
method = post;
}
}
else {
throw new SolrServerException("Unsupported method: "+request.getMethod() );
}
}
catch( NoHttpResponseException r ) {
method = null;
if(is != null) {
is.close();
}
// If out of tries then just rethrow (as normal error).
if (tries < 1) {
throw r;
}
}
}
} catch (IOException ex) {
throw new SolrServerException("error reading streams", ex);
}
// TODO: move to a interceptor?
method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS,
followRedirects);
method.addHeader("User-Agent", AGENT);
InputStream respBody = null;
try {
// Execute the method.
final HttpResponse response = httpClient.execute(method);
int httpStatus = response.getStatusLine().getStatusCode();
// Read the contents
String charset = EntityUtils.getContentCharSet(response.getEntity());
respBody = response.getEntity().getContent();
// handle some http level checks before trying to parse the response
switch (httpStatus) {
case HttpStatus.SC_OK:
case HttpStatus.SC_BAD_REQUEST:
break;
case HttpStatus.SC_MOVED_PERMANENTLY:
case HttpStatus.SC_MOVED_TEMPORARILY:
if (!followRedirects) {
throw new SolrServerException("Server at " + getBaseURL()
+ " sent back a redirect (" + httpStatus + ").");
}
break;
case HttpStatus.SC_NOT_FOUND:
throw new SolrServerException("Server at " + getBaseURL()
+ " was not found (404).");
default:
throw new SolrException(SolrException.ErrorCode.getErrorCode(httpStatus), "Server at " + getBaseURL()
+ " returned non ok status:" + httpStatus + ", message:"
+ response.getStatusLine().getReasonPhrase());
}
NamedList<Object> rsp = processor.processResponse(respBody, charset);
if (httpStatus != HttpStatus.SC_OK) {
String reason = null;
try {
NamedList err = (NamedList) rsp.get("error");
if (err != null) {
reason = (String) err.get("msg");
// TODO? get the trace?
}
} catch (Exception ex) {}
if (reason == null) {
StringBuilder msg = new StringBuilder();
msg.append(response.getStatusLine().getReasonPhrase());
msg.append("\n\n");
msg.append("request: " + method.getURI());
reason = java.net.URLDecoder.decode(msg.toString(), UTF_8);
}
throw new SolrException(
SolrException.ErrorCode.getErrorCode(httpStatus), reason);
}
return rsp;
} catch (ConnectException e) {
throw new SolrServerException("Server refused connection at: "
+ getBaseURL(), e);
} catch (SocketTimeoutException e) {
throw new SolrServerException(
"Timeout occured while waiting response from server at: "
+ getBaseURL(), e);
} catch (IOException e) {
throw new SolrServerException(
"IOException occured when talking to server at: " + getBaseURL(), e);
} finally {
if (respBody != null) {
try {
respBody.close();
} catch (Throwable t) {} // ignore
}
}
}
|
diff --git a/VAGGS/src/com/vaggs/Utils/DebuggingDBObjects.java b/VAGGS/src/com/vaggs/Utils/DebuggingDBObjects.java
index 3d4c376..3f855d1 100644
--- a/VAGGS/src/com/vaggs/Utils/DebuggingDBObjects.java
+++ b/VAGGS/src/com/vaggs/Utils/DebuggingDBObjects.java
@@ -1,154 +1,154 @@
package com.vaggs.Utils;
import static com.vaggs.Utils.OfyService.ofy;
import java.util.ArrayList;
import java.util.Arrays;
import com.google.appengine.labs.repackaged.com.google.common.collect.Lists;
import com.vaggs.AirportDiagram.Airport;
import com.vaggs.Route.Route;
import com.vaggs.Route.Taxiway;
import com.vaggs.Route.Transponder;
import com.vaggs.Route.Waypoint;
public class DebuggingDBObjects {
public static void createDBObjects () {
/* Transponder Code = 1 */
Route debugRoute = Route.ParseRouteByTaxiways((new Waypoint(new LatLng(41.7258, -71.4368), false, false)), "");
debugRoute.addWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.7258, -71.4368), false, false),
new Waypoint(new LatLng(41.7087976, -71.44134), false, false),
new Waypoint(new LatLng(41.73783, -71.41615), false, false),
new Waypoint(new LatLng(41.725, -71.433333), true, false)
));
//Transponder.Parse(1).setRoute(debugRoute);
//Transponder.Parse(2).setRoute(debugRoute);
ArrayList<Taxiway> taxiways = Lists.newArrayList();
Taxiway taxiway = new Taxiway('B');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.73228367493647, -71.42739772796631), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.42662525177002), false, true),
new Waypoint(new LatLng(41.72853650684023, -71.42628192901611), false, false),
new Waypoint(new LatLng(41.727479573755126, -71.42520904541016), false, true),
new Waypoint(new LatLng(41.726678855296136, -71.42430782318115), true, true),
new Waypoint(new LatLng(41.724180549563606, -71.42203330993652), false, false),
new Waypoint(new LatLng(41.72321963687659, -71.42310619354248), true, false),
new Waypoint(new LatLng(41.722707144234306, -71.42400741577148), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('A');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.732027465276374, -71.42314910888672), false, false),
new Waypoint(new LatLng(41.7312588301645, -71.42203330993652), false, true),
new Waypoint(new LatLng(41.73074640164693, -71.42087459564209), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('C');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, false),
new Waypoint(new LatLng(41.72575000938133, -71.43280506134033), false, false),
new Waypoint(new LatLng(41.72571797997234, -71.43001556396484), false, false),
new Waypoint(new LatLng(41.72571797997234, -71.42877101898193), false, false),
new Waypoint(new LatLng(41.725205507257044, -71.42696857452393), false, true),
new Waypoint(new LatLng(41.72453288061494, -71.42598152160645), true, true),
new Waypoint(new LatLng(41.722707144234306, -71.42400741577148), false, true),
new Waypoint(new LatLng(41.71783826026642, -71.41907215118408), false, false),
new Waypoint(new LatLng(41.718414857887055, -71.41825675964355), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('E');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.719536005117995, -71.43555164337158), false, true),
new Waypoint(new LatLng(41.71610843636524, -71.43426418304443), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('F');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72869664669985, -71.43306255340576), false, true),
new Waypoint(new LatLng(41.73151504289037, -71.43237590789795), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('M');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.7312588301645, -71.42203330993652), false, true),
new Waypoint(new LatLng(41.729849641905204, -71.42327785491943), false, true),
new Waypoint(new LatLng(41.727479573755126, -71.42520904541016), false, true),
new Waypoint(new LatLng(41.72626247775354, -71.42602443695068), true, true),
new Waypoint(new LatLng(41.725205507257044, -71.42696857452393), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('N');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72808811310961, -71.43435001373291), false, false),
- new Waypoint(new LatLng(41.72965747747473, -71.43061637878418), false, true),
new Waypoint(new LatLng(41.72869664669985, -71.43306255340576), false, false),
new Waypoint(new LatLng(41.729561395043916, -71.43237590789795), false, true),
+ new Waypoint(new LatLng(41.72965747747473, -71.43061637878418), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.4296293258667), true, false),
new Waypoint(new LatLng(41.72972153234874, -71.42662525177002), false, true),
new Waypoint(new LatLng(41.729849641905204, -71.42327785491943), false, true),
new Waypoint(new LatLng(41.72988166925439, -71.42160415649414), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('S');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.71796639351807, -71.4325475692749), false, true),
new Waypoint(new LatLng(41.71610843636524, -71.43426418304443), false, true),
new Waypoint(new LatLng(41.714314495734975, -71.43537998199463), false, false),
new Waypoint(new LatLng(41.713769896707845, -71.43443584442139), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('T');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72965747747473, -71.43061637878418), false, false),
new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, false),
new Waypoint(new LatLng(41.72094541960078, -71.4376974105835), false, false),
new Waypoint(new LatLng(41.72056103689838, -71.43701076507568), false, true),
new Waypoint(new LatLng(41.719536005117995, -71.43555164337158), false, true),
new Waypoint(new LatLng(41.71796639351807, -71.4325475692749), false, true),
new Waypoint(new LatLng(41.71754995951615, -71.43151760101318), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('V');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.73228367493647, -71.42739772796631), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.4296293258667), true, true),
new Waypoint(new LatLng(41.72575000938133, -71.43280506134033), false, true),
new Waypoint(new LatLng(41.72056103689838, -71.43701076507568), false, true)
));
taxiways.add(taxiway);
Airport kpvd = new Airport("kpvd", null, null, null, "");
kpvd.setTaxiways(taxiways);
kpvd.setRouteStartingPoints(Arrays.asList(new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, true)));
ofy().save().entities(kpvd).now();
AtcUser josh = new AtcUser("[email protected]");
AtcUser hawk = new AtcUser("[email protected]");
AtcUser max = new AtcUser("[email protected]");
ofy().save().entity(josh).now();
ofy().save().entity(hawk).now();
ofy().save().entity(max).now();
}
}
| false | true | public static void createDBObjects () {
/* Transponder Code = 1 */
Route debugRoute = Route.ParseRouteByTaxiways((new Waypoint(new LatLng(41.7258, -71.4368), false, false)), "");
debugRoute.addWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.7258, -71.4368), false, false),
new Waypoint(new LatLng(41.7087976, -71.44134), false, false),
new Waypoint(new LatLng(41.73783, -71.41615), false, false),
new Waypoint(new LatLng(41.725, -71.433333), true, false)
));
//Transponder.Parse(1).setRoute(debugRoute);
//Transponder.Parse(2).setRoute(debugRoute);
ArrayList<Taxiway> taxiways = Lists.newArrayList();
Taxiway taxiway = new Taxiway('B');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.73228367493647, -71.42739772796631), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.42662525177002), false, true),
new Waypoint(new LatLng(41.72853650684023, -71.42628192901611), false, false),
new Waypoint(new LatLng(41.727479573755126, -71.42520904541016), false, true),
new Waypoint(new LatLng(41.726678855296136, -71.42430782318115), true, true),
new Waypoint(new LatLng(41.724180549563606, -71.42203330993652), false, false),
new Waypoint(new LatLng(41.72321963687659, -71.42310619354248), true, false),
new Waypoint(new LatLng(41.722707144234306, -71.42400741577148), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('A');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.732027465276374, -71.42314910888672), false, false),
new Waypoint(new LatLng(41.7312588301645, -71.42203330993652), false, true),
new Waypoint(new LatLng(41.73074640164693, -71.42087459564209), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('C');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, false),
new Waypoint(new LatLng(41.72575000938133, -71.43280506134033), false, false),
new Waypoint(new LatLng(41.72571797997234, -71.43001556396484), false, false),
new Waypoint(new LatLng(41.72571797997234, -71.42877101898193), false, false),
new Waypoint(new LatLng(41.725205507257044, -71.42696857452393), false, true),
new Waypoint(new LatLng(41.72453288061494, -71.42598152160645), true, true),
new Waypoint(new LatLng(41.722707144234306, -71.42400741577148), false, true),
new Waypoint(new LatLng(41.71783826026642, -71.41907215118408), false, false),
new Waypoint(new LatLng(41.718414857887055, -71.41825675964355), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('E');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.719536005117995, -71.43555164337158), false, true),
new Waypoint(new LatLng(41.71610843636524, -71.43426418304443), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('F');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72869664669985, -71.43306255340576), false, true),
new Waypoint(new LatLng(41.73151504289037, -71.43237590789795), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('M');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.7312588301645, -71.42203330993652), false, true),
new Waypoint(new LatLng(41.729849641905204, -71.42327785491943), false, true),
new Waypoint(new LatLng(41.727479573755126, -71.42520904541016), false, true),
new Waypoint(new LatLng(41.72626247775354, -71.42602443695068), true, true),
new Waypoint(new LatLng(41.725205507257044, -71.42696857452393), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('N');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72808811310961, -71.43435001373291), false, false),
new Waypoint(new LatLng(41.72965747747473, -71.43061637878418), false, true),
new Waypoint(new LatLng(41.72869664669985, -71.43306255340576), false, false),
new Waypoint(new LatLng(41.729561395043916, -71.43237590789795), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.4296293258667), true, false),
new Waypoint(new LatLng(41.72972153234874, -71.42662525177002), false, true),
new Waypoint(new LatLng(41.729849641905204, -71.42327785491943), false, true),
new Waypoint(new LatLng(41.72988166925439, -71.42160415649414), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('S');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.71796639351807, -71.4325475692749), false, true),
new Waypoint(new LatLng(41.71610843636524, -71.43426418304443), false, true),
new Waypoint(new LatLng(41.714314495734975, -71.43537998199463), false, false),
new Waypoint(new LatLng(41.713769896707845, -71.43443584442139), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('T');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72965747747473, -71.43061637878418), false, false),
new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, false),
new Waypoint(new LatLng(41.72094541960078, -71.4376974105835), false, false),
new Waypoint(new LatLng(41.72056103689838, -71.43701076507568), false, true),
new Waypoint(new LatLng(41.719536005117995, -71.43555164337158), false, true),
new Waypoint(new LatLng(41.71796639351807, -71.4325475692749), false, true),
new Waypoint(new LatLng(41.71754995951615, -71.43151760101318), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('V');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.73228367493647, -71.42739772796631), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.4296293258667), true, true),
new Waypoint(new LatLng(41.72575000938133, -71.43280506134033), false, true),
new Waypoint(new LatLng(41.72056103689838, -71.43701076507568), false, true)
));
taxiways.add(taxiway);
Airport kpvd = new Airport("kpvd", null, null, null, "");
kpvd.setTaxiways(taxiways);
kpvd.setRouteStartingPoints(Arrays.asList(new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, true)));
ofy().save().entities(kpvd).now();
AtcUser josh = new AtcUser("[email protected]");
AtcUser hawk = new AtcUser("[email protected]");
AtcUser max = new AtcUser("[email protected]");
ofy().save().entity(josh).now();
ofy().save().entity(hawk).now();
ofy().save().entity(max).now();
}
| public static void createDBObjects () {
/* Transponder Code = 1 */
Route debugRoute = Route.ParseRouteByTaxiways((new Waypoint(new LatLng(41.7258, -71.4368), false, false)), "");
debugRoute.addWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.7258, -71.4368), false, false),
new Waypoint(new LatLng(41.7087976, -71.44134), false, false),
new Waypoint(new LatLng(41.73783, -71.41615), false, false),
new Waypoint(new LatLng(41.725, -71.433333), true, false)
));
//Transponder.Parse(1).setRoute(debugRoute);
//Transponder.Parse(2).setRoute(debugRoute);
ArrayList<Taxiway> taxiways = Lists.newArrayList();
Taxiway taxiway = new Taxiway('B');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.73228367493647, -71.42739772796631), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.42662525177002), false, true),
new Waypoint(new LatLng(41.72853650684023, -71.42628192901611), false, false),
new Waypoint(new LatLng(41.727479573755126, -71.42520904541016), false, true),
new Waypoint(new LatLng(41.726678855296136, -71.42430782318115), true, true),
new Waypoint(new LatLng(41.724180549563606, -71.42203330993652), false, false),
new Waypoint(new LatLng(41.72321963687659, -71.42310619354248), true, false),
new Waypoint(new LatLng(41.722707144234306, -71.42400741577148), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('A');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.732027465276374, -71.42314910888672), false, false),
new Waypoint(new LatLng(41.7312588301645, -71.42203330993652), false, true),
new Waypoint(new LatLng(41.73074640164693, -71.42087459564209), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('C');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, false),
new Waypoint(new LatLng(41.72575000938133, -71.43280506134033), false, false),
new Waypoint(new LatLng(41.72571797997234, -71.43001556396484), false, false),
new Waypoint(new LatLng(41.72571797997234, -71.42877101898193), false, false),
new Waypoint(new LatLng(41.725205507257044, -71.42696857452393), false, true),
new Waypoint(new LatLng(41.72453288061494, -71.42598152160645), true, true),
new Waypoint(new LatLng(41.722707144234306, -71.42400741577148), false, true),
new Waypoint(new LatLng(41.71783826026642, -71.41907215118408), false, false),
new Waypoint(new LatLng(41.718414857887055, -71.41825675964355), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('E');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.719536005117995, -71.43555164337158), false, true),
new Waypoint(new LatLng(41.71610843636524, -71.43426418304443), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('F');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72869664669985, -71.43306255340576), false, true),
new Waypoint(new LatLng(41.73151504289037, -71.43237590789795), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('M');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.7312588301645, -71.42203330993652), false, true),
new Waypoint(new LatLng(41.729849641905204, -71.42327785491943), false, true),
new Waypoint(new LatLng(41.727479573755126, -71.42520904541016), false, true),
new Waypoint(new LatLng(41.72626247775354, -71.42602443695068), true, true),
new Waypoint(new LatLng(41.725205507257044, -71.42696857452393), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('N');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72808811310961, -71.43435001373291), false, false),
new Waypoint(new LatLng(41.72869664669985, -71.43306255340576), false, false),
new Waypoint(new LatLng(41.729561395043916, -71.43237590789795), false, true),
new Waypoint(new LatLng(41.72965747747473, -71.43061637878418), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.4296293258667), true, false),
new Waypoint(new LatLng(41.72972153234874, -71.42662525177002), false, true),
new Waypoint(new LatLng(41.729849641905204, -71.42327785491943), false, true),
new Waypoint(new LatLng(41.72988166925439, -71.42160415649414), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('S');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.71796639351807, -71.4325475692749), false, true),
new Waypoint(new LatLng(41.71610843636524, -71.43426418304443), false, true),
new Waypoint(new LatLng(41.714314495734975, -71.43537998199463), false, false),
new Waypoint(new LatLng(41.713769896707845, -71.43443584442139), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('T');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72965747747473, -71.43061637878418), false, false),
new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, false),
new Waypoint(new LatLng(41.72094541960078, -71.4376974105835), false, false),
new Waypoint(new LatLng(41.72056103689838, -71.43701076507568), false, true),
new Waypoint(new LatLng(41.719536005117995, -71.43555164337158), false, true),
new Waypoint(new LatLng(41.71796639351807, -71.4325475692749), false, true),
new Waypoint(new LatLng(41.71754995951615, -71.43151760101318), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('V');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.73228367493647, -71.42739772796631), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.4296293258667), true, true),
new Waypoint(new LatLng(41.72575000938133, -71.43280506134033), false, true),
new Waypoint(new LatLng(41.72056103689838, -71.43701076507568), false, true)
));
taxiways.add(taxiway);
Airport kpvd = new Airport("kpvd", null, null, null, "");
kpvd.setTaxiways(taxiways);
kpvd.setRouteStartingPoints(Arrays.asList(new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, true)));
ofy().save().entities(kpvd).now();
AtcUser josh = new AtcUser("[email protected]");
AtcUser hawk = new AtcUser("[email protected]");
AtcUser max = new AtcUser("[email protected]");
ofy().save().entity(josh).now();
ofy().save().entity(hawk).now();
ofy().save().entity(max).now();
}
|
diff --git a/lib-core/src/main/java/com/stratelia/webactiv/beans/admin/Admin.java b/lib-core/src/main/java/com/stratelia/webactiv/beans/admin/Admin.java
index 523694680a..64def72245 100644
--- a/lib-core/src/main/java/com/stratelia/webactiv/beans/admin/Admin.java
+++ b/lib-core/src/main/java/com/stratelia/webactiv/beans/admin/Admin.java
@@ -1,6703 +1,6705 @@
/**
* Copyright (C) 2000 - 2011 Silverpeas
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of the GPL, you may
* redistribute this Program in connection with Free/Libre Open Source Software ("FLOSS")
* applications as described in Silverpeas's FLOSS exception. You should have received a copy of the
* text describing the FLOSS exception, and it is also available here:
* "http://repository.silverpeas.com/legal/licensing"
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.stratelia.webactiv.beans.admin;
import com.google.common.collect.Sets;
import com.silverpeas.admin.components.*;
import com.silverpeas.admin.notification.AdminNotificationService;
import com.silverpeas.admin.spaces.SpaceInstanciator;
import com.silverpeas.admin.spaces.SpaceTemplate;
import com.silverpeas.util.ArrayUtil;
import com.silverpeas.util.StringUtil;
import com.silverpeas.util.i18n.I18NHelper;
import com.stratelia.silverpeas.containerManager.ContainerManager;
import com.stratelia.silverpeas.contentManager.ContentManager;
import com.stratelia.silverpeas.domains.ldapdriver.LDAPSynchroUserItf;
import com.stratelia.silverpeas.peasCore.URLManager;
import com.stratelia.silverpeas.silvertrace.SilverTrace;
import static com.stratelia.silverpeas.silvertrace.SilverTrace.MODULE_ADMIN;
import com.stratelia.webactiv.SilverpeasRole;
import com.stratelia.webactiv.beans.admin.cache.*;
import com.stratelia.webactiv.organization.AdminPersistenceException;
import com.stratelia.webactiv.organization.OrganizationSchemaPool;
import com.stratelia.webactiv.organization.ScheduledDBReset;
import com.stratelia.webactiv.organization.UserRow;
import com.stratelia.webactiv.util.DBUtil;
import com.stratelia.webactiv.util.ResourceLocator;
import com.stratelia.webactiv.util.exception.SilverpeasException;
import com.stratelia.webactiv.util.indexEngine.model.FullIndexEntry;
import com.stratelia.webactiv.util.indexEngine.model.IndexEngineProxy;
import com.stratelia.webactiv.util.pool.ConnectionPool;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.*;
import javax.inject.Inject;
import org.apache.commons.lang3.time.FastDateFormat;
/**
* @author neysseri
*
*/
/**
* The class Admin is the main class of the Administrator.<BR/> The role of the administrator is to
* create and maintain spaces.
*/
public final class Admin {
public static final String SPACE_KEY_PREFIX = "WA";
// Divers
static private final Object semaphore = new Object();
static private boolean delUsersOnDiffSynchro = true;
static private boolean shouldFallbackGroupNames = true;
static private boolean shouldFallbackUserLogins = false;
static private String m_groupSynchroCron = "";
static private String m_domainSynchroCron = "";
// Helpers
static private final SpaceInstManager spaceManager = new SpaceInstManager();
static private final ComponentInstManager componentManager = new ComponentInstManager();
static private final ProfileInstManager profileManager = new ProfileInstManager();
static private final SpaceProfileInstManager spaceProfileManager = new SpaceProfileInstManager();
static private final GroupManager groupManager = new GroupManager();
static private final UserManager userManager = new UserManager();
static private final ProfiledObjectManager profiledObjectManager = new ProfiledObjectManager();
static private final GroupProfileInstManager groupProfileManager = new GroupProfileInstManager();
// Component instanciator
static private Instanciateur componentInstanciator = null;
static private SpaceInstanciator spaceInstanciator = null;
// Entreprise client space Id
static private String adminDBDriver = null;
static private String productionDbUrl;
static private String productionDbLogin;
static private String productionDbPassword;
static private int m_nEntrepriseClientSpaceId = 0;
static private String administratorMail = null;
static private String m_sDAPIGeneralAdminId = null;
// User Logs
static private Map<String, UserLog> loggedUsers = Collections.synchronizedMap(
new HashMap<String, UserLog>(0));
private static FastDateFormat formatter = FastDateFormat.getInstance("dd/MM/yyyy HH:mm:ss:S");
// Cache management
static private final AdminCache cache = new AdminCache();
// DB Connections Scheduled Resets
static private final ScheduledDBReset scheduledDBReset;
public static final String basketSuffix = " (Restauré)";
static private SynchroGroupScheduler groupSynchroScheduler = null;
static private SynchroDomainScheduler domainSynchroScheduler = null;
static private ResourceLocator roleMapping = null;
static private boolean useProfileInheritance = false;
private static transient boolean cacheLoaded = false;
@Inject
AdminNotificationService adminNotificationService;
static {
// Load silverpeas admin resources
ResourceLocator resources = new ResourceLocator("com.stratelia.webactiv.beans.admin.admin",
"");
roleMapping = new ResourceLocator("com.silverpeas.admin.roleMapping", "");
useProfileInheritance = resources.getBoolean("UseProfileInheritance", false);
adminDBDriver = resources.getString("AdminDBDriver");
productionDbUrl = resources.getString("WaProductionDb");
productionDbLogin = resources.getString("WaProductionUser");
productionDbPassword = resources.getString("WaProductionPswd");
m_nEntrepriseClientSpaceId = Integer.parseInt(resources.getString("EntrepriseClientSpaceId"));
administratorMail = resources.getString("AdministratorEMail");
m_sDAPIGeneralAdminId = resources.getString("DAPIGeneralAdminId");
scheduledDBReset = new ScheduledDBReset();
scheduledDBReset.initialize(resources.getString("DBConnectionResetScheduler", ""));
shouldFallbackGroupNames = resources.getBoolean("FallbackGroupNames", true);
shouldFallbackUserLogins = resources.getBoolean("FallbackUserLogins", false);
m_domainSynchroCron = resources.getString("DomainSynchroCron", "* 4 * * *");
m_groupSynchroCron = resources.getString("GroupSynchroCron", "* 5 * * *");
delUsersOnDiffSynchro = resources.getBoolean("DelUsersOnThreadedSynchro", true);
// Cache management
cache.setCacheAvailable(StringUtil.getBooleanValue(resources.getString("UseCache", "1")));
componentInstanciator = new Instanciateur();
}
Admin() {
if (spaceInstanciator == null) {
spaceInstanciator = new SpaceInstanciator(getAllComponents());
}
// Init tree cache
synchronized (Admin.class) {
if (!cacheLoaded) {
reloadCache();
}
}
}
public void reloadCache() {
cache.resetCache();
TreeCache.clearCache();
GroupCache.clearCache();
try {
SilverTrace.info(MODULE_ADMIN, "admin.startServer", "root.MSG_GEN_PARAM_VALUE",
"Start filling tree cache...");
List<SpaceInstLight> spaces =
spaceManager.getAllSpaces(DomainDriverManagerFactory.getCurrentDomainDriverManager());
for (SpaceInstLight space : spaces) {
addSpaceInTreeCache(space, false);
}
SilverTrace.info(MODULE_ADMIN, "admin.startServer", "root.MSG_GEN_PARAM_VALUE",
"Tree cache filled !");
} catch (Exception e) {
SilverTrace.error("admin", "Constructor", "ERROR_WHEN_INITIALIZING_ADMIN", e);
}
cacheLoaded = true;
}
// -------------------------------------------------------------------------
// Start Server actions
// -------------------------------------------------------------------------
public void startServer() {
// init synchronization of domains
List<String> synchroDomainIds = new ArrayList<String>();
DomainDriverManager ddm = DomainDriverManagerFactory.getCurrentDomainDriverManager();
Domain[] domains = null;
try {
domains = ddm.getAllDomains();
} catch (AdminException e) {
SilverTrace.error("admin", "Admin.startServer()",
"admin.CANT_LOAD_DOMAINS_DURING_INITIALIZATION", e);
}
if (domains != null) {
for (Domain domain : domains) {
DomainDriver synchroDomain;
try {
synchroDomain = ddm.getDomainDriver(Integer.parseInt(domain.getId()));
if (synchroDomain != null && synchroDomain.isSynchroThreaded()) {
synchroDomainIds.add(domain.getId());
}
} catch (Exception e) {
SilverTrace.error("admin", "Admin.startServer()",
"admin.CANT_LOAD_DOMAIN_DURING_INITIALIZATION", "domainId = " + domain.getId(), e);
}
}
}
domainSynchroScheduler = new SynchroDomainScheduler();
domainSynchroScheduler.initialize(m_domainSynchroCron, synchroDomainIds);
// init synchronization of groups
Group[] groups = null;
try {
groups = getSynchronizedGroups();
} catch (AdminException e) {
SilverTrace.error("admin", "Admin.startServer()",
"admin.CANT_LOAD_SYNCHRONIZED_GROUPS_DURING_INITIALIZATION", e);
}
List<String> synchronizedGroupIds = new ArrayList<String>();
if (groups != null) {
for (Group group : groups) {
if (group.isSynchronized()) {
synchronizedGroupIds.add(group.getId());
}
}
}
groupSynchroScheduler = new SynchroGroupScheduler();
groupSynchroScheduler.initialize(m_groupSynchroCron, synchronizedGroupIds);
}
private void addSpaceInTreeCache(SpaceInstLight space, boolean addSpaceToSuperSpace)
throws NumberFormatException, AdminException {
Space spaceInCache = new Space();
spaceInCache.setSpace(space);
List<ComponentInstLight> components = componentManager.getComponentsInSpace(
Integer.parseInt(space.getShortId()));
spaceInCache.setComponents(components);
List<SpaceInstLight> subSpaces = getSubSpaces(space.getShortId());
spaceInCache.setSubspaces(subSpaces);
TreeCache.addSpace(space.getShortId(), spaceInCache);
for (SpaceInstLight subSpace : subSpaces) {
addSpaceInTreeCache(subSpace, false);
}
if (addSpaceToSuperSpace) {
if (!space.isRoot()) {
TreeCache.addSubSpace(space.getFatherId(), space);
}
}
}
// -------------------------------------------------------------------------
// SPACE RELATED FUNCTIONS
// -------------------------------------------------------------------------
/**
* Get Enterprise space id.
*
* @return The general space id
*/
public String getGeneralSpaceId() {
return SPACE_KEY_PREFIX + m_nEntrepriseClientSpaceId;
}
public void createSpaceIndex(int spaceId) {
try {
SpaceInstLight space = getSpaceInstLight(String.valueOf(spaceId));
createSpaceIndex(space);
} catch (AdminException e) {
SilverTrace.error(MODULE_ADMIN, "admin.createSpaceIndex", "root.MSG_GEN_PARAM_VALUE",
"spaceId = " + spaceId);
}
}
public void createSpaceIndex(SpaceInstLight spaceInst) {
SilverTrace.info(MODULE_ADMIN, "admin.createSpaceIndex",
"root.MSG_GEN_PARAM_VALUE", "Space Name : " + spaceInst.getName() + " Space Id : "
+ spaceInst.getShortId());
if (spaceInst != null) {
// Index the space
String spaceId = spaceInst.getFullId();
FullIndexEntry indexEntry = new FullIndexEntry("Spaces", "Space", spaceId);
indexEntry.setTitle(spaceInst.getName());
indexEntry.setPreView(spaceInst.getDescription());
indexEntry.setCreationUser(String.valueOf(spaceInst.getCreatedBy()));
IndexEngineProxy.addIndexEntry(indexEntry);
}
}
public void deleteSpaceIndex(SpaceInst spaceInst) {
SilverTrace.info("admin", "admin.deleteSpaceIndex", "root.MSG_GEN_PARAM_VALUE",
"Space Name : " + spaceInst.getName() + " Space Id : " + spaceInst.getId());
String spaceId = getSpaceId(spaceInst);
FullIndexEntry indexEntry = new FullIndexEntry("Spaces", "Space", spaceId);
IndexEngineProxy.removeIndexEntry(indexEntry.getPK());
}
/**
* add a space instance in database
*
* @param userId Id of user who add the space
* @param spaceInst SpaceInst object containing information about the space to be created
* @return the created space id
*/
public String addSpaceInst(String userId, SpaceInst spaceInst) throws AdminException {
Connection connectionProd = null;
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
domainDriverManager.startTransaction(false);
try {
SilverTrace.info(MODULE_ADMIN, "admin.addSpaceInst", "root.MSG_GEN_PARAM_VALUE",
"Space Name : " + spaceInst.getName() + " NbCompo: " + spaceInst.getNumComponentInst());
connectionProd = openConnection(productionDbUrl, productionDbLogin, productionDbPassword,
false);
// Open the connections with auto-commit to false
if (!spaceInst.isRoot()) {
// It's a subspace
// Convert the client id in driver id
spaceInst.setDomainFatherId(getDriverSpaceId(spaceInst.getDomainFatherId()));
if (useProfileInheritance && !spaceInst.isInheritanceBlocked()) {
// inherits profiles from super space
// set super space profiles to new space
setSpaceProfilesToSubSpace(spaceInst, null);
}
}
// Create the space instance
spaceInst.setCreatorUserId(userId);
String sSpaceInstId = spaceManager.createSpaceInst(spaceInst, domainDriverManager);
spaceInst.setId(getClientSpaceId(sSpaceInstId));
// put new space in cache
cache.opAddSpace(getSpaceInstById(sSpaceInstId, true));
// Instantiate the components
ArrayList<ComponentInst> alCompoInst = spaceInst.getAllComponentsInst();
for (ComponentInst componentInst : alCompoInst) {
componentInst.setDomainFatherId(spaceInst.getId());
addComponentInst(userId, componentInst, false);
}
// commit the transactions
domainDriverManager.commit();
connectionProd.commit();
SpaceInstLight space = getSpaceInstLight(sSpaceInstId);
addSpaceInTreeCache(space, true);
// indexation de l'espace
SilverTrace.info(MODULE_ADMIN, "admin.addSpaceInst", "root.MSG_GEN_PARAM_VALUE",
"Indexation : spaceInst = " + spaceInst.getName());
createSpaceIndex(space);
return spaceInst.getId();
} catch (Exception e) {
try {
// Roll back the transactions
domainDriverManager.rollback();
connectionProd.rollback();
cache.resetCache();
} catch (Exception e1) {
SilverTrace.error(MODULE_ADMIN, "Admin.addSpaceInst", "root.EX_ERR_ROLLBACK", e1);
}
throw new AdminException("Admin.addSpaceInst", SilverpeasException.ERROR,
"admin.EX_ERR_ADD_SPACE", "space name : '" + spaceInst.getName() + "'", e);
} finally {
// close connection
domainDriverManager.releaseOrganizationSchema();
DBUtil.close(connectionProd);
}
}
/**
* Delete the given space The delete is apply recursively to the sub-spaces
*
* @param userId Id of user who deletes the space
* @param spaceId Id of the space to be deleted
* @param definitive
* @return the deleted space id
* @throws AdminException
*/
public String deleteSpaceInstById(String userId, String spaceId, boolean definitive) throws
AdminException {
return deleteSpaceInstById(userId, spaceId, true, definitive);
}
/**
* Delete the given space if it's not the general space The delete is apply recursively to the
* sub-spaces
*
* @param userId Id of user who deletes the space
* @param spaceId Id of the space to be deleted
* @param startNewTransaction Flag : must be true at first call to initialize transaction, then
* false for recurrents calls
* @param definitive
* @return the deleted space id
* @throws AdminException
*/
public String deleteSpaceInstById(String userId, String spaceId, boolean startNewTransaction,
boolean definitive) throws AdminException {
SilverTrace.spy(MODULE_ADMIN, "Admin.deleteSpaceInstById()", spaceId, "ASP", "", userId,
SilverTrace.SPY_ACTION_DELETE);
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getFactory().getDomainDriverManager();
try {
if (startNewTransaction) {
domainDriverManager.startTransaction(false);
}
// Convert the client id in driver id
String sDriverSpaceId = getDriverSpaceId(spaceId);
// Get the space to delete
SpaceInst spaceInst = getSpaceInstById(sDriverSpaceId, true);
if (!definitive) {
// Update the space in tables
spaceManager.sendSpaceToBasket(domainDriverManager, sDriverSpaceId,
spaceInst.getName() + Admin.basketSuffix, userId);
// delete all profiles (space, components and subspaces)
deleteSpaceProfiles(spaceInst);
// notify logical deletion
notifyOnSpaceLogicalDeletion(spaceId, userId);
} else {
// Get all the sub-spaces
String[] subSpaceIds = getAllSubSpaceIds(spaceId);
// Delete subspaces
for (String subSpaceid : subSpaceIds) {
deleteSpaceInstById(userId, subSpaceid, false, true);
}
// Delete subspaces already in bin
List<SpaceInstLight> removedSpaces = getRemovedSpaces();
for (SpaceInstLight removedSpace : removedSpaces) {
if (sDriverSpaceId.equals(removedSpace.getFatherId())) {
deleteSpaceInstById(userId, removedSpace.getFullId(), false, true);
}
}
// delete the space profiles instance
for (int nI = 0; nI < spaceInst.getNumSpaceProfileInst(); nI++) {
deleteSpaceProfileInst(spaceInst.getSpaceProfileInst(nI).getId(), false);
}
// Delete the components
ArrayList<ComponentInst> alCompoInst = spaceInst.getAllComponentsInst();
for (ComponentInst anAlCompoInst : alCompoInst) {
deleteComponentInst(userId, getClientComponentId(anAlCompoInst), true, false);
}
// Delete the components already in bin
List<ComponentInstLight> removedComponents = getRemovedComponents();
for (ComponentInstLight removedComponent : removedComponents) {
if (spaceId.equals(removedComponent.getDomainFatherId())) {
deleteComponentInst(userId, removedComponent.getId(), true, false);
}
}
// Delete the space in tables
spaceManager.deleteSpaceInst(spaceInst, domainDriverManager);
}
if (startNewTransaction) {
domainDriverManager.commit();
}
cache.opRemoveSpace(spaceInst);
TreeCache.removeSpace(sDriverSpaceId);
// desindexation de l'espace
deleteSpaceIndex(spaceInst);
return spaceId;
} catch (Exception e) {
// Roll back the transactions
if (startNewTransaction) {
rollback();
}
throw new AdminException("Admin.deleteSpaceInstById", SilverpeasException.ERROR,
"admin.EX_ERR_DELETE_SPACE",
"user Id : '" + userId + "', space Id : '" + spaceId + "'", e);
} finally {
if (startNewTransaction) {
domainDriverManager.releaseOrganizationSchema();
}
}
}
private void notifyOnSpaceLogicalDeletion(String spaceId, String userId) {
// notify of space logical deletion
adminNotificationService.notifyOnDeletionOf(getClientSpaceId(spaceId), userId);
// notify of direct sub spaces logical deletion too
List<SpaceInstLight> spaces = TreeCache.getSubSpaces(getDriverSpaceId(spaceId));
for (SpaceInstLight space : spaces) {
notifyOnSpaceLogicalDeletion(space.getFullId(), userId);
}
}
private void deleteSpaceProfiles(SpaceInst spaceInst) throws AdminException {
// delete the space profiles
for (int nI = 0; nI < spaceInst.getNumSpaceProfileInst(); nI++) {
deleteSpaceProfileInst(spaceInst.getSpaceProfileInst(nI).getId(), false);
}
// delete the components profiles
List<ComponentInst> components = spaceInst.getAllComponentsInst();
for (ComponentInst component : components) {
for (int p = 0; p < component.getNumProfileInst(); p++) {
if (!component.getProfileInst(p).isInherited()) {
deleteProfileInst(component.getProfileInst(p).getId(), false);
}
}
}
// delete the subspace profiles
String[] subSpaceIds = spaceInst.getSubSpaceIds();
for (int i = 0; subSpaceIds != null && i < subSpaceIds.length; i++) {
SpaceInst subSpace = getSpaceInstById(subSpaceIds[i]);
deleteSpaceProfiles(subSpace);
}
}
/**
* @param spaceId
* @throws AdminException
*/
public void restoreSpaceFromBasket(String spaceId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getFactory().getDomainDriverManager();
domainDriverManager.startTransaction(false);
try {
// Start transaction
// Convert the client id in driver id
String driverSpaceId = getDriverSpaceId(spaceId);
// update data in database
spaceManager.removeSpaceFromBasket(domainDriverManager, driverSpaceId);
// force caches to be refreshed
cache.removeSpaceInst(driverSpaceId);
TreeCache.removeSpace(driverSpaceId);
// Get the space and put it in the cache
SpaceInst spaceInst = getSpaceInstById(driverSpaceId, true);
// set superspace profiles to space
if (useProfileInheritance && !spaceInst.isInheritanceBlocked() && !spaceInst.isRoot()) {
updateSpaceInheritance(spaceInst, false);
}
domainDriverManager.commit();
// indexation de l'espace
SilverTrace.info(MODULE_ADMIN, "admin.restoreSpaceFromBasket",
"root.MSG_GEN_PARAM_VALUE", "Indexation : spaceInst = " + spaceInst.getName());
createSpaceIndex(Integer.parseInt(driverSpaceId));
// reset space and eventually subspace
cache.opAddSpace(spaceInst);
addSpaceInTreeCache(getSpaceInstLight(driverSpaceId), true);
} catch (Exception e) {
rollback();
throw new AdminException("Admin.restoreSpaceFromBasket", SilverpeasException.ERROR,
"admin.EX_ERR_RESTORE_SPACE_FROM_BASKET", "spaceId = " + spaceId);
} finally {
domainDriverManager.releaseOrganizationSchema();
}
}
/**
* Get the space instance with the given space id.
*
* @param spaceId client space id
* @return Space information as SpaceInst object.
* @throws AdminException
*/
public SpaceInst getSpaceInstById(String spaceId) throws AdminException {
try {
SpaceInst spaceInst = getSpaceInstById(spaceId, false);
if (spaceInst == null) {
return null;
}
// Put the client space Id back
spaceInst.setId(spaceId);
// Put the client component Id back
List<ComponentInst> alCompoInst = spaceInst.getAllComponentsInst();
for (ComponentInst component : alCompoInst) {
String sClientComponentId = getClientComponentId(component);
component.setId(sClientComponentId);
}
// Put the client sub spaces Id back
String[] asSubSpaceIds = spaceInst.getSubSpaceIds();
for (int nI = 0; asSubSpaceIds != null && nI < asSubSpaceIds.length; nI++) {
asSubSpaceIds[nI] = getClientSpaceId(asSubSpaceIds[nI]);
}
spaceInst.setSubSpaceIds(asSubSpaceIds);
return spaceInst;
} catch (Exception e) {
throw new AdminException("Admin.getSpaceInstById", SilverpeasException.ERROR,
"admin.EX_ERR_GET_SPACE", " space Id : '" + spaceId + "'", e);
}
}
/**
* Get the space instance with the given space id
*
* @param spaceId client space id
* @param useDriverSpaceId true is space id is in 'driver' format, false for 'client' format
* @return Space information as SpaceInst object
*/
private SpaceInst getSpaceInstById(String spaceId, boolean useDriverSpaceId)
throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getFactory().getDomainDriverManager();
try {
String driverSpaceId;
// Convert the client id in driver id
if (useDriverSpaceId) {
driverSpaceId = spaceId;
} else {
driverSpaceId = getDriverSpaceId(spaceId);
}
SpaceInst spaceInst = cache.getSpaceInst(driverSpaceId);
if (spaceInst == null) {
// Get space instance
spaceInst = spaceManager.getSpaceInstById(domainDriverManager, driverSpaceId);
if (spaceInst != null) {
// Store the spaceInst in cache
cache.putSpaceInst(spaceInst);
}
}
return spaceManager.copy(spaceInst);
} catch (Exception e) {
throw new AdminException("Admin.getSpaceInstById", SilverpeasException.ERROR,
"admin.EX_ERR_GET_SPACE", " space Id : '" + spaceId + "'", e);
}
}
/**
* @param userId
* @return
* @throws AdminException
*/
public SpaceInst getPersonalSpace(String userId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getFactory().getDomainDriverManager();
return spaceManager.getPersonalSpace(domainDriverManager, userId);
}
/**
* Get all the subspaces Ids available in Silverpeas given a domainFatherId (client id format)
*
* @param domainFatherId Id of the father space
* @return an array of String containing the ids of spaces that are child of given space.
* @throws AdminException
*/
public String[] getAllSubSpaceIds(String domainFatherId) throws AdminException {
SilverTrace.debug(MODULE_ADMIN, "Admin.getAllSubSpaceIds",
"root.MSG_GEN_ENTER_METHOD", "father space id: '" + domainFatherId + "'");
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getFactory().getDomainDriverManager();
try {
// get all sub space ids
String[] asDriverSpaceIds = spaceManager.getAllSubSpaceIds(domainDriverManager,
getDriverSpaceId(domainFatherId));
// Convert all the driver space ids in client space ids
asDriverSpaceIds = getClientSpaceIds(asDriverSpaceIds);
return asDriverSpaceIds;
} catch (Exception e) {
throw new AdminException("Admin.getAllSubSpaceIds", SilverpeasException.ERROR,
"admin.EX_ERR_GET_ALL_SUBSPACE_IDS", " father space Id : '" + domainFatherId + "'", e);
}
}
/**
* Updates the space (with the given name) with the given space Updates only the node
*
* @param spaceInstNew SpaceInst object containing new information for space to be updated
* @return the updated space id.
* @throws AdminException
*/
public String updateSpaceInst(SpaceInst spaceInstNew) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getFactory().getDomainDriverManager();
domainDriverManager.startTransaction(false);
try {
SpaceInst oldSpace = getSpaceInstById(spaceInstNew.getId());
// Open the connections with auto-commit to false
SilverTrace.debug(MODULE_ADMIN, "Admin.updateSpaceInst",
"root.MSG_GEN_ENTER_METHOD", "Before id: '" + spaceInstNew.getId() + "' after Id: "
+ getDriverSpaceId(spaceInstNew.getId()));
// Convert the client id in driver id
spaceInstNew.setId(getDriverSpaceId(spaceInstNew.getId()));
// Update the space in tables
spaceManager.updateSpaceInst(domainDriverManager, spaceInstNew);
if (useProfileInheritance && (oldSpace.isInheritanceBlocked() != spaceInstNew.
isInheritanceBlocked())) {
updateSpaceInheritance(oldSpace, spaceInstNew.isInheritanceBlocked());
}
// commit the transactions
domainDriverManager.commit();
cache.opUpdateSpace(spaceInstNew);
TreeCache.getSpaceInstLight(spaceInstNew.getId()).setInheritanceBlocked(spaceInstNew.
isInheritanceBlocked());
// Update space in TreeCache
SpaceInstLight spaceLight = spaceManager.getSpaceInstLightById(domainDriverManager,
getDriverSpaceId(spaceInstNew.getId()));
spaceLight.setInheritanceBlocked(spaceInstNew.isInheritanceBlocked());
TreeCache.updateSpace(spaceLight);
// indexation de l'espace
SilverTrace.info(MODULE_ADMIN, "admin.updateSpaceInst", "root.MSG_GEN_PARAM_VALUE",
"Indexation : spaceInst = " + spaceInstNew.getName());
createSpaceIndex(spaceLight);
return spaceInstNew.getId();
} catch (Exception e) {
rollback();
throw new AdminException("Admin.updateSpaceInst", SilverpeasException.ERROR,
"admin.EX_ERR_UPDATE_SPACE", "space Id : '" + spaceInstNew.getId() + "'", e);
} finally {
domainDriverManager.releaseOrganizationSchema();
}
}
/**
* @param spaceId
* @param orderNum
* @throws AdminException
*/
public void updateSpaceOrderNum(String spaceId, int orderNum) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getFactory().getDomainDriverManager();
try {
SilverTrace.debug(MODULE_ADMIN, "Admin.updateSpaceOrderNum", "root.MSG_GEN_ENTER_METHOD",
"Space id: '" + spaceId + "' New Order num: " + Integer.toString(orderNum));
String driverSpaceId = getDriverSpaceId(spaceId);
// Open the connections with auto-commit to false
domainDriverManager.startTransaction(false);
// Update the space in tables
spaceManager.updateSpaceOrder(domainDriverManager, driverSpaceId, orderNum);
// commit the transactions
domainDriverManager.commit();
cache.opUpdateSpace(spaceManager.getSpaceInstById(domainDriverManager, driverSpaceId));
// Updating TreeCache
SpaceInstLight space = TreeCache.getSpaceInstLight(driverSpaceId);
// Update space order
space.setOrderNum(orderNum);
if (!space.isRoot()) {
// Update brothers sort in TreeCache
TreeCache.setSubspaces(space.getFatherId(), getSubSpaces(space.getFatherId()));
}
} catch (Exception e) {
rollback();
throw new AdminException("Admin.updateSpaceOrderNum", SilverpeasException.ERROR,
"admin.EX_ERR_UPDATE_SPACE", "space Id : '" + spaceId + "'", e);
} finally {
domainDriverManager.releaseOrganizationSchema();
}
}
/**
* Update the inheritance mode between a subSpace and its space. If inheritanceBlocked is true
* then all inherited space profiles are removed. If inheritanceBlocked is false then all subSpace
* profiles are removed and space profiles are inherited.
*
* @param space
* @param inheritanceBlocked
* @throws AdminException
*/
private void updateSpaceInheritance(SpaceInst space,
boolean inheritanceBlocked) throws AdminException {
try {
if (inheritanceBlocked) {
// suppression des droits hérités de l'espace
List<SpaceProfileInst> inheritedProfiles = space.getInheritedProfiles();
for (SpaceProfileInst profile : inheritedProfiles) {
deleteSpaceProfileInst(profile.getId(), false);
}
} else {
// Héritage des droits de l'espace
// 1 - suppression des droits spécifiques du sous espace
List<SpaceProfileInst> profiles = space.getProfiles();
for (SpaceProfileInst profile : profiles) {
if (profile != null && !"Manager".equalsIgnoreCase(profile.getName())) {
deleteSpaceProfileInst(profile.getId(), false);
}
}
if (!space.isRoot()) {
// 2 - affectation des droits de l'espace au sous espace
setSpaceProfilesToSubSpace(space, null, true, false);
}
}
} catch (AdminException e) {
rollback();
throw new AdminException("Admin.updateComponentInst", SilverpeasException.ERROR,
"admin.EX_ERR_UPDATE_SPACE", "spaceId = " + space.getId(), e);
}
}
/**
* Tests if a space with given space id exists.
*
* @param spaceId if of space to be tested
* @return true if the given space instance name is an existing space
*/
public boolean isSpaceInstExist(String spaceId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getFactory().getDomainDriverManager();
try {
return spaceManager.isSpaceInstExist(domainDriverManager, getDriverSpaceId(spaceId));
} catch (AdminException e) {
throw new AdminException("Admin.isSpaceInstExist", SilverpeasException.ERROR,
"admin.EX_ERR_IS_SPACE_EXIST", "space Id : '" + spaceId + "'", e);
}
}
/**
* Return all the root spaces Ids available in Silverpeas.
*
* @return all the root spaces Ids available in Silverpeas.
* @throws AdminException
*/
public String[] getAllRootSpaceIds() throws AdminException {
SilverTrace.debug(MODULE_ADMIN, "Admin.getAllSpaceIds", "root.MSG_GEN_ENTER_METHOD");
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getFactory().getDomainDriverManager();
try {
String[] driverSpaceIds = spaceManager.getAllRootSpaceIds(domainDriverManager);
// Convert all the driver space ids in client space ids
driverSpaceIds = getClientSpaceIds(driverSpaceIds);
return driverSpaceIds;
} catch (Exception e) {
throw new AdminException("Admin.getAllSpaceIds", SilverpeasException.ERROR,
"admin.EX_ERR_GET_ALL_SPACE_IDS", e);
}
}
/**
* Retrieve spaces from root to component
*
* @param componentId the target component
* @return a List of SpaceInstLight
* @throws AdminException
*/
public List<SpaceInstLight> getPathToComponent(String componentId) throws AdminException {
List<SpaceInstLight> path = new ArrayList<SpaceInstLight>(0);
ComponentInstLight component = getComponentInstLight(componentId);
if (component != null) {
String spaceId = component.getDomainFatherId();
return getPathToSpace(spaceId, true);
}
return path;
}
/**
* Retrieve spaces from root to space identified by spaceId
*
* @param spaceId the target space
* @param includeTarget
* @return a List of SpaceInstLight
* @throws AdminException
*/
public List<SpaceInstLight> getPathToSpace(String spaceId, boolean includeTarget) throws
AdminException {
List<SpaceInstLight> path = new ArrayList<SpaceInstLight>(10);
SpaceInstLight space = getSpaceInstLight(getDriverSpaceId(spaceId));
if (space != null) {
if (includeTarget) {
path.add(0, space);
}
while (!space.isRoot()) {
String fatherId = space.getFatherId();
space = getSpaceInstLight(fatherId);
path.add(0, space);
}
}
return path;
}
/**
* Return the all the spaces Ids available in Silverpeas.
*
* @return the all the spaces Ids available in Silverpeas.
* @throws AdminException
*/
public String[] getAllSpaceIds() throws AdminException {
SilverTrace.debug(MODULE_ADMIN, "Admin.getAllSpaceIds", "root.MSG_GEN_ENTER_METHOD");
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getFactory().getDomainDriverManager();
try {
String[] driverSpaceIds = spaceManager.getAllSpaceIds(domainDriverManager);
// Convert all the driver space ids in client space ids
driverSpaceIds = getClientSpaceIds(driverSpaceIds);
return driverSpaceIds;
} catch (Exception e) {
throw new AdminException("Admin.getAllSpaceIds", SilverpeasException.ERROR,
"admin.EX_ERR_GET_ALL_SPACE_IDS", e);
}
}
/**
* Returns all spaces which has been removed but not definitely deleted.
*
* @return a List of SpaceInstLight
* @throws AdminException
*/
public List<SpaceInstLight> getRemovedSpaces() throws AdminException {
SilverTrace.debug(MODULE_ADMIN, "Admin.getRemovedSpaces", "root.MSG_GEN_ENTER_METHOD");
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getFactory().getDomainDriverManager();
try {
return spaceManager.getRemovedSpaces(domainDriverManager);
} catch (Exception e) {
throw new AdminException("Admin.getRemovedSpaces", SilverpeasException.ERROR,
"admin.EX_ERR_GET_REMOVED_SPACES", e);
}
}
/**
* Returns all components which has been removed but not definitely deleted.
*
* @return a List of ComponentInstLight
* @throws AdminException
*/
public List<ComponentInstLight> getRemovedComponents() throws AdminException {
SilverTrace.debug(MODULE_ADMIN, "Admin.getRemovedComponents", "root.MSG_GEN_ENTER_METHOD");
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getFactory().getDomainDriverManager();
try {
return componentManager.getRemovedComponents(domainDriverManager);
} catch (Exception e) {
throw new AdminException("Admin.getRemovedComponents", SilverpeasException.ERROR,
"admin.EX_ERR_GET_REMOVED_COMPONENTS", e);
}
}
/**
* Return the the spaces name corresponding to the given space ids
*
* @param asClientSpaceIds
* @return
* @throws AdminException
*/
public String[] getSpaceNames(String[] asClientSpaceIds) throws AdminException {
if (asClientSpaceIds == null) {
return ArrayUtil.EMPTY_STRING_ARRAY;
}
try {
String[] asSpaceNames = new String[asClientSpaceIds.length];
for (int nI = 0; nI < asClientSpaceIds.length; nI++) {
SpaceInstLight spaceInst = getSpaceInstLightById(asClientSpaceIds[nI]);
asSpaceNames[nI] = spaceInst.getName();
}
return asSpaceNames;
} catch (Exception e) {
throw new AdminException("Admin.getSpaceNames", SilverpeasException.ERROR,
"admin.EX_ERR_GET_SPACE_NAMES", e);
}
}
public Map<String, SpaceTemplate> getAllSpaceTemplates() {
return spaceInstanciator.getAllSpaceTemplates();
}
public SpaceInst getSpaceInstFromTemplate(String templateName) {
return spaceInstanciator.getSpaceToInstanciate(templateName);
}
// -------------------------------------------------------------------------
// COMPONENT RELATED FUNCTIONS
// -------------------------------------------------------------------------
/**
* Return all the components name available in Silverpeas.
*
* @return all the components name available in Silverpeas
* @throws AdminException
*/
public Map<String, String> getAllComponentsNames() throws AdminException {
SilverTrace.debug(MODULE_ADMIN, "Admin.getAllComponentsNames", "root.MSG_GEN_ENTER_METHOD");
Map<String, String> components = Instanciateur.getAllComponentsNames();
for (Map.Entry<String, String> entry : components.entrySet()) {
SilverTrace.debug(MODULE_ADMIN, "Admin.getAllComponentsNames",
"admin.MSG_INFO_COMPONENT_FOUND", entry.getKey() + ": " + entry.getValue());
}
return components;
}
/**
* Return all the components of silverpeas read in the xmlComponent directory.
*
* @return all the components of silverpeas read in the xmlComponent directory.
*/
public Map<String, WAComponent> getAllComponents() {
return Instanciateur.getWAComponents();
}
/**
* Return the component Inst corresponding to the given ID
*
* @param sClientComponentId
* @return the component Inst corresponding to the given ID
* @throws AdminException
*/
public ComponentInst getComponentInst(String sClientComponentId) throws AdminException {
try {
ComponentInst componentInst = getComponentInst(sClientComponentId, false, null);
componentInst.setId(getClientComponentId(componentInst));
componentInst.setDomainFatherId(getClientSpaceId(componentInst.getDomainFatherId()));
return componentInst;
} catch (Exception e) {
throw new AdminException("Admin.getComponentInst", SilverpeasException.ERROR,
"admin.EX_ERR_GET_COMPONENT", "component Id: '" + sClientComponentId + "'", e);
}
}
/**
* Return the component Inst Light corresponding to the given ID
*
* @param componentId
* @return the component Inst Light corresponding to the given ID
* @throws AdminException
*/
public ComponentInstLight getComponentInstLight(String componentId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getFactory().getDomainDriverManager();
try {
String driverComponentId = getDriverComponentId(componentId);
return componentManager.getComponentInstLight(domainDriverManager, driverComponentId);
} catch (Exception e) {
throw new AdminException("Admin.getComponentInstLight", SilverpeasException.ERROR,
"admin.EX_ERR_GET_COMPONENT", "component Id: '" + componentId + "'", e);
}
}
/**
* Return the component Inst corresponding to the given ID.
*
* @param componentId
* @param isDriverComponentId
* @param fatherDriverSpaceId
* @return the component Inst corresponding to the given ID.
* @throws AdminException
*/
private ComponentInst getComponentInst(String componentId, boolean isDriverComponentId,
String fatherDriverSpaceId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getFactory().getDomainDriverManager();
String driverComponentId;
try {
// Converts space id if necessary
if (isDriverComponentId) {
driverComponentId = componentId;
} else {
driverComponentId = getDriverComponentId(componentId);
}
// Get the component instance
ComponentInst componentInst = cache.getComponentInst(driverComponentId);
SilverTrace.info(MODULE_ADMIN, "Admin.getComponentInst", "root.MSG_GEN_ENTER_METHOD",
"componentInst=" + componentInst + " id=" + driverComponentId);
if (componentInst == null) {
// Get component instance from database
componentInst = componentManager.getComponentInst(domainDriverManager,
driverComponentId, fatherDriverSpaceId);
SilverTrace.info(MODULE_ADMIN, "Admin.getComponentInst",
"root.MSG_GEN_ENTER_METHOD", "componentInst FatherId=" + componentInst.
getDomainFatherId());
// Store component instance in cache
cache.putComponentInst(componentInst);
}
return componentManager.copy(componentInst);
} catch (Exception e) {
throw new AdminException("Admin.getComponentInst", SilverpeasException.ERROR,
"admin.EX_ERR_GET_COMPONENT", "component Id: '" + componentId + "'", e);
}
}
/**
* Get the parameters for the given component.
*
* @param componentId
* @return the parameters for the given component.
*/
public List<Parameter> getComponentParameters(String componentId) {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getFactory().getDomainDriverManager();
try {
return componentManager.getParameters(domainDriverManager, getDriverComponentId(componentId));
} catch (Exception e) {
SilverTrace.error(MODULE_ADMIN, "Admin.getComponentParameters",
"admin.EX_ERR_GET_COMPONENT_PARAMS", "sComponentId: '" + componentId + "'", e);
return Collections.<Parameter>emptyList();
}
}
/**
* Return the value of the parameter for the given component and the given name of parameter
*
* @param componentId
* @param parameterName
* @return the value of the parameter for the given component and the given name of parameter
*/
public String getComponentParameterValue(String componentId, String parameterName) {
try {
ComponentInst component = getComponentInst(componentId);
if (component == null) {
SilverTrace.error(MODULE_ADMIN, "Admin.getComponentParameterValue",
"admin.EX_ERR_GET_COMPONENT_PARAMS", "Component not found - sComponentId: '"
+ componentId + "'");
return StringUtil.EMPTY;
}
return component.getParameterValue(parameterName);
} catch (Exception e) {
SilverTrace.error(MODULE_ADMIN, "Admin.getComponentParameterValue",
"admin.EX_ERR_GET_COMPONENT_PARAMS", "sComponentId: '" + componentId + "'", e);
return "";
}
}
public void restoreComponentFromBasket(String componentId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getFactory().getDomainDriverManager();
try {
// Start transaction
domainDriverManager.startTransaction(false);
// update data in database
componentManager.restoreComponentFromBasket(domainDriverManager, getDriverComponentId(
componentId));
// Get the component and put it in the cache
ComponentInst componentInst = getComponentInst(componentId);
if (useProfileInheritance && !componentInst.isInheritanceBlocked()) {
// inherits profiles from space
setSpaceProfilesToComponent(componentInst, null);
}
domainDriverManager.commit();
cache.opUpdateComponent(componentInst);
ComponentInstLight component = getComponentInstLight(componentId);
TreeCache.addComponent(getDriverComponentId(componentId), component,
getDriverSpaceId(component.getDomainFatherId()));
createComponentIndex(component);
} catch (Exception e) {
rollback();
throw new AdminException("Admin.restoreComponentFromBasket", SilverpeasException.ERROR,
"admin.EX_ERR_RESTORE_COMPONENT_FROM_BASKET", "componentId = " + componentId);
} finally {
domainDriverManager.releaseOrganizationSchema();
}
}
/**
* Create the index for the specified component.
*
* @param componentId
*/
public void createComponentIndex(String componentId) {
try {
ComponentInstLight component = getComponentInstLight(componentId);
createComponentIndex(component);
} catch (AdminException e) {
SilverTrace.error(MODULE_ADMIN, "Admin.createComponentIndex",
"admin.EX_ERR_GET_COMPONENT_PARAMS", "componentId: '" + componentId + "'", e);
}
}
/**
* Create the index for the specified component.
*
* @param componentInst
*/
public void createComponentIndex(ComponentInstLight componentInst) {
if (componentInst != null) {
// Index the component
SilverTrace.debug(MODULE_ADMIN, "Admin.createComponentIndex", "root.MSG_GEN_ENTER_METHOD",
"componentInst.getName() = " + componentInst.getName() + "' componentInst.getId() = "
+ componentInst.getId() + " componentInst.getLabel() = " + componentInst.getLabel());
String componentId;
if (componentInst.getId().startsWith(componentInst.getName())) {
componentId = componentInst.getId();
} else {
componentId = componentInst.getName().concat(componentInst.getId());
}
FullIndexEntry indexEntry = new FullIndexEntry("Components", "Component", componentId);
indexEntry.setTitle(componentInst.getLabel());
indexEntry.setPreView(componentInst.getDescription());
indexEntry.setCreationUser(Integer.toString(componentInst.getCreatedBy()));
IndexEngineProxy.addIndexEntry(indexEntry);
}
}
/**
* Delete the index for the specified component.
*
* @param componentInst
*/
public void deleteComponentIndex(ComponentInst componentInst) {
String componentId = componentInst.getName().concat(componentInst.getId());
FullIndexEntry indexEntry = new FullIndexEntry("Components", "Component", componentId);
IndexEngineProxy.removeIndexEntry(indexEntry.getPK());
}
public String addComponentInst(String sUserId, ComponentInst componentInst)
throws AdminException {
return addComponentInst(sUserId, componentInst, true);
}
/**
* Add the given component instance in Silverpeas.
*
* @param userId
* @param componentInst
* @param startNewTransaction
* @return
* @throws AdminException
*/
public String addComponentInst(String userId, ComponentInst componentInst,
boolean startNewTransaction) throws AdminException {
Connection connectionProd = null;
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getFactory().getDomainDriverManager();
try {
connectionProd = openConnection(productionDbUrl, productionDbLogin, productionDbPassword,
false);
if (startNewTransaction) {
// Open the connections with auto-commit to false
domainDriverManager.startTransaction(false);
}
// Get the father space inst
SpaceInst spaceInstFather = getSpaceInstById(componentInst.getDomainFatherId());
// Create the component instance
String driverComponentId =
componentManager.createComponentInst(componentInst, domainDriverManager,
getDriverSpaceId(spaceInstFather.getId()));
// Add the component to the space
spaceInstFather.addComponentInst(componentInst);
// Put the new Id for client
componentInst.setId(driverComponentId);
// Instantiate the component
String componentName = componentInst.getName();
String componentId = componentName + componentInst.getId();
String[] asCompoNames = {componentName};
String[] asCompoIds = {componentId};
instantiateComponents(userId, asCompoIds, asCompoNames, spaceInstFather.getId(),
connectionProd);
// !!! Hard coded workaround !!!!!!!
if ("sources".equals(componentName) || "documentation".equals(componentName) || "infoTracker".
equals(componentName)) {
// Create the manager objects
ContainerManager containerManager = new ContainerManager();
ContentManager contentManager = new ContentManager();
// Call the register functions
containerManager.registerNewContainerInstance(connectionProd,
componentId, "containerPDC", "fileBoxPlus");
contentManager.registerNewContentInstance(connectionProd, componentId,
"containerPDC", "fileBoxPlus");
} else if (isContentManagedComponent(componentName)) {
// Create the manager objects
ContainerManager containerManager = new ContainerManager();
ContentManager contentManager = new ContentManager();
// Call the register functions
containerManager.registerNewContainerInstance(connectionProd, componentId, "containerPDC",
componentName);
contentManager.registerNewContentInstance(connectionProd, componentId, "containerPDC",
componentName);
}
if (useProfileInheritance && !componentInst.isInheritanceBlocked()) {
// inherits profiles from space
setSpaceProfilesToComponent(componentInst, spaceInstFather);
}
// commit the transactions
if (startNewTransaction) {
domainDriverManager.commit();
}
connectionProd.commit();
cache.opAddComponent(componentInst);
ComponentInstLight component = getComponentInstLight(componentId);
TreeCache.addComponent(driverComponentId, component,
getDriverSpaceId(spaceInstFather.getId()));
// indexation du composant
createComponentIndex(component);
return componentId;
} catch (Exception e) {
try {
if (startNewTransaction) {
domainDriverManager.rollback();
}
connectionProd.rollback();
} catch (Exception e1) {
SilverTrace.error(MODULE_ADMIN, "Admin.addComponentInst", "root.EX_ERR_ROLLBACK", e1);
}
throw new AdminException("Admin.addComponentInst", SilverpeasException.ERROR,
"admin.EX_ERR_ADD_COMPONENT", "component name: '" + componentInst.getName() + "'", e);
} finally {
if (startNewTransaction) {
domainDriverManager.releaseOrganizationSchema();
}
DBUtil.close(connectionProd);
}
}
boolean isContentManagedComponent(String componentName) {
return "expertLocator".equals(componentName) || "questionReply".equals(componentName)
|| "whitePages".equals(componentName) || "kmelia".equals(componentName) || "survey".
equals(
componentName) || "toolbox".equals(componentName) || "quickinfo".equals(componentName)
|| "almanach".equals(componentName) || "quizz".equals(componentName) || "forums".equals(
componentName) || "pollingStation".equals(componentName) || "bookmark".equals(
componentName) || "chat".equals(componentName) || "infoLetter".equals(componentName)
|| "webSites".equals(componentName) || "gallery".equals(componentName) || "blog".equals(
componentName);
}
/**
* Delete the specified component.
*
* @param userId
* @param componentId
* @param definitive
* @return
* @throws AdminException
*/
public String deleteComponentInst(String userId, String componentId, boolean definitive) throws
AdminException {
return deleteComponentInst(userId, componentId, definitive, true);
}
/**
* Deletes the given component instance in Silverpeas
*
* @param userId the unique identifier of the user requesting the deletion.
* @param componentId the client identifier of the component instance (for a kmelia instance of id
* 666, the client identifier of the instance is kmelia666)
* @param definitive is the component instance deletion is definitive? If not, the component
* instance is moved into the bin.
* @param startNewTransaction is the deletion has to occur within a new transaction?
* @return the client component instance identifier.
* @throws AdminException if an error occurs while deleting the component instance.
*/
public String deleteComponentInst(String userId, String componentId, boolean definitive,
boolean startNewTransaction) throws AdminException {
Connection connectionProd = null;
SilverTrace.spy(MODULE_ADMIN, "Admin.deleteComponentInst()", "ACP", componentId, "", userId,
SilverTrace.SPY_ACTION_DELETE);
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getFactory().getDomainDriverManager();
try {
if (startNewTransaction) {
// Open the connections with auto-commit to false
domainDriverManager.startTransaction(false);
}
// Convert the client id in driver id
String sDriverComponentId = getDriverComponentId(componentId);
// Get the component to delete
ComponentInst componentInst = getComponentInst(sDriverComponentId, true, null);
// Get the father id
String sFatherClientId = componentInst.getDomainFatherId();
if (!definitive) {
// delete the profiles instance
for (int nI = 0; nI < componentInst.getNumProfileInst(); nI++) {
deleteProfileInst(componentInst.getProfileInst(nI).getId(), false);
}
componentManager.sendComponentToBasket(domainDriverManager, sDriverComponentId,
componentInst.getLabel() + Admin.basketSuffix, userId);
} else {
connectionProd = openConnection(productionDbUrl, productionDbLogin, productionDbPassword,
false);
// Uninstantiate the components
String componentName = componentInst.getName();
String[] asCompoName = {componentName};
String[] asCompoId = {componentId};
unInstantiateComponents(userId, asCompoId, asCompoName, getClientSpaceId(sFatherClientId),
connectionProd);
// delete the profiles instance
for (int nI = 0; nI < componentInst.getNumProfileInst(); nI++) {
deleteProfileInst(componentInst.getProfileInst(nI).getId(), false);
}
// Delete the component
componentManager.deleteComponentInst(componentInst, domainDriverManager);
// !!! Hard coded workaround !!!!!!!
if ("sources".equals(componentName) || "documentation".equals(componentName)
|| "infoTracker".equals(componentName)) {
// Create the manager objects
ContainerManager containerManager = new ContainerManager();
ContentManager contentManager = new ContentManager();
// Call the unregister functions
containerManager.unregisterNewContainerInstance(connectionProd, componentId,
"containerPDC", "fileBoxPlus");
contentManager.unregisterNewContentInstance(connectionProd, componentId, "containerPDC",
"fileBoxPlus");
} else if (isContentManagedComponent(componentName)) {
// Create the manager objects
ContainerManager containerManager = new ContainerManager();
ContentManager contentManager = new ContentManager();
// Call the unregister functions
containerManager.unregisterNewContainerInstance(connectionProd, componentId,
"containerPDC", componentName);
contentManager.unregisterNewContentInstance(connectionProd, componentId, "containerPDC",
componentName);
}
// commit the transactions
connectionProd.commit();
}
if (startNewTransaction) {
domainDriverManager.commit();
}
cache.opRemoveComponent(componentInst);
TreeCache.removeComponent(getDriverSpaceId(sFatherClientId), componentId);
// desindexation du composant
deleteComponentIndex(componentInst);
return componentId;
} catch (Exception e) {
try {
// Roll back the transactions
if (startNewTransaction) {
domainDriverManager.rollback();
}
if (connectionProd != null) {
connectionProd.rollback();
}
} catch (Exception e1) {
SilverTrace.error(MODULE_ADMIN, "Admin.deleteComponentInst",
"root.EX_ERR_ROLLBACK", e1);
}
throw new AdminException("Admin.deleteComponentInst", SilverpeasException.ERROR,
"admin.EX_ERR_DELETE_COMPONENT",
"component Id: '" + componentId + "'", e);
} finally {
if (startNewTransaction) {
domainDriverManager.releaseOrganizationSchema();
}
DBUtil.close(connectionProd);
}
}
/**
* @param componentId
* @param orderNum
* @throws AdminException
*/
public void updateComponentOrderNum(String componentId, int orderNum) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getFactory().getDomainDriverManager();
try {
SilverTrace.debug(MODULE_ADMIN, "Admin.updateComponentOrderNum", "root.MSG_GEN_ENTER_METHOD",
"Component id: '" + componentId + "' New Order num: " + orderNum);
String driverComponentId = getDriverComponentId(componentId);
// Open the connections with auto-commit to false
domainDriverManager.startTransaction(false);
// Update the Component in tables
componentManager.updateComponentOrder(domainDriverManager, driverComponentId, orderNum);
domainDriverManager.commit();
cache.opUpdateComponent(componentManager.getComponentInst(domainDriverManager,
driverComponentId, null));
} catch (Exception e) {
rollback();
throw new AdminException("Admin.updateComponentOrderNum", SilverpeasException.ERROR,
"admin.EX_ERR_UPDATE_COMPONENT", "Component Id : '" + componentId + "'", e);
} finally {
domainDriverManager.releaseOrganizationSchema();
}
}
/**
* Update the given component in Silverpeas.
*
* @param componentInstNew
* @return
* @throws AdminException
*/
public String updateComponentInst(ComponentInst componentInstNew) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getFactory().getDomainDriverManager();
try {
ComponentInst oldComponentInst = getComponentInst(componentInstNew.getId());
String componentClientId = getClientComponentId(oldComponentInst);
// Open the connections with auto-commit to false
domainDriverManager.startTransaction(false);
// Convert the client space Id in driver space Id
String sDriverComponentId = getDriverComponentId(componentInstNew.getId());
componentInstNew.setId(sDriverComponentId);
// Update the components in tables
componentManager.updateComponentInst(domainDriverManager, componentInstNew);
// Update the inherited rights
if (useProfileInheritance && (oldComponentInst.isInheritanceBlocked() != componentInstNew.
isInheritanceBlocked())) {
updateComponentInheritance(oldComponentInst, componentInstNew.isInheritanceBlocked());
}
// commit the transactions
domainDriverManager.commit();
cache.opUpdateComponent(componentInstNew);
TreeCache.getComponent(componentClientId).setInheritanceBlocked(componentInstNew.
isInheritanceBlocked());
// put clientId as Id
componentInstNew.setId(componentClientId);
// indexation du composant
createComponentIndex(componentClientId);
return componentClientId;
} catch (Exception e) {
rollback();
throw new AdminException("Admin.updateComponentInst", SilverpeasException.ERROR,
"admin.EX_ERR_UPDATE_COMPONENT", "component Id: '" + componentInstNew.getId() + "'", e);
} finally {
domainDriverManager.releaseOrganizationSchema();
}
}
/**
* Update the inheritance mode between a component and its space. If inheritanceBlocked is true
* then all inherited space profiles are removed. If inheritanceBlocked is false then all
* component profiles are removed and space profiles are inherited.
*
* @param component
* @param inheritanceBlocked
* @throws AdminException
*/
private void updateComponentInheritance(ComponentInst component, boolean inheritanceBlocked)
throws AdminException {
try {
if (inheritanceBlocked) {
// suppression des droits hérités de l'espace
List<ProfileInst> inheritedProfiles = component.getInheritedProfiles();
for (ProfileInst profile : inheritedProfiles) {
deleteProfileInst(profile.getId(), false);
}
} else {
// suppression des droits du composant
List<ProfileInst> profiles = component.getProfiles();
for (ProfileInst profile : profiles) {
deleteProfileInst(profile.getId(), false);
}
// affectation des droits de l'espace
setSpaceProfilesToComponent(component, null);
}
} catch (AdminException e) {
rollback();
throw new AdminException("Admin.updateComponentInst", SilverpeasException.ERROR,
"admin.EX_ERR_UPDATE_COMPONENT", "component Id: '" + component.getId() + "'", e);
}
}
/**
* Set space profiles to a subspace. There is no persistance. The subspace object is enriched.
*
* @param subSpace the object to set profiles
* @param space the object to get profiles
* @throws AdminException
*/
private void setSpaceProfilesToSubSpace(final SpaceInst subSpace, final SpaceInst space)
throws AdminException {
setSpaceProfilesToSubSpace(subSpace, space, false, false);
}
protected void setSpaceProfilesToSubSpace(final SpaceInst subSpace, final SpaceInst space,
boolean persist, boolean startNewTransaction)
throws AdminException {
SpaceInst currentSpace = space;
if (currentSpace == null) {
currentSpace = getSpaceInstById(subSpace.getDomainFatherId(), true);
}
setSpaceProfileToSubSpace(subSpace, currentSpace, SilverpeasRole.admin);
setSpaceProfileToSubSpace(subSpace, currentSpace, SilverpeasRole.publisher);
setSpaceProfileToSubSpace(subSpace, currentSpace, SilverpeasRole.writer);
setSpaceProfileToSubSpace(subSpace, currentSpace, SilverpeasRole.reader);
if (persist) {
for (SpaceProfileInst profile : subSpace.getInheritedProfiles()) {
if (StringUtil.isDefined(profile.getId())) {
updateSpaceProfileInst(profile, null, startNewTransaction);
} else {
addSpaceProfileInst(profile, null, startNewTransaction);
}
}
}
}
/**
* Set space profile to a subspace. There is no persistance. The subspace object is enriched.
*
* @param subSpace the object to set profiles
* @param space the object to get profiles
* @param role the name of the profile
* @throws AdminException
*/
private void setSpaceProfileToSubSpace(SpaceInst subSpace, SpaceInst space, SilverpeasRole role) {
String profileName = role.toString();
SpaceProfileInst subSpaceProfile = subSpace.getInheritedSpaceProfileInst(profileName);
if (subSpaceProfile != null) {
subSpaceProfile.removeAllGroups();
subSpaceProfile.removeAllUsers();
}
// Retrieve superSpace local profile
SpaceProfileInst profile = space.getSpaceProfileInst(profileName);
if (profile != null) {
if (subSpaceProfile == null) {
subSpaceProfile = new SpaceProfileInst();
subSpaceProfile.setName(profileName);
subSpaceProfile.setInherited(true);
}
subSpaceProfile.addGroups(profile.getAllGroups());
subSpaceProfile.addUsers(profile.getAllUsers());
}
// Retrieve superSpace inherited profile
SpaceProfileInst inheritedProfile = space.getInheritedSpaceProfileInst(profileName);
if (inheritedProfile != null) {
if (subSpaceProfile == null) {
subSpaceProfile = new SpaceProfileInst();
subSpaceProfile.setName(profileName);
subSpaceProfile.setInherited(true);
}
subSpaceProfile.addGroups(inheritedProfile.getAllGroups());
subSpaceProfile.addUsers(inheritedProfile.getAllUsers());
}
if (subSpaceProfile != null) {
subSpace.addSpaceProfileInst(subSpaceProfile);
}
}
public void setSpaceProfilesToComponent(ComponentInst component, SpaceInst space) throws
AdminException {
setSpaceProfilesToComponent(component, space, false);
}
/**
* Set space profile to a component. There is persistance.
*
* @param component the object to set profiles
* @param space the object to get profiles
* @throws AdminException
*/
public void setSpaceProfilesToComponent(ComponentInst component, SpaceInst space,
boolean startNewTransaction) throws AdminException {
WAComponent waComponent = Instanciateur.getWAComponent(component.getName());
List<Profile> componentRoles = waComponent.getProfiles();
if (space == null) {
space = getSpaceInstById(component.getDomainFatherId(), false);
}
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
if (startNewTransaction) {
domainDriverManager.startTransaction(false);
}
for (Profile componentRole : componentRoles) {
ProfileInst inheritedProfile = component.getInheritedProfileInst(componentRole.getName());
if (inheritedProfile != null) {
inheritedProfile.removeAllGroups();
inheritedProfile.removeAllUsers();
} else {
inheritedProfile = new ProfileInst();
inheritedProfile.setComponentFatherId(component.getId());
inheritedProfile.setInherited(true);
inheritedProfile.setName(componentRole.getName());
}
List<String> spaceRoles = componentRole2SpaceRoles(componentRole.getName(),
component.getName());
for (String spaceRole : spaceRoles) {
SpaceProfileInst spaceProfile = space.getSpaceProfileInst(spaceRole);
if (spaceProfile != null) {
inheritedProfile.addGroups(spaceProfile.getAllGroups());
inheritedProfile.addUsers(spaceProfile.getAllUsers());
}
spaceProfile = space.getInheritedSpaceProfileInst(spaceRole);
if (spaceProfile != null) {
inheritedProfile.addGroups(spaceProfile.getAllGroups());
inheritedProfile.addUsers(spaceProfile.getAllUsers());
}
}
if (StringUtil.isDefined(inheritedProfile.getId())) {
updateProfileInst(inheritedProfile, null, false);
} else {
if (!inheritedProfile.isEmpty()) {
addProfileInst(inheritedProfile, null, false);
}
}
}
if (startNewTransaction) {
domainDriverManager.commit();
}
} catch (Exception e) {
if (startNewTransaction) {
rollback();
}
throw new AdminException("Admin.setSpaceProfilesToComponent", SilverpeasException.ERROR,
"admin.EX_ERR_SET_PROFILES", e);
} finally {
if (startNewTransaction) {
domainDriverManager.releaseOrganizationSchema();
}
}
}
/**
* Move the given component in Silverpeas.
*
* @param spaceId
* @param componentId
* @param idComponentBefore
* @param componentInsts
* @throws AdminException
*/
public void moveComponentInst(String spaceId, String componentId, String idComponentBefore,
ComponentInst[] componentInsts) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getFactory().getDomainDriverManager();
try {
SilverTrace.info(MODULE_ADMIN, "admin.moveComponentInst", "root.MSG_GEN_PARAM_VALUE",
"spaceId= " + spaceId + " componentId=" + componentId);
String sDriverComponentId = getDriverComponentId(componentId);
// Convert the client space Id in driver space Id
String sDriverSpaceId = getDriverSpaceId(spaceId);
SilverTrace.info(MODULE_ADMIN, "admin.moveComponentInst", "root.MSG_GEN_PARAM_VALUE",
"sDriverSpaceId= " + sDriverSpaceId + " sDriverComponentId=" + sDriverComponentId);
ComponentInst componentInst = getComponentInst(componentId);
String oldSpaceId = componentInst.getDomainFatherId();
// Open the connections with auto-commit to false
domainDriverManager.startTransaction(false);
// Update the components in tables
componentManager.moveComponentInst(domainDriverManager, sDriverSpaceId, sDriverComponentId);
componentInst.setDomainFatherId(sDriverSpaceId);
// set space profiles to component if it not use its own rights
if (!componentInst.isInheritanceBlocked()) {
setSpaceProfilesToComponent(componentInst, null);
}
// Set component in order
SilverTrace.info(MODULE_ADMIN, "admin.moveComponentInst", "root.MSG_GEN_PARAM_VALUE",
"Avant setComponentPlace: componentId=" + componentId + " idComponentBefore="
+ idComponentBefore);
setComponentPlace(componentId, idComponentBefore, componentInsts);
// Update extraParamPage from Space if necessary
SpaceInst fromSpace = getSpaceInstById(getDriverSpaceId(oldSpaceId));
String spaceHomePage = fromSpace.getFirstPageExtraParam();
SilverTrace.info(MODULE_ADMIN, "admin.moveComponentInst", "root.MSG_GEN_PARAM_VALUE",
"FirstPageExtraParam=" + spaceHomePage + " oldSpaceId=" + oldSpaceId);
if (StringUtil.isDefined(spaceHomePage) && spaceHomePage.equals(componentId)) {
fromSpace.setFirstPageExtraParam("");
fromSpace.setFirstPageType(0);
updateSpaceInst(fromSpace);
}
// commit the transactions
domainDriverManager.commit();
// Remove component from the Cache
cache.resetSpaceInst();
cache.resetComponentInst();
TreeCache.setComponents(getDriverSpaceId(oldSpaceId),
componentManager.getComponentsInSpace(Integer.parseInt(getDriverSpaceId(oldSpaceId))));
TreeCache.setComponents(getDriverSpaceId(spaceId),
componentManager.getComponentsInSpace(Integer.parseInt(getDriverSpaceId(spaceId))));
} catch (Exception e) {
rollback();
throw new AdminException("Admin.moveComponentInst", SilverpeasException.ERROR,
"admin.EX_ERR_MOVE_COMPONENT",
"spaceId = " + spaceId + " component Id: '" + componentId + " ", e);
} finally {
domainDriverManager.releaseOrganizationSchema();
}
}
public void setComponentPlace(String componentId, String idComponentBefore,
ComponentInst[] m_BrothersComponents) throws AdminException {
int orderNum = 0;
int i;
ComponentInst theComponent = getComponentInst(componentId);
for (i = 0; i < m_BrothersComponents.length; i++) {
if (idComponentBefore.equals(m_BrothersComponents[i].getId())) {
theComponent.setOrderNum(orderNum);
updateComponentOrderNum(theComponent.getId(), orderNum);
orderNum++;
}
if (m_BrothersComponents[i].getOrderNum() != orderNum) {
m_BrothersComponents[i].setOrderNum(orderNum);
updateComponentOrderNum(m_BrothersComponents[i].getId(), orderNum);
}
orderNum++;
}
if (orderNum == i) {
theComponent.setOrderNum(orderNum);
updateComponentOrderNum(theComponent.getId(), orderNum);
}
}
public String getRequestRouter(String sComponentName) {
WAComponent wac = Instanciateur.getWAComponent(sComponentName);
if (wac == null || !StringUtil.isDefined(wac.getRouter())) {
return "R" + sComponentName;
}
return wac.getRouter();
}
// --------------------------------------------------------------------------------------------------------
// PROFILE RELATED FUNCTIONS
// --------------------------------------------------------------------------------------------------------
/**
* Get all the profiles name available for the given component.
*
* @param sComponentName
* @return
* @throws AdminException
*/
public String[] getAllProfilesNames(String sComponentName) throws AdminException {
String[] asProfiles = null;
WAComponent wac = Instanciateur.getWAComponent(sComponentName);
if (wac != null) {
List<Profile> profiles = wac.getProfiles();
List<String> profileNames = new ArrayList<String>(profiles.size());
for (Profile profile : profiles) {
profileNames.add(profile.getName());
}
asProfiles = profileNames.toArray(new String[profileNames.size()]);
}
if (asProfiles != null) {
return asProfiles;
}
return ArrayUtil.EMPTY_STRING_ARRAY;
}
/**
* Get the profile label from its name.
*
* @param sComponentName
* @param sProfileName
* @return
* @throws AdminException
*/
public String getProfileLabelfromName(String sComponentName, String sProfileName, String lang)
throws AdminException {
WAComponent wac = Instanciateur.getWAComponent(sComponentName);
if (wac != null) {
List<Profile> profiles = wac.getProfiles();
String sProfileLabel = sProfileName;
for (Profile profile : profiles) {
if (profile.getName().equals(sProfileName)) {
return profile.getLabel().get(lang);
}
}
return sProfileLabel;
}
return sProfileName;
}
/**
* Get the profile instance corresponding to the given id
*
* @param sProfileId
* @return
* @throws AdminException
*/
public ProfileInst getProfileInst(String sProfileId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
ProfileInst profileInst = cache.getProfileInst(sProfileId);
if (profileInst == null) {
profileInst = profileManager.getProfileInst(domainDriverManager, sProfileId, null);
cache.putProfileInst(profileInst);
}
return profileInst;
}
public List<ProfileInst> getProfilesByObject(String objectId, String objectType,
String componentId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
List<ProfileInst> profiles = profiledObjectManager.getProfiles(domainDriverManager,
Integer.parseInt(objectId), objectType,
Integer.parseInt(getDriverComponentId(componentId)));
return profiles;
}
public String[] getProfilesByObjectAndUserId(int objectId, String objectType, String componentId,
String userId) throws AdminException {
List<String> groups = getAllGroupsOfUser(userId);
return profiledObjectManager.getUserProfileNames(objectId, objectType,
Integer.parseInt(getDriverComponentId(componentId)), Integer.parseInt(userId), groups);
}
public boolean isObjectAvailable(String componentId, int objectId, String objectType,
String userId) throws AdminException {
if (userId == null) {
return true;
}
return getProfilesByObjectAndUserId(objectId, objectType, componentId, userId).length > 0;
}
public String addProfileInst(ProfileInst profileInst) throws AdminException {
return addProfileInst(profileInst, null, true);
}
public String addProfileInst(ProfileInst profileInst, String userId) throws AdminException {
return addProfileInst(profileInst, userId, true);
}
/**
* Get the given profile instance from Silverpeas
*/
private String addProfileInst(ProfileInst profileInst, String userId, boolean startNewTransaction)
throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
if (startNewTransaction) {
domainDriverManager.startTransaction(false);
}
String sDriverFatherId = getDriverComponentId(profileInst.getComponentFatherId());
String sProfileId = profileManager.createProfileInst(profileInst, domainDriverManager,
sDriverFatherId);
profileInst.setId(sProfileId);
if (profileInst.getObjectId() == -1 || profileInst.getObjectId() == 0) {
ComponentInst componentInstFather = getComponentInst(sDriverFatherId, true, null);
componentInstFather.addProfileInst(profileInst);
if (StringUtil.isDefined(userId)) {
componentInstFather.setUpdaterUserId(userId);
updateComponentInst(componentInstFather);
}
}
if (startNewTransaction) {
domainDriverManager.commit();
}
if (profileInst.getObjectId() == -1 || profileInst.getObjectId() == 0) {
cache.opAddProfile(profileManager.getProfileInst(domainDriverManager, sProfileId, null));
}
return sProfileId;
} catch (Exception e) {
if (startNewTransaction) {
rollback();
}
throw new AdminException("Admin.addProfileInst", SilverpeasException.ERROR,
"admin.EX_ERR_ADD_PROFILE", "profile name: '" + profileInst.getName() + "'", e);
} finally {
if (startNewTransaction) {
domainDriverManager.releaseOrganizationSchema();
}
}
}
public String deleteProfileInst(String sProfileId, String userId) throws AdminException {
return deleteProfileInst(sProfileId, userId, true);
}
private String deleteProfileInst(String sProfileId, boolean startNewTransaction) throws
AdminException {
return deleteProfileInst(sProfileId, null, startNewTransaction);
}
/**
* Delete the given profile from Silverpeas
*
* @param profileId
* @param userId
* @param startNewTransaction
* @return
* @throws AdminException
*/
private String deleteProfileInst(String profileId, String userId, boolean startNewTransaction)
throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
ProfileInst profile = profileManager.getProfileInst(domainDriverManager, profileId, null);
try {
if (startNewTransaction) {
domainDriverManager.startTransaction(false);
}
profileManager.deleteProfileInst(profile, domainDriverManager);
if (StringUtil.isDefined(
userId) && (profile.getObjectId() == -1 || profile.getObjectId() == 0)) {
ComponentInst component = getComponentInst(profile.getComponentFatherId(), true, null);
component.setUpdaterUserId(userId);
updateComponentInst(component);
}
if (startNewTransaction) {
domainDriverManager.commit();
}
if (profile.getObjectId() == -1 || profile.getObjectId() == 0) {
cache.opRemoveProfile(profile);
}
return profileId;
} catch (Exception e) {
if (startNewTransaction) {
rollback();
}
throw new AdminException("Admin.deleteProfileInst", SilverpeasException.ERROR,
"admin.EX_ERR_DELETE_PROFILE", "profile Id: '" + profileId + "'", e);
} finally {
if (startNewTransaction) {
domainDriverManager.releaseOrganizationSchema();
}
}
}
public String updateProfileInst(ProfileInst profileInstNew) throws AdminException {
return updateProfileInst(profileInstNew, null, true);
}
public String updateProfileInst(ProfileInst profileInstNew, String userId) throws AdminException {
return updateProfileInst(profileInstNew, userId, true);
}
/**
* Update the given profile in Silverpeas.
*
* @param newProfile
* @param userId
* @param startNewTransaction
* @return
* @throws AdminException
*/
private String updateProfileInst(ProfileInst newProfile, String userId,
boolean startNewTransaction) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
if (StringUtil.isDefined(userId)) {
SilverTrace.spy(MODULE_ADMIN, "Admin.updateProfileInst", "unknown", newProfile.
getComponentFatherId(), newProfile.getName(), userId, SilverTrace.SPY_ACTION_UPDATE);
}
try {
if (startNewTransaction) {
domainDriverManager.startTransaction(false);
}
profileManager.updateProfileInst(domainDriverManager, newProfile);
if (StringUtil.isDefined(
userId) && (newProfile.getObjectId() == -1 || newProfile.getObjectId() == 0)) {
ComponentInst component = getComponentInst(newProfile.getComponentFatherId(), true, null);
component.setUpdaterUserId(userId);
updateComponentInst(component);
}
if (startNewTransaction) {
domainDriverManager.commit();
}
if (newProfile.getObjectId() == -1 || newProfile.getObjectId() == 0) {
cache.opUpdateProfile(newProfile);
}
return newProfile.getId();
} catch (Exception e) {
if (startNewTransaction) {
rollback();
}
throw new AdminException("Admin.updateProfileInst", SilverpeasException.ERROR,
"admin.EX_ERR_UPDATE_PROFILE", "profile Id: '" + newProfile.getId() + "'", e);
} finally {
if (startNewTransaction) {
domainDriverManager.releaseOrganizationSchema();
}
}
}
// --------------------------------------------------------------------------------------------------------
// SPACE PROFILE RELATED FUNCTIONS
// --------------------------------------------------------------------------------------------------------
/**
* Get the space profile instance corresponding to the given ID
*
* @param speceProfileId
* @return
* @throws AdminException
*/
public SpaceProfileInst getSpaceProfileInst(String speceProfileId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
return spaceProfileManager.getSpaceProfileInst(domainDriverManager, speceProfileId, null);
}
public String addSpaceProfileInst(SpaceProfileInst spaceProfile, String userId) throws
AdminException {
return addSpaceProfileInst(spaceProfile, userId, true);
}
/**
* Add the space profile instance from Silverpeas.
*
* @param spaceProfile
* @param userId
* @param startNewTransaction
* @return
* @throws AdminException
*/
private String addSpaceProfileInst(SpaceProfileInst spaceProfile, String userId,
boolean startNewTransaction) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
if (startNewTransaction) {
domainDriverManager.startTransaction(false);
}
String spaceId = getDriverComponentId(spaceProfile.getSpaceFatherId());
String sSpaceProfileId = spaceProfileManager.createSpaceProfileInst(spaceProfile,
domainDriverManager, spaceId);
spaceProfile.setId(sSpaceProfileId);
if (StringUtil.isDefined(userId)) {
SpaceInst spaceInstFather = getSpaceInstById(spaceId, false);
spaceInstFather.setUpdaterUserId(userId);
updateSpaceInst(spaceInstFather);
}
// add new profile in spaces cache
SpaceInst spaceInst = cache.getSpaceInst(spaceId);
if (spaceInst != null) {
spaceInst.addSpaceProfileInst(spaceProfile);
}
if (!spaceProfile.isInherited()) {
SpaceProfileInst inheritedProfile = spaceProfileManager.getInheritedSpaceProfileInstByName(
domainDriverManager, spaceId, spaceProfile.getName());
if (inheritedProfile != null) {
spaceProfile.addGroups(inheritedProfile.getAllGroups());
spaceProfile.addUsers(inheritedProfile.getAllUsers());
}
}
spreadSpaceProfile(spaceId, spaceProfile);
if (startNewTransaction) {
domainDriverManager.commit();
}
cache.opAddSpaceProfile(spaceProfile);
return sSpaceProfileId;
} catch (Exception e) {
if (startNewTransaction) {
rollback();
}
throw new AdminException("Admin.addSpaceProfileInst", SilverpeasException.ERROR,
"admin.EX_ERR_ADD_SPACE_PROFILE", "space profile name: '" + spaceProfile.getName()
+ "'",
e);
} finally {
if (startNewTransaction) {
domainDriverManager.releaseOrganizationSchema();
}
}
}
public String deleteSpaceProfileInst(String sSpaceProfileId, String userId)
throws AdminException {
return deleteSpaceProfileInst(sSpaceProfileId, userId, true);
}
private String deleteSpaceProfileInst(String sSpaceProfileId, boolean startNewTransaction) throws
AdminException {
return deleteSpaceProfileInst(sSpaceProfileId, null, startNewTransaction);
}
/**
* Delete the given space profile from Silverpeas
*/
private String deleteSpaceProfileInst(String sSpaceProfileId, String userId,
boolean startNewTransaction) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
SpaceProfileInst spaceProfileInst = spaceProfileManager.getSpaceProfileInst(domainDriverManager,
sSpaceProfileId, null);
try {
if (startNewTransaction) {
domainDriverManager.startTransaction(false);
}
spaceProfileManager.deleteSpaceProfileInst(spaceProfileInst, domainDriverManager);
cache.opRemoveSpaceProfile(spaceProfileInst);
spaceProfileInst.removeAllGroups();
spaceProfileInst.removeAllUsers();
String spaceId = getDriverComponentId(spaceProfileInst.getSpaceFatherId());
if (StringUtil.isDefined(userId)) {
SpaceInst spaceInstFather = getSpaceInstById(spaceId, false);
spaceInstFather.setUpdaterUserId(userId);
updateSpaceInst(spaceInstFather);
}
if (!spaceProfileInst.isInherited()) {
SpaceProfileInst inheritedProfile =
spaceProfileManager.getInheritedSpaceProfileInstByName(domainDriverManager, spaceId,
spaceProfileInst.getName());
if (inheritedProfile != null) {
spaceProfileInst.addGroups(inheritedProfile.getAllGroups());
spaceProfileInst.addUsers(inheritedProfile.getAllUsers());
}
}
spreadSpaceProfile(spaceId, spaceProfileInst);
if (startNewTransaction) {
domainDriverManager.commit();
}
return sSpaceProfileId;
} catch (Exception e) {
if (startNewTransaction) {
rollback();
}
throw new AdminException("Admin.deleteSpaceProfileInst", SilverpeasException.ERROR,
"admin.EX_ERR_DELETE_SPACEPROFILE", "space profile Id: '" + sSpaceProfileId + "'", e);
} finally {
if (startNewTransaction) {
domainDriverManager.releaseOrganizationSchema();
}
}
}
/**
* Update the given space profile in Silverpeas
*/
private String updateSpaceProfileInst(SpaceProfileInst newSpaceProfile) throws AdminException {
return updateSpaceProfileInst(newSpaceProfile, null);
}
public String updateSpaceProfileInst(SpaceProfileInst newSpaceProfile, String userId) throws
AdminException {
return updateSpaceProfileInst(newSpaceProfile, userId, true);
}
public String updateSpaceProfileInst(SpaceProfileInst newSpaceProfile, String userId,
boolean startNewTransaction)
throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
if (startNewTransaction) {
domainDriverManager.startTransaction(false);
}
SpaceProfileInst oldSpaceProfile = spaceProfileManager.getSpaceProfileInst(
domainDriverManager, newSpaceProfile.getId(), null);
String sSpaceProfileNewId = spaceProfileManager.updateSpaceProfileInst(oldSpaceProfile,
domainDriverManager, newSpaceProfile);
if (!"Manager".equalsIgnoreCase(oldSpaceProfile.getName())) {
String spaceId = getDriverSpaceId(newSpaceProfile.getSpaceFatherId());
if (StringUtil.isDefined(userId)) {
SpaceInst spaceInstFather = getSpaceInstById(spaceId, false);
spaceInstFather.setUpdaterUserId(userId);
updateSpaceInst(spaceInstFather);
}
// Add inherited users and groups for this role
SpaceProfileInst inheritedProfile =
spaceProfileManager.getInheritedSpaceProfileInstByName(domainDriverManager, spaceId,
oldSpaceProfile.getName());
if (inheritedProfile != null) {
newSpaceProfile.addGroups(inheritedProfile.getAllGroups());
newSpaceProfile.addUsers(inheritedProfile.getAllUsers());
}
spreadSpaceProfile(spaceId, newSpaceProfile);
}
if (startNewTransaction) {
domainDriverManager.commit();
}
cache.opUpdateSpaceProfile(spaceProfileManager.getSpaceProfileInst(domainDriverManager,
newSpaceProfile.getId(), null));
return sSpaceProfileNewId;
} catch (Exception e) {
if (startNewTransaction) {
rollback();
}
throw new AdminException("Admin.updateSpaceProfileInst", SilverpeasException.ERROR,
"admin.EX_ERR_UPDATE_SPACEPROFILE", "space profile Id: '" + newSpaceProfile.getId()
+ "'", e);
} finally {
if (startNewTransaction) {
domainDriverManager.releaseOrganizationSchema();
}
}
}
private String spaceRole2ComponentRole(String spaceRole, String componentName) {
return roleMapping.getString(componentName + "_" + spaceRole);
}
private List<String> componentRole2SpaceRoles(String componentRole,
String componentName) {
List<String> roles = new ArrayList<String>();
String role = spaceRole2ComponentRole(SilverpeasRole.admin.toString(), componentName);
if (role != null && role.equalsIgnoreCase(componentRole)) {
roles.add(SilverpeasRole.admin.toString());
}
role = spaceRole2ComponentRole(SilverpeasRole.publisher.toString(), componentName);
if (role != null && role.equalsIgnoreCase(componentRole)) {
roles.add(SilverpeasRole.publisher.toString());
}
role = spaceRole2ComponentRole(SilverpeasRole.writer.toString(), componentName);
if (role != null && role.equalsIgnoreCase(componentRole)) {
roles.add(SilverpeasRole.writer.toString());
}
role = spaceRole2ComponentRole(SilverpeasRole.reader.toString(), componentName);
if (role != null && role.equalsIgnoreCase(componentRole)) {
roles.add(SilverpeasRole.reader.toString());
}
return roles;
}
private void spreadSpaceProfile(String spaceId, SpaceProfileInst spaceProfile)
throws AdminException {
SilverTrace.info("admin", "Admin.spreadSpaceProfile", "root.MSG_GEN_ENTER_METHOD",
"spaceId = " + spaceId + ", profile = " + spaceProfile.getName());
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
// update profile in components
List<ComponentInstLight> components = TreeCache.getComponents(spaceId);
for (ComponentInstLight component : components) {
if (component != null && !component.isInheritanceBlocked()) {
String componentRole = spaceRole2ComponentRole(spaceProfile.getName(),
component.getName());
if (componentRole != null) {
ProfileInst inheritedProfile = profileManager.getInheritedProfileInst(domainDriverManager,
getDriverComponentId(component.getId()),
componentRole);
if (inheritedProfile != null) {
inheritedProfile.removeAllGroups();
inheritedProfile.removeAllUsers();
inheritedProfile.addGroups(spaceProfile.getAllGroups());
inheritedProfile.addUsers(spaceProfile.getAllUsers());
//updateProfileInst(inheritedProfile);
List<String> profilesToCheck = componentRole2SpaceRoles(componentRole,
component.getName());
profilesToCheck.remove(spaceProfile.getName()); // exclude current space profile
for (String profileToCheck : profilesToCheck) {
SpaceProfileInst spi = spaceProfileManager.getSpaceProfileInstByName(
domainDriverManager, spaceId, profileToCheck);
if (spi != null) {
inheritedProfile.addGroups(spi.getAllGroups());
inheritedProfile.addUsers(spi.getAllUsers());
}
}
updateProfileInst(inheritedProfile);
} else {
inheritedProfile = new ProfileInst();
inheritedProfile.setComponentFatherId(component.getId());
inheritedProfile.setName(componentRole);
inheritedProfile.setInherited(true);
inheritedProfile.addGroups(spaceProfile.getAllGroups());
inheritedProfile.addUsers(spaceProfile.getAllUsers());
if (inheritedProfile.getNumGroup() > 0 || inheritedProfile.getNumUser() > 0) {
addProfileInst(inheritedProfile);
}
}
}
}
}
// update profile in subspaces
List<SpaceInstLight> subSpaces = TreeCache.getSubSpaces(spaceId);
for (SpaceInstLight subSpace : subSpaces) {
if (!subSpace.isInheritanceBlocked()) {
SpaceProfileInst subSpaceProfile =
spaceProfileManager.getInheritedSpaceProfileInstByName(domainDriverManager,
subSpace.getShortId(), spaceProfile.getName());
if (subSpaceProfile != null) {
subSpaceProfile.setGroups(spaceProfile.getAllGroups());
subSpaceProfile.setUsers(spaceProfile.getAllUsers());
updateSpaceProfileInst(subSpaceProfile);
} else {
subSpaceProfile = new SpaceProfileInst();
subSpaceProfile.setName(spaceProfile.getName());
subSpaceProfile.setInherited(true);
subSpaceProfile.setSpaceFatherId(subSpace.getShortId());
subSpaceProfile.addGroups(spaceProfile.getAllGroups());
subSpaceProfile.addUsers(spaceProfile.getAllUsers());
if (!subSpaceProfile.getAllGroups().isEmpty() || !subSpaceProfile.getAllUsers().isEmpty()) {
addSpaceProfileInst(subSpaceProfile, null);
}
}
}
}
}
// -------------------------------------------------------------------------
// GROUP RELATED FUNCTIONS
// -------------------------------------------------------------------------
/**
* Get the group names corresponding to the given group ids.
*
* @param groupIds
* @return
* @throws AdminException
*/
public String[] getGroupNames(String[] groupIds) throws AdminException {
if (groupIds == null) {
return ArrayUtil.EMPTY_STRING_ARRAY;
}
String[] asGroupNames = new String[groupIds.length];
for (int nI = 0; nI < groupIds.length; nI++) {
asGroupNames[nI] = getGroupName(groupIds[nI]);
}
return asGroupNames;
}
/**
* Get the group name corresponding to the given group id.
*
* @param sGroupId
* @return
* @throws AdminException
*/
public String getGroupName(String sGroupId) throws AdminException {
return getGroup(sGroupId).getName();
}
/**
* Get the all the groups ids available in Silverpeas.
*
* @return
* @throws AdminException
*/
public String[] getAllGroupIds() throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
return groupManager.getAllGroupIds(domainDriverManager);
}
/**
* Tests if group exists in Silverpeas.
*
* @param groupName
* @return true if a group with the given name
* @throws AdminException
*/
public boolean isGroupExist(String groupName) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
return groupManager.isGroupExist(domainDriverManager, groupName);
}
/**
* Get group information with the given id
*
* @param groupId
* @return
* @throws AdminException
*/
public Group getGroup(String groupId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
return groupManager.getGroup(domainDriverManager, groupId);
}
public List<String> getPathToGroup(String groupId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
return groupManager.getPathToGroup(domainDriverManager, groupId);
}
/**
* Get group information with the given group name.
*
* @param groupName
* @param domainFatherId
* @return
* @throws AdminException
*/
public Group getGroupByNameInDomain(String groupName, String domainFatherId)
throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
return groupManager.getGroupByNameInDomain(domainDriverManager, groupName, domainFatherId);
}
/**
* Get groups information with the given ids.
*
* @param asGroupId
* @return
* @throws AdminException
*/
public Group[] getGroups(String[] asGroupId) throws AdminException {
if (asGroupId == null) {
return ArrayUtil.EMPTY_GROUP_ARRAY;
}
Group[] aGroup = new Group[asGroupId.length];
for (int nI = 0; nI < asGroupId.length; nI++) {
aGroup[nI] = getGroup(asGroupId[nI]);
}
return aGroup;
}
/**
* Add the given group in Silverpeas.
*
* @param group
* @return
* @throws AdminException
*/
public String addGroup(Group group) throws AdminException {
try {
return addGroup(group, false);
} catch (Exception e) {
throw new AdminException("Admin.addGroup", SilverpeasException.ERROR,
"admin.EX_ERR_ADD_GROUP", "group name: '" + group.getName() + "'", e);
}
}
/**
* Add the given group in Silverpeas.
*
* @param group
* @param onlyInSilverpeas
* @return
* @throws AdminException
*/
public String addGroup(Group group, boolean onlyInSilverpeas) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
domainDriverManager.startTransaction(false);
if (group.getDomainId() != null && !onlyInSilverpeas) {
domainDriverManager.startTransaction(group.getDomainId(), false);
}
String sGroupId = groupManager.addGroup(domainDriverManager, group, onlyInSilverpeas);
group.setId(sGroupId);
domainDriverManager.commit();
if (group.getDomainId() != null && !onlyInSilverpeas) {
domainDriverManager.commit(group.getDomainId());
}
if (group.isSynchronized()) {
groupSynchroScheduler.addGroup(sGroupId);
}
cache.opAddGroup(group);
return sGroupId;
} catch (Exception e) {
try {
domainDriverManager.rollback();
if (group.getDomainId() != null && !onlyInSilverpeas) {
domainDriverManager.rollback(group.getDomainId());
}
} catch (Exception e1) {
SilverTrace.error("admin", "Admin.addGroup", "root.EX_ERR_ROLLBACK", e1);
}
throw new AdminException("Admin.addGroup", SilverpeasException.ERROR,
"admin.EX_ERR_ADD_GROUP", "group name: '" + group.getName() + "'", e);
} finally {
domainDriverManager.releaseOrganizationSchema();
if (group.getDomainId() != null && !onlyInSilverpeas) {
domainDriverManager.releaseOrganizationSchema();
}
}
}
/**
* Delete the group with the given Id The delete is apply recursively to the sub-groups.
*
* @param sGroupId
* @return
* @throws AdminException
*/
public String deleteGroupById(String sGroupId) throws AdminException {
try {
return deleteGroupById(sGroupId, false);
} catch (Exception e) {
throw new AdminException("Admin.deleteGroupById", SilverpeasException.ERROR,
"admin.EX_ERR_DELETE_GROUP", "group Id: '" + sGroupId + "'", e);
}
}
/**
* Delete the group with the given Id The delete is apply recursively to the sub-groups.
*
* @param sGroupId
* @param onlyInSilverpeas
* @return
* @throws AdminException
*/
public String deleteGroupById(String sGroupId, boolean onlyInSilverpeas) throws AdminException {
Group group = null;
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
// Get group information
group = getGroup(sGroupId);
if (group == null) {
throw new AdminException("Admin.deleteGroupById", SilverpeasException.ERROR,
"admin.EX_ERR_GROUP_NOT_FOUND", "group Id: '" + sGroupId + "'");
}
domainDriverManager.startTransaction(false);
if (group.getDomainId() != null && !onlyInSilverpeas) {
domainDriverManager.startTransaction(group.getDomainId(), false);
}
String sReturnGroupId = groupManager.deleteGroupById(domainDriverManager, group,
onlyInSilverpeas);
domainDriverManager.commit();
if (group.getDomainId() != null && !onlyInSilverpeas) {
domainDriverManager.commit(group.getDomainId());
}
if (group.isSynchronized()) {
groupSynchroScheduler.removeGroup(sGroupId);
}
cache.opRemoveGroup(group);
return sReturnGroupId;
} catch (Exception e) {
try {
domainDriverManager.rollback();
if (group != null && group.getDomainId() != null && !onlyInSilverpeas) {
domainDriverManager.rollback(group.getDomainId());
}
} catch (Exception e1) {
SilverTrace.error("admin", "Admin.deleteGroupById", "root.EX_ERR_ROLLBACK", e1);
}
throw new AdminException("Admin.deleteGroupById", SilverpeasException.ERROR,
"admin.EX_ERR_GROUP_NOT_FOUND", "group Id: '" + sGroupId + "'", e);
} finally {
domainDriverManager.releaseOrganizationSchema();
if (group.getDomainId() != null && !onlyInSilverpeas) {
domainDriverManager.releaseOrganizationSchema();
}
}
}
/**
* Update the given group in Silverpeas and specific.
*
* @param group
* @return
* @throws AdminException
*/
public String updateGroup(Group group) throws AdminException {
try {
return updateGroup(group, false);
} catch (Exception e) {
throw new AdminException("Admin.updateGroup", SilverpeasException.ERROR,
"admin.EX_ERR_UPDATE_GROUP", "group name: '" + group.getName() + "'", e);
}
}
/**
* Update the given group in Silverpeas and specific
*
* @param group
* @param onlyInSilverpeas
* @return
* @throws AdminException
*/
public String updateGroup(Group group, boolean onlyInSilverpeas) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
domainDriverManager.startTransaction(false);
if (group.getDomainId() != null && !onlyInSilverpeas) {
domainDriverManager.startTransaction(group.getDomainId(), false);
}
String sGroupId = groupManager.updateGroup(domainDriverManager, group, onlyInSilverpeas);
domainDriverManager.commit();
if (group.getDomainId() != null && !onlyInSilverpeas) {
domainDriverManager.commit(group.getDomainId());
}
cache.opUpdateGroup(getGroup(sGroupId));
return sGroupId;
} catch (Exception e) {
try {
domainDriverManager.rollback();
if (group.getDomainId() != null && !onlyInSilverpeas) {
domainDriverManager.rollback(group.getDomainId());
}
} catch (Exception e1) {
SilverTrace.error("admin", "Admin.updateGroup", "root.EX_ERR_ROLLBACK", e1);
}
throw new AdminException("Admin.updateGroup", SilverpeasException.ERROR,
"admin.EX_ERR_UPDATE_GROUP", "group name: '" + group.getName() + "'", e);
} finally {
domainDriverManager.releaseOrganizationSchema();
if (group.getDomainId() != null && !onlyInSilverpeas) {
domainDriverManager.releaseOrganizationSchema();
}
}
}
public void removeUserFromGroup(String sUserId, String sGroupId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
// Start transaction
domainDriverManager.startTransaction(false);
// Update group
groupManager.removeUserFromGroup(domainDriverManager, sUserId, sGroupId);
// Commit the transaction
domainDriverManager.commit();
cache.opUpdateGroup(getGroup(sGroupId));
} catch (Exception e) {
try {
// Roll back the transactions
domainDriverManager.rollback();
} catch (Exception e1) {
SilverTrace.error("admin", "Admin.removeUserFromGroup", "root.EX_ERR_ROLLBACK", e1);
}
throw new AdminException("Admin.removeUserFromGroup", SilverpeasException.ERROR,
"admin.EX_ERR_UPDATE_GROUP", "groupId = " + sGroupId + ", userId = " + sUserId, e);
} finally {
domainDriverManager.releaseOrganizationSchema();
}
}
public void addUserInGroup(String sUserId, String sGroupId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
// Start transaction
domainDriverManager.startTransaction(false);
// Update group
groupManager.addUserInGroup(domainDriverManager, sUserId, sGroupId);
// Commit the transaction
domainDriverManager.commit();
cache.opUpdateGroup(getGroup(sGroupId));
} catch (Exception e) {
try {
// Roll back the transactions
domainDriverManager.rollback();
} catch (Exception e1) {
SilverTrace.error("admin", "Admin.addUserInGroup", "root.EX_ERR_ROLLBACK", e1);
}
throw new AdminException("Admin.addUserInGroup", SilverpeasException.ERROR,
"admin.EX_ERR_UPDATE_GROUP", "groupId = " + sGroupId + ", userId = " + sUserId, e);
} finally {
domainDriverManager.releaseOrganizationSchema();
}
}
/**
* Get Silverpeas organization
*/
public AdminGroupInst[] getAdminOrganization() throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
return groupManager.getAdminOrganization(domainDriverManager);
}
/**
* Gets the set of Ids denoting the direct subgroups of a given group
*
* @param groupId The ID of the parent group
* @return the Ids as an array of
* <code>String</code>.
*/
public String[] getAllSubGroupIds(String groupId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
return groupManager.getAllSubGroupIds(domainDriverManager, groupId);
}
public String[] getAllSubGroupIdsRecursively(String groupId)
throws AdminException {
List<String> groupIds = groupManager.getAllSubGroupIdsRecursively(groupId);
return groupIds.toArray(new String[groupIds.size()]);
}
/**
* Gets the set of Ids denoting the groups without any parent.
*
* @return the Ids as an array of
* <code>String</code>.
*/
public String[] getAllRootGroupIds() throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
return groupManager.getAllRootGroupIds(domainDriverManager);
}
/**
* Gets all root user groups in Silverpeas. A root group is the group of users without any other
* parent group.
*
* @return an array of user groups.
* @throws AdminException if an error occurs whil getting the root user groups.
*/
public Group[] getAllRootGroups() throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
return groupManager.getAllRootGroups(domainDriverManager);
}
//
// --------------------------------------------------------------------------------------------------------
// GROUP PROFILE RELATED FUNCTIONS
// --------------------------------------------------------------------------------------------------------
/**
* Get the group profile instance corresponding to the given ID
*/
public GroupProfileInst getGroupProfileInst(String groupId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
return groupProfileManager.getGroupProfileInst(domainDriverManager, null, groupId);
}
public String addGroupProfileInst(GroupProfileInst spaceProfileInst)
throws AdminException {
return addGroupProfileInst(spaceProfileInst, true);
}
/**
* Add the space profile instance from Silverpeas
*/
public String addGroupProfileInst(GroupProfileInst groupProfileInst,
boolean startNewTransaction) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
if (startNewTransaction) {
// Open the connections with auto-commit to false
domainDriverManager.startTransaction(false);
}
// Create the space profile instance
Group group = getGroup(groupProfileInst.getGroupId());
String sProfileId = groupProfileManager.createGroupProfileInst(
groupProfileInst, domainDriverManager, group.getId());
groupProfileInst.setId(sProfileId);
if (startNewTransaction) {
// commit the transactions
domainDriverManager.commit();
}
// m_Cache.opAddSpaceProfile(m_GroupProfileInstManager.getGroupProfileInst(m_DDManager,
// sSpaceProfileId, null));
return sProfileId;
} catch (Exception e) {
if (startNewTransaction) {
rollback();
}
throw new AdminException("Admin.addGroupProfileInst",
SilverpeasException.ERROR, "admin.EX_ERR_ADD_SPACE_PROFILE",
"group roleName = " + groupProfileInst.getName(), e);
} finally {
domainDriverManager.releaseOrganizationSchema();
}
}
public String deleteGroupProfileInst(String groupId) throws AdminException {
return deleteGroupProfileInst(groupId, true);
}
/**
* Delete the given space profile from Silverpeas
*/
public String deleteGroupProfileInst(String groupId, boolean startNewTransaction)
throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
// Get the SpaceProfile to delete
GroupProfileInst groupProfileInst =
groupProfileManager.getGroupProfileInst(domainDriverManager, null, groupId);
try {
if (startNewTransaction) {
domainDriverManager.startTransaction(false);
}
// Delete the Profile in tables
groupProfileManager.deleteGroupProfileInst(groupProfileInst, domainDriverManager);
if (startNewTransaction) {
// commit the transactions
domainDriverManager.commit();
}
return groupId;
} catch (Exception e) {
if (startNewTransaction) {
rollback();
}
throw new AdminException("Admin.deleteGroupProfileInst",
SilverpeasException.ERROR, "admin.EX_ERR_DELETE_GROUPPROFILE",
"groupId = " + groupId, e);
} finally {
if (startNewTransaction) {
domainDriverManager.releaseOrganizationSchema();
}
}
}
/**
* Update the given space profile in Silverpeas
*/
public String updateGroupProfileInst(GroupProfileInst groupProfileInstNew)
throws AdminException {
String sSpaceProfileNewId = groupProfileInstNew.getId();
if (!StringUtil.isDefined(sSpaceProfileNewId)) {
sSpaceProfileNewId = addGroupProfileInst(groupProfileInstNew);
} else {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
domainDriverManager.startTransaction(false);
GroupProfileInst oldSpaceProfile =
groupProfileManager.getGroupProfileInst(domainDriverManager, null,
groupProfileInstNew.getGroupId());
// Update the group profile in tables
groupProfileManager.updateGroupProfileInst(oldSpaceProfile,
domainDriverManager, groupProfileInstNew);
domainDriverManager.commit();
} catch (Exception e) {
rollback();
throw new AdminException("Admin.updateGroupProfileInst",
SilverpeasException.ERROR, "admin.EX_ERR_UPDATE_SPACEPROFILE",
"space profile Id: '" + groupProfileInstNew.getId() + "'", e);
} finally {
domainDriverManager.releaseOrganizationSchema();
}
}
return sSpaceProfileNewId;
}
/**
* @throws AdminException
*/
public void indexAllGroups() throws AdminException {
Domain[] domains = getAllDomains(); //All domains except Mixt Domain (id -1)
for (Domain domain : domains) {
try {
indexGroups(domain.getId());
} catch (Exception e) {
SilverTrace.error("admin", "Admin.indexAllGroups", "admin.CANT_INDEX_GROUPS",
"domainId = " + domain.getId(), e);
}
}
//Mixt Domain (id -1)
try {
indexGroups("-1");
} catch (Exception e) {
SilverTrace.error("admin", "Admin.indexAllGroups", "admin.CANT_INDEX_GROUPS",
"domainId = -1", e);
}
}
/**
* @param domainId
* @throws AdminException
*/
public void indexGroups(String domainId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
domainDriverManager.indexAllGroups(domainId);
} catch (Exception e) {
throw new AdminException("Admin.indexGroups",
SilverpeasException.ERROR, "admin.CANT_INDEX_GROUPS", "domainId = " + domainId, e);
}
}
// -------------------------------------------------------------------------
// USER RELATED FUNCTIONS
// -------------------------------------------------------------------------
/**
* Get all the users Ids available in Silverpeas
*/
public String[] getAllUsersIds() throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
return userManager.getAllUsersIds(domainDriverManager);
}
/**
* Get the user detail corresponding to the given user Id
*
* @param sUserId the user id.
* @return the user detail corresponding to the given user Id
* @throws AdminException
*/
public UserDetail getUserDetail(String sUserId) throws AdminException {
if (!StringUtil.isDefined(sUserId) || "-1".equals(sUserId)) {
return null;
}
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
UserDetail ud = cache.getUserDetail(sUserId);
if (ud == null) {
ud = userManager.getUserDetail(domainDriverManager, sUserId);
if (ud != null) {
cache.putUserDetail(sUserId, ud);
}
}
return ud;
}
/**
* Get the user details corresponding to the given user Ids.
*
* @param userIds
* @return the user details corresponding to the given user Ids.
* @throws AdminException
*/
public UserDetail[] getUserDetails(String[] userIds) throws AdminException {
if (userIds == null) {
return ArrayUtil.EMPTY_USER_DETAIL_ARRAY;
}
List<UserDetail> users = new ArrayList<UserDetail>(userIds.length);
for (String userId : userIds) {
try {
users.add(getUserDetail(userId));
} catch (AdminException e) {
SilverTrace.error("admin", "Admin.getUserDetails", "admin.EX_ERR_GET_USER_DETAILS",
"user id: '" + userId + "'", e);
}
}
return users.toArray(new UserDetail[users.size()]);
}
/**
* Get the user Id corresponding to Domain/Login
*
* @param sLogin
* @param sDomainId
* @return
* @throws AdminException
*/
public String getUserIdByLoginAndDomain(String sLogin, String sDomainId) throws AdminException {
Domain[] theDomains;
String valret = null;
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
if (!StringUtil.isDefined(sDomainId)) {
try {
theDomains = domainDriverManager.getAllDomains();
} catch (Exception e) {
throw new AdminException("Admin.getUserIdByLoginAndDomain",
SilverpeasException.ERROR, "admin.EX_ERR_GET_USER_BY_LOGIN_DOMAIN",
"login: '" + sLogin + "', domain id: '" + sDomainId + "'", e);
}
for (int i = 0; i < theDomains.length && valret == null; i++) {
try {
valret = userManager.getUserIdByLoginAndDomain(domainDriverManager, sLogin,
theDomains[i].getId());
} catch (Exception e) {
throw new AdminException("Admin.getUserIdByLoginAndDomain", SilverpeasException.ERROR,
"admin.EX_ERR_GET_USER_BY_LOGIN_DOMAIN", "login: '" + sLogin + "', domain id: '"
+ sDomainId + "'", e);
}
}
if (valret == null) {
throw new AdminException("Admin.getUserIdByLoginAndDomain", SilverpeasException.ERROR,
"admin.EX_ERR_USER_NOT_FOUND", "login: '" + sLogin + "', in all domains");
}
} else {
valret = userManager.getUserIdByLoginAndDomain(domainDriverManager, sLogin, sDomainId);
}
return valret;
}
/**
* @param authenticationKey The authentication key.
* @return The user id corresponding to the authentication key.
* @throws Exception
*/
public String getUserIdByAuthenticationKey(String authenticationKey) throws Exception {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
Map<String, String> userParameters = domainDriverManager.authenticate(authenticationKey);
String login = userParameters.get("login");
String domainId = userParameters.get("domainId");
return userManager.getUserIdByLoginAndDomain(domainDriverManager, login, domainId);
}
/**
* Get the user corresponding to the given user Id (only infos in cache table)
*
* @param sUserId
* @return
* @throws AdminException
*/
public UserFull getUserFull(String sUserId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
return userManager.getUserFull(domainDriverManager, sUserId);
}
public UserFull getUserFull(String domainId, String specificId) throws Exception {
SilverTrace.info("admin", "admin.getUserFull", "root.MSG_GEN_ENTER_METHOD",
"domainId=" + domainId);
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
DomainDriver synchroDomain = domainDriverManager.getDomainDriver(Integer.parseInt(domainId));
return synchroDomain.getUserFull(specificId);
}
/**
* Add the given user in Silverpeas and specific domain.
*
* @param userDetail
* @return the new user id.
* @throws AdminException
*/
public String addUser(UserDetail userDetail) throws AdminException {
try {
return addUser(userDetail, false);
} catch (Exception e) {
throw new AdminException("Admin.addUser", SilverpeasException.ERROR,
"admin.EX_ERR_ADD_USER", userDetail.getFirstName() + " " + userDetail.getLastName(), e);
}
}
/**
* Add the given user in Silverpeas and specific domain
*
* @param userDetail user to add
* @param addOnlyInSilverpeas true if user must not be added in distant datasource (used by
* synchronization tools)
* @return id of created user
*/
public String addUser(UserDetail userDetail, boolean addOnlyInSilverpeas) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
// Start transaction
domainDriverManager.startTransaction(false);
if (userDetail.getDomainId() != null && !addOnlyInSilverpeas) {
domainDriverManager.startTransaction(userDetail.getDomainId(), false);
}
// add user
String sUserId = userManager.addUser(domainDriverManager, userDetail, addOnlyInSilverpeas);
// Commit the transaction
domainDriverManager.commit();
if (userDetail.getDomainId() != null && !addOnlyInSilverpeas) {
domainDriverManager.commit(userDetail.getDomainId());
}
cache.opAddUser(userManager.getUserDetail(domainDriverManager, sUserId));
// return group id
return sUserId;
} catch (Exception e) {
try {
// Roll back the transactions
domainDriverManager.rollback();
if (userDetail.getDomainId() != null && !addOnlyInSilverpeas) {
domainDriverManager.rollback(userDetail.getDomainId());
}
} catch (Exception e1) {
SilverTrace.error("admin", "Admin.addUser", "root.EX_ERR_ROLLBACK", e1);
}
throw new AdminException("Admin.addUser", SilverpeasException.ERROR,
"admin.EX_ERR_ADD_USER", userDetail.getFirstName() + " " + userDetail.getLastName(), e);
} finally {
domainDriverManager.releaseOrganizationSchema();
if (userDetail.getDomainId() != null && !addOnlyInSilverpeas) {
domainDriverManager.releaseOrganizationSchema();
}
}
}
/**
* Delete the given user from silverpeas and specific domain
*/
public String deleteUser(String sUserId) throws AdminException {
try {
if (m_sDAPIGeneralAdminId.equals(sUserId)) {
SilverTrace.warn("admin", "Admin.deleteUser",
"admin.MSG_WARN_TRY_TO_DELETE_GENERALADMIN");
return null;
}
return deleteUser(sUserId, false);
} catch (Exception e) {
throw new AdminException("Admin.deleteUser", SilverpeasException.ERROR,
"admin.EX_ERR_DELETE_USER", "user id : '" + sUserId + "'", e);
}
}
/**
* Delete the given user from silverpeas and specific domain
*/
public String deleteUser(String sUserId, boolean onlyInSilverpeas) throws AdminException {
UserDetail user = null;
boolean transactionStarted = false;
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
// Get user information from Silverpeas database only
user = getUserDetail(sUserId);
if (user == null) {
throw new AdminException("Admin.deleteUser", SilverpeasException.ERROR,
"admin.EX_ERR_USER_NOT_FOUND", "user id : '" + sUserId + "'");
}
// Start transaction
domainDriverManager.startTransaction(false);
if (user.getDomainId() != null && !onlyInSilverpeas) {
transactionStarted = true;
domainDriverManager.startTransaction(user.getDomainId(), false);
}
// Delete the user
String sReturnUserId = userManager.deleteUser(domainDriverManager, user, onlyInSilverpeas);
// Commit the transaction
domainDriverManager.commit();
if (user.getDomainId() != null && !onlyInSilverpeas) {
domainDriverManager.commit(user.getDomainId());
}
cache.opRemoveUser(user);
return sReturnUserId;
} catch (Exception e) {
try {
// Roll back the transactions
domainDriverManager.rollback();
if (transactionStarted) {
domainDriverManager.rollback(user.getDomainId());
}
} catch (Exception e1) {
SilverTrace.error("admin", "Admin.deleteUser", "root.EX_ERR_ROLLBACK", e1);
}
throw new AdminException("Admin.deleteUser", SilverpeasException.ERROR,
"admin.EX_ERR_DELETE_USER", "user id : '" + sUserId + "'", e);
} finally {
domainDriverManager.releaseOrganizationSchema();
if (transactionStarted) {
domainDriverManager.releaseOrganizationSchema();
}
}
}
/**
* Update the given user (ONLY IN SILVERPEAS)
*/
public String updateUser(UserDetail user) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
// Start transaction
domainDriverManager.startTransaction(false);
// Update user
String sUserId = userManager.updateUser(domainDriverManager, user);
// Commit the transaction
domainDriverManager.commit();
cache.opUpdateUser(userManager.getUserDetail(domainDriverManager, sUserId));
return sUserId;
} catch (Exception e) {
rollback();
throw new AdminException("Admin.updateUser", SilverpeasException.ERROR,
"admin.EX_ERR_UPDATE_USER", "user id : '" + user.getId() + "'", e);
} finally {
domainDriverManager.releaseOrganizationSchema();
}
}
/**
* Update the given user in Silverpeas and specific domain
*/
public String updateUserFull(UserFull user) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
// Start transaction
domainDriverManager.startTransaction(false);
if (user.getDomainId() != null) {
domainDriverManager.startTransaction(user.getDomainId(), false);
}
// Update user
String sUserId = userManager.updateUserFull(domainDriverManager, user);
// Commit the transaction
domainDriverManager.commit();
if (user.getDomainId() != null) {
domainDriverManager.commit(user.getDomainId());
}
cache.opUpdateUser(userManager.getUserDetail(domainDriverManager, sUserId));
return sUserId;
} catch (Exception e) {
try {
// Roll back the transactions
domainDriverManager.rollback();
if (user.getDomainId() != null) {
domainDriverManager.rollback(user.getDomainId());
}
} catch (Exception e1) {
SilverTrace.error("admin", "Admin.updateUserFull", "root.EX_ERR_ROLLBACK", e1);
}
throw new AdminException("Admin.updateUserFull", SilverpeasException.ERROR,
"admin.EX_ERR_UPDATE_USER", "user id : '" + user.getId() + "'", e);
} finally {
domainDriverManager.releaseOrganizationSchema();
if (user.getDomainId() != null) {
domainDriverManager.releaseOrganizationSchema();
}
}
}
// -------------------------------------------------------------------------
// COMPONENT RELATED FUNCTIONS
// -------------------------------------------------------------------------
/**
* Instantiate the space Components
*/
private void instantiateComponents(String userId, String[] asComponentIds,
String[] asComponentNames, String sSpaceId, Connection connectionProd)
throws AdminException {
try {
for (int nI = 0; nI < asComponentIds.length; nI++) {
SilverTrace.debug("admin", "Admin.instantiateComponents",
"root.MSG_GEN_ENTER_METHOD", "spaceid: " + sSpaceId + " and component "
+ asComponentIds[nI]);
componentInstanciator.setConnection(connectionProd);
componentInstanciator.setSpaceId(sSpaceId);
componentInstanciator.setComponentId(asComponentIds[nI]);
componentInstanciator.setUserId(userId);
componentInstanciator.instantiateComponentName(asComponentNames[nI]);
}
} catch (Exception e) {
throw new AdminException("Admin.instantiateComponents",
SilverpeasException.ERROR, "admin.EX_ERR_INSTANTIATE_COMPONENTS", e);
}
}
/**
* Uninstantiate the space Components
*/
private void unInstantiateComponents(String userId, String[] asComponentIds,
String[] asComponentNames, String sSpaceId, Connection connectionProd) {
for (int nI = 0; nI < asComponentIds.length; nI++) {
try {
SilverTrace.debug("admin", "Admin.instantiateComponents",
"root.MSG_GEN_ENTER_METHOD", "spaceid: " + sSpaceId + " and component "
+ asComponentIds[nI]);
componentInstanciator.setConnection(connectionProd);
componentInstanciator.setSpaceId(sSpaceId);
componentInstanciator.setComponentId(asComponentIds[nI]);
componentInstanciator.setUserId(userId);
componentInstanciator.unInstantiateComponentName(asComponentNames[nI]);
} catch (Exception e) {
SilverTrace.warn("admin", "Admin.unInstantiateComponents",
"admin.EX_ERR_UNINSTANTIATE_COMPONENTS", "Deleting data from component '"
+ asComponentNames[nI] + "' failed", e);
}
}
}
// -------------------------------------------------------------------------
// CONVERSION CLIENT <--> DRIVER SPACE ID
// -------------------------------------------------------------------------
/**
* Converts client space id to driver space id
*/
private String getDriverSpaceId(String sClientSpaceId) {
if (sClientSpaceId != null && sClientSpaceId.startsWith(SPACE_KEY_PREFIX)) {
return sClientSpaceId.substring(SPACE_KEY_PREFIX.length());
}
return sClientSpaceId;
}
/**
* Converts driver space id to client space id
*/
public String getClientSpaceId(String sDriverSpaceId) {
if (sDriverSpaceId != null && !sDriverSpaceId.startsWith(SPACE_KEY_PREFIX)) {
return SPACE_KEY_PREFIX + sDriverSpaceId;
}
return sDriverSpaceId;
}
/**
* Converts driver space ids to client space ids
*/
public String[] getClientSpaceIds(String[] asDriverSpaceIds) throws Exception {
String[] asClientSpaceIds = new String[asDriverSpaceIds.length];
for (int nI = 0; nI < asDriverSpaceIds.length; nI++) {
asClientSpaceIds[nI] = getClientSpaceId(asDriverSpaceIds[nI]);
}
return asClientSpaceIds;
}
private String getDriverComponentId(String sClientComponentId) {
SilverTrace.debug("admin", "Admin.getDriverComponentId",
"root.MSG_GEN_ENTER_METHOD", "component id: " + sClientComponentId);
if (sClientComponentId == null) {
return "";
}
return getTableClientComponentIdFromClientComponentId(sClientComponentId);
}
/**
* Return 23 for parameter kmelia23
*/
private String getTableClientComponentIdFromClientComponentId(String sClientComponentId) {
String sTableClientId = "";
// Remove the component name to get the table client id
char[] cBuf = sClientComponentId.toCharArray();
for (int nI = 0; nI < cBuf.length && sTableClientId.length() == 0; nI++) {
if (cBuf[nI] == '0' || cBuf[nI] == '1' || cBuf[nI] == '2' || cBuf[nI] == '3' || cBuf[nI]
== '4' || cBuf[nI] == '5' || cBuf[nI] == '6' || cBuf[nI] == '7' || cBuf[nI] == '8'
|| cBuf[nI] == '9') {
sTableClientId = sClientComponentId.substring(nI);
}
}
return sTableClientId;
}
/**
* Return kmelia23 for parameter 23
*/
private String getClientComponentId(ComponentInst component) {
return getClientComponentId(component.getName(), component.getId());
}
private String getClientComponentId(String componentName, String sDriverComponentId) {
if (StringUtil.isInteger(sDriverComponentId)) {
return componentName + sDriverComponentId;
}
// id is already in client format
return sDriverComponentId;
}
// -------------------------------------------------------------------------
// DOMAIN QUERY
// -------------------------------------------------------------------------
/**
* Create a new domain
*/
public String addDomain(Domain theDomain) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
String id = domainDriverManager.createDomain(theDomain);
// Update the synchro scheduler
DomainDriver domainDriver = domainDriverManager.getDomainDriver(Integer.parseInt(id));
if (domainDriver.isSynchroThreaded()) {
domainSynchroScheduler.addDomain(id);
}
return id;
} catch (Exception e) {
throw new AdminException("Admin.addDomain", SilverpeasException.ERROR,
"admin.EX_ERR_ADD_DOMAIN", "domain name : '" + theDomain.getName() + "'", e);
}
}
/**
* Update a domain
*/
public String updateDomain(Domain domain) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
DomainCache.removeDomain(domain.getId());
return domainDriverManager.updateDomain(domain);
} catch (Exception e) {
throw new AdminException("Admin.updateDomain", SilverpeasException.ERROR,
"admin.EX_ERR_UPDATE_DOMAIN", "domain name : '" + domain.getName() + "'", e);
}
}
/**
* Remove a domain
*/
public String removeDomain(String domainId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
// Remove all users
UserDetail[] toRemoveUDs = userManager.getUsersOfDomain(domainDriverManager,
domainId);
if (toRemoveUDs != null) {
for (UserDetail user : toRemoveUDs) {
try {
deleteUser(user.getId(), false);
} catch (Exception e) {
deleteUser(user.getId(), true);
}
}
}
// Remove all groups
Group[] toRemoveGroups = groupManager.getGroupsOfDomain(domainDriverManager,
domainId);
if (toRemoveGroups != null) {
for (Group group : toRemoveGroups) {
try {
deleteGroupById(group.getId(), false);
} catch (Exception e) {
deleteGroupById(group.getId(), true);
}
}
}
// Remove the domain
domainDriverManager.removeDomain(domainId);
// Update the synchro scheduler
domainSynchroScheduler.removeDomain(domainId);
DomainCache.removeDomain(domainId);
return domainId;
} catch (Exception e) {
throw new AdminException("Admin.removeDomain", SilverpeasException.ERROR,
"admin.MSG_ERR_DELETE_DOMAIN", "domain Id : '" + domainId + "'", e);
}
}
/**
* Get all domains
*/
public Domain[] getAllDomains() throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
return domainDriverManager.getAllDomains();
} catch (Exception e) {
throw new AdminException("Admin.getAllDomains",
SilverpeasException.ERROR, "admin.EX_ERR_GET_ALL_DOMAINS", e);
}
}
/**
* Get a domain with given id
*/
public Domain getDomain(String domainId) throws AdminException {
try {
if (!StringUtil.isDefined(domainId) || !StringUtil.isInteger(domainId)) {
domainId = "-1";
}
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
Domain domain = DomainCache.getDomain(domainId);
if (domain == null) {
domain = domainDriverManager.getDomain(domainId);
DomainCache.addDomain(domain);
}
return domain;
} catch (Exception e) {
throw new AdminException("Admin.getDomain", SilverpeasException.ERROR,
"admin.EX_ERR_GET_DOMAIN", "domain Id : '" + domainId + "'", e);
}
}
/**
* Get a domain with given id
*/
public long getDomainActions(String domainId) throws AdminException {
try {
if (domainId != null && domainId.equals("-1")) {
return DomainDriver.ACTION_MASK_MIXED_GROUPS;
}
return DomainDriverManagerFactory.getCurrentDomainDriverManager().getDomainActions(domainId);
} catch (Exception e) {
throw new AdminException("Admin.getDomainActions",
SilverpeasException.ERROR, "admin.EX_ERR_GET_DOMAIN", "domain Id : '" + domainId + "'",
e);
}
}
public Group[] getRootGroupsOfDomain(String domainId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
return groupManager.getRootGroupsOfDomain(domainDriverManager, domainId);
} catch (Exception e) {
throw new AdminException("Admin.getGroupsOfDomain",
SilverpeasException.ERROR, "admin.EX_ERR_GET_DOMAIN", "domain Id : '" + domainId + "'",
e);
}
}
public Group[] getSynchronizedGroups() throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
return groupManager.getSynchronizedGroups(domainDriverManager);
} catch (Exception e) {
throw new AdminException("Admin.getGroupsOfDomain",
SilverpeasException.ERROR, "admin.EX_ERR_GET_DOMAIN", e);
}
}
public String[] getRootGroupIdsOfDomain(String domainId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
return groupManager.getRootGroupIdsOfDomain(domainDriverManager, domainId);
} catch (Exception e) {
throw new AdminException("Admin.getRootGroupIdsOfDomain",
SilverpeasException.ERROR, "admin.EX_ERR_GET_DOMAIN", "domain Id : '" + domainId + "'",
e);
}
}
public UserDetail[] getAllUsersOfGroup(String groupId) throws AdminException {
try {
List<String> groupIds = new ArrayList<String>();
groupIds.add(groupId);
groupIds.addAll(groupManager.getAllSubGroupIdsRecursively(groupId));
return userManager.getAllUsersOfGroups(groupIds);
} catch (Exception e) {
throw new AdminException("Admin.getAllUsersOfGroup",
SilverpeasException.ERROR, "admin.EX_ERR_GET_DOMAIN", "Group Id : '" + groupId + "'",
e);
}
}
public UserDetail[] getUsersOfDomain(String domainId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
if ("-1".equals(domainId) && domainId != null) {
return ArrayUtil.EMPTY_USER_DETAIL_ARRAY;
}
return userManager.getUsersOfDomain(domainDriverManager, domainId);
} catch (Exception e) {
throw new AdminException("Admin.getUsersOfDomain",
SilverpeasException.ERROR, "admin.EX_ERR_GET_DOMAIN", "domain Id : '" + domainId + "'",
e);
}
}
public String[] getUserIdsOfDomain(String domainId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
if ("-1".equals(domainId) && domainId != null) {
return ArrayUtil.EMPTY_STRING_ARRAY;
}
return userManager.getUserIdsOfDomain(domainDriverManager, domainId);
} catch (Exception e) {
throw new AdminException("Admin.getUserIdsOfDomain",
SilverpeasException.ERROR, "admin.EX_ERR_GET_DOMAIN", "domain Id : '" + domainId + "'",
e);
}
}
// -------------------------------------------------------------------------
// USERS QUERY
// -------------------------------------------------------------------------
/**
* Get the user id for the given login password
*/
public String authenticate(String sKey, String sSessionId,
boolean isAppInMaintenance) throws AdminException {
return authenticate(sKey, sSessionId, isAppInMaintenance, true);
}
/**
* Get the user id for the given login password
*/
public String authenticate(String sKey, String sSessionId, boolean isAppInMaintenance,
boolean removeKey) throws AdminException {
String sUserId;
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
// Authenticate the given user
Map<String, String> loginDomain = domainDriverManager.authenticate(sKey, removeKey);
if ((!loginDomain.containsKey("login")) || (!loginDomain.containsKey("domainId"))) {
throw new AdminException("Admin.authenticate", SilverpeasException.WARNING,
"admin.MSG_ERR_AUTHENTICATE_USER", "key : '" + sKey + "'");
}
// Get the Silverpeas userId
String sLogin = loginDomain.get("login");
String sDomainId = loginDomain.get("domainId");
DomainDriver synchroDomain = domainDriverManager.getDomainDriver(Integer.parseInt(
sDomainId));
// Get the user Id or import it if the domain accept it
try {
sUserId = userManager.getUserIdByLoginAndDomain(domainDriverManager, sLogin,
sDomainId);
} catch (Exception ex) {
if (synchroDomain.isSynchroOnLoginEnabled() && !isAppInMaintenance) {//Try to import new user
SilverTrace.warn("admin", "Admin.authenticate",
"admin.EX_ERR_USER_NOT_FOUND", "Login: '" + sLogin + "', Domain: " + sDomainId, ex);
sUserId = synchronizeImportUserByLogin(sDomainId, sLogin,
synchroDomain.isSynchroOnLoginRecursToGroups());
} else {
throw ex;
}
}
// Synchronize the user if the domain needs it
if (synchroDomain.isSynchroOnLoginEnabled() && !isAppInMaintenance) {
try {
synchronizeUser(sUserId, synchroDomain.isSynchroOnLoginRecursToGroups());
} catch (Exception ex) {
SilverTrace.warn("admin", "Admin.authenticate",
"admin.MSG_ERR_SYNCHRONIZE_USER", "UserId=" + sUserId + " Login: '" + sLogin
+ "', Domain: " + sDomainId, ex);
}
}
// Check that the user is not already in the pool
UserLog userLog = loggedUsers.get(sUserId);
if (userLog != null) {
// The user is already logged, remove it
loggedUsers.remove(sUserId);
SilverTrace.info("admin", "Admin.authenticate",
"admin.MSG_USER_ALREADY_LOGGED", "user id: '" + sUserId + "', log time: "
+ formatter.format(userLog.getLogDate()));
}
// Add the user in the pool of UserLog
userLog = new UserLog();
userLog.setSessionId(sSessionId);
userLog.setUserId(sUserId);
userLog.setUserLogin(sLogin);
userLog.setLogDate(new Date());
loggedUsers.put(sUserId, userLog);
return sUserId;
} catch (Exception e) {
throw new AdminException("Admin.authenticate",
SilverpeasException.WARNING, "admin.MSG_ERR_AUTHENTICATE_USER",
"key : '" + sKey + "'", e);
}
}
// ---------------------------------------------------------------------------------------------
// QUERY FUNCTIONS
// ---------------------------------------------------------------------------------------------
public String[] getDirectGroupsIdsOfUser(String userId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
return groupManager.getDirectGroupsOfUser(domainDriverManager, userId);
} catch (Exception e) {
throw new AdminException("Admin.getDirectGroupsIdsOfUser",
SilverpeasException.ERROR, "admin.EX_ERR_GROUP_NOT_FOUND",
"user Id : '" + userId + "'", e);
}
}
public UserDetail[] searchUsers(UserDetail modelUser, boolean isAnd)
throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
return userManager.searchUsers(domainDriverManager, modelUser, isAnd);
} catch (Exception e) {
throw new AdminException("Admin.searchUsers", SilverpeasException.ERROR,
"admin.EX_ERR_USER_NOT_FOUND", e);
}
}
public Group[] searchGroups(Group modelGroup, boolean isAnd) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
return groupManager.searchGroups(domainDriverManager, modelGroup, isAnd);
} catch (Exception e) {
throw new AdminException("Admin.searchGroups", SilverpeasException.ERROR,
"admin.EX_ERR_GROUP_NOT_FOUND", e);
}
}
/**
* Get the spaces ids allowed for the given user Id
*/
public String[] getUserSpaceIds(String sUserId) throws AdminException {
List<String> spaceIds = new ArrayList<String>();
// getting all components availables
List<String> componentIds = getAllowedComponentIds(sUserId);
for (String componentId : componentIds) {
List<SpaceInstLight> spaces = TreeCache.getComponentPath(componentId);
for (SpaceInstLight space : spaces) {
if (!spaceIds.contains(space.getFullId())) {
spaceIds.add(space.getFullId());
}
}
}
return spaceIds.toArray(new String[spaceIds.size()]);
}
private List<String> getAllGroupsOfUser(String userId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
List<String> allGroupsOfUser = GroupCache.getAllGroupIdsOfUser(userId);
if (allGroupsOfUser == null) {
// group ids of user is not yet processed
// process it and store it in cache
allGroupsOfUser = new ArrayList<String>();
String[] directGroupIds = groupManager.getDirectGroupsOfUser(domainDriverManager, userId);
for (String directGroupId : directGroupIds) {
Group group = groupManager.getGroup(directGroupId);
if (group != null) {
allGroupsOfUser.add(group.getId());
while (StringUtil.isDefined(group.getSuperGroupId())) {
group = groupManager.getGroup(group.getSuperGroupId());
if (group != null) {
allGroupsOfUser.add(group.getId());
}
}
}
}
// store groupIds of user in cache
GroupCache.setAllGroupIdsOfUser(userId, allGroupsOfUser);
}
return allGroupsOfUser;
}
private List<String> getAllowedComponentIds(String userId) throws AdminException {
return getAllowedComponentIds(userId, null);
}
private List<String> getAllowedComponentIds(String userId, String componentName)
throws AdminException {
// getting all groups of users
List<String> allGroupsOfUser = getAllGroupsOfUser(userId);
return componentManager.getAllowedComponentIds(Integer.parseInt(userId), allGroupsOfUser,
null, componentName);
}
/**
* Get the root spaces ids allowed for the given user Id
*/
public String[] getUserRootSpaceIds(String sUserId) throws AdminException {
try {
List<String> result = new ArrayList<String>();
// getting all components availables
List<String> componentIds = getAllowedComponentIds(sUserId);
// getting all root spaces (sorted)
String[] rootSpaceIds = getAllRootSpaceIds();
// retain only allowed root spaces
for (String rootSpaceId : rootSpaceIds) {
if (isSpaceContainsOneComponent(componentIds, getDriverSpaceId(rootSpaceId), true)) {
result.add(rootSpaceId);
}
}
return result.toArray(new String[result.size()]);
} catch (Exception e) {
throw new AdminException("Admin.getUserRootSpaceIds",
SilverpeasException.ERROR,
"admin.EX_ERR_GET_USER_ALLOWED_ROOTSPACE_IDS", "user Id : '" + sUserId + "'", e);
}
}
public String[] getUserSubSpaceIds(String sUserId, String spaceId) throws AdminException {
try {
List<String> result = new ArrayList<String>();
// getting all components availables
List<String> componentIds = getAllowedComponentIds(sUserId);
// getting all subspaces
List<SpaceInstLight> subspaces = TreeCache.getSubSpaces(getDriverSpaceId(spaceId));
for (SpaceInstLight subspace : subspaces) {
if (isSpaceContainsOneComponent(componentIds, subspace.getShortId(), true)) {
result.add(subspace.getShortId());
}
}
return result.toArray(new String[result.size()]);
} catch (Exception e) {
throw new AdminException("Admin.getUserRootSpaceIds",
SilverpeasException.ERROR,
"admin.EX_ERR_GET_USER_ALLOWED_ROOTSPACE_IDS", "user Id : '" + sUserId + "'", e);
}
}
/**
* This method permit to know if given space is allowed to given user.
*
* @param userId
* @param spaceId
* @return true if user is allowed to access to one component (at least) in given space, false
* otherwise.
* @throws AdminException
*/
public boolean isSpaceAvailable(String userId, String spaceId) throws AdminException {
List<String> componentIds = getAllowedComponentIds(userId);
return isSpaceContainsOneComponent(componentIds, getDriverSpaceId(spaceId), true);
}
private boolean isSpaceContainsOneComponent(List<String> componentIds, String spaceId,
boolean checkInSubspaces) {
boolean find = false;
List<ComponentInstLight> components =
new ArrayList<ComponentInstLight>(TreeCache.getComponents(spaceId));
// Is there at least one component available ?
for (int c = 0; !find && c < components.size(); c++) {
find = componentIds.contains(components.get(c).getId());
}
if (find) {
return true;
} else {
if (checkInSubspaces) {
// check in subspaces
List<SpaceInstLight> subspaces =
new ArrayList<SpaceInstLight>(TreeCache.getSubSpaces(spaceId));
for (int s = 0; !find && s < subspaces.size(); s++) {
find =
isSpaceContainsOneComponent(componentIds, subspaces.get(s).getShortId(),
checkInSubspaces);
}
}
}
return find;
}
/**
* Get subspaces of a given space available to a user.
*
* @param userId
* @param spaceId
* @return a list of SpaceInstLight
* @throws AdminException
* @author neysseri
*/
public List<SpaceInstLight> getSubSpacesOfUser(String userId, String spaceId)
throws AdminException {
SilverTrace.info("admin", "Admin.getSubSpacesOfUser",
"root.MSG_GEN_ENTER_METHOD", "userId = " + userId + ", spaceId = " + spaceId);
try {
List<SpaceInstLight> result = new ArrayList<SpaceInstLight>();
// getting all components availables
List<String> componentIds = getAllowedComponentIds(userId);
// getting all subspaces
List<SpaceInstLight> subspaces = TreeCache.getSubSpaces(getDriverSpaceId(spaceId));
for (SpaceInstLight subspace : subspaces) {
if (isSpaceContainsOneComponent(componentIds, subspace.getShortId(), true)) {
result.add(subspace);
}
}
return result;
} catch (Exception e) {
throw new AdminException("Admin.getSubSpacesOfUser",
SilverpeasException.ERROR, "admin.EX_ERR_GET_USER_ALLOWED_SUBSPACES",
"userId = " + userId + ", spaceId = " + spaceId, e);
}
}
public List<SpaceInstLight> getSubSpaces(String spaceId)
throws AdminException {
SilverTrace.info("admin", "Admin.getSubSpaces", "root.MSG_GEN_ENTER_METHOD", "spaceId = "
+ spaceId);
try {
return spaceManager.getSubSpaces(getDriverSpaceId(spaceId));
} catch (Exception e) {
throw new AdminException("Admin.getSubSpaces",
SilverpeasException.ERROR, "admin.EX_ERR_GET_SUBSPACES",
"spaceId = " + spaceId, e);
}
}
/**
* Get components of a given space (and subspaces) available to a user.
*
* @param userId
* @param spaceId
* @return a list of ComponentInstLight
* @throws AdminException
* @author neysseri
*/
public List<ComponentInstLight> getAvailCompoInSpace(String userId, String spaceId)
throws AdminException {
SilverTrace.info("admin", "Admin.getAvailCompoInSpace",
"root.MSG_GEN_ENTER_METHOD", "userId = " + userId + ", spaceId = " + spaceId);
try {
List<String> allowedComponentIds = getAllowedComponentIds(userId);
List<ComponentInstLight> allowedComponents = new ArrayList<ComponentInstLight>();
List<ComponentInstLight> allComponents =
TreeCache.getComponentsInSpaceAndSubspaces(getDriverSpaceId(spaceId));
for (ComponentInstLight component : allComponents) {
if (allowedComponentIds.contains(component.getId())) {
allowedComponents.add(component);
}
}
return allowedComponents;
} catch (Exception e) {
throw new AdminException("Admin.getAvailCompoInSpace",
SilverpeasException.ERROR,
"admin.EX_ERR_GET_USER_ALLOWED_COMPONENTS", "userId = " + userId + ", spaceId = "
+ spaceId, e);
}
}
public Map<String, SpaceAndChildren> getTreeView(String userId, String spaceId)
throws AdminException {
SilverTrace.info("admin", "Admin.getTreeView", "root.MSG_GEN_ENTER_METHOD",
"userId = " + userId + ", spaceId = " + spaceId);
spaceId = getDriverSpaceId(spaceId);
// Step 1 - get all availables spaces and components
Collection<SpaceInstLight> spacesLight = getSubSpacesOfUser(userId, spaceId);
Collection<ComponentInstLight> componentsLight = getAvailCompoInSpace(userId, spaceId);
SilverTrace.info("admin", "Admin.getTreeView", "root.MSG_GEN_PARAM_VALUE",
"SQL Queries done !");
// Step 2 - build HashTable
Map<String, SpaceAndChildren> spaceTrees = new HashMap<String, SpaceAndChildren>();
Iterator<SpaceInstLight> it = spacesLight.iterator();
while (it.hasNext()) {
SpaceInstLight space = it.next();
spaceTrees.put(space.getFullId(), new SpaceAndChildren(space));
}
// Step 3 - add root space to hashtable
SpaceInstLight rootSpace = getSpaceInstLight(spaceId);
spaceTrees.put(rootSpace.getFullId(), new SpaceAndChildren(rootSpace));
// Step 4 - build dependances
it = spacesLight.iterator();
while (it.hasNext()) {
SpaceInstLight child = it.next();
String fatherId = SPACE_KEY_PREFIX + child.getFatherId();
SpaceAndChildren father = spaceTrees.get(fatherId);
if (father != null) {
father.addSubSpace(child);
}
}
for (ComponentInstLight child : componentsLight) {
String fatherId = SPACE_KEY_PREFIX + child.getDomainFatherId();
SpaceAndChildren father = spaceTrees.get(fatherId);
if (father != null) {
father.addComponent(child);
}
}
SilverTrace.info("admin", "Admin.getTreeView", "root.MSG_GEN_EXIT_METHOD",
"userId = " + userId + ", spaceId = " + spaceId);
return spaceTrees;
}
/**
* Get all spaces available to a user. N levels compliant. Infos of each space are in
* SpaceInstLight object.
*
* @param userId
* @return an ordered list of SpaceInstLight. Built according a depth-first algorithm.
* @throws Exception
* @author neysseri
*/
public List<SpaceInstLight> getUserSpaceTreeview(String userId) throws Exception {
SilverTrace.info("admin", "Admin.getUserSpaceTreeview",
"root.MSG_GEN_ENTER_METHOD", "user id = " + userId);
Set<String> componentsId = Sets.newHashSet(getAvailCompoIds(userId));
Set<String> authorizedIds = new HashSet<String>(100);
if (!componentsId.isEmpty()) {
String componentId = componentsId.iterator().next();
componentsId.remove(componentId);
filterSpaceFromComponents(authorizedIds, componentsId, componentId);
}
String[] rootSpaceIds = getAllRootSpaceIds(userId);
List<SpaceInstLight> treeview = new ArrayList<SpaceInstLight>(authorizedIds.size());
for (String spaceId : rootSpaceIds) {
String currentSpaceId = getDriverSpaceId(spaceId);
if (authorizedIds.contains(currentSpaceId)) {
treeview.add(TreeCache.getSpaceInstLight(currentSpaceId));
addAuthorizedSpaceToTree(treeview, authorizedIds, currentSpaceId, 1);
}
}
return treeview;
}
void addAuthorizedSpaceToTree(List<SpaceInstLight> treeview, Set<String> authorizedIds,
String spaceId, int level) {
SilverTrace.debug("admin", "Admin.addAuthorizedSpaceToTree", "root.MSG_GEN_ENTER_METHOD",
"size of treeview = " + treeview.size());
List<SpaceInstLight> subSpaces = TreeCache.getSubSpaces(spaceId);
for (SpaceInstLight space : subSpaces) {
String subSpaceId = getDriverSpaceId(space.getFullId());
if (authorizedIds.contains(subSpaceId)) {
space.setLevel(level);
treeview.add(space);
addAuthorizedSpaceToTree(treeview, authorizedIds, subSpaceId, level + 1);
}
}
}
/**
* @param spaces list of authorized spaces built by this method
* @param componentsId list of components' id (base to get authorized spaces)
* @param space a space candidate to be in authorized spaces list
*/
void addAuthorizedSpace(Set<String> spaces, Set<String> componentsId, SpaceInstLight space) {
SilverTrace.debug("admin", "Admin.addAuthorizedSpace", "root.MSG_GEN_ENTER_METHOD",
"#componentIds = " + componentsId.size());
if (space != null && !SpaceInst.STATUS_REMOVED.equals(space.getStatus())
&& !spaces.contains(space.getShortId())) {
SilverTrace.debug("admin", "Admin.addAuthorizedSpace", "root.MSG_GEN_PARAM_VALUE",
"space = " + space.getFullId());
String spaceId = getDriverSpaceId(space.getFullId());
spaces.add(spaceId);
componentsId.removeAll(TreeCache.getComponentIds(spaceId));
if (!space.isRoot()) {
String fatherId = getDriverSpaceId(space.getFatherId());
if (!spaces.contains(fatherId)) {
SpaceInstLight parent = TreeCache.getSpaceInstLight(fatherId);
addAuthorizedSpace(spaces, componentsId, parent);
}
}
}
}
void filterSpaceFromComponents(Set<String> spaces, Set<String> componentsId, String componentId) {
SilverTrace.debug("admin", "Admin.filterSpaceFromComponents", "root.MSG_GEN_ENTER_METHOD",
"#componentIds = " + componentsId.size() + ", componentId = " + componentId);
SpaceInstLight space = TreeCache.getSpaceContainingComponent(componentId);
addAuthorizedSpace(spaces, componentsId, space);
if (!componentsId.isEmpty()) {
String newComponentId = componentsId.iterator().next();
componentsId.remove(newComponentId);
filterSpaceFromComponents(spaces, componentsId, newComponentId);
}
}
public String[] getAllowedSubSpaceIds(String userId, String spaceFatherId) throws AdminException {
return getUserSubSpaceIds(userId, spaceFatherId);
}
private SpaceInstLight getSpaceInstLight(String spaceId)
throws AdminException {
SilverTrace.info("admin", "Admin.getSpaceInstLight",
"root.MSG_GEN_ENTER_METHOD", "spaceId = " + spaceId);
return getSpaceInstLight(spaceId, -1);
}
private SpaceInstLight getSpaceInstLight(String spaceId, int level) throws AdminException {
SilverTrace.info("admin", "Admin.getSpaceInstLight", "root.MSG_GEN_ENTER_METHOD",
"spaceId = " + spaceId + ", level = " + level);
SpaceInstLight sil = TreeCache.getSpaceInstLight(spaceId);
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
if (sil == null) {
sil = spaceManager.getSpaceInstLightById(domainDriverManager, spaceId);
}
if (sil != null) {
if (level != -1) {
sil.setLevel(level);
}
if (sil.getLevel() == -1) {
sil.setLevel(TreeCache.getSpaceLevel(spaceId));
}
}
return sil;
}
/**
* Get the space instance light (only spaceid, fatherId and name) with the given space id
*
* @param sClientSpaceId client space id (as WAxx)
* @return Space information as SpaceInstLight object
*/
public SpaceInstLight getSpaceInstLightById(String sClientSpaceId) throws AdminException {
try {
return getSpaceInstLight(getDriverSpaceId(sClientSpaceId));
} catch (Exception e) {
throw new AdminException("Admin.getSpaceInstLightById",
SilverpeasException.ERROR, "admin.EX_ERR_GET_SPACE", " space Id : '" + sClientSpaceId
+ "'", e);
}
}
/**
* Return the higher space according to a subspace (N level compliant)
*
* @param spaceId the subspace id
* @return a SpaceInstLight object
* @throws AdminException
*/
public SpaceInstLight getRootSpace(String spaceId) throws AdminException {
SpaceInstLight sil = getSpaceInstLight(getDriverSpaceId(spaceId));
while (sil != null && !sil.isRoot()) {
sil = getSpaceInstLight(sil.getFatherId());
}
return sil;
}
/**
* Get the spaces ids manageable by given group Id
*/
public String[] getGroupManageableSpaceIds(String sGroupId)
throws AdminException {
String[] asManageableSpaceIds;
ArrayList<String> alManageableSpaceIds = new ArrayList<String>();
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
// Get user manageable space ids from database
List<String> groupIds = new ArrayList<String>();
groupIds.add(sGroupId);
List<String> manageableSpaceIds = spaceManager.getManageableSpaceIds(null, groupIds);
asManageableSpaceIds = manageableSpaceIds.toArray(new String[manageableSpaceIds.size()]);
// Inherits manageability rights for space children
String[] childSpaceIds;
for (String asManageableSpaceId : asManageableSpaceIds) {
// add manageable space id in result
if (!alManageableSpaceIds.contains(asManageableSpaceId)) {
alManageableSpaceIds.add(asManageableSpaceId);
}
// calculate manageable space's childs
childSpaceIds = spaceManager.getAllSubSpaceIds(domainDriverManager,
asManageableSpaceId);
// add them in result
for (String childSpaceId : childSpaceIds) {
if (!alManageableSpaceIds.contains(childSpaceId)) {
alManageableSpaceIds.add(childSpaceId);
}
}
}
// Put user manageable space ids in cache
asManageableSpaceIds = alManageableSpaceIds.toArray(new String[alManageableSpaceIds.size()]);
return asManageableSpaceIds;
} catch (Exception e) {
throw new AdminException("Admin.getGroupManageableSpaceIds",
SilverpeasException.ERROR,
"admin.EX_ERR_GET_USER_MANAGEABLE_SPACE_IDS", "group Id : '" + sGroupId + "'", e);
}
}
/**
* Get the spaces ids manageable by given user Id
*/
public String[] getUserManageableSpaceIds(String sUserId) throws AdminException {
String[] asManageableSpaceIds;
ArrayList<String> alManageableSpaceIds = new ArrayList<String>();
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
// Get user manageable space ids from cache
asManageableSpaceIds = cache.getManageableSpaceIds(sUserId);
if (asManageableSpaceIds == null) {
// Get user manageable space ids from database
List<String> groupIds = getAllGroupsOfUser(sUserId);
asManageableSpaceIds = userManager.getManageableSpaceIds(sUserId, groupIds);
// Inherits manageability rights for space children
String[] childSpaceIds;
for (String asManageableSpaceId : asManageableSpaceIds) {
// add manageable space id in result
if (!alManageableSpaceIds.contains(asManageableSpaceId)) {
alManageableSpaceIds.add(asManageableSpaceId);
}
// calculate manageable space's childs
childSpaceIds = spaceManager.getAllSubSpaceIds(domainDriverManager,
asManageableSpaceId);
// add them in result
for (String childSpaceId : childSpaceIds) {
if (!alManageableSpaceIds.contains(childSpaceId)) {
alManageableSpaceIds.add(childSpaceId);
}
}
}
// Put user manageable space ids in cache
asManageableSpaceIds = alManageableSpaceIds.toArray(
new String[alManageableSpaceIds.size()]);
cache.putManageableSpaceIds(sUserId, asManageableSpaceIds);
}
return asManageableSpaceIds;
} catch (Exception e) {
throw new AdminException("Admin.getUserManageableSpaceIds",
SilverpeasException.ERROR,
"admin.EX_ERR_GET_USER_MANAGEABLE_SPACE_IDS", "user Id : '" + sUserId + "'", e);
}
}
/**
* Get the spaces roots ids manageable by given user Id
*/
public String[] getUserManageableSpaceRootIds(String sUserId)
throws AdminException {
try {
// Get user manageable space ids from database
List<String> groupIds = getAllGroupsOfUser(sUserId);
String[] asManageableSpaceIds = userManager.getManageableSpaceIds(sUserId, groupIds);
// retain only root spaces
List<String> manageableRootSpaceIds = new ArrayList<String>();
for (String asManageableSpaceId : asManageableSpaceIds) {
SpaceInstLight space = TreeCache.getSpaceInstLight(asManageableSpaceId);
if (space.isRoot()) {
manageableRootSpaceIds.add(asManageableSpaceId);
}
}
return manageableRootSpaceIds.toArray(new String[manageableRootSpaceIds.size()]);
} catch (Exception e) {
throw new AdminException("Admin.getUserManageableSpaceRootIds",
SilverpeasException.ERROR,
"admin.EX_ERR_GET_USER_MANAGEABLE_SPACE_IDS", "user Id : '" + sUserId + "'", e);
}
}
/**
* Get the sub space ids manageable by given user Id in given space
*/
public String[] getUserManageableSubSpaceIds(String sUserId,
String sParentSpaceId) throws AdminException {
try {
// Get user manageable space ids from database
List<String> groupIds = getAllGroupsOfUser(sUserId);
String[] asManageableSpaceIds = userManager.getManageableSpaceIds(sUserId, groupIds);
String parentSpaceId = getDriverSpaceId(sParentSpaceId);
// retain only sub spaces
boolean find;
List<String> manageableRootSpaceIds = new ArrayList<String>();
for (String manageableSpaceId : asManageableSpaceIds) {
find = false;
SpaceInstLight space = TreeCache.getSpaceInstLight(manageableSpaceId);
while (!space.isRoot() && !find) {
if (parentSpaceId.equals(space.getFatherId())) {
manageableRootSpaceIds.add(manageableSpaceId);
find = true;
} else {
space = TreeCache.getSpaceInstLight(space.getFatherId());
}
}
}
return manageableRootSpaceIds.toArray(new String[manageableRootSpaceIds.size()]);
} catch (Exception e) {
throw new AdminException("Admin.getManageableSubSpaceIds",
SilverpeasException.ERROR,
"admin.EX_ERR_GET_USER_MANAGEABLE_SPACE_IDS", "user Id : '" + sUserId + "' Space = "
+ sParentSpaceId, e);
}
}
public List<String> getUserManageableGroupIds(String sUserId) throws AdminException {
try {
// get all groups of user
List<String> groupIds = getAllGroupsOfUser(sUserId);
return groupManager.getManageableGroupIds(sUserId, groupIds);
} catch (Exception e) {
throw new AdminException("Admin.getUserManageableGroupIds",
SilverpeasException.ERROR,
"admin.EX_ERR_GET_USER_MANAGEABLE_GROUP_IDS", "userId + " + sUserId,
e);
}
}
/**
* Get the component ids allowed for the given user Id in the given space
*/
public String[] getAvailCompoIds(String sClientSpaceId, String sUserId)
throws AdminException {
String[] asAvailCompoIds;
try {
// Converts client space id to driver space id
String spaceId = getDriverSpaceId(sClientSpaceId);
// Get available component ids from cache
asAvailCompoIds = cache.getAvailCompoIds(spaceId, sUserId);
if (asAvailCompoIds == null) {
// Get available component ids from database
List<ComponentInstLight> components = getAvailCompoInSpace(sUserId, sClientSpaceId);
List<String> componentIds = new ArrayList<String>();
for (ComponentInstLight component : components) {
componentIds.add(component.getId());
}
asAvailCompoIds = componentIds.toArray(new String[componentIds.size()]);
// Store available component ids in cache
cache.putAvailCompoIds(spaceId, sUserId, asAvailCompoIds);
}
return asAvailCompoIds;
// return getClientComponentIds(asAvailCompoIds);
} catch (Exception e) {
throw new AdminException("Admin.getAvailCompoIds",
SilverpeasException.ERROR,
"admin.EX_ERR_GET_USER_AVAILABLE_COMPONENT_IDS", "user Id : '" + sUserId + "'", e);
}
}
public boolean isComponentAvailable(String componentId, String userId)
throws AdminException {
try {
return getAllowedComponentIds(userId).contains(componentId);
} catch (Exception e) {
throw new AdminException("Admin.isComponentAvailable",
SilverpeasException.ERROR, "admin.EX_ERR_IS_COMPONENT_AVAILABLE",
"user Id : '" + userId + "'" + " , component Id : '" + componentId + "'", e);
}
}
public boolean isComponentManageable(String componentId, String userId) throws AdminException {
boolean manageable = getUserDetail(userId).isAccessAdmin();
if (!manageable) {
// check if user is manager of at least one space parent
String[] spaceIds = getUserManageableSpaceIds(userId);
ComponentInstLight component = getComponentInstLight(componentId);
if (component != null) {
List<String> toCheck = Arrays.asList(spaceIds);
manageable = toCheck.contains(getDriverSpaceId(component.getDomainFatherId()));
}
}
return manageable;
}
/**
* Get ids of components allowed to user in given space (not in subspaces)
*
* @return an array of componentId (kmelia12, hyperlink145...)
* @throws AdminException
*/
public String[] getAvailCompoIdsAtRoot(String sClientSpaceId, String sUserId)
throws AdminException {
try {
// Converts client space id to driver space id
String spaceId = getDriverSpaceId(sClientSpaceId);
List<String> groupIds = getAllGroupsOfUser(sUserId);
List<String> asAvailCompoIds =
componentManager.getAllowedComponentIds(Integer.parseInt(sUserId), groupIds,
spaceId);
return asAvailCompoIds.toArray(new String[asAvailCompoIds.size()]);
} catch (Exception e) {
throw new AdminException("Admin.getAvailCompoIds",
SilverpeasException.ERROR,
"admin.EX_ERR_GET_USER_AVAILABLE_COMPONENT_IDS", "user Id : '" + sUserId + "'", e);
}
}
/**
* Get the componentIds allowed for the given user Id in the given space and the componentNameRoot
*
* @param sClientSpaceId
* @param sUserId
* @param componentNameRoot
* @return ArrayList of componentIds
* @author dlesimple
*/
public List<String> getAvailCompoIdsAtRoot(String sClientSpaceId,
String sUserId, String componentNameRoot) throws AdminException {
try {
// Converts client space id to driver space id
String spaceId = getDriverSpaceId(sClientSpaceId);
// Get available component ids from database
List<ComponentInstLight> components = TreeCache.getComponents(spaceId);
List<String> allowedComponentIds = getAllowedComponentIds(sUserId);
List<String> result = new ArrayList<String>();
for (ComponentInstLight component : components) {
if (allowedComponentIds.contains(component.getId()) && component.getName().startsWith(
componentNameRoot)) {
result.add(component.getId());
}
}
return result;
} catch (Exception e) {
throw new AdminException("Admin.getAvailCompoIdsAtRoot",
SilverpeasException.ERROR,
"admin.EX_ERR_GET_USER_AVAILABLE_COMPONENT_IDS", "user Id : '" + sUserId + "'", e);
}
}
/**
* Get the component ids allowed for the given user Id.
*
* @param userId
*/
public String[] getAvailCompoIds(String userId) throws AdminException {
try {
List<String> componentIds = getAllowedComponentIds(userId);
return componentIds.toArray(new String[componentIds.size()]);
} catch (Exception e) {
throw new AdminException("Admin.getAvailCompoIds",
SilverpeasException.ERROR,
"admin.EX_ERR_GET_USER_AVAILABLE_COMPONENT_IDS", "user Id : '" + userId + "'", e);
}
}
/**
* Get the driver component ids allowed for the given user Id in the given space
*/
public String[] getAvailDriverCompoIds(String sClientSpaceId, String sUserId)
throws AdminException {
try {
// Get available component ids
List<ComponentInstLight> components = getAvailCompoInSpace(sUserId, sClientSpaceId);
List<String> componentIds = new ArrayList<String>();
for (ComponentInstLight component : components) {
componentIds.add(component.getId());
}
return componentIds.toArray(new String[componentIds.size()]);
} catch (Exception e) {
throw new AdminException("Admin.getAvailDriverCompoIds",
SilverpeasException.ERROR,
"admin.EX_ERR_GET_USER_AVAILABLE_COMPONENT_IDS", "user Id : '" + sUserId + "'", e);
}
}
public String[] getComponentIdsByNameAndUserId(String sUserId,
String sComponentName) throws AdminException {
List<String> allowedComponentIds = getAllowedComponentIds(sUserId, sComponentName);
return allowedComponentIds.toArray(new String[allowedComponentIds.size()]);
}
/**
* gets the available component for a given user
*
* @param userId user identifier used to get component
* @param componentName type of component to retrieve ( for example : kmelia, forums, blog)
* @return a list of ComponentInstLight object
* @throws AdminException
*/
public List<ComponentInstLight> getAvailComponentInstLights(
String userId, String componentName) throws AdminException {
List<ComponentInstLight> components = new ArrayList<ComponentInstLight>();
List<String> allowedComponentIds = getAllowedComponentIds(userId, componentName);
for (String allowedComponentId : allowedComponentIds) {
ComponentInstLight componentInst = getComponentInstLight(allowedComponentId);
if (componentInst.getName().equalsIgnoreCase(componentName)) {
components.add(componentInst);
}
}
return components;
}
/**
* This method returns all root spaces which contains at least one allowed component of type
* componentName in this space or subspaces.
*
* @param userId
* @param componentName the component type (kmelia, gallery...)
* @return a list of root spaces
* @throws AdminException
*/
public List<SpaceInstLight> getRootSpacesContainingComponent(String userId, String componentName)
throws AdminException {
List<SpaceInstLight> spaces = new ArrayList<SpaceInstLight>();
List<ComponentInstLight> components = getAvailComponentInstLights(userId, componentName);
for (ComponentInstLight component : components) {
List<SpaceInstLight> path = TreeCache.getComponentPath(component.getId());
if (path != null && !path.isEmpty()) {
SpaceInstLight root = path.get(0);
if (!spaces.contains(root)) {
spaces.add(root);
}
}
}
return spaces;
}
/**
* This method returns all sub spaces which contains at least one allowed component of type
* componentName in this space or subspaces.
*
* @param userId
* @param componentName the component type (kmelia, gallery...)
* @return a list of root spaces
* @throws AdminException
*/
public List<SpaceInstLight> getSubSpacesContainingComponent(String spaceId, String userId,
String componentName)
throws AdminException {
List<SpaceInstLight> spaces = new ArrayList<SpaceInstLight>();
spaceId = getDriverSpaceId(spaceId);
List<ComponentInstLight> components = getAvailComponentInstLights(userId, componentName);
for (ComponentInstLight component : components) {
List<SpaceInstLight> path = TreeCache.getComponentPath(component.getId());
for (SpaceInstLight space : path) {
if (space.getFatherId().equals(spaceId)) {
if (!spaces.contains(space)) {
spaces.add(space);
}
}
}
}
return spaces;
}
/**
* Get the tuples (space id, compo id) allowed for the given user and given component name
*/
public CompoSpace[] getCompoForUser(String sUserId, String sComponentName) throws AdminException {
ArrayList<CompoSpace> alCompoSpace = new ArrayList<CompoSpace>();
try {
List<ComponentInstLight> components = getAvailComponentInstLights(sUserId, sComponentName);
for (ComponentInstLight componentInst : components) {
// Create new instance of CompoSpace
CompoSpace compoSpace = new CompoSpace();
// Set the component Id
compoSpace.setComponentId(componentInst.getId());
// Set the component label
if (StringUtil.isDefined(componentInst.getLabel())) {
compoSpace.setComponentLabel(componentInst.getLabel());
} else {
compoSpace.setComponentLabel(componentInst.getName());
}
// Set the space label
compoSpace.setSpaceId(getClientSpaceId(componentInst.getDomainFatherId()));
SpaceInstLight spaceInst = getSpaceInstLightById(componentInst.getDomainFatherId());
compoSpace.setSpaceLabel(spaceInst.getName());
alCompoSpace.add(compoSpace);
}
return alCompoSpace.toArray(new CompoSpace[alCompoSpace.size()]);
} catch (Exception e) {
throw new AdminException("Admin.getCompoForUser",
SilverpeasException.ERROR,
"admin.EX_ERR_GET_USER_AVAILABLE_INSTANCES_OF_COMPONENT",
"user Id : '" + sUserId + "', component name: '" + sComponentName + "'", e);
}
}
/**
* Return the compo id for the given component name
*/
public String[] getCompoId(String sComponentName) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
// Build the list of instanciated components with given componentName
String[] asMatchingComponentIds =
componentManager.getAllCompoIdsByComponentName(domainDriverManager, sComponentName);
return asMatchingComponentIds;
} catch (Exception e) {
throw new AdminException("Admin.getCompoId", SilverpeasException.ERROR,
"admin.EX_ERR_GET_AVAILABLE_INSTANCES_OF_COMPONENT",
"component name: '" + sComponentName + "'", e);
}
}
/**
* Get all the profiles Id for the given user
*/
public String[] getProfileIds(String sUserId) throws AdminException {
try {
// Get the component instance from cache
String[] asProfilesIds = cache.getProfileIds(sUserId);
if (asProfilesIds == null) {
// retrieve value from database
asProfilesIds =
profileManager.getProfileIdsOfUser(sUserId, getAllGroupsOfUser(sUserId));
// store values in cache
if (asProfilesIds != null) {
cache.putProfileIds(sUserId, asProfilesIds);
}
}
return asProfilesIds;
} catch (Exception e) {
throw new AdminException("Admin.getProfiles", SilverpeasException.ERROR,
"admin.EX_ERR_GET_USER_PROFILES", "user Id : '" + sUserId + "'", e);
}
}
/**
* Get all the profiles Id for the given group
*/
public String[] getProfileIdsOfGroup(String sGroupId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
try {
// retrieve value from database
return profileManager.getProfileIdsOfGroup(domainDriverManager, sGroupId);
} catch (Exception e) {
throw new AdminException("Admin.getProfileIdsOfGroup",
SilverpeasException.ERROR, "admin.EX_ERR_GET_GROUP_PROFILES",
"group Id : '" + sGroupId + "'", e);
}
}
/**
* Get the profile names of the given user for the given component
*/
public String[] getCurrentProfiles(String sUserId, ComponentInst componentInst)
throws AdminException {
ArrayList<String> alProfiles = new ArrayList<String>();
try {
// Build the list of profiles containing the given user
String[] asProfileIds = getProfileIds(sUserId);
for (String asProfileId : asProfileIds) {
for (int nJ = 0; nJ < componentInst.getNumProfileInst(); nJ++) {
if (componentInst.getProfileInst(nJ).getId().equals(asProfileId)) {
alProfiles.add(componentInst.getProfileInst(nJ).getName());
}
}
}
return arrayListToString(removeTuples(alProfiles));
} catch (Exception e) {
SilverTrace.error("admin", "Admin.getCurrentProfiles", "admin.MSG_ERR_GET_CURRENT_PROFILE",
e);
return ArrayUtil.EMPTY_STRING_ARRAY;
}
}
/**
* Get the profile names of the given user for the given component
*/
public String[] getCurrentProfiles(String sUserId, String componentId)
throws AdminException {
return profileManager.getProfileNamesOfUser(sUserId, getAllGroupsOfUser(sUserId), Integer.
parseInt(getDriverComponentId(componentId)));
}
/**
* if bAllProfiles = true, return all the user details for the given space and given component if
* bAllProfiles = false, return the user details only for the given profile for the given space
* and given component
*/
public UserDetail[] getUsers(boolean bAllProfiles, String sProfile,
String sClientSpaceId, String sClientComponentId) throws AdminException {
ArrayList<String> alUserIds = new ArrayList<String>();
try {
ComponentInst componentInst = getComponentInst(
getDriverComponentId(sClientComponentId), true,
getDriverSpaceId(sClientSpaceId));
for (ProfileInst profile : componentInst.getAllProfilesInst()) {
if (profile != null) {
if (profile.getName().equals(sProfile) || bAllProfiles) {
// add direct users
alUserIds.addAll(profile.getAllUsers());
// add users of groups
List<String> groupIds = profile.getAllGroups();
for (String groupId : groupIds) {
List<String> subGroupIds = groupManager.getAllSubGroupIdsRecursively(groupId);
// add current group
subGroupIds.add(groupId);
if (subGroupIds != null && subGroupIds.size() > 0) {
UserDetail[] users = userManager.getAllUsersOfGroups(subGroupIds);
for (UserDetail user : users) {
alUserIds.add(user.getId());
}
}
}
}
}
}
removeTuples(alUserIds);
// Get the users details
UserDetail[] userDetails = new UserDetail[alUserIds.size()];
for (int nI = 0; nI < userDetails.length; nI++) {
userDetails[nI] = getUserDetail(alUserIds.get(nI));
}
return userDetails;
} catch (Exception e) {
throw new AdminException("Admin.getUsers", SilverpeasException.ERROR,
"admin.EX_ERR_GET_USERS_FOR_PROFILE_AND_COMPONENT", "profile : '" + sProfile
+ "', space Id: '" + sClientSpaceId + "' component Id: '" + sClientComponentId, e);
}
}
/**
* For use in userPanel : return the direct sub-groups
*/
public Group[] getAllSubGroups(String parentGroupId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
String[] theIds = groupManager.getAllSubGroupIds(domainDriverManager, parentGroupId);
return getGroups(theIds);
}
/**
* For use in userPanel : return the users that are direct child of a given group
*/
public UserDetail[] getFiltredDirectUsers(String sGroupId,
String sUserLastNameFilter) throws AdminException {
Group theGroup = getGroup(sGroupId);
if (theGroup == null) {
return ArrayUtil.EMPTY_USER_DETAIL_ARRAY;
}
String[] usersIds = theGroup.getUserIds();
if (usersIds == null || usersIds.length <= 0) {
return ArrayUtil.EMPTY_USER_DETAIL_ARRAY;
}
if (sUserLastNameFilter == null || sUserLastNameFilter.length() <= 0) {
return getUserDetails(usersIds);
}
String upperFilter = sUserLastNameFilter.toUpperCase();
ArrayList<UserDetail> matchedUsers = new ArrayList<UserDetail>();
for (int i = 0; i < usersIds.length; i++) {
UserDetail currentUser = getUserDetail(usersIds[i]);
if (currentUser != null && currentUser.getLastName().toUpperCase().startsWith(upperFilter)) {
matchedUsers.add(currentUser);
}
}
return matchedUsers.toArray(new UserDetail[matchedUsers.size()]);
}
/**
* For use in userPanel : return the total number of users recursivly contained in a group
*/
public int getAllSubUsersNumber(String sGroupId) throws AdminException {
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
if (!StringUtil.isDefined(sGroupId)) {
return userManager.getUserNumber(domainDriverManager);
} else {
// add users directly in this group
int nb = groupManager.getNBUsersDirectlyInGroup(sGroupId);
// add users in sub groups
List<String> groupIds = groupManager.getAllSubGroupIdsRecursively(sGroupId);
for (String groupId : groupIds) {
nb += groupManager.getNBUsersDirectlyInGroup(groupId);
}
return nb;
}
}
/**
* this method gets number user in domain. If domain id is null, it returns number user of all
* domain
*/
public int getUsersNumberOfDomain(String domainId) throws AdminException {
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
try {
if (!StringUtil.isDefined(domainId)) {
return userManager.getUserNumber(domainDriverManager);
}
if ("-1".equals(domainId)) {
return 0;
}
return userManager.getUsersNumberOfDomain(domainDriverManager, domainId);
} catch (Exception e) {
throw new AdminException("Admin.getUsersOfDomain",
SilverpeasException.ERROR, "admin.EX_ERR_GET_DOMAIN", "domain Id : '" + domainId + "'",
e);
}
}
/**
* Get the Ids of the administrators
*/
public String[] getAdministratorUserIds(String fromUserId) throws AdminException {
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
return userManager.getAllAdminIds(domainDriverManager, getUserDetail(fromUserId));
}
/**
* Get administrator Email
*
* @return String
*/
public String getAdministratorEmail() {
return administratorMail;
}
/**
* Get the administrator email
*/
public String getDAPIGeneralAdminId() {
return "0";
}
/**
* Get the list of connected users
*/
public UserLog[] getUserConnected() {
UserLog[] userLogs = new UserLog[loggedUsers.size()];
int nI = 0;
for (String user : loggedUsers.keySet()) {
userLogs[nI++] = loggedUsers.get(user);
}
return userLogs;
}
// -------------------------------------------------------------------------
// CONNECTION TOOLS
// -------------------------------------------------------------------------
/**
* Open a connection
*/
private Connection openConnection(String sDbUrl, String sUser, String sPswd,
boolean bAutoCommit) throws AdminException {
try {
// Load the driver (registers itself)
Class.forName(adminDBDriver);
// Get the connection to the DB
Connection connection = DriverManager.getConnection(sDbUrl, sUser, sPswd);
connection.setAutoCommit(bAutoCommit);
return connection;
} catch (Exception e) {
throw new AdminException("Admin.openConnection",
SilverpeasException.FATAL, "root.EX_CONNECTION_OPEN_FAILED",
"Db url: '" + sDbUrl + "', user: '" + sUser + "'", e);
}
}
// -------------------------------------------------------------------------
// UTILS
// -------------------------------------------------------------------------
private String[] arrayListToString(ArrayList<String> al) {
if (al == null) {
return ArrayUtil.EMPTY_STRING_ARRAY;
}
String[] as = new String[al.size()];
for (int nI = 0; nI < al.size(); nI++) {
as[nI] = al.get(nI);
}
return as;
}
private ArrayList<String> removeTuples(ArrayList<String> al) {
if (al == null) {
return new ArrayList<String>();
}
for (int nI = 0; nI < al.size(); nI++) {
while (al.lastIndexOf(al.get(nI)) != al.indexOf(al.get(nI))) {
al.remove(al.lastIndexOf(al.get(nI)));
}
}
return al;
}
// -------------------------------------------------------------------
// RE-INDEXATION
// -------------------------------------------------------------------
public String[] getAllSpaceIds(String sUserId) throws Exception {
return getClientSpaceIds(getUserSpaceIds(sUserId));
}
/**
* Return all the root spaces Id available in webactiv
*/
public String[] getAllRootSpaceIds(String sUserId) throws Exception {
return getClientSpaceIds(getUserRootSpaceIds(sUserId));
}
/**
* Return all the subSpaces Id available in webactiv given a space id (driver format)
*/
public String[] getAllSubSpaceIds(String sSpaceId, String sUserId)
throws Exception {
return getClientSpaceIds(getUserSubSpaceIds(sUserId, sSpaceId));
}
/**
* Return all the components Id in the subspaces available in webactiv given a space id
*/
public String[] getAllComponentIds(String sSpaceId) throws Exception {
ArrayList<String> alCompoIds = new ArrayList<String>();
// Get the compo of this space
SpaceInst spaceInst = getSpaceInstById(sSpaceId);
ArrayList<ComponentInst> alCompoInst = spaceInst.getAllComponentsInst();
if (alCompoInst != null) {
for (ComponentInst anAlCompoInst : alCompoInst) {
alCompoIds.add(anAlCompoInst.getId());
}
}
return arrayListToString(alCompoIds);
}
/**
* Return all the componentIds recursively in the subspaces available in webactiv given a space id
*/
public String[] getAllComponentIdsRecur(String sSpaceId) throws Exception {
List<ComponentInstLight> components =
TreeCache.getComponentsInSpaceAndSubspaces(getDriverSpaceId(sSpaceId));
List<String> componentIds = new ArrayList<String>();
for (ComponentInstLight component : components) {
componentIds.add(component.getId());
}
return componentIds.toArray(new String[componentIds.size()]);
}
/**
* Return all the components Id recursively in (Space+subspaces, or only subspaces or in
* Silverpeas) available in silverpeas given a userId and a componentNameRoot
*
* @param sSpaceId
* @param sUserId
* @param componentNameRoot
* @param inCurrentSpace
* @param inAllSpaces
* @return Array of componentsIds
* @author dlesimple
*/
public String[] getAllComponentIdsRecur(String sSpaceId, String sUserId,
String componentNameRoot, boolean inCurrentSpace, boolean inAllSpaces)
throws Exception {
SilverTrace.info("admin", "Admin.getAllComponentIdsRecur",
"root.MSG_GEN_PARAM_VALUE", "inCurrentSpace=" + inCurrentSpace + " inAllSpaces="
+ inAllSpaces);
ArrayList<String> alCompoIds = new ArrayList<String>();
// In All silverpeas
if (inAllSpaces) {
CompoSpace[] cs = getCompoForUser(sUserId, componentNameRoot);
for (CompoSpace c : cs) {
alCompoIds.add(c.getComponentId());
}
} else {
alCompoIds = getAllComponentIdsRecur(sSpaceId, sUserId,
componentNameRoot, inCurrentSpace);
}
return arrayListToString(alCompoIds);
}
/**
* Return all the components Id recursively in (Space+subspaces, or only subspaces) available in
* webactiv given a userId and a componentNameRoot
*
* @param sSpaceId
* @param sUserId
* @param componentNameRoot
* @param inCurrentSpace
* @return ArrayList of componentsIds
* @author dlesimple
*/
private ArrayList<String> getAllComponentIdsRecur(String sSpaceId, String sUserId,
String componentNameRoot, boolean inCurrentSpace) throws Exception {
ArrayList<String> alCompoIds = new ArrayList<String>();
SpaceInst spaceInst = getSpaceInstById(sSpaceId);
getComponentIdsByNameAndUserId(sUserId, componentNameRoot);
// Get components in the root of the space
if (inCurrentSpace) {
String[] componentIds = getAvailCompoIdsAtRoot(sSpaceId, sUserId);
if (componentIds != null) {
for (String componentId : componentIds) {
ComponentInstLight compo = getComponentInstLight(componentId);
if (compo.getName().equals(componentNameRoot)) {
alCompoIds.add(compo.getId());
}
}
}
}
// Get components in sub spaces
String[] asSubSpaceIds = getAllSubSpaceIds(sSpaceId);
for (int nI = 0;
asSubSpaceIds != null && nI < asSubSpaceIds.length;
nI++) {
SilverTrace.info("admin", "Admin.getAllComponentIdsRecur",
"root.MSG_GEN_PARAM.VALUE", "Sub spaceId=" + asSubSpaceIds[nI]);
spaceInst = getSpaceInstById(asSubSpaceIds[nI]);
String[] componentIds = getAvailCompoIds(spaceInst.getId(), sUserId);
if (componentIds != null) {
for (String componentId : componentIds) {
ComponentInstLight compo = getComponentInstLight(componentId);
if (compo.getName().equals(componentNameRoot)) {
SilverTrace.info("admin", "Admin.getAllComponentIdsRecur",
"root.MSG_GEN_PARAM.VALUE", "componentId in subspace=" + compo.getId());
alCompoIds.add(compo.getId());
}
}
}
}
return alCompoIds;
}
public void synchronizeGroupByRule(String groupId, boolean scheduledMode) throws AdminException {
SilverTrace.info("admin", "Admin.synchronizeGroup", "root.MSG_GEN_ENTER_METHOD",
"groupId = " + groupId);
Group group = getGroup(groupId);
String rule = group.getRule();
String domainId = group.getDomainId();
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
if (StringUtil.isDefined(rule)) {
try {
if (!scheduledMode) {
SynchroGroupReport.setTraceLevel(SynchroGroupReport.TRACE_LEVEL_DEBUG);
SynchroGroupReport.startSynchro();
}
SynchroGroupReport.warn("admin.synchronizeGroup", "Synchronisation du groupe '" + group.
getName() + "' - Regle de synchronisation = \"" + rule + "\"", null);
String[] actualUserIds = group.getUserIds();
domainDriverManager.startTransaction(false);
// Getting users according to rule
List<String> userIds = null;
if (rule.toLowerCase().startsWith("ds_")) {
if (rule.toLowerCase().startsWith("ds_accesslevel")) {
userIds = synchronizeGroupByAccessRoleRule(rule, domainId);
} else if (rule.toLowerCase().startsWith("ds_domain")) {
userIds = synchronizeGroupByDomainRule(rule, domainId);
}
} else if (rule.toLowerCase().startsWith("dc_")) {
// Extracting property name and searching property value
String propertyName = rule.substring(rule.indexOf("_") + 1, rule.indexOf("=")).trim();
String propertyValue = rule.substring(rule.indexOf("=") + 1).trim();
userIds = new ArrayList<String>();
if (domainId == null) {
// All users by extra information
Domain[] domains = getAllDomains();
for (Domain domain : domains) {
userIds.addAll(
getUserIdsBySpecificProperty(domain.getId(), propertyName, propertyValue));
}
} else {
userIds.addAll(getUserIdsBySpecificProperty(domainId, propertyName, propertyValue));
}
} else {
SilverTrace.error("admin", "Admin.synchronizeGroup", "admin.MSG_ERR_SYNCHRONIZE_GROUP",
"rule '" + rule + "' for groupId '" + groupId + "' is not correct !");
}
// Add users
List<String> newUsers = new ArrayList<String>();
for (int i = 0; userIds != null && i < userIds.size(); i++) {
String userId = userIds.get(i);
boolean bFound = false;
for (int j = 0; j < actualUserIds.length && !bFound; j++) {
if (actualUserIds[j].equals(userId)) {
bFound = true;
}
}
if (!bFound) {
newUsers.add(userId);
SynchroGroupReport.info("admin.synchronizeGroup", "Ajout de l'utilisateur " + userId,
null);
}
}
SynchroGroupReport.warn("admin.synchronizeGroup",
"Ajout de " + newUsers.size() + " utilisateur(s)",
null);
if (!newUsers.isEmpty()) {
domainDriverManager.getOrganization().group.addUsersInGroup(newUsers.toArray(
new String[newUsers.size()]), Integer.parseInt(groupId), false);
}
// Remove users
List<String> removedUsers = new ArrayList<String>();
for (String actualUserId : actualUserIds) {
boolean bFound = false;
for (int j = 0; userIds != null && j < userIds.size() && !bFound; j++) {
if (userIds.get(j).equals(actualUserId)) {
bFound = true;
}
}
if (!bFound) {
removedUsers.add(actualUserId);
SynchroGroupReport.info("admin.synchronizeGroup", "Suppression de l'utilisateur "
+ actualUserId, null);
}
}
SynchroGroupReport.warn("admin.synchronizeGroup", "Suppression de " + removedUsers.size()
+ " utilisateur(s)", null);
if (removedUsers.size() > 0) {
domainDriverManager.getOrganization().group.removeUsersFromGroup(
removedUsers.toArray(new String[removedUsers.size()]), Integer.parseInt(groupId),
false);
}
domainDriverManager.commit();
} catch (Exception e) {
try {
// Roll back the transactions
domainDriverManager.rollback();
} catch (Exception e1) {
SilverTrace.error("admin", "Admin.synchronizeGroup", "root.EX_ERR_ROLLBACK", e1);
}
SynchroGroupReport.error("admin.synchronizeGroup",
"Problème lors de la synchronisation : " + e.getMessage(), null);
throw new AdminException("Admin.synchronizeGroup",
SilverpeasException.ERROR, "admin.MSG_ERR_SYNCHRONIZE_GROUP",
"groupId : '" + groupId + "'", e);
} finally {
if (!scheduledMode) {
SynchroGroupReport.stopSynchro();
}
domainDriverManager.releaseOrganizationSchema();
}
}
}
private List<String> synchronizeGroupByDomainRule(String rule, String domainId)
throws AdminPersistenceException {
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
List<String> userIds = Collections.emptyList();
// Extracting domain id
String dId = rule.substring(rule.indexOf("=") + 1).trim();
// Available only for "domaine mixte"
if (domainId == null || "-1".equals(domainId)) {
userIds = Arrays.asList(domainDriverManager.getOrganization().user.getUserIdsOfDomain(
Integer.parseInt(dId)));
}
return userIds;
}
private List<String> synchronizeGroupByAccessRoleRule(String rule, String domainId)
throws AdminException {
List<String> userIds;// Extracting access level
String accessLevel = rule.substring(rule.indexOf("=") + 1).trim();
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
if ("*".equalsIgnoreCase(accessLevel)) {
// All users In case of "Domaine mixte", we retrieve all users of all domains
// Else we get only users of group's domain
if (domainId == null) {
userIds = Arrays.asList(userManager.getAllUsersIds(domainDriverManager));
} else {
userIds = Arrays.asList(userManager.getUserIdsOfDomain(domainDriverManager, domainId));
}
} else {
// All users by access level
if (domainId == null) {
userIds = Arrays.asList(domainDriverManager.getOrganization().user.getUserIdsByAccessLevel(
accessLevel));
} else {
userIds = Arrays.asList(userManager.getUserIdsOfDomainAndAccessLevel(domainDriverManager,
domainId, accessLevel));
}
}
return userIds;
}
private List<String> getUserIdsBySpecificProperty(String domainId, String propertyName,
String propertyValue) throws AdminException {
int iDomainId = Integer.parseInt(domainId);
UserDetail[] users = ArrayUtil.EMPTY_USER_DETAIL_ARRAY;
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
DomainDriver domainDriver = null;
try {
domainDriver = domainDriverManager.getDomainDriver(iDomainId);
} catch (Exception e) {
SynchroGroupReport.info("admin.getUserIdsBySpecificProperty",
"Erreur ! Domaine " + iDomainId + " inaccessible !", null);
}
if (domainDriver != null) {
try {
users = domainDriver.getUsersBySpecificProperty(propertyName,
propertyValue);
if (users == null) {
SynchroGroupReport.info("admin.getUserIdsBySpecificProperty",
"La propriété '" + propertyName + "' n'est pas définie dans le domaine "
+ iDomainId, null);
}
} catch (Exception e) {
SynchroGroupReport.info("admin.getUserIdsBySpecificProperty", "Domain " + domainId
+ " ne supporte pas les groupes synchronisés", null);
}
}
List<String> specificIds = new ArrayList<String>();
if (users != null) {
for (UserDetail user : users) {
specificIds.add(user.getSpecificId());
}
}
// We have to find users according to theirs specificIds
UserRow[] usersInDomain =
domainDriverManager.getOrganization().user.getUsersBySpecificIds(iDomainId, specificIds);
List<String> userIds = new ArrayList<String>();
if (usersInDomain != null) {
for (UserRow userInDomain : usersInDomain) {
userIds.add(Integer.toString(userInDomain.id));
}
}
return userIds;
}
// //////////////////////////////////////////////////////////
// Synchronization tools
// //////////////////////////////////////////////////////////
private List<String> translateGroupIds(String sDomainId, String[] groupSpecificIds,
boolean recursGroups) throws Exception {
List<String> convertedGroupIds = new ArrayList<String>();
String groupId;
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
for (String groupSpecificId : groupSpecificIds) {
try {
groupId = groupManager.getGroupIdBySpecificIdAndDomainId(domainDriverManager,
groupSpecificId, sDomainId);
} catch (AdminException e) {
// The group doesn't exist -> Synchronize him
groupId = null;
SilverTrace.warn("admin", "Admin.translateGroupIds",
"admin.EX_ERR_GROUP_NOT_FOUND", "SpecId=" + groupSpecificId, e);
if (recursGroups) {
try {
groupId = synchronizeImportGroup(sDomainId, groupSpecificId,
null, true, true);
} catch (AdminException ex) {
// The group's synchro failed -> ignore him
SilverTrace.warn("admin", "Admin.translateGroupIds",
"admin.MSG_ERR_SYNCHRONIZE_GROUP", "SpecId=" + groupSpecificId, ex);
groupId = null;
}
}
}
if (groupId != null) {
convertedGroupIds.add(groupId);
}
}
return convertedGroupIds;
}
private String[] translateUserIds(String sDomainId, String[] userSpecificIds)
throws Exception {
List<String> convertedUserIds = new ArrayList<String>();
String userId;
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
for (String userSpecificId : userSpecificIds) {
try {
userId = userManager.getUserIdBySpecificIdAndDomainId(domainDriverManager, userSpecificId,
sDomainId);
} catch (AdminException e) {
// The user doesn't exist -> Synchronize him
SilverTrace.warn("admin", "Admin.translateUserIds",
"admin.EX_ERR_USER_NOT_FOUND", "SpecId=" + userSpecificId, e);
try {
userId = synchronizeImportUser(sDomainId, userSpecificId, false);
} catch (AdminException ex) {
// The user's synchro failed -> Ignore him
SilverTrace.warn("admin", "Admin.translateUserIds",
"admin.MSG_ERR_SYNCHRONIZE_USER", "SpecId=" + userSpecificId,
ex);
userId = null;
}
}
if (userId != null) {
convertedUserIds.add(userId);
}
}
return convertedUserIds.toArray(new String[convertedUserIds.size()]);
}
/**
*
*/
public String synchronizeGroup(String groupId, boolean recurs) throws Exception {
SilverTrace.info("admin", "admin.synchronizeGroup",
"root.MSG_GEN_ENTER_METHOD", "GroupId=" + groupId);
Group theGroup = getGroup(groupId);
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
if (theGroup.isSynchronized()) {
synchronizeGroupByRule(groupId, false);
} else {
DomainDriver synchroDomain =
domainDriverManager.getDomainDriver(Integer.parseInt(theGroup.getDomainId()));
Group gr = synchroDomain.synchroGroup(theGroup.getSpecificId());
gr.setId(groupId);
gr.setDomainId(theGroup.getDomainId());
gr.setSuperGroupId(theGroup.getSuperGroupId());
internalSynchronizeGroup(synchroDomain, gr, recurs);
}
return groupId;
}
/**
*
*/
public String synchronizeImportGroup(String domainId, String groupKey,
String askedParentId, boolean recurs, boolean isIdKey) throws Exception {
SilverTrace.info("admin", "admin.synchronizeImportGroup",
"root.MSG_GEN_ENTER_METHOD", "groupKey=" + groupKey);
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
DomainDriver synchroDomain = domainDriverManager.getDomainDriver(Integer.parseInt(
domainId));
Group gr;
if (isIdKey) {
gr = synchroDomain.synchroGroup(groupKey);
} else {
gr = synchroDomain.importGroup(groupKey);
}
gr.setDomainId(domainId);
// We now search for the parent of this group
// ------------------------------------------
// First, we get the parents of the group
String[] parentSpecificIds = synchroDomain.getGroupMemberGroupIds(gr.getSpecificId());
String parentId = null;
for (int i = 0; i < parentSpecificIds.length && parentId == null; i++) {
try {
parentId = groupManager.getGroupIdBySpecificIdAndDomainId(
domainDriverManager, parentSpecificIds[i], domainId);
if (askedParentId != null && !askedParentId.isEmpty() && !askedParentId.equals(
parentId)) {
// It is not the matching parent
parentId = null;
}
} catch (AdminException e) {
// The user doesn't exist -> Synchronize him
parentId = null;
}
}
if (parentId == null && (parentSpecificIds.length > 0 || (askedParentId != null
&& askedParentId.length() > 0))) {// We
// can't
// add
// the
// group
// (just
// the
// same
// restriction as for the directories...)
throw new AdminException("Admin.synchronizeImportGroup",
SilverpeasException.ERROR, "admin.EX_ERR_GROUP_PARENT_NOT_PRESENT",
"group name : '" + groupKey + "'");
}
// The group is a root group or have a known parent
gr.setSuperGroupId(parentId);
// We must first add the group with no child. Then, the childs will be added
// during the internal synchronization function call
String[] specificIds = gr.getUserIds();
gr.setUserIds(ArrayUtil.EMPTY_STRING_ARRAY);
String groupId = addGroup(gr, true);
gr.setId(groupId);
gr.setUserIds(specificIds);
internalSynchronizeGroup(synchroDomain, gr, recurs);
return groupId;
}
/**
*
*/
public String synchronizeRemoveGroup(String groupId) throws Exception {
SilverTrace.info("admin", "admin.synchronizeRemoveGroup",
"root.MSG_GEN_ENTER_METHOD", "GroupId=" + groupId);
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
Group theGroup = getGroup(groupId);
DomainDriver synchroDomain =
domainDriverManager.getDomainDriver(Integer.parseInt(theGroup.getDomainId()));
synchroDomain.removeGroup(theGroup.getSpecificId());
return deleteGroupById(groupId, true);
}
protected void internalSynchronizeGroup(DomainDriver synchroDomain,
Group latestGroup, boolean recurs) throws Exception {
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
latestGroup.setUserIds(translateUserIds(latestGroup.getDomainId(),
latestGroup.getUserIds()));
updateGroup(latestGroup, true);
if (recurs) {
Group[] childs = synchroDomain.getGroups(latestGroup.getSpecificId());
for (int i = 0; i < childs.length; i++) {
String existingGroupId = null;
try {
existingGroupId =
groupManager.getGroupIdBySpecificIdAndDomainId(domainDriverManager,
childs[i].getSpecificId(), latestGroup.getDomainId());
Group existingGroup = getGroup(existingGroupId);
if (existingGroup.getSuperGroupId().equals(latestGroup.getId())) {
// Only synchronize the group if latestGroup is his true parent
synchronizeGroup(existingGroupId, recurs);
}
} catch (AdminException e) {
// The group doesn't exist -> Import him
if (existingGroupId == null) { // Import the new group
synchronizeImportGroup(latestGroup.getDomainId(), childs[i].getSpecificId(),
latestGroup.getId(), recurs, true);
}
}
}
}
}
/**
* Synchronize Users and groups between cache and domain's datastore
*/
public String synchronizeUser(String userId, boolean recurs) throws Exception {
Collection<UserDetail> listUsersUpdate = new ArrayList<UserDetail>();
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
SilverTrace.info("admin", "admin.synchronizeUser", "root.MSG_GEN_ENTER_METHOD", "userId="
+ userId);
try {
// Start transaction
domainDriverManager.startTransaction(false);
UserDetail theUserDetail = getUserDetail(userId);
DomainDriver synchroDomain = domainDriverManager.getDomainDriver(Integer.parseInt(
theUserDetail.getDomainId()));
// Synchronize the user's infos
UserDetail ud = synchroDomain.synchroUser(theUserDetail.getSpecificId());
ud.setId(userId);
ud.setAccessLevel(theUserDetail.getAccessLevel());
ud.setDomainId(theUserDetail.getDomainId());
if (!ud.equals(theUserDetail)) {
userManager.updateUser(domainDriverManager, ud);
cache.opUpdateUser(userManager.getUserDetail(domainDriverManager, userId));
}
// Synchro manuelle : Ajoute ou Met à jour l'utilisateur
listUsersUpdate.add(ud);
// Synchronize the user's groups
String[] incGroupsSpecificId = synchroDomain.getUserMemberGroupIds(
theUserDetail.getSpecificId());
List<String> incGroupsId = translateGroupIds(theUserDetail.getDomainId(),
incGroupsSpecificId, recurs);
String[] oldGroupsId = groupManager.getDirectGroupsOfUser(domainDriverManager, userId);
for (String oldGroupId : oldGroupsId) {
if (incGroupsId.contains(oldGroupId)) { // No changes have to be
// performed to the group -> Remove it
incGroupsId.remove(oldGroupId);
} else {
Group grpToRemove = groupManager.getGroup(domainDriverManager, oldGroupId);
if (theUserDetail.getDomainId().equals(grpToRemove.getDomainId())) {
// Remove the user from this group
groupManager.removeUserFromGroup(domainDriverManager, userId, oldGroupId);
cache.opRemoveUserFromGroup(userId, oldGroupId);
}
}
}
// Now the remaining groups of the vector are the groups where the user is
// newly added
for (String includedGroupId : incGroupsId) {
groupManager.addUserInGroup(domainDriverManager, userId, includedGroupId);
cache.opAddUserInGroup(userId, includedGroupId);
}
// traitement spécifique des users selon l'interface implémentée
processSpecificSynchronization(theUserDetail.getDomainId(), null, listUsersUpdate, null);
// Commit the transaction
domainDriverManager.commit();
// return user id
return userId;
} catch (Exception e) {
rollback();
throw new AdminException("Admin.synchronizeUser", SilverpeasException.ERROR,
"admin.EX_ERR_UPDATE_USER", "user id : '" + userId + "'", e);
} finally {
domainDriverManager.releaseOrganizationSchema();
}
}
/**
* Synchronize Users and groups between cache and domain's datastore
*/
public String synchronizeImportUserByLogin(String domainId, String userLogin, boolean recurs)
throws Exception {
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
SilverTrace.info("admin", "admin.synchronizeImportUserByLogin",
"root.MSG_GEN_ENTER_METHOD", "userLogin=" + userLogin);
DomainDriver synchroDomain = domainDriverManager.getDomainDriver(Integer.parseInt(
domainId));
UserDetail ud = synchroDomain.importUser(userLogin);
ud.setDomainId(domainId);
String userId = addUser(ud, true);
// Synchronizes the user to add it to the groups and recursivaly add the groups
synchronizeUser(userId, recurs);
return userId;
}
/**
* Synchronize Users and groups between cache and domain's datastore
*/
public String synchronizeImportUser(String domainId, String specificId, boolean recurs) throws
Exception {
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
SilverTrace.info("admin", "admin.synchronizeImportUser",
"root.MSG_GEN_ENTER_METHOD", "specificId=" + specificId);
DomainDriver synchroDomain = domainDriverManager.getDomainDriver(Integer.parseInt(
domainId));
UserDetail ud = synchroDomain.getUser(specificId);
ud.setDomainId(domainId);
String userId = addUser(ud, true);
// Synchronizes the user to add it to the groups and recursivaly add the groups
synchronizeUser(userId, recurs);
return userId;
}
public List<DomainProperty> getSpecificPropertiesToImportUsers(String domainId,
String language) throws Exception {
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
SilverTrace.info("admin", "admin.getSpecificPropertiesToImportUsers",
"root.MSG_GEN_ENTER_METHOD", "domainId=" + domainId);
DomainDriver synchroDomain = domainDriverManager.getDomainDriver(Integer.parseInt(
domainId));
return synchroDomain.getPropertiesToImport(language);
}
public UserDetail[] searchUsers(String domainId, Map<String, String> query)
throws Exception {
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
SilverTrace.info("admin", "admin.searchUsers", "root.MSG_GEN_ENTER_METHOD",
"domainId=" + domainId);
DomainDriver synchroDomain = domainDriverManager.getDomainDriver(Integer.parseInt(domainId));
return synchroDomain.getUsersByQuery(query);
}
/**
* Synchronize Users and groups between cache and domain's datastore.
*
* @param userId
* @return
* @throws Exception
*/
public String synchronizeRemoveUser(String userId) throws Exception {
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
SilverTrace.info("admin", "admin.synchronizeRemoveUser", "root.MSG_GEN_ENTER_METHOD",
"userId=" + userId);
UserDetail theUserDetail = getUserDetail(userId);
DomainDriver synchroDomain = domainDriverManager.getDomainDriver(Integer.parseInt(theUserDetail.
getDomainId()));
synchroDomain.removeUser(theUserDetail.getSpecificId());
deleteUser(userId, true);
List<UserDetail> listUsersRemove = new ArrayList<UserDetail>();
listUsersRemove.add(theUserDetail);
processSpecificSynchronization(theUserDetail.getDomainId(), null, null, listUsersRemove);
return userId;
}
public String synchronizeSilverpeasWithDomain(String sDomainId) throws Exception {
return synchronizeSilverpeasWithDomain(sDomainId, false);
}
/**
* Synchronize Users and groups between cache and domain's datastore
*/
public String synchronizeSilverpeasWithDomain(String sDomainId, boolean threaded)
throws AdminException {
String sReport = "Starting synchronization...\n\n";
Map<String, String> userIds = new HashMap<String, String>();
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
synchronized (semaphore) {
SilverTrace.info("admin", "admin.synchronizeSilverpeasWithDomain",
"root.MSG_GEN_ENTER_METHOD", "domainID=" + sDomainId);
// Démarrage de la synchro avec la Popup d'affichage
if (threaded) {
SynchroReport.setTraceLevel(SynchroReport.TRACE_LEVEL_WARN);
}
SynchroReport.startSynchro();
try {
SynchroReport.warn("admin.synchronizeSilverpeasWithDomain",
"Domain '" + domainDriverManager.getDomain(sDomainId).getName() + "', Id : "
+ sDomainId, null);
// Start synchronization
domainDriverManager.beginSynchronization(sDomainId);
DomainDriver synchroDomain =
domainDriverManager.getDomainDriver(Integer.parseInt(sDomainId));
Domain theDomain = domainDriverManager.getDomain(sDomainId);
String fromTimeStamp = theDomain.getTheTimeStamp();
String toTimeStamp = synchroDomain.getTimeStamp(fromTimeStamp);
SilverTrace.info("admin", "admin.synchronizeSilverpeasWithDomain",
"root.MSG_GEN_ENTER_METHOD", "TimeStamps from " + fromTimeStamp + " to "
+ toTimeStamp);
if (fromTimeStamp.equals(toTimeStamp)) {
String uptodate =
"Domain '" + domainDriverManager.getDomain(sDomainId).getName()
+ "' is already up-to-date !";
SynchroReport.warn("admin.synchronizeSilverpeasWithDomain", uptodate, null);
sReport += uptodate + "\n";
} else {
// Start transaction
domainDriverManager.startTransaction(false);
domainDriverManager.startTransaction(sDomainId, false);
// Synchronize users
if (synchroDomain.mustImportUsers() || threaded) {
sReport += synchronizeUsers(sDomainId, userIds, fromTimeStamp, toTimeStamp, threaded,
true);
} else {
sReport += synchronizeUsers(sDomainId, userIds, fromTimeStamp, toTimeStamp, threaded,
false);
}
// Synchronize groups
sReport += "\n" + synchronizeGroups(sDomainId, userIds, fromTimeStamp, toTimeStamp);
// All the synchro is finished -> set the new timestamp
// ----------------------------------------------------
theDomain.setTheTimeStamp(toTimeStamp);
updateDomain(theDomain);
// Commit the transaction
domainDriverManager.commit();
domainDriverManager.commit(sDomainId);
}
// End synchronization
String sDomainSpecificErrors = domainDriverManager.endSynchronization(sDomainId, false);
SynchroReport.warn("admin.synchronizeSilverpeasWithDomain", "----------------"
+ sDomainSpecificErrors, null);
return sReport + "\n----------------\n" + sDomainSpecificErrors;
} catch (Exception e) {
try {
// End synchronization
domainDriverManager.endSynchronization(sDomainId, true);
// Roll back the transactions
domainDriverManager.rollback();
domainDriverManager.rollback(sDomainId);
} catch (Exception e1) {
SilverTrace.error("admin", "Admin.synchronizeSilverpeasWithDomain",
"root.EX_ERR_ROLLBACK", e1);
}
SynchroReport.error("admin.synchronizeSilverpeasWithDomain",
"Problème lors de la synchronisation : " + e.getMessage(), null);
throw new AdminException("Admin.synchronizeSilverpeasWithDomain",
SilverpeasException.ERROR, "admin.EX_ERR_SYNCHRONIZE_DOMAIN",
"domain id : '" + sDomainId + "'\nReport:" + sReport, e);
} finally {
SynchroReport.stopSynchro();// Fin de synchro avec la Popup d'affichage
// Reset the cache
cache.resetCache();
domainDriverManager.releaseOrganizationSchema();
}
}
}
/**
* Synchronize users between cache and domain's datastore
*/
private String synchronizeUsers(String domainId, Map<String, String> userIds,
String fromTimeStamp, String toTimeStamp, boolean threaded, boolean importUsers)
throws AdminException {
boolean bFound;
String specificId;
String sReport = "User synchronization : \n";
String message;
DomainDriverManager domainDriverManager =
DomainDriverManagerFactory.getCurrentDomainDriverManager();
Collection<UserDetail> addedUsers = new ArrayList<UserDetail>();
Collection<UserDetail> updateUsers = new ArrayList<UserDetail>();
Collection<UserDetail> removedUsers = new ArrayList<UserDetail>();
SynchroReport.warn("admin.synchronizeUsers", "Starting users synchronization...", null);
try {
// Clear conversion table
userIds.clear();
// Get all users of the domain from distant datasource
DomainDriver domainDriver = domainDriverManager.getDomainDriver(Integer.parseInt(domainId));
UserDetail[] distantUDs = domainDriver.getAllChangedUsers(fromTimeStamp, toTimeStamp);
message = distantUDs.length
+ " user(s) have been changed in LDAP since the last synchronization";
sReport += message + "\n";
SynchroReport.info("admin.synchronizeUsers", message, null);
// Get all users of the domain from Silverpeas
UserDetail[] silverpeasUDs = userManager.getUsersOfDomain(domainDriverManager, domainId);
SynchroReport.info("admin.synchronizeUsers", "Adding or updating users in database...", null);
// Add new users or update existing ones from distant datasource
for (UserDetail distantUD : distantUDs) {
bFound = false;
specificId = distantUD.getSpecificId();
SilverTrace.info("admin", "admin.synchronizeUsers", "root.MSG_GEN_PARAM_VALUE",
"%%%%FULLSYNCHRO%%%%>Deal with user : " + specificId);
// search for user in Silverpeas database
for (int nJ = 0; nJ < silverpeasUDs.length && !bFound; nJ++) {
if (silverpeasUDs[nJ].getSpecificId().equals(specificId) || (shouldFallbackUserLogins
&& silverpeasUDs[nJ].getLogin().equals(
distantUD.getLogin()))) {
bFound = true;
distantUD.setId(silverpeasUDs[nJ].getId());
distantUD.setAccessLevel(silverpeasUDs[nJ].getAccessLevel());
userIds.put(specificId, silverpeasUDs[nJ].getId());
}
}
distantUD.setDomainId(domainId);
if (bFound) {
// update user
updateUserDuringSynchronization(domainDriverManager, distantUD, updateUsers, sReport);
} else if (importUsers) {
// add user
addUserDuringSynchronization(domainDriverManager, distantUD, addedUsers, userIds, sReport);
}
}
if (!threaded || (threaded && delUsersOnDiffSynchro)) {
// Delete obsolete users from Silverpeas
SynchroReport.info("admin.synchronizeUsers", "Removing users from database...", null);
distantUDs = domainDriverManager.getAllUsers(domainId);
for (UserDetail silverpeasUD : silverpeasUDs) {
bFound = false;
specificId = silverpeasUD.getSpecificId();
// search for user in distant datasource
for (int nJ = 0; nJ < distantUDs.length && !bFound; nJ++) {
if (distantUDs[nJ].getSpecificId().equals(specificId) || (shouldFallbackUserLogins
&& silverpeasUD.getLogin().equals(
distantUDs[nJ].getLogin()))) {
bFound = true;
}
}
// if found, do nothing, else delete
if (!bFound) {
deleteUserDuringSynchronization(domainDriverManager, silverpeasUD, removedUsers,
sReport);
}
}
}
// traitement spécifique des users selon l'interface implémentée
processSpecificSynchronization(domainId, addedUsers, updateUsers, removedUsers);
message = "Users synchronization terminated";
sReport += message + "\n";
SynchroReport.warn("admin.synchronizeUsers", message, null);
message =
"# of updated users : " + updateUsers.size() + ", added : " + addedUsers.size()
+ ", removed : " + removedUsers.size();
sReport += message + "\n";
SynchroReport.warn("admin.synchronizeUsers", message, null);
return sReport;
} catch (Exception e) {
SynchroReport.error("admin.synchronizeUsers", "Problem during synchronization of users : "
+ e.getMessage(), null);
throw new AdminException("admin.synchronizeUsers",
SilverpeasException.ERROR, "admin.EX_ERR_SYNCHRONIZE_DOMAIN_USERS",
"domainId : '" + domainId + "'\nReport:" + sReport, e);
}
}
private void updateUserDuringSynchronization(DomainDriverManager domainDriverManager,
UserDetail distantUD, Collection<UserDetail> updatedUsers, String sReport) {
String specificId = distantUD.getSpecificId();
try {
SilverTrace.info("admin", "admin.updateUserDuringSynchronization",
"root.MSG_GEN_PARAM_VALUE",
"%%%%FULLSYNCHRO%%%%>Update User : " + distantUD.getId());
String silverpeasId = userManager.updateUser(domainDriverManager, distantUD);
updatedUsers.add(distantUD);
String message =
"user " + distantUD.getDisplayedName() + " updated (id:" + silverpeasId
+ " / specificId:" + specificId + ")";
SynchroReport.warn("admin.synchronizeUsers", message, null);
sReport += message + "\n";
} catch (AdminException aeMaj) {
SilverTrace.info("admin", "admin.updateUserDuringSynchronization",
"root.MSG_GEN_PARAM_VALUE",
"%%%%FULLSYNCHRO%%%%>PB Updating User ! " + specificId, aeMaj);
String message = "problem updating user " + distantUD.getDisplayedName() + " (specificId:"
+ specificId + ") - " + aeMaj.getMessage();
SynchroReport.warn("admin.synchronizeUsers", message, null);
sReport += message + "\n";
sReport += "user has not been updated\n";
}
}
private void addUserDuringSynchronization(DomainDriverManager domainDriverManager,
UserDetail distantUD, Collection<UserDetail> addedUsers, Map<String, String> userIds,
String sReport) {
String specificId = distantUD.getSpecificId();
try {
String silverpeasId = userManager.addUser(domainDriverManager, distantUD, true);
if (silverpeasId.equals("")) {
SilverTrace.info("admin", "admin.addUserDuringSynchronization",
"root.MSG_GEN_PARAM_VALUE",
"%%%%FULLSYNCHRO%%%%>PB Adding User ! " + specificId);
String message = "problem adding user " + distantUD.getDisplayedName() + "(specificId:"
+ specificId + ") - Login and LastName must be set !!!";
sReport += message + "\n";
SynchroReport.warn("admin.synchronizeUsers", message, null);
sReport += "user has not been added\n";
} else {
SilverTrace.info("admin", "admin.addUserDuringSynchronization",
"root.MSG_GEN_PARAM_VALUE", "%%%%FULLSYNCHRO%%%%>Add User : " + silverpeasId);
addedUsers.add(distantUD);
String message = "user " + distantUD.getDisplayedName() + " added (id:" + silverpeasId
+ " / specificId:" + specificId + ")";
sReport += message + "\n";
SynchroReport.warn("admin.synchronizeUsers", message, null);
userIds.put(specificId, silverpeasId);
}
} catch (AdminException ae) {
SilverTrace.info("admin", "admin.addUserDuringSynchronization",
"root.MSG_GEN_PARAM_VALUE",
"%%%%FULLSYNCHRO%%%%>PB Adding User ! " + specificId, ae);
String message = "problem adding user " + distantUD.getDisplayedName() + "(specificId:"
+ specificId + ") - " + ae.getMessage();
SynchroReport.warn("admin.synchronizeUsers", message, null);
sReport += message + "\n";
sReport += "user has not been added\n";
}
}
private void deleteUserDuringSynchronization(DomainDriverManager domainDriverManager,
UserDetail silverpeasUD, Collection<UserDetail> deletedUsers, String sReport) {
String specificId = silverpeasUD.getSpecificId();
try {
SilverTrace.info("admin", "admin.deleteUserDuringSynchronization",
"root.MSG_GEN_PARAM_VALUE",
"%%%%FULLSYNCHRO%%%%>Delete User : " + silverpeasUD);
userManager.deleteUser(domainDriverManager, silverpeasUD, true);
deletedUsers.add(silverpeasUD);
String message =
"user " + silverpeasUD.getDisplayedName() + " deleted (id:" + specificId + ")";
sReport += message + "\n";
SynchroReport.warn("admin.synchronizeUsers", message, null);
} catch (AdminException aeDel) {
SilverTrace.info("admin", "admin.deleteUserDuringSynchronization",
"root.MSG_GEN_PARAM_VALUE",
"%%%%FULLSYNCHRO%%%%>PB deleting User ! " + specificId, aeDel);
String message =
"problem deleting user " + silverpeasUD.getDisplayedName() + " (specificId:"
+ specificId + ") - " + aeDel.getMessage();
sReport += message + "\n";
SynchroReport.warn("admin.synchronizeUsers", message, null);
sReport += "user has not been deleted\n";
}
}
private void processSpecificSynchronization(String domainId, Collection<UserDetail> usersAdded,
Collection<UserDetail> usersUpdated, Collection<UserDetail> usersRemoved) throws Exception {
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
Domain theDomain = domainDriverManager.getDomain(domainId);
String propDomainFileName = theDomain.getPropFileName();
ResourceLocator propDomainLdap = new ResourceLocator(propDomainFileName, "");
String nomClasseSynchro = propDomainLdap.getString("synchro.Class");
if (StringUtil.isDefined(nomClasseSynchro)) {
Collection<UserDetail> added = usersAdded;
Collection<UserDetail> updated = usersUpdated;
Collection<UserDetail> removed = usersRemoved;
if (added == null) {
added = new ArrayList<UserDetail>();
}
if (updated == null) {
updated = new ArrayList<UserDetail>();
}
if (removed == null) {
removed = new ArrayList<UserDetail>();
}
try {
LDAPSynchroUserItf synchroUser = (LDAPSynchroUserItf) Class.forName(nomClasseSynchro).
newInstance();
if (synchroUser != null) {
synchroUser.processUsers(added, updated, removed);
}
} catch (Exception e) {
SilverTrace.warn("admin", "admin.synchronizeOnlyExistingUsers",
"root.MSG_GEN_PARAM_VALUE", "Pb Loading class traitement Users ! ", e);
}
}
}
/**
* Synchronize groups between cache and domain's datastore
*/
private String synchronizeGroups(String domainId, Map<String, String> userIds,
String fromTimeStamp, String toTimeStamp) throws Exception {
boolean bFound;
String specificId;
String sReport = "Group synchronization : \n";
Map<String, Group> allDistantGroups = new HashMap<String, Group>();
int iNbGroupsAdded = 0;
int iNbGroupsMaj = 0;
int iNbGroupsDeleted = 0;
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
SynchroReport.warn("admin.synchronizeGroups", "Starting groups synchronization...", null);
try {
// Get all root groups of the domain from distant datasource
Group[] distantRootGroups = domainDriverManager.getAllRootGroups(domainId);
// Get all groups of the domain from Silverpeas
Group[] silverpeasGroups = groupManager.getGroupsOfDomain(domainDriverManager, domainId);
SynchroReport.info("admin.synchronizeGroups", "Adding or updating groups in database...",
null);
// Check for new groups resursively
sReport += checkOutGroups(domainId, silverpeasGroups, distantRootGroups, allDistantGroups,
userIds, null, iNbGroupsAdded, iNbGroupsMaj, iNbGroupsDeleted);
// Delete obsolete groups
SynchroReport.info("admin.synchronizeGroups", "Removing groups from database...", null);
Group[] distantGroups = allDistantGroups.values().toArray(
new Group[allDistantGroups.size()]);
for (Group silverpeasGroup : silverpeasGroups) {
bFound = false;
specificId = silverpeasGroup.getSpecificId();
// search for group in distant datasource
for (int nJ = 0; nJ < distantGroups.length && !bFound; nJ++) {
if (distantGroups[nJ].getSpecificId().equals(specificId)) {
bFound = true;
} else if (shouldFallbackGroupNames && distantGroups[nJ].getName().equals(specificId)) {
bFound = true;
}
}
// if found, do nothing, else delete
if (!bFound) {
try {
SilverTrace.info("admin", "admin.synchronizeGroups", "root.MSG_GEN_PARAM_VALUE",
"%%%%FULLSYNCHRO%%%%>Delete group : " + silverpeasGroup.getId() + " - "
+ specificId);
groupManager.deleteGroupById(domainDriverManager, silverpeasGroup, true);
iNbGroupsDeleted++;
sReport += "deleting group " + silverpeasGroup.getName() + "(id:" + specificId + ")\n";
SynchroReport.warn("admin.synchronizeGroups", "Group " + silverpeasGroup.getName()
+ " deleted (SpecificId:" + specificId + ")", null);
} catch (AdminException aeDel) {
SilverTrace.info("admin", "admin.synchronizeGroups", "root.MSG_GEN_PARAM_VALUE",
"%%%%FULLSYNCHRO%%%%>PB deleting group ! " + specificId, aeDel);
sReport += "problem deleting group " + silverpeasGroup.getName() + " (specificId:"
+ specificId + ") - " + aeDel.getMessage() + "\n";
sReport += "group has not been deleted\n";
}
}
}
sReport += "Groups synchronization terminated\n";
SynchroReport.info("admin.synchronizeGroups",
"# of groups updated : " + iNbGroupsMaj + ", added : " + iNbGroupsAdded
+ ", deleted : " + iNbGroupsDeleted, null);
SynchroReport.warn("admin.synchronizeGroups", "Groups synchronization terminated", null);
return sReport;
} catch (Exception e) {
SynchroReport.error("admin.synchronizeGroups",
"Problème lors de la synchronisation des groupes : " + e.getMessage(), null);
throw new AdminException("admin.synchronizeGroups", SilverpeasException.ERROR,
"admin.EX_ERR_SYNCHRONIZE_DOMAIN_GROUPS",
"domain id : '" + domainId + "'\nReport:" + sReport, e);
}
}
/**
* Checks for new groups resursively
*/
// Au 1er appel : (domainId,silverpeasGroups,distantRootGroups,
// allDistantGroups(vide), userIds, null)
// No need to refresh cache : the cache is reseted at the end of the
// synchronization
private String checkOutGroups(String domainId, Group[] existingGroups, Group[] testedGroups,
Map<String, Group> allIncluededGroups, Map<String, String> userIds, String superGroupId,
int iNbGroupsAdded, int iNbGroupsMaj, int iNbGroupsDeleted) throws Exception {
boolean bFound;
String specificId;
String silverpeasId = null;
String report = "";
String result;
for (Group testedGroup : testedGroups) {
allIncluededGroups.put(testedGroup.getSpecificId(), testedGroup);
}
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
// Add new groups or update existing ones from distant datasource
for (Group testedGroup : testedGroups) {
bFound = false;
specificId = testedGroup.getSpecificId();
SilverTrace.info("admin", "admin.checkOutGroups",
"root.MSG_GEN_PARAM_VALUE", "%%%%FULLSYNCHRO%%%%>Deal with group : " + specificId);
// search for group in Silverpeas database
for (int nJ = 0;
nJ < existingGroups.length && !bFound;
nJ++) {
if (existingGroups[nJ].getSpecificId().equals(specificId)) {
bFound = true;
testedGroup.setId(existingGroups[nJ].getId());
} else if (shouldFallbackGroupNames && existingGroups[nJ].getSpecificId().equals(
testedGroup.getName())) {
bFound = true;
testedGroup.setId(existingGroups[nJ].getId());
}
}
// Prepare Group to be at Silverpeas format
testedGroup.setDomainId(domainId);
// Set the Parent Id
if (bFound) {
SynchroReport.debug("admin.checkOutGroups", "avant maj du groupe " + specificId
+ ", recherche de ses groupes parents", null);
} else {
SynchroReport.debug("admin.checkOutGroups", "avant ajout du groupe " + specificId
+ ", recherche de ses groupes parents", null);
}
String[] groupParentsIds = domainDriverManager.getGroupMemberGroupIds(domainId, testedGroup.
getSpecificId());
if ((groupParentsIds == null) || (groupParentsIds.length == 0)) {
testedGroup.setSuperGroupId(null);
SynchroReport.debug("admin.checkOutGroups", "le groupe " + specificId + " n'a pas de père",
null);
} else {
testedGroup.setSuperGroupId(superGroupId);
if (superGroupId != null)// sécurité
{
SynchroReport.debug("admin.checkOutGroups",
"le groupe " + specificId + " a pour père le groupe " + domainDriverManager.
getGroup(
superGroupId).getSpecificId() + " d'Id base " + superGroupId, null);
}
}
String[] groupUserIds = testedGroup.getUserIds();
List<String> convertedUserIds = new ArrayList<String>();
for (String groupUserId : groupUserIds) {
if (userIds.get(groupUserId) != null) {
convertedUserIds.add(userIds.get(groupUserId));
}
}
// Le groupe contiendra une liste d'IDs de users existant ds la base et
// non + une liste de logins récupérés via LDAP
testedGroup.setUserIds(convertedUserIds.toArray(new String[convertedUserIds.size()]));
// if found, update, else create
if (bFound)// MAJ
{
try {
SilverTrace.info("admin", "admin.checkOutGroups", "root.MSG_GEN_PARAM_VALUE",
"%%%%FULLSYNCHRO%%%%>Update group : " + testedGroup.getId());
result = groupManager.updateGroup(domainDriverManager, testedGroup, true);
if (StringUtil.isDefined(result)) {
iNbGroupsMaj++;
silverpeasId = testedGroup.getId();
report += "updating group " + testedGroup.getName() + "(id:" + specificId + ")\n";
SynchroReport.warn("admin.checkOutGroups", "maj groupe " + testedGroup.getName()
+ " (id:" + silverpeasId + ") OK",
null);
} else// le name groupe non renseigné
{
SilverTrace.info("admin", "admin.checkOutGroups",
"root.MSG_GEN_PARAM_VALUE",
"%%%%FULLSYNCHRO%%%%>PB Updating Group ! " + specificId);
report += "problem updating group id : " + specificId + "\n";
}
} catch (AdminException aeMaj) {
SilverTrace.info("admin", "admin.checkOutGroups",
"root.MSG_GEN_PARAM_VALUE",
"%%%%FULLSYNCHRO%%%%>PB Updating Group ! " + specificId, aeMaj);
report += "problem updating group " + testedGroup.getName() + " (id:" + specificId + ") "
+ aeMaj.getMessage() + "\n";
report += "group has not been updated\n";
}
} else { // AJOUT
try {
silverpeasId = groupManager.addGroup(domainDriverManager, testedGroup, true);
if (StringUtil.isDefined(silverpeasId)) {
iNbGroupsAdded++;
SilverTrace.info("admin", "admin.checkOutGroups", "root.MSG_GEN_PARAM_VALUE",
"%%%%FULLSYNCHRO%%%%>Add group : " + silverpeasId);
report += "adding group " + testedGroup.getName() + "(id:" + specificId + ")\n";
SynchroReport.warn("admin.checkOutGroups", "ajout groupe " + testedGroup.getName()
+ " (id:" + silverpeasId + ") OK",
null);
} else { // le name groupe non renseigné
SilverTrace.info("admin", "admin.checkOutGroups", "root.MSG_GEN_PARAM_VALUE",
"%%%%FULLSYNCHRO%%%%>PB Adding Group ! " + specificId);
report += "problem adding group id : " + specificId + "\n";
}
} catch (AdminException aeAdd) {
SilverTrace.info("admin", "admin.checkOutGroups", "root.MSG_GEN_PARAM_VALUE",
"%%%%FULLSYNCHRO%%%%>PB Adding Group ! " + specificId, aeAdd);
report += "problem adding group " + testedGroup.getName() + " (id:" + specificId + ") "
+ aeAdd.getMessage() + "\n";
report += "group has not been added\n";
}
}
// Recurse with subgroups
if (silverpeasId != null && silverpeasId.length() > 0) {
Group[] subGroups = domainDriverManager.getGroups(silverpeasId);
if (subGroups != null && subGroups.length > 0) {
Group[] cleanSubGroups = removeCrossReferences(subGroups,
allIncluededGroups, specificId);
if (cleanSubGroups != null && cleanSubGroups.length > 0) {
SynchroReport.info("admin.checkOutGroups",
"Ajout ou mise à jour de " + cleanSubGroups.length + " groupes fils du groupe "
+ specificId + "...", null);
report += checkOutGroups(domainId, existingGroups, cleanSubGroups,
allIncluededGroups,
userIds, silverpeasId, iNbGroupsAdded, iNbGroupsMaj, iNbGroupsDeleted);
}
}
}
}
return report;
}
/**
* Remove cross reference risk between groups
*/
private Group[] removeCrossReferences(Group[] subGroups, Map<String, Group> allIncluededGroups,
String fatherId) throws Exception {
ArrayList<Group> cleanSubGroups = new ArrayList<Group>();
//noinspection UnusedAssignment,UnusedAssignment,UnusedAssignment
for (Group subGroup : subGroups) {
if (allIncluededGroups.get(subGroup.getSpecificId()) == null) {
cleanSubGroups.add(subGroup);
} else {
SilverTrace.warn("admin", "Admin.removeCrossReferences", "root.MSG_GEN_PARAM_VALUE",
"Cross removed for child : " + subGroup.getSpecificId() + " of father : " + fatherId);
}
}
return cleanSubGroups.toArray(new Group[cleanSubGroups.size()]);
}
// -------------------------------------------------------------------------
// For SelectionPeas
// -------------------------------------------------------------------------
public String[] searchUsersIds(String sGroupId, String componentId, String[] profileIds,
UserDetail modelUser) throws AdminException {
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
try {
List<String> userIds = new ArrayList<String>();
if (StringUtil.isDefined(sGroupId)) {
// search users in group and subgroups
UserDetail[] users = getAllUsersOfGroup(sGroupId);
for (UserDetail user :
users) {
userIds.add(user.getId());
}
if (userIds.isEmpty()) {
userIds = null;
}
} else if (profileIds != null && profileIds.length > 0) {
// search users in profiles
for (String profileId : profileIds) {
ProfileInst profile = profileManager.getProfileInst(domainDriverManager, profileId,
null);
// add users directly attach to profile
userIds.addAll(profile.getAllUsers());
// add users indirectly attach to profile (groups attached to profile)
List<String> groupIds = profile.getAllGroups();
List<String> allGroupIds = new ArrayList<String>();
for (String groupId : groupIds) {
allGroupIds.add(groupId);
allGroupIds.addAll(groupManager.getAllSubGroupIdsRecursively(groupId));
}
userIds.addAll(userManager.getAllUserIdsOfGroups(allGroupIds));
}
if (userIds.isEmpty()) {
userIds = null;
}
} else if (StringUtil.isDefined(componentId)) {
// search users in component
userIds.addAll(getUserIdsForComponent(componentId));
if (userIds.isEmpty()) {
userIds = null;
}
} else {
// get all users
userIds = new ArrayList<String>();
}
if (userIds == null) {
return ArrayUtil.EMPTY_STRING_ARRAY;
}
return userManager.searchUsersIds(domainDriverManager, userIds, modelUser);
} catch (Exception e) {
throw new AdminException("Admin.searchUsersIds", SilverpeasException.ERROR,
"admin.EX_ERR_USER_NOT_FOUND", e);
}
}
private List<String> getUserIdsForComponent(String componentId) throws AdminException {
List<String> userIds = new ArrayList<String>();
ComponentInst component = getComponentInst(componentId);
if (component != null) {
if (component.isPublic()) {
// component is public, all users are allowed to access it
return Arrays.asList(getAllUsersIds());
} else {
List<ProfileInst> profiles = component.getAllProfilesInst();
for (ProfileInst profile : profiles) {
userIds.addAll(getUserIdsForComponentProfile(profile));
}
}
}
return userIds;
}
private List<String> getUserIdsForComponentProfile(ProfileInst profile) throws AdminException {
List<String> userIds = new ArrayList<String>();
// add users directly attach to profile
userIds.addAll(profile.getAllUsers());
// add users indirectly attach to profile (groups attached to profile)
List<String> groupIds = profile.getAllGroups();
List<String> allGroupIds = new ArrayList<String>();
for (String groupId : groupIds) {
allGroupIds.add(groupId);
allGroupIds.addAll(groupManager.getAllSubGroupIdsRecursively(groupId));
}
userIds.addAll(userManager.getAllUserIdsOfGroups(allGroupIds));
return userIds;
}
public UserDetail[] searchUsers(final SearchCriteria searchCriteria) throws AdminException {
List<String> userIds = null;
if (searchCriteria.isCriterionOnRoleIdsSet()) {
userIds = new ArrayList<String>();
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
for (String roleId : searchCriteria.getCriterionOnRoleIds()) {
ProfileInst profile = profileManager.getProfileInst(domainDriverManager, roleId, null);
- // add users directly attach to profile
+ // users playing the role
userIds.addAll(profile.getAllUsers());
- // add users indirectly attach to profile (groups attached to profile)
+ // users of the groups (and recursively of their subgroups) playing the role
List<String> groupIds = profile.getAllGroups();
List<String> allGroupIds = new ArrayList<String>();
for (String aGroupId : groupIds) {
allGroupIds.add(aGroupId);
allGroupIds.addAll(groupManager.getAllSubGroupIdsRecursively(aGroupId));
}
userIds.addAll(userManager.getAllUserIdsOfGroups(allGroupIds));
}
} else if (searchCriteria.isCriterionOnComponentInstanceIdSet()) {
String instanceId = searchCriteria.getCriterionOnComponentInstanceId();
ComponentInst component = getComponentInst(instanceId);
if (component != null && !component.isPublic()) {
userIds = getUserIdsForComponent(instanceId);
}
}
if (searchCriteria.isCriterionOnUserIdsSet()) {
if (userIds == null) {
userIds = Arrays.asList(searchCriteria.getCriterionOnUserIds());
} else {
List<String> userIdsInCriterion = Arrays.asList(searchCriteria.getCriterionOnUserIds());
List<String> userIdsToTake = new ArrayList<String>();
for (String userId : userIds) {
if (userIdsInCriterion.contains(userId)) {
userIdsToTake.add(userId);
}
}
userIds = userIdsToTake;
}
}
UserSearchCriteriaFactory factory = UserSearchCriteriaFactory.getFactory();
UserSearchCriteria criteria = factory.getUserSearchCriteria();
if (userIds != null) {
criteria.onUserIds(userIds.toArray(new String[userIds.size()]));
}
if (searchCriteria.isCriterionOnGroupIdSet()) {
String groupId = searchCriteria.getCriterionOnGroupId();
if (groupId.equals(SearchCriteria.ANY_GROUP)) {
criteria.and().onGroupIds(UserSearchCriteria.ANY);
} else {
- criteria.and().onGroupIds(groupId);
+ List<String> groupIds = groupManager.getAllSubGroupIdsRecursively(groupId);
+ groupIds.add(groupId);
+ criteria.and().onGroupIds(groupIds.toArray(new String[groupIds.size()]));
}
}
if (searchCriteria.isCriterionOnDomainIdSet()) {
criteria.and().onDomainId(searchCriteria.getCriterionOnDomainId());
}
if (searchCriteria.isCriterionOnNameSet()) {
criteria.and().onName(searchCriteria.getCriterionOnName());
}
return userManager.getUsersMatchingCriteria(criteria);
}
public String[] searchGroupsIds(boolean isRootGroup, String componentId,
String[] profileId, Group modelGroup) throws AdminException {
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
try {
ComponentInst component = getComponentInst(componentId);
if (component != null) {
if (component.isPublic()) {
// component is public, all groups are allowed to access it
componentId = null;
}
}
return groupManager.searchGroupsIds(domainDriverManager, isRootGroup,
getDriverComponentId(componentId), profileId, modelGroup);
} catch (Exception e) {
throw new AdminException("Admin.searchGroupsIds",
SilverpeasException.ERROR, "admin.EX_ERR_GROUP_NOT_FOUND", e);
}
}
// -------------------------------------------------------------------------
// For DB connection reset
// -------------------------------------------------------------------------
public void resetAllDBConnections(boolean isScheduled) throws AdminException {
try {
SilverTrace.info("admin", "Admin.resetAllDBConnections",
"root.MSG_GEN_ENTER_METHOD",
"RESET ALL DB CONNECTIONS ! (Scheduled : " + isScheduled + ")");
OrganizationSchemaPool.releaseConnections();
ConnectionPool.releaseConnections();
} catch (Exception e) {
throw new AdminException("Admin.resetAllDBConnections",
SilverpeasException.ERROR, "root.EX_CONNECTION_CLOSE_FAILED", e);
}
}
private void rollback() {
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
try {
// Roll back the transactions
domainDriverManager.rollback();
} catch (Exception e1) {
SilverTrace.error("admin", "Admin.rollback", "root.EX_ERR_ROLLBACK", e1);
}
}
// -------------------------------------------------------------------------
// Node profile management
// -------------------------------------------------------------------------
private String getSpaceId(SpaceInst spaceInst) {
if (spaceInst.getId().startsWith(SPACE_KEY_PREFIX)) {
return spaceInst.getId();
}
return SPACE_KEY_PREFIX + spaceInst.getId();
}
public void indexAllUsers() throws AdminException {
Domain[] domains = getAllDomains();
for (Domain domain : domains) {
try {
indexUsers(domain.getId());
} catch (Exception e) {
SilverTrace.error("admin", "Admin.indexAllUsers", "admin.CANT_INDEX_USERS",
"domainId = " + domain.getId(), e);
}
}
}
public void indexUsers(String domainId) throws AdminException {
DomainDriverManager domainDriverManager = DomainDriverManagerFactory.
getCurrentDomainDriverManager();
try {
domainDriverManager.indexAllUsers(domainId);
} catch (Exception e) {
throw new AdminException("Admin.indexUsers",
SilverpeasException.ERROR, "admin.CANT_INDEX_USERS", "domainId = " + domainId, e);
}
}
public String copyAndPasteComponent(String componentId, String spaceId, String userId) throws
AdminException {
if (!StringUtil.isDefined(spaceId)) {
// cannot paste component on root
return null;
}
ComponentInst newCompo = (ComponentInst) getComponentInst(componentId).clone();
SpaceInst destinationSpace = getSpaceInstById(spaceId);
// Creation
newCompo.setId("-1");
newCompo.setDomainFatherId(destinationSpace.getId());
newCompo.setOrderNum(destinationSpace.getNumComponentInst());
newCompo.setCreateDate(new Date());
newCompo.setCreatorUserId(userId);
newCompo.setLanguage(I18NHelper.defaultLanguage);
// Rename if componentName already exists in the destination space
String label =
renameComponentName(newCompo.getLabel(I18NHelper.defaultLanguage), destinationSpace.
getAllComponentsInst());
newCompo.setLabel(label);
// Delete inherited profiles only
// It will be processed by admin
newCompo.removeInheritedProfiles();
// Add the component
String sComponentId = addComponentInst(userId, newCompo);
// Execute specific paste by the component
try {
PasteDetail pasteDetail = new PasteDetail(componentId, sComponentId, userId);
String componentRootName = URLManager.getComponentNameFromComponentId(componentId);
String className =
"com.silverpeas.component." + componentRootName + "." + componentRootName.substring(0,
1).
toUpperCase() + componentRootName.substring(1) + "Paste";
if (Class.forName(className).getClass() != null) {
ComponentPasteInterface componentPaste = (ComponentPasteInterface) Class.forName(className).
newInstance();
componentPaste.paste(pasteDetail);
}
} catch (Exception e) {
SilverTrace.warn("admin",
"Admin.copyAndPasteComponent()",
"root.GEN_EXIT_METHOD", e);
}
return sComponentId;
}
/**
* Rename component Label if necessary
*
* @param label
* @param listComponents
* @return
*/
private String renameComponentName(String label, ArrayList<ComponentInst> listComponents) {
String newComponentLabel = label;
for (ComponentInst componentInst : listComponents) {
if (componentInst.getLabel().equals(newComponentLabel)) {
newComponentLabel = "Copie de " + label;
return renameComponentName(newComponentLabel, listComponents);
}
}
return newComponentLabel;
}
public String copyAndPasteSpace(String spaceId, String toSpaceId, String userId)
throws AdminException {
String newSpaceId = null;
boolean pasteAllowed = StringUtil.isDefined(spaceId);
if (StringUtil.isDefined(toSpaceId)) {
// First, check if target space is not a sub space of paste space
List<SpaceInstLight> path = TreeCache.getSpacePath(toSpaceId);
for (int i = 0; i < path.size() && pasteAllowed; i++) {
pasteAllowed = !spaceId.equalsIgnoreCase(path.get(i).getFullId());
}
}
if (pasteAllowed) {
// paste space itself
SpaceInst newSpace = getSpaceInstById(spaceId).clone();
newSpace.setId("-1");
List<String> newBrotherIds;
if (StringUtil.isDefined(toSpaceId)) {
SpaceInst destinationSpace = getSpaceInstById(toSpaceId);
newSpace.setDomainFatherId(destinationSpace.getId());
newBrotherIds = Arrays.asList(destinationSpace.getSubSpaceIds());
} else {
newSpace.setDomainFatherId("-1");
newBrotherIds = Arrays.asList(getAllRootSpaceIds());
}
newSpace.setOrderNum(newBrotherIds.size());
newSpace.setCreateDate(new Date());
newSpace.setCreatorUserId(userId);
newSpace.setLanguage(I18NHelper.defaultLanguage);
// Rename if spaceName already used in the destination space
List<SpaceInstLight> subSpaces = new ArrayList<SpaceInstLight>();
for (String subSpaceId : newBrotherIds) {
subSpaces.add(getSpaceInstLight(getDriverSpaceId(subSpaceId)));
}
String name = renameSpace(newSpace.getName(I18NHelper.defaultLanguage), subSpaces);
newSpace.setName(name);
// Remove inherited profiles from cloned space
newSpace.removeInheritedProfiles();
// Remove components from cloned space
List<ComponentInst> components = newSpace.getAllComponentsInst();
newSpace.removeAllComponentsInst();
// Add space
newSpaceId = addSpaceInst(userId, newSpace);
// paste components of space
for (ComponentInst component : components) {
copyAndPasteComponent(component.getId(), newSpaceId, userId);
}
// paste subspaces
String[] subSpaceIds = newSpace.getSubSpaceIds();
for (String subSpaceId : subSpaceIds) {
copyAndPasteSpace(subSpaceId, newSpaceId, userId);
}
}
return newSpaceId;
}
private String renameSpace(String label, List<SpaceInstLight> listSpaces) {
String newSpaceLabel = label;
for (SpaceInstLight space : listSpaces) {
if (space.getName().equals(newSpaceLabel)) {
newSpaceLabel = "Copie de " + label;
return renameSpace(newSpaceLabel, listSpaces);
}
}
return newSpaceLabel;
}
private boolean isDefined(final UserDetail filter) {
return StringUtil.isDefined(filter.getId()) && StringUtil.isDefined(filter.getSpecificId())
&& StringUtil.isDefined(filter.getDomainId()) && StringUtil.isDefined(filter.getLogin())
&& StringUtil.isDefined(filter.getFirstName()) && StringUtil.isDefined(filter.
getLastName()) && StringUtil.isDefined(filter.geteMail())
&& StringUtil.isDefined(filter.getAccessLevel()) && StringUtil.isDefined(filter.
getLoginQuestion()) && StringUtil.isDefined(filter.getLoginAnswer());
}
}
diff --git a/lib-core/src/main/java/com/stratelia/webactiv/beans/admin/dao/UserSearchCriteriaForDAO.java b/lib-core/src/main/java/com/stratelia/webactiv/beans/admin/dao/UserSearchCriteriaForDAO.java
index e9d191cf85..965e2d3c5e 100644
--- a/lib-core/src/main/java/com/stratelia/webactiv/beans/admin/dao/UserSearchCriteriaForDAO.java
+++ b/lib-core/src/main/java/com/stratelia/webactiv/beans/admin/dao/UserSearchCriteriaForDAO.java
@@ -1,127 +1,131 @@
/*
* Copyright (C) 2000 - 2012 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection withWriter Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/legal/licensing"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.stratelia.webactiv.beans.admin.dao;
import com.stratelia.webactiv.beans.admin.UserSearchCriteria;
import java.util.HashSet;
import java.util.Set;
/**
* An implementation of the search criteria for user details stored in a SQL data source and used
* by the DAOs.
*/
public class UserSearchCriteriaForDAO implements UserSearchCriteria {
private StringBuilder query = new StringBuilder();
private Set<String> tables = new HashSet<String>();
public static UserSearchCriteriaForDAO newCriteria() {
return new UserSearchCriteriaForDAO();
}
@Override
public UserSearchCriteriaForDAO and() {
if (query.length() > 0) {
query.append(" and ");
}
return this;
}
@Override
public UserSearchCriteriaForDAO or() {
if (query.length() > 0) {
query.append(" or ");
}
return this;
}
@Override
public UserSearchCriteriaForDAO onName(String name) {
tables.add("st_user");
query.append("(lower(st_user.firstName) like lower('").
append(name).
append("') or lower(st_user.lastName) like lower('").
append(name).
append("'))");
return this;
}
@Override
public UserSearchCriteriaForDAO onGroupIds(String ... groupIds) {
tables.add("st_user");
tables.add("st_group_user_rel");
query.append("(st_group_user_rel.userid = st_user.id");
if (groupIds != ANY) {
query.append(" and st_group_user_rel.groupId in ").
append(asSQLList(groupIds));
}
query.append(")");
return this;
}
@Override
public UserSearchCriteriaForDAO onDomainId(String domainId) {
tables.add("st_user");
query.append("(st_user.domainId = ").append(Integer.valueOf(domainId)).append(")");
return this;
}
@Override
public UserSearchCriteria onUserIds(String... userIds) {
tables.add("st_user");
query.append("(st_user.id in ").append(asSQLList(userIds)).append(")");
return this;
}
@Override
public String toString() {
return query.toString();
}
@Override
public boolean isEmpty() {
return query.length() == 0;
}
public String impliedTables() {
StringBuilder tablesUsedInCriteria = new StringBuilder();
for (String aTable : tables) {
tablesUsedInCriteria.append(aTable).append(", ");
}
return tablesUsedInCriteria.substring(0, tablesUsedInCriteria.length() - 2);
}
private UserSearchCriteriaForDAO() {
}
private String asSQLList(String ... items) {
StringBuilder list = new StringBuilder("(");
for (String anItem : items) {
list.append(anItem).append(",");
}
- list.setCharAt(list.length() - 1, ')');
+ if (list.toString().endsWith(",")) {
+ list.setCharAt(list.length() - 1, ')');
+ } else {
+ list.append("null").append(")");
+ }
return list.toString();
}
}
diff --git a/web-core/src/main/java/com/stratelia/webactiv/util/viewGenerator/html/GraphicElementFactory.java b/web-core/src/main/java/com/stratelia/webactiv/util/viewGenerator/html/GraphicElementFactory.java
index a03eeae7d7..20a903fe1f 100644
--- a/web-core/src/main/java/com/stratelia/webactiv/util/viewGenerator/html/GraphicElementFactory.java
+++ b/web-core/src/main/java/com/stratelia/webactiv/util/viewGenerator/html/GraphicElementFactory.java
@@ -1,973 +1,976 @@
/**
* Copyright (C) 2000 - 2011 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://repository.silverpeas.com/legal/licensing"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.stratelia.webactiv.util.viewGenerator.html;
import static com.stratelia.silverpeas.peasCore.MainSessionController.MAIN_SESSION_CONTROLLER_ATT;
import com.silverpeas.util.StringUtil;
import com.silverpeas.util.i18n.I18NHelper;
import com.stratelia.silverpeas.peasCore.MainSessionController;
import com.stratelia.silverpeas.peasCore.URLManager;
import com.stratelia.silverpeas.silvertrace.SilverTrace;
import com.stratelia.webactiv.beans.admin.ComponentInstLight;
import com.stratelia.webactiv.beans.admin.SpaceInstLight;
import com.stratelia.webactiv.util.ResourceLocator;
import com.stratelia.webactiv.util.viewGenerator.html.arrayPanes.ArrayPane;
import com.stratelia.webactiv.util.viewGenerator.html.arrayPanes.ArrayPaneSilverpeasV5;
import com.stratelia.webactiv.util.viewGenerator.html.board.Board;
import com.stratelia.webactiv.util.viewGenerator.html.board.BoardSilverpeasV5;
import com.stratelia.webactiv.util.viewGenerator.html.browseBars.BrowseBar;
import com.stratelia.webactiv.util.viewGenerator.html.browseBars.BrowseBarComplete;
import com.stratelia.webactiv.util.viewGenerator.html.buttonPanes.ButtonPane;
import com.stratelia.webactiv.util.viewGenerator.html.buttonPanes.ButtonPaneWA2;
import com.stratelia.webactiv.util.viewGenerator.html.buttons.Button;
import com.stratelia.webactiv.util.viewGenerator.html.buttons.ButtonSilverpeasV5;
import com.stratelia.webactiv.util.viewGenerator.html.calendar.Calendar;
import com.stratelia.webactiv.util.viewGenerator.html.calendar.CalendarWA1;
import com.stratelia.webactiv.util.viewGenerator.html.formPanes.FormPane;
import com.stratelia.webactiv.util.viewGenerator.html.formPanes.FormPaneWA;
import com.stratelia.webactiv.util.viewGenerator.html.frame.Frame;
import com.stratelia.webactiv.util.viewGenerator.html.frame.FrameSilverpeasV5;
import com.stratelia.webactiv.util.viewGenerator.html.iconPanes.IconPane;
import com.stratelia.webactiv.util.viewGenerator.html.iconPanes.IconPaneWA;
import com.stratelia.webactiv.util.viewGenerator.html.monthCalendar.MonthCalendar;
import com.stratelia.webactiv.util.viewGenerator.html.monthCalendar.MonthCalendarWA1;
import com.stratelia.webactiv.util.viewGenerator.html.navigationList.NavigationList;
import com.stratelia.webactiv.util.viewGenerator.html.navigationList.NavigationListSilverpeasV5;
import com.stratelia.webactiv.util.viewGenerator.html.operationPanes.OperationPane;
import com.stratelia.webactiv.util.viewGenerator.html.operationPanes.OperationPaneSilverpeasV5Web20;
import com.stratelia.webactiv.util.viewGenerator.html.pagination.Pagination;
import com.stratelia.webactiv.util.viewGenerator.html.pagination.PaginationSP;
import com.stratelia.webactiv.util.viewGenerator.html.progressMessage.ProgressMessage;
import com.stratelia.webactiv.util.viewGenerator.html.progressMessage.ProgressMessageSilverpeasV5;
import com.stratelia.webactiv.util.viewGenerator.html.tabs.TabbedPane;
import com.stratelia.webactiv.util.viewGenerator.html.tabs.TabbedPaneSilverpeasV5;
import com.stratelia.webactiv.util.viewGenerator.html.window.Window;
import com.stratelia.webactiv.util.viewGenerator.html.window.WindowWeb20V5;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* The GraphicElementFactory is the only class to instanciate in this package. You should have one
* factory for each client (for future evolution). The GraphicElementFactory is responsible from
* graphic component instanciation. You should never directly instanciate a component without using
* this factory ! This class uses the "factory design pattern".
*/
public class GraphicElementFactory {
/**
* The key with which is associated the resources wrapper used by a Silverpeas component instance
* and that is carried in each request.
*/
public static final String RESOURCES_KEY = "resources";
public static final String GE_FACTORY_SESSION_ATT = "SessionGraphicElementFactory";
private final static ResourceLocator settings = new ResourceLocator(
"com.stratelia.webactiv.util.viewGenerator.settings.graphicElementFactorySettings", "");
private ResourceLocator lookSettings = null;
private ResourceLocator silverpeasLookSettings = null;
private ResourceLocator favoriteLookSettings = null;
private final static String defaultLook =
"com.stratelia.webactiv.util.viewGenerator.settings.Initial";
private final static ResourceLocator generalSettings = new ResourceLocator(
"com.stratelia.webactiv.general", I18NHelper.defaultLanguage);
private final static String iconsPath = URLManager.getApplicationURL() + settings.getString(
"IconsPath");
private ResourceLocator multilang = null;
private String currentLookName = null;
private String externalStylesheet = null;
private String componentId = null;
private MainSessionController mainSessionController = null;
private String spaceId = null;
private boolean componentMainPage = false;
public static final String defaultLookName = "Initial";
private static final String JQUERY_JS = "jquery-1.7.1.min.js";
private static final String JQUERY_INCLUDE_JS = "jquery-include.js";
private static final String JQUERYUI_JS = "jquery-ui-1.8.16.custom.min.js";
private static final String JQUERYUI_CSS = "ui-lightness/jquery-ui-1.8.16.custom.css";
private static final String JQUERYJSON_JS = "jquery.json-2.3.min.js";
+ private static final String SILVERPEAS_JS = "silverpeas.js";
/**
* Constructor declaration
*
* @param look
* @see
*/
public GraphicElementFactory(String look) {
setLook(look);
}
public static String getIconsPath() {
return iconsPath;
}
public static ResourceLocator getGeneralSettings() {
return generalSettings;
}
public ResourceLocator getMultilang() {
if (multilang == null) {
String language = getLanguage();
multilang = new ResourceLocator(
"com.stratelia.webactiv.util.viewGenerator.multilang.graphicElementFactoryBundle",
language);
}
return multilang;
}
private String getLanguage() {
String language = I18NHelper.defaultLanguage;
if (mainSessionController != null) {
language = mainSessionController.getFavoriteLanguage();
}
return language;
}
/**
* Get the settings for the factory.
*
* @return The ResourceLocator returned contains all default environment settings necessary to
* know wich component to instanciate, but also to know how to generate html code.
*/
public static ResourceLocator getSettings() {
return settings;
}
/**
* Method declaration
*
* @return Customer specific look settings if defined, default look settings otherwise
* @see
*/
public ResourceLocator getLookSettings() {
SilverTrace.info("viewgenerator", "GraphicElementFactory.getLookSettings()",
"root.MSG_GEN_ENTER_METHOD");
if (lookSettings == null) {
ResourceLocator silverpeasSettings = getSilverpeasLookSettings();
SilverTrace.info("viewgenerator",
"GraphicElementFactory.getLookSettings()",
"root.MSG_GEN_EXIT_METHOD", "lookSettings == null");
// get the customer lookSettings
try {
lookSettings =
new ResourceLocator(
"com.stratelia.webactiv.util.viewGenerator.settings.lookSettings", "",
silverpeasSettings);
} catch (java.util.MissingResourceException e) {
// the customer lookSettings is undefined get the default silverpeas looks
lookSettings = silverpeasSettings;
}
}
SilverTrace.info("viewgenerator",
"GraphicElementFactory.getLookSettings()", "root.MSG_GEN_EXIT_METHOD");
return lookSettings;
}
/**
* Method declaration
*
* @return the default look settings ResourceLocator
* @see
*/
public ResourceLocator getSilverpeasLookSettings() {
SilverTrace.info("viewgenerator",
"GraphicElementFactory.getSilverpeasLookSettings()",
"root.MSG_GEN_ENTER_METHOD");
if (silverpeasLookSettings == null) {
silverpeasLookSettings = new ResourceLocator(
"com.stratelia.webactiv.util.viewGenerator.settings.defaultLookSettings", "");
}
return silverpeasLookSettings;
}
/**
* Method declaration
*
* @return
* @see
*/
public ResourceLocator getFavoriteLookSettings() {
return this.favoriteLookSettings;
}
/**
* Method declaration
*
* @param look
* @see
*/
public final void setLook(String look) {
lookSettings = getLookSettings();
String selectedLook;
// get the customer lookSettings
try {
selectedLook = lookSettings.getString(look, null);
} catch (java.util.MissingResourceException e) {
// the customer lookSettings is undefined
// get the default silverpeas looks
// lookSettings = null;
SilverTrace.info("viewgenerator", "GraphicElementFactory.setLook()",
"root.MSG_GEN_PARAM_VALUE", " customer lookSettings is undefined !");
lookSettings = getSilverpeasLookSettings();
selectedLook = silverpeasLookSettings.getString(look, null);
if (selectedLook == null) {
// ce look n'existe plus, look par defaut
selectedLook = defaultLook;
}
}
SilverTrace.info("viewgenerator", "GraphicElementFactory.setLook()",
"root.MSG_GEN_PARAM_VALUE", " look = " + look
+ " | corresponding settings = " + selectedLook);
this.favoriteLookSettings = new ResourceLocator(selectedLook, "");
currentLookName = look;
}
public String getCurrentLookName() {
return currentLookName;
}
public void setExternalStylesheet(String externalStylesheet) {
this.externalStylesheet = externalStylesheet;
}
public String getExternalStylesheet() {
return this.externalStylesheet;
}
public boolean hasExternalStylesheet() {
return (externalStylesheet != null);
}
/**
* Method declaration
*
* @return
* @see
*/
public String getLookFrame() {
SilverTrace.info("viewgenerator", "GraphicElementFactory.getLookFrame()",
"root.MSG_GEN_PARAM_VALUE", " FrameJSP = "
+ getFavoriteLookSettings().getString("FrameJSP"));
return getFavoriteLookSettings().getString("FrameJSP");
}
/**
* Method declaration
*
* @return
* @see
*/
public String getLookStyleSheet() {
SilverTrace.info("viewgenerator", "GraphicElementFactory.getLookStyleSheet()",
"root.MSG_GEN_ENTER_METHOD");
String standardStyle = "/util/styleSheets/globalSP_SilverpeasV5.css";
String standardStyleForIE = "/util/styleSheets/globalSP_SilverpeasV5-IE.css";
String contextPath = getGeneralSettings().getString("ApplicationURL");
String charset = getGeneralSettings().getString("charset", "UTF-8");
StringBuilder code = new StringBuilder();
code.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=");
code.append(charset);
code.append("\"/>\n");
String specificJS = null;
if (externalStylesheet == null) {
code.append("<link type=\"text/css\" href=\"").append(contextPath).append(
"/util/styleSheets/jquery/").append(JQUERYUI_CSS).append("\" rel=\"stylesheet\"/>\n");
// define CSS(default and specific) and JS (specific) dedicated to current component
StringBuilder defaultComponentCSS = null;
StringBuilder specificComponentCSS = null;
if (StringUtil.isDefined(componentId) && mainSessionController != null) {
ComponentInstLight component =
mainSessionController.getOrganizationController().getComponentInstLight(componentId);
if (component != null) {
String componentName = component.getName();
String genericComponentName = getGenericComponentName(componentName);
defaultComponentCSS = new StringBuilder(50);
defaultComponentCSS.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"")
.append(contextPath).
append("/").append(genericComponentName).append("/jsp/styleSheets/").append(
genericComponentName).append(".css").append("\"/>\n");
String specificStyle = getFavoriteLookSettings().getString("StyleSheet." + componentName);
if (StringUtil.isDefined(specificStyle)) {
specificComponentCSS = new StringBuilder(50);
specificComponentCSS.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"");
specificComponentCSS.append(specificStyle).append("\"/>\n");
}
specificJS = getFavoriteLookSettings().getString("JavaScript." + componentName);
}
}
// append default global CSS
code.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"").append(contextPath);
code.append(standardStyle).append("\"/>\n");
code.append("<!--[if IE]>\n");
code.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"").append(
contextPath).append(standardStyleForIE).append("\"/>\n");
code.append("<![endif]-->\n");
// append default CSS of current component
if (defaultComponentCSS != null) {
code.append(defaultComponentCSS);
}
// append specific global CSS
appendSpecificCSS(code);
// append specific CSS of current component
if (specificComponentCSS != null) {
code.append(specificComponentCSS);
}
} else {
code.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"").append(externalStylesheet)
.append("\"/>\n");
}
// append javascript
code.append("<script type=\"text/javascript\">var webContext='").append(contextPath).append(
"';").append("</script>\n");
code.append("<script type=\"text/javascript\" src=\"").append(contextPath).append(
+ "/util/javaScript/").append(SILVERPEAS_JS).append("\"></script>\n");
+ code.append("<script type=\"text/javascript\" src=\"").append(contextPath).append(
"/util/javaScript/jquery/").append(JQUERY_JS).append("\"></script>\n");
code.append("<script type=\"text/javascript\" src=\"").append(contextPath).append(
"/util/javaScript/jquery/").append(JQUERYJSON_JS).append("\"></script>\n");
code.append("<script type=\"text/javascript\" src=\"").append(contextPath).append(
"/util/javaScript/jquery/").append(JQUERYUI_JS).append("\"></script>\n");
code.append("<script type=\"text/javascript\" src=\"").append(contextPath).append(
"/util/javaScript/jquery/").append(JQUERY_INCLUDE_JS).append("\"></script>\n");
if (StringUtil.isDefined(specificJS)) {
code.append("<script type=\"text/javascript\" src=\"").append(specificJS).append(
"\"></script>\n");
}
if (isComponentMainPage()) {
code.append("<script type=\"text/javascript\" src=\"").append(contextPath).append(
"/util/javaScript/jquery/jquery.cookie.js\"></script>\n");
}
if (getFavoriteLookSettings() != null
&& getFavoriteLookSettings().getString("OperationPane").toLowerCase().endsWith("web20")) {
code.append(getYahooElements());
}
SilverTrace.info("viewgenerator", "GraphicElementFactory.getLookStyleSheet()",
"root.MSG_GEN_EXIT_METHOD");
return code.toString();
}
/**
* Retrieve space look <br/> Look Style behavior algorithm is : <ul> <li>Use specific space look
* if defined</li> <li>else if use the user defined look settings</li> <li>else if use the default
* look settings</li> </ul>
*
* @param code the current state of the HTML produced for the header.
*/
private void appendSpecificCSS(StringBuilder code) {
if (StringUtil.isDefined(this.spaceId)) {
SpaceInstLight curSpace = mainSessionController.getOrganizationController().getSpaceInstLightById(
this.spaceId);
if (curSpace != null) {
String spaceLookStyle = curSpace.getLook();
getSpaceLook(code, curSpace, spaceLookStyle);
return;
}
}
appendDefaultLookCSS(code);
}
/**
* @param code the current state of the HTML produced for the header.
* @param curSpace
* @param spaceLookStyle
*/
private void getSpaceLook(StringBuilder code, SpaceInstLight curSpace, String spaceLookStyle) {
if (StringUtil.isDefined(spaceLookStyle)) {
setLook(spaceLookStyle);
String lookStyle = getFavoriteLookSettings().getString("StyleSheet");
if (StringUtil.isDefined(lookStyle)) {
code.append("<link id=\"specificCSSid\" rel=\"stylesheet\" type=\"text/css\" href=\"");
code.append(lookStyle).append("\"/>\n");
}
} else {
// Check the parent space look (recursive method)
if (!curSpace.isRoot()) {
String fatherSpaceId = curSpace.getFatherId();
SpaceInstLight fatherSpace =
mainSessionController.getOrganizationController().getSpaceInstLightById(fatherSpaceId);
spaceLookStyle = fatherSpace.getLook();
getSpaceLook(code, fatherSpace, spaceLookStyle);
} else {
appendDefaultLookCSS(code);
}
}
}
/**
* Append the default look CSS.
*
* @param code the current state of the HTML produced for the header.
*/
private void appendDefaultLookCSS(StringBuilder code) {
String userLookStyle = this.getDefaultLookName();
setLook(userLookStyle);
String lookStyle = getFavoriteLookSettings().getString("StyleSheet");
if (StringUtil.isDefined(lookStyle)) {
code.append("<link id=\"specificCSSid\" rel=\"stylesheet\" type=\"text/css\" href=\"");
code.append(lookStyle).append("\"/>\n");
}
}
/**
* Some logical components have got the same technical component. For example, "toolbox" component
* is technically "kmelia"
*
* @return the "implementation" name of the given component
*/
private String getGenericComponentName(String componentName) {
if ("toolbox".equalsIgnoreCase(componentName) || "kmax".equalsIgnoreCase(componentName)) {
return "kmelia";
} if ("pollingstation".equalsIgnoreCase(componentName)) {
return "survey";
}
return componentName;
}
private String getYahooElements() {
String contextPath = getGeneralSettings().getString("ApplicationURL");
StringBuilder code = new StringBuilder();
code.append("<!-- CSS for Menu -->\n");
code.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"");
code.append(getSettings().getString("YUIMenuCss",
contextPath + "/util/yui/menu/assets/menu.css"));
code.append("\"/>\n");
code.append("<!-- Page-specific styles -->\n");
code.append("<style type=\"text/css\">\n");
code.append(" div.yuimenu {\n");
code.append(" position:dynamic;\n");
code.append(" visibility:hidden;\n");
code.append(" }\n");
code.append("</style>\n");
code.append("<script type=\"text/javascript\" src=\"").append(contextPath);
code.append("/util/yui/yahoo-dom-event/yahoo-dom-event.js\"></script>\n");
code.append("<script type=\"text/javascript\" src=\"").append(contextPath);
code.append("/util/yui/container/container_core-min.js\"></script>\n");
code.append("<script type=\"text/javascript\" src=\"").append(contextPath);
code.append("/util/yui/menu/menu-min.js\"></script>\n");
return code.toString();
}
/**
* Method declaration
*
* @return
* @see
*/
public String getIcon(String iconKey) {
SilverTrace.info("viewgenerator", "GraphicElementFactory.getIcon()",
"root.MSG_GEN_ENTER_METHOD", "iconKey = " + iconKey);
return getFavoriteLookSettings().getString(iconKey, null);
}
/**
* Method declaration
*
* @return
* @see
*/
public List<String> getAvailableLooks() {
ResourceLocator theLookSettings = getLookSettings();
Enumeration<String> keys = theLookSettings.getKeys();
List<String> availableLooks = new ArrayList<String>();
while (keys.hasMoreElements()) {
availableLooks.add(keys.nextElement());
}
return availableLooks;
}
/**
* Construct a new button.
*
* @param label The new button label
* @param action The action associated exemple : "javascript:onClick=history.back()", or
* "http://www.stratelia.com/"
* @param disabled Specify if the button is disabled or not. If disabled, no action will be
* possible.
* @return returns an object implementing the FormButton interface. That's the new button to use.
*/
public Button getFormButton(String label, String action, boolean disabled) {
Button button = null;
String buttonClassName = getFavoriteLookSettings().getString("Button");
try {
button = (Button) Class.forName(buttonClassName).newInstance();
} catch (Exception e) {
SilverTrace.error("viewgenerator", "GraphicElementFactory.getFormButton()",
"viewgenerator.EX_CANT_GET_BUTTON", "", e);
button = new ButtonSilverpeasV5();
} finally {
button.init(label, action, disabled);
}
return button;
}
/**
* Construct a new frame.
*
* @param title The new frame title
* @return returns an object implementing the Frame interface. That's the new frame to use.
*/
public Frame getFrame() {
Frame frame;
String frameClassName = getFavoriteLookSettings().getString("Frame");
try {
frame = (Frame) Class.forName(frameClassName).newInstance();
} catch (Exception e) {
SilverTrace.error("viewgenerator", "GraphicElementFactory.getFrame()",
"viewgenerator.EX_CANT_GET_FRAME", "", e);
frame = new FrameSilverpeasV5();
}
return frame;
}
/**
* Construct a new board.
*
* @return returns an object implementing the Board interface. That's the new board to use.
*/
public Board getBoard() {
Board board;
String boardClassName = getFavoriteLookSettings().getString("Board");
try {
board = (Board) Class.forName(boardClassName).newInstance();
} catch (Exception e) {
SilverTrace.error("viewgenerator", "GraphicElementFactory.getBoard()",
"viewgenerator.EX_CANT_GET_FRAME", "", e);
board = new BoardSilverpeasV5();
}
return board;
}
/**
* Construct a new navigation list.
*
* @return returns an object implementing the NavigationList interface.
*/
public NavigationList getNavigationList() {
NavigationList navigationList;
String navigationListClassName = getFavoriteLookSettings().getString(
"NavigationList");
try {
navigationList = (NavigationList) Class.forName(navigationListClassName).newInstance();
} catch (Exception e) {
SilverTrace.error("viewgenerator", "GraphicElementFactory.getNavigationList()",
"viewgenerator.EX_CANT_GET_NAVIGATIONLIST", "", e);
navigationList = new NavigationListSilverpeasV5();
}
return navigationList;
}
/**
* Construct a new button.
*
* @param label The new button label
* @param action The action associated exemple : "javascript:history.back()", or
* "http://www.stratelia.com/"
* @param disabled Specify if the button is disabled or not. If disabled, no action will be
* possible.
* @param imagePath The path where the images needed to display buttons will be found.
* @return returns an object implementing the FormButton interface. That's the new button to use.
* @deprecated
*/
public Button getFormButton(String label, String action, boolean disabled,
String imagePath) {
return getFormButton(label, action, disabled);
}
/**
* Build a new TabbedPane.
*
* @return An object implementing the TabbedPane interface.
*/
public TabbedPane getTabbedPane() {
String tabbedPaneClassName = getFavoriteLookSettings().getString(
"TabbedPane");
TabbedPane tabbedPane = null;
try {
tabbedPane = (TabbedPane) Class.forName(tabbedPaneClassName).newInstance();
} catch (Exception e) {
SilverTrace.error("viewgenerator", "GraphicElementFactory.getTabbedPane()",
"viewgenerator.EX_CANT_GET_TABBED_PANE", "", e);
tabbedPane = new TabbedPaneSilverpeasV5();
} finally {
tabbedPane.init(1);
}
return tabbedPane;
}
/**
* Build a new TabbedPane.
*
* @return An object implementing the TabbedPane interface.
*/
public TabbedPane getTabbedPane(int nbLines) {
String tabbedPaneClassName = getFavoriteLookSettings().getString(
"TabbedPane");
TabbedPane tabbedPane = null;
try {
tabbedPane = (TabbedPane) Class.forName(tabbedPaneClassName).newInstance();
} catch (Exception e) {
SilverTrace.error("viewgenerator", "GraphicElementFactory.getTabbedPane()",
"viewgenerator.EX_CANT_GET_TABBED_PANE", " nbLines = " + nbLines, e);
tabbedPane = new TabbedPaneSilverpeasV5();
} finally {
tabbedPane.init(nbLines);
}
return tabbedPane;
}
/**
* Build a new ArrayPane.
*
* @param name The name from your array. This name has to be unique in the session. It will
* be used to put some information (including the sorted column), in the
* session. exemple : "MyToDoArrayPane"
* @param pageContext The page context computed by the servlet or JSP. The PageContext is used to
* both get new request (sort on a new column), and keep the current state (via
* the session).
* @return An object implementing the ArrayPane interface.
* @deprecated
*/
public ArrayPane getArrayPane(String name,
javax.servlet.jsp.PageContext pageContext) {
String arrayPaneClassName = getFavoriteLookSettings().getString("ArrayPane");
ArrayPane arrayPane = null;
try {
arrayPane = (ArrayPane) Class.forName(arrayPaneClassName).newInstance();
} catch (Exception e) {
SilverTrace.error("viewgenerator",
"GraphicElementFactory.getArrayPane()",
"viewgenerator.EX_CANT_GET_ARRAY_PANE", " name = " + name, e);
arrayPane = new ArrayPaneSilverpeasV5();
} finally {
arrayPane.init(name, pageContext);
}
return arrayPane;
}
/**
* Build a new ArrayPane.
*
* @param name The name from your array. This name has to be unique in the session. It will be
* used to put some information (including the sorted column), in the session.
* exemple : "MyToDoArrayPane"
* @param request The http request (to get entering action, like sort operation)
* @param session The client session (to get the old status, like on which column we are sorted)
* @return An object implementing the ArrayPane interface.
* @deprecated
*/
public ArrayPane getArrayPane(String name, ServletRequest request, HttpSession session) {
String arrayPaneClassName = getFavoriteLookSettings().getString("ArrayPane");
ArrayPane arrayPane = null;
try {
arrayPane = (ArrayPane) Class.forName(arrayPaneClassName).newInstance();
} catch (Exception e) {
SilverTrace.error("viewgenerator",
"GraphicElementFactory.getArrayPane()",
"viewgenerator.EX_CANT_GET_ARRAY_PANE", " name = " + name, e);
arrayPane = new ArrayPaneSilverpeasV5();
} finally {
arrayPane.init(name, request, session);
}
return arrayPane;
}
/**
* Build a new ArrayPane.
*
* @param name The name from your array. This name has to be unique in the session. It will be
* used to put some information (including the sorted column), in the session.
* exemple : "MyToDoArrayPane"
* @param url The url to root sorting action. This url can contain parameters. exemple :
* http://localhost/webactiv/Rkmelia/topicManager?topicId=12
* @param request The http request (to get entering action, like sort operation)
* @param session The client session (to get the old status, like on which column we are sorted)
* @return An object implementing the ArrayPane interface.
*/
public ArrayPane getArrayPane(String name, String url, ServletRequest request,
HttpSession session) {
String arrayPaneClassName = getFavoriteLookSettings().getString("ArrayPane");
ArrayPane arrayPane = null;
try {
arrayPane = (ArrayPane) Class.forName(arrayPaneClassName).newInstance();
} catch (Exception e) {
SilverTrace.error("viewgenerator",
"GraphicElementFactory.getArrayPane()",
"viewgenerator.EX_CANT_GET_ARRAY_PANE", " name = " + name, e);
arrayPane = new ArrayPaneSilverpeasV5();
} finally {
arrayPane.init(name, url, request, session);
}
return arrayPane;
}
/**
* Build a new main Window using the object specified in the properties.
*
* @return An object implementing Window interface
*/
public Window getWindow() {
String windowClassName = getFavoriteLookSettings().getString("Window");
Window window = null;
try {
window = (Window) Class.forName(windowClassName).newInstance();
} catch (Exception e) {
SilverTrace.error("viewgenerator", "GraphicElementFactory.getWindow()",
"viewgenerator.EX_CANT_GET_WINDOW", "", e);
window = new WindowWeb20V5();
} finally {
window.init(this);
}
return window;
}
/**
* Build a new ButtonPane.
*
* @return An object implementing the ButtonPane interface
*/
public ButtonPane getButtonPane() {
String buttonPaneClassName = getFavoriteLookSettings().getString(
"ButtonPane");
try {
return (ButtonPane) Class.forName(buttonPaneClassName).newInstance();
} catch (Exception e) {
SilverTrace.error("viewgenerator", "GraphicElementFactory.getButtonPane()",
"viewgenerator.EX_CANT_GET_BUTTON_PANE", "", e);
return new ButtonPaneWA2();
}
}
/**
* Build a new IconPane.
*
* @return An object implementing the IconPane interface.
*/
public IconPane getIconPane() {
String iconPaneClassName = getFavoriteLookSettings().getString("IconPane");
try {
return (IconPane) Class.forName(iconPaneClassName).newInstance();
} catch (Exception e) {
SilverTrace.error("viewgenerator", "GraphicElementFactory.getIconPane()",
"viewgenerator.EX_CANT_GET_ICON_PANE", "", e);
return new IconPaneWA();
}
}
/**
* Build a new FormPane.
*
* @param name
* @param actionURL
* @param pageContext
* @return
*/
public FormPane getFormPane(String name, String actionURL,
javax.servlet.jsp.PageContext pageContext) {
return new FormPaneWA(name, actionURL, pageContext);
}
/**
* Build a new OperationPane.
*
* @return An object implementing the OperationPane interface.
*/
public OperationPane getOperationPane() {
String operationPaneClassName = getFavoriteLookSettings().getString("OperationPane");
OperationPane operationPane;
try {
operationPane = (OperationPane) Class.forName(operationPaneClassName).newInstance();
} catch (Exception e) {
SilverTrace.error("viewgenerator", "GraphicElementFactory.getOperationPane()",
"viewgenerator.EX_CANT_GET_OPERATION_PANE", "", e);
operationPane = new OperationPaneSilverpeasV5Web20();
}
operationPane.setMultilang(getMultilang());
return operationPane;
}
/**
* Build a new BrowseBar.
*
* @return An object implementing the BrowseBar interface.
*/
public BrowseBar getBrowseBar() {
String browseBarClassName = getFavoriteLookSettings().getString("BrowseBar");
try {
BrowseBar browseBar = (BrowseBar) Class.forName(browseBarClassName).newInstance();
browseBar.setComponentId(componentId);
browseBar.setMainSessionController(mainSessionController);
return browseBar;
} catch (Exception e) {
SilverTrace.error("viewgenerator", "GraphicElementFactory.getBrowseBar()",
"viewgenerator.EX_CANT_GET_BROWSE_BAR", "", e);
BrowseBar browseBar = new BrowseBarComplete();
browseBar.setComponentId(componentId);
browseBar.setMainSessionController(mainSessionController);
return browseBar;
}
}
/**
* Build a new monthCalendar.
*
* @param String : the language to use by the monthCalendar
* @return an object implementing the monthCalendar interface
*/
public MonthCalendar getMonthCalendar(String language) {
return new MonthCalendarWA1(language);
}
/**
* Build a new Calendar.
*
* @param String : the language to use by the monthCalendar
* @return an object implementing the monthCalendar interface
*/
public Calendar getCalendar(String context, String language, Date date) {
return new CalendarWA1(context, language, date);
}
public Pagination getPagination(int nbItems, int nbItemsPerPage, int firstItemIndex) {
String paginationClassName = getFavoriteLookSettings().getString("Pagination");
Pagination pagination;
if (paginationClassName == null) {
paginationClassName =
"com.stratelia.webactiv.util.viewGenerator.html.pagination.PaginationSP";
}
try {
pagination = (Pagination) Class.forName(paginationClassName).newInstance();
} catch (Exception e) {
SilverTrace.info("viewgenerator", "GraphicElementFactory.getPagination()",
"viewgenerator.EX_CANT_GET_PAGINATION", "", e);
pagination = new PaginationSP();
}
pagination.init(nbItems, nbItemsPerPage, firstItemIndex);
pagination.setMultilang(getMultilang());
return pagination;
}
public ProgressMessage getProgressMessage(List<String> messages) {
String progressClassName = getFavoriteLookSettings().getString("Progress");
ProgressMessage progress;
if (progressClassName == null) {
progressClassName =
"com.stratelia.webactiv.util.viewGenerator.html.progressMessage.ProgressMessageSilverpeasV5";
}
try {
progress = (ProgressMessage) Class.forName(progressClassName).newInstance();
} catch (Exception e) {
SilverTrace.info("viewgenerator", "GraphicElementFactory.getProgressMessage()",
"viewgenerator.EX_CANT_GET_PROGRESSMESSAGE", "", e);
progress = new ProgressMessageSilverpeasV5();
}
progress.init(messages);
progress.setMultilang(getMultilang());
return progress;
}
public void setComponentId(String componentId) {
this.componentId = componentId;
}
public String getComponentId() {
return componentId;
}
public MainSessionController getMainSessionController() {
return mainSessionController;
}
public void setHttpRequest(HttpServletRequest request) {
HttpSession session = request.getSession(true);
mainSessionController =
(MainSessionController) session.getAttribute(MAIN_SESSION_CONTROLLER_ATT);
componentMainPage = request.getRequestURI().endsWith("/Main");
}
public boolean isComponentMainPage() {
return componentMainPage;
}
/**
* @return the space identifier
*/
public String getSpaceId() {
return spaceId;
}
/**
* @param spaceId the space identifier to set (full identifier with WA + number)
*/
public void setSpaceId(String spaceId) {
this.spaceId = spaceId;
}
/**
* Retrieve default look name
*
* @return user personal look settings if defined, default look settings otherwise
*/
public String getDefaultLookName() {
// Retrieve user personal look settings
String userLookStyle;
try {
userLookStyle = mainSessionController.getPersonalization().getLook();
} catch (Exception t) {
SilverTrace.error("viewgenerator", "GEF", "problem to retrieve user look", t);
userLookStyle = defaultLookName;
}
return userLookStyle;
}
}
| false | false | null | null |
diff --git a/src/java/is/idega/idegaweb/egov/application/presentation/ApplicationForm.java b/src/java/is/idega/idegaweb/egov/application/presentation/ApplicationForm.java
index 4898911..e28ce86 100644
--- a/src/java/is/idega/idegaweb/egov/application/presentation/ApplicationForm.java
+++ b/src/java/is/idega/idegaweb/egov/application/presentation/ApplicationForm.java
@@ -1,581 +1,586 @@
/*
* $Id$ Created on Jan 12, 2006
*
* Copyright (C) 2006 Idega Software hf. All Rights Reserved.
*
* This software is the proprietary information of Idega hf. Use is subject to license terms.
*/
package is.idega.idegaweb.egov.application.presentation;
import is.idega.block.family.business.FamilyLogic;
import is.idega.block.family.business.NoChildrenFound;
import is.idega.idegaweb.egov.application.ApplicationConstants;
import is.idega.idegaweb.egov.application.business.ApplicationBusiness;
import is.idega.idegaweb.egov.application.data.Application;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import javax.ejb.FinderException;
import javax.faces.component.UIComponent;
import javax.servlet.http.Cookie;
import com.idega.business.IBOLookup;
import com.idega.business.IBOLookupException;
import com.idega.business.IBORuntimeException;
import com.idega.core.builder.data.ICPage;
import com.idega.core.contact.data.Email;
import com.idega.core.contact.data.Phone;
import com.idega.core.location.data.Address;
import com.idega.core.location.data.PostalCode;
import com.idega.idegaweb.IWApplicationContext;
import com.idega.idegaweb.IWMainApplication;
import com.idega.idegaweb.IWResourceBundle;
import com.idega.presentation.Block;
import com.idega.presentation.IWContext;
import com.idega.presentation.Layer;
import com.idega.presentation.Page;
import com.idega.presentation.text.Heading1;
import com.idega.presentation.text.Link;
import com.idega.presentation.text.ListItem;
import com.idega.presentation.text.Lists;
import com.idega.presentation.text.Paragraph;
import com.idega.presentation.text.Text;
import com.idega.presentation.ui.DropdownMenu;
import com.idega.user.business.NoEmailFoundException;
import com.idega.user.business.NoPhoneFoundException;
import com.idega.user.business.UserBusiness;
import com.idega.user.data.User;
import com.idega.util.Age;
import com.idega.util.CoreConstants;
import com.idega.util.CreditCardChecker;
import com.idega.util.CreditCardType;
import com.idega.util.IWTimestamp;
import com.idega.util.PersonalIDFormatter;
import com.idega.util.PresentationUtil;
public abstract class ApplicationForm extends Block {
private static final String BUNDLE_IDENTIFIER = "is.idega.idegaweb.egov.application";
private static final String COOKIE_NAME = "applicationWindow_";
protected static final String PARAMETER_NO_USER = "prm_no_user";
private static final String ATTRIBUTE_CARD_TYPES = "egov.application.card.types";
private static final String DEFAULT_CARD_TYPES = CreditCardType.VISA.getCode() + "," + CreditCardType.MASTERCARD.getCode();
private ICPage iWindowPage;
private int iWidth = 400;
private int iHeight = 400;
private boolean iHasErrors = false;
private Map<Integer, Boolean> iPhaseErrors;
private Map<String, String> iErrors;
@Override
public void main(IWContext iwc) {
PresentationUtil.addStyleSheetToHeader(iwc, iwc.getIWMainApplication().getBundle(ApplicationConstants.IW_BUNDLE_IDENTIFIER).getVirtualPathWithFileNameString("style/application.css"));
if (iwc.isParameterSet(PARAMETER_NO_USER)) {
setError(PARAMETER_NO_USER, getResourceBundle(iwc).getLocalizedString("application_error.no_user_selected", "No user selected."));
}
present(iwc);
}
@Override
public String getBundleIdentifier() {
return BUNDLE_IDENTIFIER;
}
protected void setError(String parameter, String error) {
setError(-1, parameter, error);
}
protected void setError(int phase, String parameter, String error) {
if (this.iErrors == null) {
this.iErrors = new LinkedHashMap<String, String>();
}
this.iHasErrors = true;
if (phase > 0) {
if (iPhaseErrors == null) {
iPhaseErrors = new HashMap<Integer, Boolean>();
}
iPhaseErrors.put(new Integer(phase), Boolean.TRUE);
}
this.iErrors.put(parameter, error);
}
protected boolean hasErrors() {
return this.iHasErrors;
}
protected boolean hasErrors(int phase) {
if (iPhaseErrors == null) {
return false;
}
else {
Boolean hasErrors = iPhaseErrors.get(new Integer(phase));
if (hasErrors != null) {
return hasErrors.booleanValue();
}
return false;
}
}
protected boolean hasError(String parameter) {
if (hasErrors()) {
return this.iErrors.containsKey(parameter);
}
return false;
}
/**
* Adds the errors encountered
*
* @param iwc
* @param errors
*/
protected void addErrors(IWContext iwc, UIComponent parent) {
+ addErrors(-1, iwc, parent);
+ }
+ protected void addErrors(int phase, IWContext iwc, UIComponent parent) {
if (this.iHasErrors) {
Layer layer = new Layer(Layer.DIV);
layer.setStyleClass("errorLayer");
Layer image = new Layer(Layer.DIV);
image.setStyleClass("errorImage");
layer.add(image);
- Heading1 heading = new Heading1(getResourceBundle(iwc).getLocalizedString("application_errors_occured", "There was a problem with the following items"));
+ Heading1 heading = phase <= 0 ?
+ new Heading1(getResourceBundle(iwc).getLocalizedString("application_errors_occured", "There was a problem with the following items")) :
+ new Heading1(getResourceBundle(iwc).getLocalizedString("application_errors_occured_" + phase, "There was a problem with the following items"));
layer.add(heading);
Lists list = new Lists();
layer.add(list);
for (Iterator<String> iter = this.iErrors.values().iterator(); iter.hasNext();) {
String element = iter.next();
ListItem item = new ListItem();
item.add(new Text(element));
list.add(item);
}
parent.getChildren().add(layer);
}
}
protected Layer getReceiptLayer(IWContext iwc, String heading, String body) {
addWindowToOpen(iwc, getParentPage());
return getDisplayLayer(heading, body, "receipt", "receiptImage");
}
private void addWindowToOpen(IWContext iwc, Page page) {
if (this.iWindowPage != null) {
boolean hasSeenWindow = false;
Cookie[] cookies = iwc.getCookies();
if (cookies != null) {
if (cookies.length > 0) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals(COOKIE_NAME + this.iWindowPage.getPrimaryKey().toString())) {
hasSeenWindow = true;
continue;
}
}
}
}
if (!hasSeenWindow) {
page.setWindowToOpenOnLoad(this.iWindowPage, this.iWidth, this.iHeight);
Cookie cookie = new Cookie(COOKIE_NAME + this.iWindowPage.getPrimaryKey().toString(), "true");
cookie.setMaxAge(24 * 60 * 60);
cookie.setPath("/");
iwc.addCookies(cookie);
}
}
}
protected Layer getStopLayer(String heading, String body) {
return getDisplayLayer(heading, body, "stop", "stopImage");
}
private Layer getDisplayLayer(String header, String body, String layerClass, String imageClass) {
Layer layer = new Layer(Layer.DIV);
layer.setStyleClass(layerClass);
Layer image = new Layer(Layer.DIV);
image.setStyleClass(imageClass);
layer.add(image);
Heading1 heading = new Heading1(header);
layer.add(heading);
Paragraph paragraph = new Paragraph();
paragraph.add(new Text(body));
layer.add(paragraph);
return layer;
}
protected Layer getPersonInfo(IWContext iwc, User user) throws RemoteException {
return getPersonInfo(iwc, user, true);
}
protected Layer getPersonInfo(IWContext iwc, User user, boolean showAddress) throws RemoteException {
return getPersonInfo(iwc, user, showAddress, false);
}
protected Layer getPersonInfo(IWContext iwc, User user, boolean showAddress, boolean showContactInfo) throws RemoteException {
Layer layer = new Layer(Layer.DIV);
layer.setStyleClass("info");
if (user != null) {
Address address = getUserBusiness(iwc).getUsersMainAddress(user);
PostalCode postal = null;
if (address != null) {
postal = address.getPostalCode();
}
Phone phone = null;
Email email = null;
if (showContactInfo) {
try {
phone = getUserBusiness(iwc).getUsersHomePhone(user);
}
catch (NoPhoneFoundException e) {
//No phone found...
}
try {
email = getUserBusiness(iwc).getUsersMainEmail(user);
}
catch (NoEmailFoundException e) {
//No email found...
}
}
Layer personInfo = new Layer(Layer.DIV);
personInfo.setStyleClass("personInfo");
personInfo.setID("name");
personInfo.add(new Text(user.getName()));
layer.add(personInfo);
personInfo = new Layer(Layer.DIV);
personInfo.setStyleClass("personInfo");
personInfo.setID("personalID");
personInfo.add(new Text(PersonalIDFormatter.format(user.getPersonalID(), iwc.getCurrentLocale())));
layer.add(personInfo);
if (phone != null) {
personInfo = new Layer(Layer.DIV);
personInfo.setStyleClass("personInfo");
personInfo.setID("phone");
personInfo.add(new Text(phone.getNumber()));
layer.add(personInfo);
}
personInfo = new Layer(Layer.DIV);
personInfo.setStyleClass("personInfo");
personInfo.setID("address");
if (address != null && showAddress) {
personInfo.add(new Text(address.getStreetAddress()));
}
layer.add(personInfo);
if (email != null) {
personInfo = new Layer(Layer.DIV);
personInfo.setStyleClass("personInfo");
personInfo.setID("email");
personInfo.add(new Text(email.getEmailAddress()));
layer.add(personInfo);
}
personInfo = new Layer(Layer.DIV);
personInfo.setStyleClass("personInfo");
personInfo.setID("postal");
if (postal != null && showAddress) {
personInfo.add(new Text(postal.getPostalAddress()));
}
layer.add(personInfo);
}
return layer;
}
protected DropdownMenu getUserChooser(IWContext iwc, User user, User chosenUser, String parameterName, IWResourceBundle iwrb) throws RemoteException {
return getUserChooser(iwc, null, user, chosenUser, parameterName, iwrb);
}
protected DropdownMenu getUserChooser(IWContext iwc, Object applicationPK, User user, User chosenUser, String parameterName, IWResourceBundle iwrb) throws RemoteException {
Collection<User> children = null;
try {
children = getMemberFamilyLogic(iwc).getChildrenInCustodyOf(user);
}
catch (NoChildrenFound e) {
children = new ArrayList<User>();
}
children.add(user);
return getUserChooser(iwc, applicationPK, user, chosenUser, children, parameterName, iwrb);
}
protected DropdownMenu getUserChooser(IWContext iwc, Object applicationPK, User user, User chosenUser, Collection<User> children, String parameterName, IWResourceBundle iwrb) throws RemoteException {
Application application = null;
if (applicationPK != null) {
try {
application = getApplicationBusiness(iwc).getApplication(applicationPK);
}
catch (FinderException fe) {
log(fe);
}
}
else {
try {
application = getApplicationBusiness(iwc).getApplication(getCaseCode());
}
catch (FinderException fe) {
// Nothing found, continuing...
}
}
DropdownMenu menu = new DropdownMenu(parameterName);
menu.setStyleClass("userSelector");
for (Iterator<User> iter = children.iterator(); iter.hasNext();) {
User element = iter.next();
boolean addUser = true;
if (application != null) {
if (application.getAgeFrom() > -1 && application.getAgeTo() > -1) {
if (element.getDateOfBirth() != null) {
IWTimestamp stamp = new IWTimestamp(element.getDateOfBirth());
stamp.setDay(1);
stamp.setMonth(1);
Age age = new Age(stamp.getDate());
addUser = (application.getAgeFrom() <= age.getYears() && application.getAgeTo() >= age.getYears());
}
else {
addUser = false;
}
}
}
if (!addUser && addOveragedUser(iwc, user)) {
addUser = true;
}
if (addUser) {
menu.addMenuElement(element.getPrimaryKey().toString(), element.getName());
}
}
menu.addMenuElementFirst(CoreConstants.EMPTY, iwrb.getLocalizedString("select_applicant", "Select applicant"));
if (chosenUser != null) {
menu.setSelectedElement(chosenUser.getPrimaryKey().toString());
}
return menu;
}
protected boolean addOveragedUser(IWContext iwc, User user) {
return false;
}
private Layer getPhases(int phase, int totalPhases) {
Layer layer = new Layer(Layer.DIV);
layer.setStyleClass("phases");
Lists list = new Lists();
for (int a = 1; a <= totalPhases; a++) {
ListItem item = new ListItem();
item.add(new Text(String.valueOf(a)));
if (a == phase) {
item.setStyleClass("current");
}
list.add(item);
}
layer.add(list);
return layer;
}
protected Layer getHeader(String text) {
return getPhasesHeader(text, -1, -1);
}
protected Layer getPhasesHeader(String text, int phase, int totalPhases) {
return getPhasesHeader(text, phase, totalPhases, true);
}
protected Layer getPhasesHeader(String text, int phase, int totalPhases, boolean showNumberInText) {
Layer layer = new Layer(Layer.DIV);
layer.setStyleClass("header");
if (phase != -1) {
Heading1 heading = new Heading1((showNumberInText ? (String.valueOf(phase) + ". ") : "") + text);
layer.add(heading);
layer.add(getPhases(phase, totalPhases));
}
else {
Heading1 heading = new Heading1(text);
layer.add(heading);
}
return layer;
}
protected void addReceipt(IWContext iwc, String heading, String subject, String text) {
addPhasesReceipt(iwc, heading, subject, text, -1, -1);
}
protected void addPhasesReceipt(IWContext iwc, String heading, String subject, String text, int phase, int totalPhases) {
addPhasesReceipt(iwc, heading, subject, text, phase, totalPhases, true);
}
protected void addPhasesReceipt(IWContext iwc, String heading, String subject, String text, int phase, int totalPhases, boolean showNumberInText) {
Layer header = new Layer(Layer.DIV);
header.setStyleClass("header");
add(header);
if (phase != -1) {
Heading1 heading1 = new Heading1((showNumberInText ? (String.valueOf(phase) + ". ") : "") + heading);
header.add(heading1);
header.add(getPhases(phase, totalPhases));
}
else {
Heading1 heading1 = new Heading1(heading);
header.add(heading1);
}
add(getReceiptLayer(iwc, subject, text));
}
protected Link getButtonLink(String text) {
Layer all = new Layer(Layer.SPAN);
all.setStyleClass("buttonSpan");
Layer left = new Layer(Layer.SPAN);
left.setStyleClass("left");
all.add(left);
Layer middle = new Layer(Layer.SPAN);
middle.setStyleClass("middle");
middle.add(new Text(text));
all.add(middle);
Layer right = new Layer(Layer.SPAN);
right.setStyleClass("right");
all.add(right);
Link link = new Link(all);
link.setStyleClass("button");
return link;
}
protected Layer getAttentionLayer(String text) {
Layer layer = new Layer(Layer.DIV);
layer.setStyleClass("attention");
Layer imageLayer = new Layer(Layer.DIV);
imageLayer.setStyleClass("attentionImage");
layer.add(imageLayer);
Layer textLayer = new Layer(Layer.DIV);
textLayer.setStyleClass("attentionText");
layer.add(textLayer);
Paragraph paragraph = new Paragraph();
paragraph.add(new Text(text));
textLayer.add(paragraph);
Layer clearLayer = new Layer(Layer.DIV);
clearLayer.setStyleClass("attentionClear");
layer.add(clearLayer);
return layer;
}
public static DropdownMenu getCardTypeDropdown(Locale locale, String parameterName) {
DropdownMenu menu = new DropdownMenu(parameterName);
IWResourceBundle iwrb = IWMainApplication.getDefaultIWMainApplication().getBundle(ApplicationConstants.IW_BUNDLE_IDENTIFIER).getResourceBundle(locale);
List<CreditCardType> types = getAllowedCardTypes();
for (Iterator<CreditCardType> it = types.iterator(); it.hasNext();) {
CreditCardType type = it.next();
menu.addMenuElement(type.getCode(), iwrb.getLocalizedString("application." + type.getCode(), type.getName()));
}
return menu;
}
public static boolean validateCardNumber(String cardNumber) {
return CreditCardChecker.isValid(cardNumber, getAllowedCardTypes());
}
public static List<CreditCardType> getAllowedCardTypes() {
List<CreditCardType> types = new ArrayList<CreditCardType>();
String allowedTypes = IWMainApplication.getDefaultIWMainApplication().getSettings().getProperty(ATTRIBUTE_CARD_TYPES, DEFAULT_CARD_TYPES);
StringTokenizer tokens = new StringTokenizer(allowedTypes, CoreConstants.COMMA);
while (tokens.hasMoreTokens()) {
String code = tokens.nextToken();
CreditCardType type = CreditCardType.getByCode(code);
if (type != null) {
types.add(type);
}
}
return types;
}
protected ApplicationBusiness getApplicationBusiness(IWApplicationContext iwac) {
try {
return IBOLookup.getServiceInstance(iwac, ApplicationBusiness.class);
}
catch (IBOLookupException ile) {
throw new IBORuntimeException(ile);
}
}
private FamilyLogic getMemberFamilyLogic(IWApplicationContext iwac) {
try {
return IBOLookup.getServiceInstance(iwac, FamilyLogic.class);
}
catch (IBOLookupException ile) {
throw new IBORuntimeException(ile);
}
}
protected UserBusiness getUserBusiness(IWApplicationContext iwac) {
try {
return IBOLookup.getServiceInstance(iwac, UserBusiness.class);
}
catch (IBOLookupException ile) {
throw new IBORuntimeException(ile);
}
}
protected abstract String getCaseCode();
protected abstract void present(IWContext iwc);
public void setWindowPage(ICPage page) {
this.iWindowPage = page;
}
public void setWindowPage(ICPage page, int width, int height) {
this.iWindowPage = page;
this.iWidth = width;
this.iHeight = height;
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/com/android/gallery3d/app/PhotoPage.java b/src/com/android/gallery3d/app/PhotoPage.java
index 51a57f2..1204d0d 100644
--- a/src/com/android/gallery3d/app/PhotoPage.java
+++ b/src/com/android/gallery3d/app/PhotoPage.java
@@ -1,778 +1,777 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.gallery3d.app;
import android.app.ActionBar.OnMenuVisibilityListener;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ShareActionProvider;
import android.widget.Toast;
import com.android.gallery3d.R;
import com.android.gallery3d.data.DataManager;
import com.android.gallery3d.data.MediaDetails;
import com.android.gallery3d.data.MediaItem;
import com.android.gallery3d.data.MediaObject;
import com.android.gallery3d.data.MediaSet;
import com.android.gallery3d.data.MtpDevice;
import com.android.gallery3d.data.Path;
import com.android.gallery3d.data.SnailSource;
import com.android.gallery3d.picasasource.PicasaSource;
import com.android.gallery3d.ui.DetailsHelper;
import com.android.gallery3d.ui.DetailsHelper.CloseListener;
import com.android.gallery3d.ui.DetailsHelper.DetailsSource;
import com.android.gallery3d.ui.GLCanvas;
import com.android.gallery3d.ui.GLView;
import com.android.gallery3d.ui.ImportCompleteListener;
import com.android.gallery3d.ui.MenuExecutor;
import com.android.gallery3d.ui.PhotoView;
import com.android.gallery3d.ui.ScreenNail;
import com.android.gallery3d.ui.SelectionManager;
import com.android.gallery3d.ui.SynchronizedHandler;
import com.android.gallery3d.util.GalleryUtils;
public class PhotoPage extends ActivityState implements
PhotoView.Listener, OrientationManager.Listener, AppBridge.Server {
private static final String TAG = "PhotoPage";
private static final int MSG_HIDE_BARS = 1;
private static final int MSG_LOCK_ORIENTATION = 2;
private static final int MSG_UNLOCK_ORIENTATION = 3;
private static final int MSG_ON_FULL_SCREEN_CHANGED = 4;
private static final int MSG_UPDATE_ACTION_BAR = 5;
private static final int HIDE_BARS_TIMEOUT = 3500;
private static final int REQUEST_SLIDESHOW = 1;
private static final int REQUEST_CROP = 2;
private static final int REQUEST_CROP_PICASA = 3;
private static final int REQUEST_EDIT = 4;
public static final String KEY_MEDIA_SET_PATH = "media-set-path";
public static final String KEY_MEDIA_ITEM_PATH = "media-item-path";
public static final String KEY_INDEX_HINT = "index-hint";
public static final String KEY_OPEN_ANIMATION_RECT = "open-animation-rect";
public static final String KEY_APP_BRIDGE = "app-bridge";
public static final String KEY_RETURN_INDEX_HINT = "return-index-hint";
private GalleryApp mApplication;
private SelectionManager mSelectionManager;
private PhotoView mPhotoView;
private PhotoPage.Model mModel;
private DetailsHelper mDetailsHelper;
private boolean mShowDetails;
private Path mPendingSharePath;
// mMediaSet could be null if there is no KEY_MEDIA_SET_PATH supplied.
// E.g., viewing a photo in gmail attachment
private MediaSet mMediaSet;
private Menu mMenu;
private int mCurrentIndex = 0;
private Handler mHandler;
private boolean mShowBars = true;
// The value of canShowBars() last time the bar updates state.
private boolean mCanShowBars = false;
private volatile boolean mActionBarAllowed = true;
private GalleryActionBar mActionBar;
private MyMenuVisibilityListener mMenuVisibilityListener;
private boolean mIsMenuVisible;
private MediaItem mCurrentPhoto = null;
private MenuExecutor mMenuExecutor;
private boolean mIsActive;
private ShareActionProvider mShareActionProvider;
private String mSetPathString;
// This is the original mSetPathString before adding the camera preview item.
private String mOriginalSetPathString;
private AppBridge mAppBridge;
private ScreenNail mScreenNail;
private MediaItem mScreenNailItem;
private OrientationManager mOrientationManager;
private NfcAdapter mNfcAdapter;
public static interface Model extends PhotoView.Model {
public void resume();
public void pause();
public boolean isEmpty();
public MediaItem getCurrentMediaItem();
public void setCurrentPhoto(Path path, int indexHint);
}
private class MyMenuVisibilityListener implements OnMenuVisibilityListener {
@Override
public void onMenuVisibilityChanged(boolean isVisible) {
mIsMenuVisible = isVisible;
refreshHidingMessage();
}
}
private final GLView mRootPane = new GLView() {
@Override
protected void renderBackground(GLCanvas view) {
view.clearBuffer();
}
@Override
protected void onLayout(
boolean changed, int left, int top, int right, int bottom) {
mPhotoView.layout(0, 0, right - left, bottom - top);
if (mShowDetails) {
mDetailsHelper.layout(left, mActionBar.getHeight(), right, bottom);
}
}
@Override
protected void orient(int displayRotation, int compensation) {
displayRotation = mOrientationManager.getDisplayRotation();
Log.d(TAG, "orient -- display rotation " + displayRotation
+ ", compensation = " + compensation);
super.orient(displayRotation, compensation);
}
};
@Override
public void onCreate(Bundle data, Bundle restoreState) {
mActionBar = mActivity.getGalleryActionBar();
mSelectionManager = new SelectionManager(mActivity, false);
mMenuExecutor = new MenuExecutor(mActivity, mSelectionManager);
mPhotoView = new PhotoView(mActivity);
mPhotoView.setListener(this);
mRootPane.addComponent(mPhotoView);
mApplication = (GalleryApp)((Activity) mActivity).getApplication();
mOrientationManager = mActivity.getOrientationManager();
mOrientationManager.addListener(this);
mSetPathString = data.getString(KEY_MEDIA_SET_PATH);
mOriginalSetPathString = mSetPathString;
mNfcAdapter = NfcAdapter.getDefaultAdapter(mActivity.getAndroidContext());
Path itemPath = Path.fromString(data.getString(KEY_MEDIA_ITEM_PATH));
if (mSetPathString != null) {
mAppBridge = (AppBridge) data.getParcelable(KEY_APP_BRIDGE);
if (mAppBridge != null) {
mOrientationManager.lockOrientation();
// Get the ScreenNail from AppBridge and register it.
mScreenNail = mAppBridge.attachScreenNail();
int id = SnailSource.registerScreenNail(mScreenNail);
Path screenNailSetPath = SnailSource.getSetPath(id);
Path screenNailItemPath = SnailSource.getItemPath(id);
mScreenNailItem = (MediaItem) mActivity.getDataManager()
.getMediaObject(screenNailItemPath);
// Combine the original MediaSet with the one for CameraScreenNail.
mSetPathString = "/combo/item/{" + screenNailSetPath +
"," + mSetPathString + "}";
// Start from the screen nail.
itemPath = screenNailItemPath;
// Action bar should not be displayed when camera starts.
mFlags |= FLAG_HIDE_ACTION_BAR;
mShowBars = false;
}
mMediaSet = mActivity.getDataManager().getMediaSet(mSetPathString);
mCurrentIndex = data.getInt(KEY_INDEX_HINT, 0);
if (mMediaSet == null) {
Log.w(TAG, "failed to restore " + mSetPathString);
}
PhotoDataAdapter pda = new PhotoDataAdapter(
mActivity, mPhotoView, mMediaSet, itemPath, mCurrentIndex,
mAppBridge == null ? -1 : 0);
mModel = pda;
mPhotoView.setModel(mModel);
pda.setDataListener(new PhotoDataAdapter.DataListener() {
@Override
public void onPhotoChanged(int index, Path item) {
mCurrentIndex = index;
if (item != null) {
MediaItem photo = mModel.getCurrentMediaItem();
if (photo != null) updateCurrentPhoto(photo);
}
updateBars();
}
@Override
public void onLoadingFinished() {
GalleryUtils.setSpinnerVisibility((Activity) mActivity, false);
if (!mModel.isEmpty()) {
MediaItem photo = mModel.getCurrentMediaItem();
if (photo != null) updateCurrentPhoto(photo);
} else if (mIsActive) {
mActivity.getStateManager().finishState(PhotoPage.this);
}
}
@Override
public void onLoadingStarted() {
GalleryUtils.setSpinnerVisibility((Activity) mActivity, true);
}
});
} else {
// Get default media set by the URI
MediaItem mediaItem = (MediaItem)
mActivity.getDataManager().getMediaObject(itemPath);
mModel = new SinglePhotoDataAdapter(mActivity, mPhotoView, mediaItem);
mPhotoView.setModel(mModel);
updateCurrentPhoto(mediaItem);
}
mHandler = new SynchronizedHandler(mActivity.getGLRoot()) {
@Override
public void handleMessage(Message message) {
switch (message.what) {
case MSG_HIDE_BARS: {
hideBars();
break;
}
case MSG_LOCK_ORIENTATION: {
mOrientationManager.lockOrientation();
updateBars();
break;
}
case MSG_UNLOCK_ORIENTATION: {
mOrientationManager.unlockOrientation();
updateBars();
break;
}
case MSG_ON_FULL_SCREEN_CHANGED: {
mAppBridge.onFullScreenChanged(message.arg1 == 1);
break;
}
case MSG_UPDATE_ACTION_BAR: {
updateBars();
break;
}
default: throw new AssertionError(message.what);
}
}
};
// start the opening animation only if it's not restored.
if (restoreState == null) {
mPhotoView.setOpenAnimationRect((Rect) data.getParcelable(KEY_OPEN_ANIMATION_RECT));
}
}
private void updateShareURI(Path path) {
if (mShareActionProvider != null) {
DataManager manager = mActivity.getDataManager();
int type = manager.getMediaType(path);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType(MenuExecutor.getMimeType(type));
intent.putExtra(Intent.EXTRA_STREAM, manager.getContentUri(path));
mShareActionProvider.setShareIntent(intent);
if (mNfcAdapter != null) {
mNfcAdapter.setBeamPushUris(new Uri[]{manager.getContentUri(path)},
(Activity)mActivity);
}
mPendingSharePath = null;
} else {
// This happens when ActionBar is not created yet.
mPendingSharePath = path;
}
}
private void updateCurrentPhoto(MediaItem photo) {
if (mCurrentPhoto == photo) return;
mCurrentPhoto = photo;
if (mCurrentPhoto == null) return;
updateMenuOperations();
updateTitle();
if (mShowDetails) {
mDetailsHelper.reloadDetails(mModel.getCurrentIndex());
}
mPhotoView.showVideoPlayIcon(
photo.getMediaType() == MediaObject.MEDIA_TYPE_VIDEO);
if ((photo.getSupportedOperations() & MediaItem.SUPPORT_SHARE) != 0) {
updateShareURI(photo.getPath());
}
}
private void updateTitle() {
if (mCurrentPhoto == null) return;
boolean showTitle = mActivity.getAndroidContext().getResources().getBoolean(
R.bool.show_action_bar_title);
if (showTitle && mCurrentPhoto.getName() != null)
mActionBar.setTitle(mCurrentPhoto.getName());
else
mActionBar.setTitle("");
}
private void updateMenuOperations() {
if (mMenu == null) return;
MenuItem item = mMenu.findItem(R.id.action_slideshow);
if (item != null) {
item.setVisible(canDoSlideShow());
}
if (mCurrentPhoto == null) return;
int supportedOperations = mCurrentPhoto.getSupportedOperations();
if (!GalleryUtils.isEditorAvailable((Context) mActivity, "image/*")) {
supportedOperations &= ~MediaObject.SUPPORT_EDIT;
}
MenuExecutor.updateMenuOperation(mMenu, supportedOperations);
}
private boolean canDoSlideShow() {
if (mMediaSet == null || mCurrentPhoto == null) {
return false;
}
if (mCurrentPhoto.getMediaType() != MediaObject.MEDIA_TYPE_IMAGE) {
return false;
}
if (mMediaSet instanceof MtpDevice) {
return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////////
// Action Bar show/hide management
//////////////////////////////////////////////////////////////////////////
private void showBars() {
if (mShowBars) return;
mShowBars = true;
mActionBar.show();
WindowManager.LayoutParams params =
((Activity) mActivity).getWindow().getAttributes();
params.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE;
((Activity) mActivity).getWindow().setAttributes(params);
refreshHidingMessage();
}
private void hideBars() {
if (!mShowBars) return;
mShowBars = false;
mActionBar.hide();
WindowManager.LayoutParams params =
((Activity) mActivity).getWindow().getAttributes();
params.systemUiVisibility = View.SYSTEM_UI_FLAG_LOW_PROFILE;
((Activity) mActivity).getWindow().setAttributes(params);
mHandler.removeMessages(MSG_HIDE_BARS);
}
private void refreshHidingMessage() {
mHandler.removeMessages(MSG_HIDE_BARS);
if (!mIsMenuVisible) {
mHandler.sendEmptyMessageDelayed(MSG_HIDE_BARS, HIDE_BARS_TIMEOUT);
}
}
private boolean canShowBars() {
// No bars if we are showing camera preview.
if (mAppBridge != null && mCurrentIndex == 0) return false;
// No bars if it's not allowed.
if (!mActionBarAllowed) return false;
// No bars if the orientation is locked.
if (mOrientationManager.isOrientationLocked()) return false;
return true;
}
private void toggleBars() {
mCanShowBars = canShowBars();
if (mShowBars) {
hideBars();
} else {
if (mCanShowBars) showBars();
}
}
private void updateBars() {
boolean v = canShowBars();
if (mCanShowBars == v) return;
mCanShowBars = v;
if (mCanShowBars) {
showBars();
} else {
hideBars();
}
}
@Override
public void onOrientationCompensationChanged(int degrees) {
mActivity.getGLRoot().setOrientationCompensation(degrees);
}
@Override
protected void onBackPressed() {
if (mShowDetails) {
hideDetails();
} else if (mScreenNail == null
|| !switchWithCaptureAnimation(-1)) {
// We are leaving this page. Set the result now.
setResult();
super.onBackPressed();
}
}
private void onUpPressed() {
if (mActivity.getStateManager().getStateCount() > 1) {
super.onBackPressed();
} else if (mOriginalSetPathString != null) {
// We're in view mode so set up the stacks on our own.
Bundle data = new Bundle(getData());
data.putString(AlbumPage.KEY_MEDIA_PATH, mOriginalSetPathString);
data.putString(AlbumPage.KEY_PARENT_MEDIA_PATH,
mActivity.getDataManager().getTopSetPath(
DataManager.INCLUDE_ALL));
mActivity.getStateManager().switchState(this, AlbumPage.class, data);
}
}
private void setResult() {
Intent result = null;
if (!mPhotoView.getFilmMode()) {
result = new Intent();
result.putExtra(KEY_RETURN_INDEX_HINT, mCurrentIndex);
}
setStateResult(Activity.RESULT_OK, result);
}
//////////////////////////////////////////////////////////////////////////
// AppBridge.Server interface
//////////////////////////////////////////////////////////////////////////
@Override
public void setCameraNaturalFrame(Rect frame) {
mPhotoView.setCameraNaturalFrame(frame);
}
@Override
public boolean switchWithCaptureAnimation(int offset) {
return mPhotoView.switchWithCaptureAnimation(offset);
}
@Override
protected boolean onCreateActionBar(Menu menu) {
MenuInflater inflater = ((Activity) mActivity).getMenuInflater();
inflater.inflate(R.menu.photo, menu);
mShareActionProvider = GalleryActionBar.initializeShareActionProvider(menu);
if (mPendingSharePath != null) updateShareURI(mPendingSharePath);
mMenu = menu;
updateMenuOperations();
updateTitle();
return true;
}
@Override
protected boolean onItemSelected(MenuItem item) {
MediaItem current = mModel.getCurrentMediaItem();
if (current == null) {
// item is not ready, ignore
return true;
}
int currentIndex = mModel.getCurrentIndex();
Path path = current.getPath();
DataManager manager = mActivity.getDataManager();
int action = item.getItemId();
boolean needsConfirm = false;
switch (action) {
case android.R.id.home: {
onUpPressed();
return true;
}
case R.id.action_slideshow: {
Bundle data = new Bundle();
data.putString(SlideshowPage.KEY_SET_PATH, mMediaSet.getPath().toString());
data.putString(SlideshowPage.KEY_ITEM_PATH, path.toString());
data.putInt(SlideshowPage.KEY_PHOTO_INDEX, currentIndex);
data.putBoolean(SlideshowPage.KEY_REPEAT, true);
mActivity.getStateManager().startStateForResult(
SlideshowPage.class, REQUEST_SLIDESHOW, data);
return true;
}
case R.id.action_crop: {
Activity activity = (Activity) mActivity;
Intent intent = new Intent(CropImage.CROP_ACTION);
intent.setClass(activity, CropImage.class);
intent.setData(manager.getContentUri(path));
activity.startActivityForResult(intent, PicasaSource.isPicasaImage(current)
? REQUEST_CROP_PICASA
: REQUEST_CROP);
return true;
}
case R.id.action_edit: {
Intent intent = new Intent(Intent.ACTION_EDIT)
.setData(manager.getContentUri(path))
.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
((Activity) mActivity).startActivityForResult(Intent.createChooser(intent, null),
REQUEST_EDIT);
return true;
}
case R.id.action_details: {
if (mShowDetails) {
hideDetails();
} else {
showDetails(currentIndex);
}
return true;
}
case R.id.action_delete:
needsConfirm = true;
case R.id.action_setas:
case R.id.action_rotate_ccw:
case R.id.action_rotate_cw:
case R.id.action_show_on_map:
mSelectionManager.deSelectAll();
mSelectionManager.toggle(path);
mMenuExecutor.onMenuClicked(item, needsConfirm, null);
return true;
case R.id.action_import:
mSelectionManager.deSelectAll();
mSelectionManager.toggle(path);
mMenuExecutor.onMenuClicked(item, needsConfirm,
new ImportCompleteListener(mActivity));
return true;
default :
return false;
}
}
private void hideDetails() {
mShowDetails = false;
mDetailsHelper.hide();
}
private void showDetails(int index) {
mShowDetails = true;
if (mDetailsHelper == null) {
mDetailsHelper = new DetailsHelper(mActivity, mRootPane, new MyDetailsSource());
mDetailsHelper.setCloseListener(new CloseListener() {
@Override
public void onClose() {
hideDetails();
}
});
}
mDetailsHelper.reloadDetails(index);
mDetailsHelper.show();
}
////////////////////////////////////////////////////////////////////////////
// Callbacks from PhotoView
////////////////////////////////////////////////////////////////////////////
@Override
public void onSingleTapUp(int x, int y) {
if (mAppBridge != null) {
if (mAppBridge.onSingleTapUp(x, y)) return;
}
MediaItem item = mModel.getCurrentMediaItem();
if (item == null || item == mScreenNailItem) {
// item is not ready or it is camera preview, ignore
return;
}
boolean playVideo =
(item.getSupportedOperations() & MediaItem.SUPPORT_PLAY) != 0;
if (playVideo) {
// determine if the point is at center (1/6) of the photo view.
// (The position of the "play" icon is at center (1/6) of the photo)
int w = mPhotoView.getWidth();
int h = mPhotoView.getHeight();
playVideo = (Math.abs(x - w / 2) * 12 <= w)
&& (Math.abs(y - h / 2) * 12 <= h);
}
if (playVideo) {
playVideo((Activity) mActivity, item.getPlayUri(), item.getName());
} else {
toggleBars();
}
}
@Override
public void lockOrientation() {
mHandler.sendEmptyMessage(MSG_LOCK_ORIENTATION);
}
@Override
public void unlockOrientation() {
mHandler.sendEmptyMessage(MSG_UNLOCK_ORIENTATION);
}
@Override
public void onActionBarAllowed(boolean allowed) {
mActionBarAllowed = allowed;
mHandler.sendEmptyMessage(MSG_UPDATE_ACTION_BAR);
}
@Override
public void onFullScreenChanged(boolean full) {
Message m = mHandler.obtainMessage(
MSG_ON_FULL_SCREEN_CHANGED, full ? 1 : 0, 0);
m.sendToTarget();
}
public static void playVideo(Activity activity, Uri uri, String title) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW)
.setDataAndType(uri, "video/*");
intent.putExtra(Intent.EXTRA_TITLE, title);
activity.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(activity, activity.getString(R.string.video_err),
Toast.LENGTH_SHORT).show();
}
}
private void setCurrentPhotoByIntent(Intent intent) {
if (intent == null) return;
Path path = mApplication.getDataManager()
.findPathByUri(intent.getData(), intent.getType());
if (path != null) {
mModel.setCurrentPhoto(path, mCurrentIndex);
}
}
@Override
protected void onStateResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_EDIT:
setCurrentPhotoByIntent(data);
break;
case REQUEST_CROP:
if (resultCode == Activity.RESULT_OK) {
setCurrentPhotoByIntent(data);
}
break;
case REQUEST_CROP_PICASA: {
if (resultCode == Activity.RESULT_OK) {
Context context = mActivity.getAndroidContext();
- // TODO: Use crop_saved instead of photo_saved after its new translation is done.
- String message = context.getString(R.string.photo_saved,
+ String message = context.getString(R.string.crop_saved,
context.getString(R.string.folder_download));
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
break;
}
case REQUEST_SLIDESHOW: {
if (data == null) break;
String path = data.getStringExtra(SlideshowPage.KEY_ITEM_PATH);
int index = data.getIntExtra(SlideshowPage.KEY_PHOTO_INDEX, 0);
if (path != null) {
mModel.setCurrentPhoto(Path.fromString(path), index);
}
}
}
}
@Override
public void onPause() {
super.onPause();
mIsActive = false;
if (mAppBridge != null) mAppBridge.setServer(null);
DetailsHelper.pause();
mPhotoView.pause();
mModel.pause();
mHandler.removeMessages(MSG_HIDE_BARS);
mActionBar.removeOnMenuVisibilityListener(mMenuVisibilityListener);
mMenuExecutor.pause();
}
@Override
protected void onResume() {
super.onResume();
mIsActive = true;
setContentPane(mRootPane);
mModel.resume();
mPhotoView.resume();
if (mMenuVisibilityListener == null) {
mMenuVisibilityListener = new MyMenuVisibilityListener();
}
mActionBar.setDisplayOptions(mSetPathString != null, true);
mActionBar.addOnMenuVisibilityListener(mMenuVisibilityListener);
if (mAppBridge != null) {
mAppBridge.setServer(this);
mPhotoView.resetToFirstPicture();
}
}
@Override
protected void onDestroy() {
if (mAppBridge != null) {
// Unregister the ScreenNail and notify mAppBridge.
SnailSource.unregisterScreenNail(mScreenNail);
mAppBridge.detachScreenNail();
mAppBridge = null;
mScreenNail = null;
}
mOrientationManager.removeListener(this);
// Remove all pending messages.
mHandler.removeCallbacksAndMessages(null);
super.onDestroy();
}
private class MyDetailsSource implements DetailsSource {
private int mIndex;
@Override
public MediaDetails getDetails() {
return mModel.getCurrentMediaItem().getDetails();
}
@Override
public int size() {
return mMediaSet != null ? mMediaSet.getMediaItemCount() : 1;
}
@Override
public int findIndex(int indexHint) {
mIndex = indexHint;
return indexHint;
}
@Override
public int getIndex() {
return mIndex;
}
}
}
| true | false | null | null |
diff --git a/src/ecjTransformer/lombok/ast/ecj/EcjTreeBuilder.java b/src/ecjTransformer/lombok/ast/ecj/EcjTreeBuilder.java
index 0f50055..422da90 100644
--- a/src/ecjTransformer/lombok/ast/ecj/EcjTreeBuilder.java
+++ b/src/ecjTransformer/lombok/ast/ecj/EcjTreeBuilder.java
@@ -1,1996 +1,1997 @@
/*
* Copyright © 2010-2011 Reinier Zwitserloot, Roel Spilker and Robbert Jan Grootjans.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package lombok.ast.ecj;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import lombok.SneakyThrows;
import lombok.ast.AnnotationDeclaration;
import lombok.ast.AnnotationValueArray;
import lombok.ast.AstVisitor;
import lombok.ast.BinaryOperator;
import lombok.ast.Comment;
import lombok.ast.ForwardingAstVisitor;
import lombok.ast.Identifier;
import lombok.ast.JavadocContainer;
import lombok.ast.KeywordModifier;
import lombok.ast.Modifiers;
import lombok.ast.Node;
import lombok.ast.Position;
import lombok.ast.RawListAccessor;
import lombok.ast.UnaryOperator;
import lombok.ast.VariableReference;
import lombok.ast.grammar.SourceStructure;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy;
import org.eclipse.jdt.internal.compiler.ast.AND_AND_Expression;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.AbstractVariableDeclaration;
import org.eclipse.jdt.internal.compiler.ast.AllocationExpression;
import org.eclipse.jdt.internal.compiler.ast.Annotation;
import org.eclipse.jdt.internal.compiler.ast.AnnotationMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.Argument;
import org.eclipse.jdt.internal.compiler.ast.ArrayAllocationExpression;
import org.eclipse.jdt.internal.compiler.ast.ArrayInitializer;
import org.eclipse.jdt.internal.compiler.ast.ArrayQualifiedTypeReference;
import org.eclipse.jdt.internal.compiler.ast.ArrayReference;
import org.eclipse.jdt.internal.compiler.ast.ArrayTypeReference;
import org.eclipse.jdt.internal.compiler.ast.AssertStatement;
import org.eclipse.jdt.internal.compiler.ast.Assignment;
import org.eclipse.jdt.internal.compiler.ast.BinaryExpression;
import org.eclipse.jdt.internal.compiler.ast.Block;
import org.eclipse.jdt.internal.compiler.ast.BreakStatement;
import org.eclipse.jdt.internal.compiler.ast.CaseStatement;
import org.eclipse.jdt.internal.compiler.ast.CastExpression;
import org.eclipse.jdt.internal.compiler.ast.CharLiteral;
import org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess;
import org.eclipse.jdt.internal.compiler.ast.CombinedBinaryExpression;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.jdt.internal.compiler.ast.CompoundAssignment;
import org.eclipse.jdt.internal.compiler.ast.ConditionalExpression;
import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration;
import org.eclipse.jdt.internal.compiler.ast.ContinueStatement;
import org.eclipse.jdt.internal.compiler.ast.DoStatement;
import org.eclipse.jdt.internal.compiler.ast.DoubleLiteral;
import org.eclipse.jdt.internal.compiler.ast.EmptyStatement;
import org.eclipse.jdt.internal.compiler.ast.EqualExpression;
import org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall;
import org.eclipse.jdt.internal.compiler.ast.Expression;
import org.eclipse.jdt.internal.compiler.ast.ExtendedStringLiteral;
import org.eclipse.jdt.internal.compiler.ast.FalseLiteral;
import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
import org.eclipse.jdt.internal.compiler.ast.FieldReference;
import org.eclipse.jdt.internal.compiler.ast.FloatLiteral;
import org.eclipse.jdt.internal.compiler.ast.ForStatement;
import org.eclipse.jdt.internal.compiler.ast.ForeachStatement;
import org.eclipse.jdt.internal.compiler.ast.IfStatement;
import org.eclipse.jdt.internal.compiler.ast.ImportReference;
import org.eclipse.jdt.internal.compiler.ast.Initializer;
import org.eclipse.jdt.internal.compiler.ast.InstanceOfExpression;
import org.eclipse.jdt.internal.compiler.ast.IntLiteral;
import org.eclipse.jdt.internal.compiler.ast.IntLiteralMinValue;
import org.eclipse.jdt.internal.compiler.ast.Javadoc;
import org.eclipse.jdt.internal.compiler.ast.LabeledStatement;
import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration;
import org.eclipse.jdt.internal.compiler.ast.LongLiteral;
import org.eclipse.jdt.internal.compiler.ast.LongLiteralMinValue;
import org.eclipse.jdt.internal.compiler.ast.MarkerAnnotation;
import org.eclipse.jdt.internal.compiler.ast.MemberValuePair;
import org.eclipse.jdt.internal.compiler.ast.MessageSend;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.NameReference;
import org.eclipse.jdt.internal.compiler.ast.NormalAnnotation;
import org.eclipse.jdt.internal.compiler.ast.NullLiteral;
import org.eclipse.jdt.internal.compiler.ast.OR_OR_Expression;
import org.eclipse.jdt.internal.compiler.ast.OperatorIds;
import org.eclipse.jdt.internal.compiler.ast.ParameterizedQualifiedTypeReference;
import org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference;
import org.eclipse.jdt.internal.compiler.ast.PostfixExpression;
import org.eclipse.jdt.internal.compiler.ast.PrefixExpression;
import org.eclipse.jdt.internal.compiler.ast.QualifiedAllocationExpression;
import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference;
import org.eclipse.jdt.internal.compiler.ast.QualifiedSuperReference;
import org.eclipse.jdt.internal.compiler.ast.QualifiedThisReference;
import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference;
import org.eclipse.jdt.internal.compiler.ast.ReturnStatement;
import org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation;
import org.eclipse.jdt.internal.compiler.ast.SingleNameReference;
import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference;
import org.eclipse.jdt.internal.compiler.ast.Statement;
import org.eclipse.jdt.internal.compiler.ast.StringLiteral;
import org.eclipse.jdt.internal.compiler.ast.StringLiteralConcatenation;
import org.eclipse.jdt.internal.compiler.ast.SuperReference;
import org.eclipse.jdt.internal.compiler.ast.SwitchStatement;
import org.eclipse.jdt.internal.compiler.ast.SynchronizedStatement;
import org.eclipse.jdt.internal.compiler.ast.ThisReference;
import org.eclipse.jdt.internal.compiler.ast.ThrowStatement;
import org.eclipse.jdt.internal.compiler.ast.TrueLiteral;
import org.eclipse.jdt.internal.compiler.ast.TryStatement;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeParameter;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.ast.UnaryExpression;
import org.eclipse.jdt.internal.compiler.ast.WhileStatement;
import org.eclipse.jdt.internal.compiler.ast.Wildcard;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.lookup.Binding;
import org.eclipse.jdt.internal.compiler.lookup.ExtraCompilerModifiers;
import org.eclipse.jdt.internal.compiler.parser.JavadocParser;
import org.eclipse.jdt.internal.compiler.parser.Parser;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import static lombok.ast.ConversionPositionInfo.getConversionPositionInfo;
/**
* Turns {@code lombok.ast} based ASTs into eclipse/ecj's {@code org.eclipse.jdt.internal.compiler.ast.ASTNode} model.
*/
public class EcjTreeBuilder {
private static final int VISIBILITY_MASK = 7;
static final char[] PACKAGE_INFO = "package-info".toCharArray();
private final Map<lombok.ast.Node, Collection<SourceStructure>> sourceStructures;
private List<? extends ASTNode> result = null;
private final String rawInput;
private final ProblemReporter reporter;
private final CompilationResult compilationResult;
private final CompilerOptions options;
private final EnumSet<BubblingFlags> bubblingFlags = EnumSet.noneOf(BubblingFlags.class);
private final EnumSet<BubblingFlags> AUTO_REMOVABLE_BUBBLING_FLAGS = EnumSet.of(BubblingFlags.LOCALTYPE);
private enum BubblingFlags {
ASSERT, LOCALTYPE, ABSTRACT_METHOD
}
private enum VariableKind {
UNSUPPORTED {
AbstractVariableDeclaration create() {
throw new UnsupportedOperationException();
}
},
FIELD {
AbstractVariableDeclaration create() {
return new FieldDeclaration();
}
},
LOCAL {
AbstractVariableDeclaration create() {
return new LocalDeclaration(null, 0, 0);
}
},
ARGUMENT {
AbstractVariableDeclaration create() {
return new Argument(null, 0, null, 0);
}
};
abstract AbstractVariableDeclaration create();
static VariableKind kind(lombok.ast.VariableDefinition node) {
//TODO rewrite this whole thing.
lombok.ast.Node parent = node.getParent();
if (parent instanceof lombok.ast.VariableDeclaration) {
if (parent.getParent() instanceof lombok.ast.TypeBody ||
parent.getParent() instanceof lombok.ast.EnumTypeBody) {
return FIELD;
} else {
return LOCAL;
}
}
if (parent instanceof lombok.ast.For ||
parent instanceof lombok.ast.ForEach){
return LOCAL;
}
if (parent instanceof lombok.ast.Catch ||
parent instanceof lombok.ast.MethodDeclaration ||
parent instanceof lombok.ast.ConstructorDeclaration){
return ARGUMENT;
}
return UNSUPPORTED;
}
}
public EcjTreeBuilder(lombok.ast.grammar.Source source, CompilerOptions options) {
this(source, createDefaultProblemReporter(options), new CompilationResult(source.getName().toCharArray(), 0, 0, 0));
}
public EcjTreeBuilder(String rawInput, String name, CompilerOptions options) {
this(rawInput, createDefaultProblemReporter(options), new CompilationResult(name.toCharArray(), 0, 0, 0));
}
private static ProblemReporter createDefaultProblemReporter(CompilerOptions options) {
return new ProblemReporter(new IErrorHandlingPolicy() {
public boolean proceedOnErrors() {
return true;
}
public boolean stopOnFirstError() {
return false;
}
}, options, new DefaultProblemFactory(Locale.ENGLISH));
}
public EcjTreeBuilder(lombok.ast.grammar.Source source, ProblemReporter reporter, CompilationResult compilationResult) {
this.options = reporter.options;
this.sourceStructures = source.getSourceStructures();
this.rawInput = source.getRawInput();
this.reporter = reporter;
this.compilationResult = compilationResult;
}
public EcjTreeBuilder(String rawInput, ProblemReporter reporter, CompilationResult compilationResult) {
this.options = reporter.options;
this.sourceStructures = null;
this.rawInput = rawInput;
this.reporter = reporter;
this.compilationResult = compilationResult;
}
private EcjTreeBuilder(EcjTreeBuilder parent) {
this.reporter = parent.reporter;
this.options = parent.options;
this.rawInput = parent.rawInput;
this.compilationResult = parent.compilationResult;
this.sourceStructures = parent.sourceStructures;
}
private EcjTreeBuilder create() {
return new EcjTreeBuilder(this);
}
private Expression toExpression(lombok.ast.Node node) {
return (Expression) toTree(node);
}
private Statement toStatement(lombok.ast.Node node) {
return (Statement) toTree(node);
}
private ASTNode toTree(lombok.ast.Node node) {
if (node == null) return null;
EcjTreeBuilder newBuilder = create();
node.accept(newBuilder.visitor);
bubblingFlags.addAll(newBuilder.bubblingFlags);
try {
return newBuilder.get();
} catch (RuntimeException e) {
System.err.printf("Node '%s' (%s) did not produce any results\n", node, node.getClass().getSimpleName());
throw e;
}
}
private char[] toName(lombok.ast.Identifier node) {
if (node == null) {
return null;
}
return node.astValue().toCharArray();
}
private <T extends ASTNode> T[] toArray(Class<T> type, List<T> list) {
if (list.isEmpty()) return null;
@SuppressWarnings("unchecked")
T[] emptyArray = (T[]) Array.newInstance(type, 0);
return list.toArray(emptyArray);
}
private <T extends ASTNode> T[] toArray(Class<T> type, lombok.ast.Node node) {
return toArray(type, toList(type, node));
}
private <T extends ASTNode> T[] toArray(Class<T> type, lombok.ast.StrictListAccessor<?, ?> accessor) {
List<T> list = Lists.newArrayList();
for (lombok.ast.Node node : accessor) {
EcjTreeBuilder newBuilder = create();
node.accept(newBuilder.visitor);
bubblingFlags.addAll(newBuilder.bubblingFlags);
List<? extends ASTNode> values;
values = newBuilder.getAll();
for (ASTNode value : values) {
if (value != null && !type.isInstance(value)) {
throw new ClassCastException(value.getClass().getName() + " cannot be cast to " + type.getName());
}
list.add(type.cast(value));
}
}
return toArray(type, list);
}
private <T extends ASTNode> List<T> toList(Class<T> type, lombok.ast.Node node) {
if (node == null) return Lists.newArrayList();
EcjTreeBuilder newBuilder = create();
node.accept(newBuilder.visitor);
bubblingFlags.addAll(newBuilder.bubblingFlags);
@SuppressWarnings("unchecked")
List<T> all = (List<T>)newBuilder.getAll();
return Lists.newArrayList(all);
}
public void visit(lombok.ast.Node node) {
node.accept(visitor);
}
public ASTNode get() {
if (result.isEmpty()) {
return null;
}
if (result.size() == 1) {
return result.get(0);
}
throw new RuntimeException("Expected only one result but got " + result.size());
}
public List<? extends ASTNode> getAll() {
return result;
}
private static <T extends ASTNode> T posParen(T in, lombok.ast.Node node) {
if (in == null) return null;
if (node instanceof lombok.ast.Expression) {
List<Position> parensPositions = ((lombok.ast.Expression)node).astParensPositions();
if (!parensPositions.isEmpty()) {
in.sourceStart = parensPositions.get(parensPositions.size() - 1).getStart();
in.sourceEnd = parensPositions.get(parensPositions.size() - 1).getEnd() - 1;
}
}
return in;
}
private static boolean isExplicitlyAbstract(Modifiers m) {
for (KeywordModifier keyword : m.astKeywords()) {
if ("abstract".equals(keyword.astName())) return true;
}
return false;
}
private static int opForBinaryExpression(BinaryExpression binExpr) {
return (binExpr.bits & ASTNode.OperatorMASK) >>> ASTNode.OperatorSHIFT;
}
private static final EnumMap<UnaryOperator, Integer> UNARY_OPERATORS = Maps.newEnumMap(UnaryOperator.class);
static {
UNARY_OPERATORS.put(UnaryOperator.BINARY_NOT, OperatorIds.TWIDDLE);
UNARY_OPERATORS.put(UnaryOperator.LOGICAL_NOT, OperatorIds.NOT);
UNARY_OPERATORS.put(UnaryOperator.UNARY_PLUS, OperatorIds.PLUS);
UNARY_OPERATORS.put(UnaryOperator.PREFIX_INCREMENT, OperatorIds.PLUS);
UNARY_OPERATORS.put(UnaryOperator.UNARY_MINUS, OperatorIds.MINUS);
UNARY_OPERATORS.put(UnaryOperator.PREFIX_DECREMENT, OperatorIds.MINUS);
UNARY_OPERATORS.put(UnaryOperator.POSTFIX_INCREMENT, OperatorIds.PLUS);
UNARY_OPERATORS.put(UnaryOperator.POSTFIX_DECREMENT, OperatorIds.MINUS);
}
private static final EnumMap<BinaryOperator, Integer> BINARY_OPERATORS = Maps.newEnumMap(BinaryOperator.class);
static {
BINARY_OPERATORS.put(BinaryOperator.PLUS_ASSIGN, OperatorIds.PLUS);
BINARY_OPERATORS.put(BinaryOperator.MINUS_ASSIGN, OperatorIds.MINUS);
BINARY_OPERATORS.put(BinaryOperator.MULTIPLY_ASSIGN, OperatorIds.MULTIPLY);
BINARY_OPERATORS.put(BinaryOperator.DIVIDE_ASSIGN, OperatorIds.DIVIDE);
BINARY_OPERATORS.put(BinaryOperator.REMAINDER_ASSIGN, OperatorIds.REMAINDER);
BINARY_OPERATORS.put(BinaryOperator.AND_ASSIGN, OperatorIds.AND);
BINARY_OPERATORS.put(BinaryOperator.XOR_ASSIGN, OperatorIds.XOR);
BINARY_OPERATORS.put(BinaryOperator.OR_ASSIGN, OperatorIds.OR);
BINARY_OPERATORS.put(BinaryOperator.SHIFT_LEFT_ASSIGN, OperatorIds.LEFT_SHIFT);
BINARY_OPERATORS.put(BinaryOperator.SHIFT_RIGHT_ASSIGN, OperatorIds.RIGHT_SHIFT);
BINARY_OPERATORS.put(BinaryOperator.BITWISE_SHIFT_RIGHT_ASSIGN, OperatorIds.UNSIGNED_RIGHT_SHIFT);
BINARY_OPERATORS.put(BinaryOperator.LOGICAL_OR, OperatorIds.OR_OR);
BINARY_OPERATORS.put(BinaryOperator.LOGICAL_AND, OperatorIds.AND_AND);
BINARY_OPERATORS.put(BinaryOperator.BITWISE_OR, OperatorIds.OR);
BINARY_OPERATORS.put(BinaryOperator.BITWISE_XOR, OperatorIds.XOR);
BINARY_OPERATORS.put(BinaryOperator.BITWISE_AND, OperatorIds.AND);
BINARY_OPERATORS.put(BinaryOperator.EQUALS, OperatorIds.EQUAL_EQUAL);
BINARY_OPERATORS.put(BinaryOperator.NOT_EQUALS, OperatorIds.NOT_EQUAL);
BINARY_OPERATORS.put(BinaryOperator.GREATER, OperatorIds.GREATER);
BINARY_OPERATORS.put(BinaryOperator.GREATER_OR_EQUAL, OperatorIds.GREATER_EQUAL);
BINARY_OPERATORS.put(BinaryOperator.LESS, OperatorIds.LESS);
BINARY_OPERATORS.put(BinaryOperator.LESS_OR_EQUAL, OperatorIds.LESS_EQUAL);
BINARY_OPERATORS.put(BinaryOperator.SHIFT_LEFT, OperatorIds.LEFT_SHIFT);
BINARY_OPERATORS.put(BinaryOperator.SHIFT_RIGHT, OperatorIds.RIGHT_SHIFT);
BINARY_OPERATORS.put(BinaryOperator.BITWISE_SHIFT_RIGHT, OperatorIds.UNSIGNED_RIGHT_SHIFT);
BINARY_OPERATORS.put(BinaryOperator.PLUS, OperatorIds.PLUS);
BINARY_OPERATORS.put(BinaryOperator.MINUS, OperatorIds.MINUS);
BINARY_OPERATORS.put(BinaryOperator.MULTIPLY, OperatorIds.MULTIPLY);
BINARY_OPERATORS.put(BinaryOperator.DIVIDE, OperatorIds.DIVIDE);
BINARY_OPERATORS.put(BinaryOperator.REMAINDER, OperatorIds.REMAINDER);
}
private final AstVisitor visitor = new ForwardingAstVisitor() {
@Override
public boolean visitCompilationUnit(lombok.ast.CompilationUnit node) {
int sourceLength = rawInput == null ? 0 : rawInput.length();
CompilationUnitDeclaration cud = new CompilationUnitDeclaration(reporter, compilationResult, sourceLength);
cud.bits |= ASTNode.HasAllMethodBodies;
cud.currentPackage = (ImportReference) toTree(node.astPackageDeclaration());
cud.imports = toArray(ImportReference.class, node.astImportDeclarations());
cud.types = toArray(TypeDeclaration.class, node.astTypeDeclarations());
if (CharOperation.equals(PACKAGE_INFO, cud.getMainTypeName())) {
TypeDeclaration[] newTypes;
if (cud.types == null) {
newTypes = new TypeDeclaration[1];
} else {
newTypes = new TypeDeclaration[cud.types.length + 1];
System.arraycopy(cud.types, 0, newTypes, 1, cud.types.length);
}
TypeDeclaration decl = new TypeDeclaration(compilationResult);
decl.name = PACKAGE_INFO.clone();
decl.modifiers = ClassFileConstants.AccDefault | ClassFileConstants.AccInterface;
newTypes[0] = decl;
cud.types = newTypes;
}
bubblingFlags.remove(BubblingFlags.ASSERT);
bubblingFlags.removeAll(AUTO_REMOVABLE_BUBBLING_FLAGS);
if (!bubblingFlags.isEmpty()) {
throw new RuntimeException("Unhandled bubbling flags left: " + bubblingFlags);
}
return set(node, cud);
}
private boolean set(lombok.ast.Node node, ASTNode value) {
if (result != null) throw new IllegalStateException("result is already set");
if (node instanceof lombok.ast.Expression) {
int parens = ((lombok.ast.Expression)node).getIntendedParens();
value.bits |= (parens << ASTNode.ParenthesizedSHIFT) & ASTNode.ParenthesizedMASK;
posParen(value, node);
}
if (value instanceof NameReference) {
updateRestrictionFlags(node, (NameReference)value);
}
List<ASTNode> result = Lists.newArrayList();
if (value != null) result.add(value);
EcjTreeBuilder.this.result = result;
return true;
}
private boolean set(lombok.ast.Node node, List<? extends ASTNode> values) {
if (values.isEmpty()) System.err.printf("Node '%s' (%s) did not produce any results\n", node, node.getClass().getSimpleName());
if (result != null) throw new IllegalStateException("result is already set");
result = values;
return true;
}
@Override
public boolean visitPackageDeclaration(lombok.ast.PackageDeclaration node) {
long[] pos = partsToPosArray(node.rawParts());
ImportReference pkg = new ImportReference(chain(node.astParts()), pos, true, ClassFileConstants.AccDefault);
pkg.annotations = toArray(Annotation.class, node.astAnnotations());
pkg.declarationSourceStart = jstart(node);
pkg.declarationSourceEnd = pkg.declarationEnd = end(node);
return set(node, pkg);
}
//TODO Create a test file with a whole bunch of comments. Possibly in a separate non-idempotency subdir, as printing comments idempotently is a rough nut to crack.
@Override
public boolean visitImportDeclaration(lombok.ast.ImportDeclaration node) {
int staticFlag = node.astStaticImport() ? ClassFileConstants.AccStatic : ClassFileConstants.AccDefault;
long[] pos = partsToPosArray(node.rawParts());
ImportReference imp = new ImportReference(chain(node.astParts()), pos, node.astStarImport(), staticFlag);
imp.declarationSourceStart = start(node);
imp.declarationSourceEnd = imp.declarationEnd = end(node);
return set(node, imp);
}
@Override
public boolean visitClassDeclaration(lombok.ast.ClassDeclaration node) {
TypeDeclaration decl = createTypeBody(node.astBody().astMembers(), node, true, 0);
decl.annotations = toArray(Annotation.class, node.astModifiers().astAnnotations());
decl.superclass = (TypeReference) toTree(node.astExtending());
decl.superInterfaces = toArray(TypeReference.class, node.astImplementing());
markTypeReferenceIsSuperType(decl);
decl.typeParameters = toArray(TypeParameter.class, node.astTypeVariables());
decl.name = toName(node.astName());
updateTypeBits(node.getParent(), decl, false);
setupJavadoc(decl, node);
//TODO test inner types. Give em everything - (abstract) methods, initializers, static initializers, MULTIPLE initializers.
return set(node, decl);
}
private void updateTypeBits(lombok.ast.Node parent, TypeDeclaration decl, boolean isEnum) {
if (parent == null) {
return;
}
if (parent instanceof lombok.ast.CompilationUnit) {
char[] mainTypeName = new CompilationUnitDeclaration(reporter, compilationResult, 0).getMainTypeName();
if (!CharOperation.equals(decl.name, mainTypeName)) {
decl.bits |= ASTNode.IsSecondaryType;
}
return;
}
if (parent instanceof lombok.ast.TypeBody ||
parent instanceof lombok.ast.EnumTypeBody) {
decl.bits |= ASTNode.IsMemberType;
return;
}
//TODO test if a type declared in an enum constant is possible
decl.bits |= ASTNode.IsLocalType;
bubblingFlags.add(BubblingFlags.LOCALTYPE);
}
private void markTypeReferenceIsSuperType(TypeDeclaration decl) {
if (decl.superclass != null) {
decl.superclass.bits |= ASTNode.IsSuperType;
}
if (decl.superInterfaces != null) {
for (TypeReference t : decl.superInterfaces) {
t.bits |= ASTNode.IsSuperType;
}
}
}
@Override
public boolean visitInterfaceDeclaration(lombok.ast.InterfaceDeclaration node) {
TypeDeclaration decl = createTypeBody(node.astBody().astMembers(), node, false, ClassFileConstants.AccInterface);
decl.annotations = toArray(Annotation.class, node.astModifiers().astAnnotations());
decl.superInterfaces = toArray(TypeReference.class, node.astExtending());
markTypeReferenceIsSuperType(decl);
decl.typeParameters = toArray(TypeParameter.class, node.astTypeVariables());
decl.name = toName(node.astName());
updateTypeBits(node.getParent(), decl, false);
setupJavadoc(decl, node);
return set(node, decl);
}
@Override
public boolean visitEnumDeclaration(lombok.ast.EnumDeclaration node) {
FieldDeclaration[] fields = null;
if (node.astBody() != null) {
fields = toArray(FieldDeclaration.class, node.astBody().astConstants());
}
TypeDeclaration decl = createTypeBody(node.astBody().astMembers(), node, true, ClassFileConstants.AccEnum, fields);
decl.annotations = toArray(Annotation.class, node.astModifiers().astAnnotations());
decl.superInterfaces = toArray(TypeReference.class, node.astImplementing());
markTypeReferenceIsSuperType(decl);
decl.name = toName(node.astName());
updateTypeBits(node.getParent(), decl, true);
setupJavadoc(decl, node);
return set(node, decl);
}
@Override
public boolean visitEnumConstant(lombok.ast.EnumConstant node) {
//TODO check where the javadoc and annotations go: the field or the type
FieldDeclaration decl = new FieldDeclaration();
decl.annotations = toArray(Annotation.class, node.astAnnotations());
decl.name = toName(node.astName());
decl.sourceStart = start(node.astName());
decl.sourceEnd = end(node.astName());
decl.declarationSourceStart = decl.modifiersSourceStart = jstart(node);
decl.declarationSourceEnd = decl.declarationEnd = end(node);
AllocationExpression init;
if (node.astBody() == null) {
init = new AllocationExpression();
init.enumConstant = decl;
} else {
TypeDeclaration type = createTypeBody(node.astBody().astMembers(), null, false, 0);
type.sourceStart = type.sourceEnd = start(node.astBody());
type.bodyEnd--;
type.declarationSourceStart = type.sourceStart;
type.declarationSourceEnd = end(node);
type.name = CharOperation.NO_CHAR;
type.bits &= ~ASTNode.IsMemberType;
decl.bits |= ASTNode.HasLocalType;
type.bits |= ASTNode.IsLocalType | ASTNode.IsAnonymousType;
init = new QualifiedAllocationExpression(type);
init.enumConstant = decl;
}
init.arguments = toArray(Expression.class, node.astArguments());
decl.initialization = init;
if (bubblingFlags.remove(BubblingFlags.LOCALTYPE)) {
decl.bits |= ASTNode.HasLocalType;
}
setupJavadoc(decl, node);
return set(node, decl);
}
@Override
public boolean visitAnnotationDeclaration(lombok.ast.AnnotationDeclaration node) {
TypeDeclaration decl = createTypeBody(node.astBody().astMembers(), node, false,
ClassFileConstants.AccAnnotation | ClassFileConstants.AccInterface);
+ decl.annotations = toArray(Annotation.class, node.astModifiers().astAnnotations());
decl.name = toName(node.astName());
updateTypeBits(node.getParent(), decl, false);
setupJavadoc(decl, node);
return set(node, decl);
}
private void setupJavadoc(ASTNode node, lombok.ast.JavadocContainer container) {
if (container != null && container.rawJavadoc() instanceof lombok.ast.Comment) {
lombok.ast.Comment javadoc = (Comment) container.rawJavadoc();
boolean markDep = javadoc.isMarkedDeprecated();
if (node instanceof AbstractMethodDeclaration) {
AbstractMethodDeclaration decl = (AbstractMethodDeclaration) node;
decl.javadoc = (Javadoc) toTree(javadoc);
if (markDep) decl.modifiers |= ClassFileConstants.AccDeprecated;
}
if (node instanceof FieldDeclaration) {
FieldDeclaration decl = (FieldDeclaration) node;
decl.javadoc = (Javadoc) toTree(javadoc);
if (markDep) decl.modifiers |= ClassFileConstants.AccDeprecated;
}
if (node instanceof TypeDeclaration) {
TypeDeclaration decl = (TypeDeclaration) node;
decl.javadoc = (Javadoc) toTree(javadoc);
if (markDep) decl.modifiers |= ClassFileConstants.AccDeprecated;
}
}
}
@Override
public boolean visitConstructorDeclaration(lombok.ast.ConstructorDeclaration node) {
ConstructorDeclaration decl = new ConstructorDeclaration(compilationResult);
decl.bodyStart = start(node.rawBody()) + 1;
decl.bodyEnd = end(node.rawBody()) - 1;
decl.declarationSourceStart = jstart(node);
decl.declarationSourceEnd = end(node);
decl.sourceStart = start(node.astTypeName());
/* set sourceEnd */ {
Position ecjPos = getConversionPositionInfo(node, "signature");
decl.sourceEnd = ecjPos == null ? posOfStructure(node, ")", Integer.MAX_VALUE, true) : ecjPos.getEnd() - 1;
if (!node.rawThrownTypeReferences().isEmpty()) {
decl.sourceEnd = end(node.rawThrownTypeReferences().last());
}
}
decl.annotations = toArray(Annotation.class, node.astModifiers().astAnnotations());
decl.modifiers = toModifiers(node.astModifiers());
decl.typeParameters = toArray(TypeParameter.class, node.astTypeVariables());
decl.arguments = toArray(Argument.class, node.astParameters());
decl.thrownExceptions = toArray(TypeReference.class, node.astThrownTypeReferences());
decl.statements = toArray(Statement.class, node.astBody().astContents());
decl.selector = toName(node.astTypeName());
setupJavadoc(decl, node);
if (decl.statements == null || decl.statements.length == 0 || !(decl.statements[0] instanceof ExplicitConstructorCall)) {
decl.constructorCall = new ExplicitConstructorCall(ExplicitConstructorCall.ImplicitSuper);
decl.constructorCall.sourceStart = decl.sourceStart;
decl.constructorCall.sourceEnd = decl.sourceEnd;
} else {
//TODO check how super() and this() work
decl.constructorCall = (ExplicitConstructorCall)decl.statements[0];
if (decl.statements.length > 1) {
Statement[] newStatements = new Statement[decl.statements.length - 1];
System.arraycopy(decl.statements, 1, newStatements, 0, newStatements.length);
decl.statements = newStatements;
} else {
decl.statements = null;
}
}
if (bubblingFlags.remove(BubblingFlags.LOCALTYPE)) {
decl.bits |= ASTNode.HasLocalType;
}
// Unlike other method(-like) constructs, while ConstructorDeclaration has a
// explicitDeclarations field, its kept at 0, so we don't need to calculate that value here.
if (isUndocumented(node.astBody())) decl.bits |= ASTNode.UndocumentedEmptyBlock;
setupJavadoc(decl, node);
return set(node, decl);
}
@Override
public boolean visitMethodDeclaration(lombok.ast.MethodDeclaration node) {
MethodDeclaration decl = new MethodDeclaration(compilationResult);
decl.declarationSourceStart = jstart(node);
decl.declarationSourceEnd = end(node);
decl.sourceStart = start(node.astMethodName());
boolean setOriginalPosOnType = false;
/* set sourceEnd */ {
Position ecjPos = getConversionPositionInfo(node, "signature");
decl.sourceEnd = ecjPos == null ? posOfStructure(node, ")", Integer.MAX_VALUE, true) : ecjPos.getEnd() - 1;
int postDims = posOfStructure(node, "]", Integer.MAX_VALUE, true);
if (postDims > decl.sourceEnd) {
decl.sourceEnd = postDims;
setOriginalPosOnType = true;
}
if (!node.rawThrownTypeReferences().isEmpty()) {
decl.sourceEnd = end(node.rawThrownTypeReferences().last());
}
}
if (node.rawBody() == null) {
decl.bodyStart = decl.sourceEnd + 1;
decl.bodyEnd = end(node) - 1;
} else {
decl.bodyStart = start(node.rawBody()) + 1;
decl.bodyEnd = end(node.rawBody()) - 1;
}
decl.annotations = toArray(Annotation.class, node.astModifiers().astAnnotations());
decl.modifiers = toModifiers(node.astModifiers());
decl.returnType = (TypeReference) toTree(node.astReturnTypeReference());
if (setOriginalPosOnType) {
if (decl.returnType instanceof ArrayTypeReference) {
((ArrayTypeReference)decl.returnType).originalSourceEnd = end(node.rawReturnTypeReference());
}
}
decl.typeParameters = toArray(TypeParameter.class, node.astTypeVariables());
decl.arguments = toArray(Argument.class, node.astParameters());
decl.selector = toName(node.astMethodName());
decl.thrownExceptions = toArray(TypeReference.class, node.astThrownTypeReferences());
if (node.astBody() == null) {
decl.modifiers |= ExtraCompilerModifiers.AccSemicolonBody;
} else {
decl.statements = toArray(Statement.class, node.astBody().astContents());
if (decl.statements != null) {
for (Statement s : decl.statements) {
if (s instanceof LocalDeclaration) decl.explicitDeclarations++;
}
}
}
if (bubblingFlags.remove(BubblingFlags.LOCALTYPE)) {
decl.bits |= ASTNode.HasLocalType;
}
if (isExplicitlyAbstract(node.astModifiers())) {
bubblingFlags.add(BubblingFlags.ABSTRACT_METHOD);
}
if (isUndocumented(node.astBody())) decl.bits |= ASTNode.UndocumentedEmptyBlock;
setupJavadoc(decl, node);
return set(node, decl);
}
@Override
public boolean visitAnnotationMethodDeclaration(lombok.ast.AnnotationMethodDeclaration node) {
AnnotationMethodDeclaration decl = new AnnotationMethodDeclaration(compilationResult);
decl.modifiers = toModifiers(node.astModifiers()) + ExtraCompilerModifiers.AccSemicolonBody;
decl.declarationSourceStart = jstart(node);
decl.declarationSourceEnd = end(node);
decl.sourceStart = start(node.astMethodName());
boolean setOriginalPosOnType = false;
/* set sourceEnd */ {
Position ecjSigPos = getConversionPositionInfo(node, "signature");
Position ecjExtDimPos = getConversionPositionInfo(node, "extendedDimensions");
if (ecjSigPos != null && ecjExtDimPos != null) {
decl.sourceEnd = ecjSigPos.getEnd() - 1;
decl.extendedDimensions = ecjExtDimPos.getStart();
} else {
decl.sourceEnd = posOfStructure(node, ")", Integer.MAX_VALUE, true);
int postDims = posOfStructure(node, "]", Integer.MAX_VALUE, true);
decl.extendedDimensions = countStructure(node, "]");
if (postDims > decl.sourceEnd) {
decl.sourceEnd = postDims;
setOriginalPosOnType = true;
}
}
}
decl.bodyStart = end(node);
decl.bodyEnd = end(node);
if (node.astDefaultValue() != null) {
decl.modifiers |= ClassFileConstants.AccAnnotationDefault;
}
decl.annotations = toArray(Annotation.class, node.astModifiers().astAnnotations());
decl.defaultValue = toExpression(node.astDefaultValue());
decl.selector = toName(node.astMethodName());
decl.returnType = (TypeReference) toTree(node.astReturnTypeReference());
if (setOriginalPosOnType) {
if (decl.returnType instanceof ArrayTypeReference) {
((ArrayTypeReference)decl.returnType).originalSourceEnd = end(node.rawReturnTypeReference());
}
}
if (isExplicitlyAbstract(node.astModifiers())) {
bubblingFlags.add(BubblingFlags.ABSTRACT_METHOD);
}
return set(node, decl);
}
private TypeDeclaration createTypeBody(lombok.ast.StrictListAccessor<lombok.ast.TypeMember, ?> members, lombok.ast.TypeDeclaration type, boolean canHaveConstructor, int extraModifiers, FieldDeclaration... initialFields) {
TypeDeclaration decl = new TypeDeclaration(compilationResult);
decl.modifiers = (type == null ? 0 : toModifiers(type.astModifiers())) | extraModifiers;
if (members.isEmpty() && isUndocumented(members.owner())) decl.bits |= ASTNode.UndocumentedEmptyBlock;
if (type != null) {
decl.sourceStart = start(type.astName());
decl.sourceEnd = end(type.astName());
decl.declarationSourceStart = jstart(type);
decl.declarationSourceEnd = end(type);
if (!(type instanceof AnnotationDeclaration) || !type.astModifiers().isEmpty() || type.rawJavadoc() != null) {
decl.modifiersSourceStart = jstart(type.astModifiers());
} else {
decl.modifiersSourceStart = -1;
}
}
decl.bodyStart = start(members.owner()) + 1;
decl.bodyEnd = end(members.owner());
boolean hasExplicitConstructor = false;
List<AbstractMethodDeclaration> methods = Lists.newArrayList();
List<FieldDeclaration> fields = Lists.newArrayList();
List<TypeDeclaration> types = Lists.newArrayList();
if (initialFields != null) fields.addAll(Arrays.asList(initialFields));
for (lombok.ast.TypeMember member : members) {
if (member instanceof lombok.ast.ConstructorDeclaration) {
hasExplicitConstructor = true;
AbstractMethodDeclaration method =(AbstractMethodDeclaration)toTree(member);
methods.add(method);
} else if (member instanceof lombok.ast.MethodDeclaration ||
member instanceof lombok.ast.AnnotationMethodDeclaration) {
AbstractMethodDeclaration method =(AbstractMethodDeclaration)toTree(member);
methods.add(method);
} else if (member instanceof lombok.ast.VariableDeclaration) {
for (FieldDeclaration field : toList(FieldDeclaration.class, member)) {
fields.add(field);
}
} else if (member instanceof lombok.ast.StaticInitializer) {
fields.add((FieldDeclaration) toTree(member));
} else if (member instanceof lombok.ast.InstanceInitializer) {
fields.add((FieldDeclaration) toTree(member));
} else if (member instanceof lombok.ast.TypeDeclaration) {
TypeDeclaration innerType = (TypeDeclaration) toTree(member);
//TODO check if you need to do this too for static inners.
if (innerType != null) {
innerType.enclosingType = decl;
types.add(innerType);
}
} else {
throw new RuntimeException("Unhandled member type " + member.getClass().getSimpleName());
}
}
if (!hasExplicitConstructor && canHaveConstructor) {
ConstructorDeclaration defaultConstructor = new ConstructorDeclaration(compilationResult);
defaultConstructor.bits |= ASTNode.IsDefaultConstructor;
defaultConstructor.constructorCall = new ExplicitConstructorCall(ExplicitConstructorCall.ImplicitSuper);
defaultConstructor.modifiers = decl.modifiers & VISIBILITY_MASK;
defaultConstructor.selector = toName(type.astName());
defaultConstructor.sourceStart = defaultConstructor.declarationSourceStart =
defaultConstructor.constructorCall.sourceStart =
start(type.astName());
defaultConstructor.sourceEnd = defaultConstructor.bodyEnd =
defaultConstructor.constructorCall.sourceEnd =
defaultConstructor.declarationSourceEnd =
end(type.astName());
methods.add(0, defaultConstructor);
}
decl.memberTypes = toArray(TypeDeclaration.class, types);
decl.methods = toArray(AbstractMethodDeclaration.class, methods);
decl.fields = toArray(FieldDeclaration.class, fields);
if (bubblingFlags.contains(BubblingFlags.ASSERT)) {
decl.bits |= ASTNode.ContainsAssertion;
}
if (bubblingFlags.remove(BubblingFlags.ABSTRACT_METHOD)) {
decl.bits |= ASTNode.HasAbstractMethods;
}
decl.addClinit();
return decl;
}
@Override
public boolean visitExpressionStatement(lombok.ast.ExpressionStatement node) {
Statement statement = toStatement(node.astExpression());
try {
Field f = statement.getClass().getField("statementEnd");
f.set(statement, end(node));
} catch (Exception ignore) {
// Not all these classes may have a statementEnd.
}
return set(node, statement);
}
@Override
public boolean visitConstructorInvocation(lombok.ast.ConstructorInvocation node) {
AllocationExpression inv;
if (node.astQualifier() != null || node.astAnonymousClassBody() != null) {
if (node.astAnonymousClassBody() != null) {
TypeDeclaration decl = createTypeBody(node.astAnonymousClassBody().astMembers(), null, false, 0);
Position ecjSigPos = getConversionPositionInfo(node, "signature");
decl.sourceStart = ecjSigPos == null ? start(node.rawTypeReference()) : ecjSigPos.getStart();
decl.sourceEnd = ecjSigPos == null ? posOfStructure(node, ")", Integer.MAX_VALUE, false) - 1 : ecjSigPos.getEnd() - 1;
decl.declarationSourceStart = decl.sourceStart;
decl.declarationSourceEnd = end(node);
decl.name = CharOperation.NO_CHAR;
decl.bits |= ASTNode.IsAnonymousType | ASTNode.IsLocalType;
bubblingFlags.add(BubblingFlags.LOCALTYPE);
inv = new QualifiedAllocationExpression(decl);
} else {
inv = new QualifiedAllocationExpression();
}
if (node.astQualifier() != null) {
((QualifiedAllocationExpression)inv).enclosingInstance = toExpression(node.astQualifier());
}
} else {
inv = new AllocationExpression();
}
if (!node.astConstructorTypeArguments().isEmpty()) {
inv.typeArguments = toArray(TypeReference.class, node.astConstructorTypeArguments());
}
inv.type = (TypeReference) toTree(node.astTypeReference());
inv.arguments = toArray(Expression.class, node.astArguments());
inv.sourceStart = start(node);
inv.sourceEnd = end(node);
return set(node, inv);
}
@Override
public boolean visitAlternateConstructorInvocation(lombok.ast.AlternateConstructorInvocation node) {
ExplicitConstructorCall inv = new ExplicitConstructorCall(ExplicitConstructorCall.This);
inv.sourceStart = posOfStructure(node, "this", 0, true);
inv.sourceEnd = end(node);
// inv.modifiers = decl.modifiers & VISIBILITY_MASK;
if (!node.astConstructorTypeArguments().isEmpty()) {
inv.typeArguments = toArray(TypeReference.class, node.astConstructorTypeArguments());
Position ecjTypeArgsPos = getConversionPositionInfo(node, "typeArguments");
inv.typeArgumentsSourceStart = ecjTypeArgsPos == null ? posOfStructure(node, "<", 0, true) : ecjTypeArgsPos.getStart();
}
inv.arguments = toArray(Expression.class, node.astArguments());
return set(node, inv);
}
@Override
public boolean visitSuperConstructorInvocation(lombok.ast.SuperConstructorInvocation node) {
ExplicitConstructorCall inv = new ExplicitConstructorCall(ExplicitConstructorCall.Super);
inv.sourceStart = start(node);
inv.sourceEnd = end(node);
// inv.modifiers = decl.modifiers & VISIBILITY_MASK;
if (!node.astConstructorTypeArguments().isEmpty()) {
inv.typeArguments = toArray(TypeReference.class, node.astConstructorTypeArguments());
Position ecjTypeArgsPos = getConversionPositionInfo(node, "typeArguments");
inv.typeArgumentsSourceStart = ecjTypeArgsPos == null ? posOfStructure(node, "<", 0, true) : ecjTypeArgsPos.getStart();
}
inv.arguments = toArray(Expression.class, node.astArguments());
inv.qualification = toExpression(node.astQualifier());
return set(node, inv);
}
@Override
public boolean visitMethodInvocation(lombok.ast.MethodInvocation node) {
MessageSend inv = new MessageSend();
inv.sourceStart = start(node);
inv.sourceEnd = end(node);
inv.nameSourcePosition = pos(node.astName());
inv.arguments = toArray(Expression.class, node.astArguments());
inv.receiver = toExpression(node.astOperand());
if (inv.receiver instanceof NameReference) {
inv.receiver.bits |= Binding.TYPE;
}
//TODO do we have an implicit this style call somewhere in our test sources?
if (inv.receiver == null) {
inv.receiver = new ThisReference(0, 0);
inv.receiver.bits |= ASTNode.IsImplicitThis;
}
if (!node.astMethodTypeArguments().isEmpty()) inv.typeArguments = toArray(TypeReference.class, node.astMethodTypeArguments());
inv.selector = toName(node.astName());
return set(node, inv);
}
@Override
public boolean visitSuper(lombok.ast.Super node) {
if (node.astQualifier() == null) {
return set(node, new SuperReference(start(node), end(node)));
}
return set(node, new QualifiedSuperReference((TypeReference) toTree(node.astQualifier()), start(node), end(node)));
}
@Override
public boolean visitUnaryExpression(lombok.ast.UnaryExpression node) {
if (node.astOperator() == UnaryOperator.UNARY_MINUS) {
if (node.astOperand() instanceof lombok.ast.IntegralLiteral && node.astOperand().getParens() == 0) {
lombok.ast.IntegralLiteral lit = (lombok.ast.IntegralLiteral)node.astOperand();
if (!lit.astMarkedAsLong() && lit.astIntValue() == Integer.MIN_VALUE) {
IntLiteralMinValue minLiteral = new IntLiteralMinValue();
minLiteral.sourceStart = start(node);
minLiteral.sourceEnd = end(node);
return set(node, minLiteral);
}
if (lit.astMarkedAsLong() && lit.astLongValue() == Long.MIN_VALUE) {
LongLiteralMinValue minLiteral = new LongLiteralMinValue();
minLiteral.sourceStart = start(node);
minLiteral.sourceEnd = end(node);
return set(node, minLiteral);
}
}
}
Expression operand = toExpression(node.astOperand());
int ecjOperator = UNARY_OPERATORS.get(node.astOperator());
switch (node.astOperator()) {
case PREFIX_INCREMENT:
case PREFIX_DECREMENT:
return set(node, new PrefixExpression(operand, IntLiteral.One, ecjOperator, start(node)));
case POSTFIX_INCREMENT:
case POSTFIX_DECREMENT:
return set(node, new PostfixExpression(operand, IntLiteral.One, ecjOperator, end(node)));
default:
UnaryExpression expr = new UnaryExpression(toExpression(node.astOperand()), ecjOperator);
expr.sourceStart = start(node);
expr.sourceEnd = end(node);
return set(node, expr);
}
}
@Override
public boolean visitBinaryExpression(lombok.ast.BinaryExpression node) {
Expression base = visitBinaryExpression0(node);
if (!(base instanceof BinaryExpression)) {
return set(node, base);
}
BinaryExpression binExpr = (BinaryExpression) base;
int op = opForBinaryExpression(binExpr);
if (binExpr.left instanceof BinaryExpression && opForBinaryExpression((BinaryExpression)binExpr.left) == op) {
CombinedBinaryExpression parent = null;
int arity = 0;
Expression newLeft = binExpr.left;
if (binExpr.left instanceof CombinedBinaryExpression) {
parent = (CombinedBinaryExpression) binExpr.left;
arity = parent.arity;
newLeft = new BinaryExpression(parent.left, parent.right, op);
}
CombinedBinaryExpression newBase = new CombinedBinaryExpression(newLeft, binExpr.right, op, 0);
newBase.arity = arity+1;
return set(node, newBase);
}
return set(node, base);
}
private Expression visitBinaryExpression0(lombok.ast.BinaryExpression node) {
Expression lhs = toExpression(node.astLeft());
Expression rhs = toExpression(node.astRight());
if (node.astOperator() == BinaryOperator.ASSIGN) {
return posParen(new Assignment(lhs, rhs, end(node)), node);
}
//TODO add a test with 1 + 2 + 3 + "" + 4 + 5 + 6 + "foo"; as well as 5 + 2 + 3 - 5 - 8 -7 - 8 * 10 + 20;
int ecjOperator = BINARY_OPERATORS.get(node.astOperator());
if (node.astOperator().isAssignment()) {
return posParen(new CompoundAssignment(lhs, rhs, ecjOperator, end(node)), node);
} else if (node.astOperator() == BinaryOperator.EQUALS || node.astOperator() == BinaryOperator.NOT_EQUALS) {
return posParen(new EqualExpression(lhs, rhs, ecjOperator), node);
} else if (node.astOperator() == BinaryOperator.LOGICAL_AND) {
return posParen(new AND_AND_Expression(lhs, rhs, ecjOperator), node);
} else if (node.astOperator() == BinaryOperator.LOGICAL_OR) {
return posParen(new OR_OR_Expression(lhs, rhs, ecjOperator), node);
} else if (node.astOperator() == BinaryOperator.PLUS && node.astLeft().getParens() == 0) {
Expression stringConcatExpr = posParen(tryStringConcat(lhs, rhs), node);
if (stringConcatExpr != null) return stringConcatExpr;
}
return posParen(new BinaryExpression(lhs, rhs, ecjOperator), node);
}
private Expression tryStringConcat(Expression lhs, Expression rhs) {
if (options.parseLiteralExpressionsAsConstants) {
if (lhs instanceof ExtendedStringLiteral) {
if (rhs instanceof CharLiteral) {
return ((ExtendedStringLiteral)lhs).extendWith((CharLiteral)rhs);
} else if (rhs instanceof StringLiteral) {
return ((ExtendedStringLiteral)lhs).extendWith((StringLiteral)rhs);
}
} else if (lhs instanceof StringLiteral) {
if (rhs instanceof CharLiteral) {
return new ExtendedStringLiteral((StringLiteral)lhs, (CharLiteral)rhs);
} else if (rhs instanceof StringLiteral) {
return new ExtendedStringLiteral((StringLiteral)lhs, (StringLiteral)rhs);
}
}
} else {
if (lhs instanceof StringLiteralConcatenation) {
if (rhs instanceof StringLiteral) {
return ((StringLiteralConcatenation)lhs).extendsWith((StringLiteral)rhs);
}
} else if (lhs instanceof StringLiteral) {
if (rhs instanceof StringLiteral) {
return new StringLiteralConcatenation((StringLiteral) lhs, (StringLiteral) rhs);
}
}
}
return null;
}
@Override
public boolean visitCast(lombok.ast.Cast node) {
Expression typeRef = toExpression(node.astTypeReference());
Expression operand = toExpression(node.astOperand());
CastExpression expr = createCastExpression(typeRef, operand);
Position ecjTypePos = getConversionPositionInfo(node, "type");
typeRef.sourceStart = ecjTypePos == null ? posOfStructure(node, "(", 0, true) + 1 : ecjTypePos.getStart();
typeRef.sourceEnd = ecjTypePos == null ? posOfStructure(node, ")", 0, true) - 1 : ecjTypePos.getEnd() - 1;
expr.sourceStart = start(node);
expr.sourceEnd = end(node);
return set(node, expr);
}
@SneakyThrows
private CastExpression createCastExpression(Expression typeRef, Expression operand) {
try {
return (CastExpression) CastExpression.class.getConstructors()[0].newInstance(operand, typeRef);
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
@Override
public boolean visitInstanceOf(lombok.ast.InstanceOf node) {
return set(node, new InstanceOfExpression(toExpression(node.astObjectReference()), (TypeReference) toTree(node.astTypeReference())));
}
@Override
public boolean visitInlineIfExpression(lombok.ast.InlineIfExpression node) {
return set(node, new ConditionalExpression(toExpression(node.astCondition()), toExpression(node.astIfTrue()), toExpression(node.astIfFalse())));
}
@Override
public boolean visitSelect(lombok.ast.Select node) {
//TODO for something like ("" + "").foo.bar;
/* try chain-of-identifiers */ {
List<lombok.ast.Identifier> selects = Lists.newArrayList();
List<Long> pos = Lists.newArrayList();
lombok.ast.Select current = node;
while (true) {
selects.add(current.astIdentifier());
pos.add(pos(current.astIdentifier()));
if (current.astOperand() instanceof lombok.ast.Select) current = (lombok.ast.Select) current.astOperand();
else if (current.astOperand() instanceof lombok.ast.VariableReference) {
selects.add(((lombok.ast.VariableReference) current.astOperand()).astIdentifier());
pos.add(pos(current.rawOperand()));
Collections.reverse(selects);
long[] posArray = new long[pos.size()];
for (int i = 0; i < posArray.length; i++) posArray[i] = pos.get(posArray.length - i - 1);
char[][] tokens = chain(selects, selects.size());
QualifiedNameReference ref = new QualifiedNameReference(tokens, posArray, start(node), end(node));
return set(node, ref);
} else {
break;
}
}
}
FieldReference ref = new FieldReference(toName(node.astIdentifier()), pos(node));
ref.nameSourcePosition = pos(node.astIdentifier());
ref.receiver = toExpression(node.astOperand());
//TODO ("" + 10).a.b = ... DONT forget to doublecheck var/type restriction flags
return set(node, ref);
}
@Override
public boolean visitTypeReference(lombok.ast.TypeReference node) {
// TODO make sure there's a test case that covers every eclipsian type ref: hierarchy on "org.eclipse.jdt.internal.compiler.ast.TypeReference".
Wildcard wildcard = null;
TypeReference ref = null;
switch (node.astWildcard()) {
case UNBOUND:
wildcard = new Wildcard(Wildcard.UNBOUND);
wildcard.sourceStart = start(node);
wildcard.sourceEnd = end(node);
return set(node, wildcard);
case EXTENDS:
wildcard = new Wildcard(Wildcard.EXTENDS);
break;
case SUPER:
wildcard = new Wildcard(Wildcard.SUPER);
break;
}
char[][] qualifiedName = null;
char[] singleName = null;
boolean qualified = node.astParts().size() != 1;
int dims = node.astArrayDimensions();
TypeReference[][] params = new TypeReference[node.astParts().size()][];
boolean hasGenerics = false;
if (!qualified) {
singleName = toName(node.astParts().first().astIdentifier());
} else {
List<lombok.ast.Identifier> identifiers = Lists.newArrayList();
for (lombok.ast.TypeReferencePart part : node.astParts()) identifiers.add(part.astIdentifier());
qualifiedName = chain(identifiers, identifiers.size());
}
{
int ctr = 0;
for (lombok.ast.TypeReferencePart part : node.astParts()) {
params[ctr] = new TypeReference[part.astTypeArguments().size()];
int ctr2 = 0;
boolean partHasGenerics = false;
for (lombok.ast.TypeReference x : part.astTypeArguments()) {
hasGenerics = true;
partHasGenerics = true;
params[ctr][ctr2++] = (TypeReference) toTree(x);
}
if (!partHasGenerics) params[ctr] = null;
ctr++;
}
}
if (!qualified) {
if (!hasGenerics) {
if (dims == 0) {
ref = new SingleTypeReference(singleName, partsToPosArray(node.rawParts())[0]);
} else {
ref = new ArrayTypeReference(singleName, dims, 0L);
ref.sourceStart = start(node);
ref.sourceEnd = end(node);
((ArrayTypeReference)ref).originalSourceEnd = end(node.rawParts().last());
}
} else {
ref = new ParameterizedSingleTypeReference(singleName, params[0], dims, partsToPosArray(node.rawParts())[0]);
if (dims > 0) ref.sourceEnd = end(node);
}
} else {
if (!hasGenerics) {
if (dims == 0) {
long[] pos = partsToPosArray(node.rawParts());
ref = new QualifiedTypeReference(qualifiedName, pos);
} else {
long[] pos = partsToPosArray(node.rawParts());
ref = new ArrayQualifiedTypeReference(qualifiedName, dims, pos);
ref.sourceEnd = end(node);
}
} else {
//TODO test what happens with generic types that also have an array dimension or two.
long[] pos = partsToPosArray(node.rawParts());
ref = new ParameterizedQualifiedTypeReference(qualifiedName, params, dims, pos);
if (dims > 0) ref.sourceEnd = end(node);
}
}
if (wildcard != null) {
wildcard.bound = ref;
ref = wildcard;
ref.sourceStart = start(node);
ref.sourceEnd = wildcard.bound.sourceEnd;
}
return set(node, ref);
}
@Override
public boolean visitTypeVariable(lombok.ast.TypeVariable node) {
// TODO test multiple bounds on a variable, e.g. <T extends A & B & C>
TypeParameter param = new TypeParameter();
param.declarationSourceStart = start(node);
param.declarationSourceEnd = end(node);
param.sourceStart = start(node.astName());
param.sourceEnd = end(node.astName());
param.name = toName(node.astName());
if (!node.astExtending().isEmpty()) {
TypeReference[] p = toArray(TypeReference.class, node.astExtending());
for (TypeReference t : p) t.bits |= ASTNode.IsSuperType;
param.type = p[0];
if (p.length > 1) {
param.bounds = new TypeReference[p.length - 1];
System.arraycopy(p, 1, param.bounds, 0, p.length - 1);
}
param.declarationSourceEnd = p[p.length - 1].sourceEnd;
}
return set(node, param);
}
@Override
public boolean visitStaticInitializer(lombok.ast.StaticInitializer node) {
Initializer init = new Initializer((Block) toTree(node.astBody()), ClassFileConstants.AccStatic);
init.declarationSourceStart = start(node);
init.sourceStart = start(node.astBody());
init.sourceEnd = init.declarationSourceEnd = end(node);
init.bodyStart = init.sourceStart + 1;
init.bodyEnd = init.sourceEnd - 1;
return set(node, init);
}
@Override
public boolean visitInstanceInitializer(lombok.ast.InstanceInitializer node) {
Initializer init = new Initializer((Block) toTree(node.astBody()), 0);
if (bubblingFlags.remove(BubblingFlags.LOCALTYPE)) {
init.bits |= ASTNode.HasLocalType;
}
init.sourceStart = init.declarationSourceStart = start(node);
init.sourceEnd = init.declarationSourceEnd = end(node);
init.bodyStart = init.sourceStart + 1;
init.bodyEnd = init.sourceEnd - 1;
return set(node, init);
}
@Override
public boolean visitIntegralLiteral(lombok.ast.IntegralLiteral node) {
if (node.astMarkedAsLong()) {
return set(node, new LongLiteral(node.rawValue().toCharArray(), start(node), end(node)));
}
return set(node, new IntLiteral(node.rawValue().toCharArray(), start(node), end(node)));
}
@Override
public boolean visitFloatingPointLiteral(lombok.ast.FloatingPointLiteral node) {
if (node.astMarkedAsFloat()) {
return set(node, new FloatLiteral(node.rawValue().toCharArray(), start(node), end(node)));
}
return set(node, new DoubleLiteral(node.rawValue().toCharArray(), start(node), end(node)));
}
@Override
public boolean visitBooleanLiteral(lombok.ast.BooleanLiteral node) {
return set(node, node.astValue() ? new TrueLiteral(start(node), end(node)) : new FalseLiteral(start(node), end(node)));
}
@Override
public boolean visitNullLiteral(lombok.ast.NullLiteral node) {
return set(node, new NullLiteral(start(node), end(node)));
}
@Override
public boolean visitVariableReference(VariableReference node) {
SingleNameReference ref = new SingleNameReference(toName(node.astIdentifier()), pos(node));
return set(node, ref);
}
@Override
public boolean visitIdentifier(lombok.ast.Identifier node) {
SingleNameReference ref = new SingleNameReference(toName(node), pos(node));
return set(node, ref);
}
@Override
public boolean visitCharLiteral(lombok.ast.CharLiteral node) {
return set(node, new CharLiteral(node.rawValue().toCharArray(), start(node), end(node)));
}
@Override
public boolean visitStringLiteral(lombok.ast.StringLiteral node) {
return set(node, new StringLiteral(node.astValue().toCharArray(), start(node), end(node), 0));
}
@Override
public boolean visitBlock(lombok.ast.Block node) {
Block block = new Block(0);
block.statements = toArray(Statement.class, node.astContents());
if (block.statements == null) {
if (isUndocumented(node)) block.bits |= ASTNode.UndocumentedEmptyBlock;
} else {
//TODO test what happens with vardecls in catch blocks and for each loops, as well as for inner blocks.
block.explicitDeclarations = 0;
for (lombok.ast.Statement s : node.astContents()) if (s instanceof lombok.ast.VariableDeclaration) block.explicitDeclarations++;
}
block.sourceStart = start(node);
block.sourceEnd = end(node);
return set(node, block);
}
@Override
public boolean visitAnnotationValueArray(AnnotationValueArray node) {
ArrayInitializer init = new ArrayInitializer();
init.sourceStart = start(node);
init.sourceEnd = end(node);
init.expressions = toArray(Expression.class, node.astValues());
return set(node, init);
}
@Override
public boolean visitArrayInitializer(lombok.ast.ArrayInitializer node) {
ArrayInitializer init = new ArrayInitializer();
init.sourceStart = start(node);
init.sourceEnd = end(node);
init.expressions = toArray(Expression.class, node.astExpressions());
return set(node, init);
}
@Override
public boolean visitArrayCreation(lombok.ast.ArrayCreation node) {
ArrayAllocationExpression aae = new ArrayAllocationExpression();
aae.sourceStart = start(node);
aae.sourceEnd = end(node);
aae.type = (TypeReference) toTree(node.astComponentTypeReference());
// TODO uncompilable parser test: new Type<Generics>[]...
// TODO uncompilable parser test: new Type[][expr][][expr]...
aae.type.bits |= ASTNode.IgnoreRawTypeCheck;
int i = 0;
Expression[] dimensions = new Expression[node.astDimensions().size()];
for (lombok.ast.ArrayDimension dim : node.astDimensions()) {
dimensions[i++] = (Expression) toTree(dim.astDimension());
}
aae.dimensions = dimensions;
aae.initializer = (ArrayInitializer) toTree(node.astInitializer());
return set(node, aae);
}
@Override
public boolean visitArrayDimension(lombok.ast.ArrayDimension node) {
return set(node, toExpression(node.astDimension()));
}
@Override
public boolean visitThis(lombok.ast.This node) {
if (node.astQualifier() == null) {
return set(node, new ThisReference(start(node), end(node)));
}
return set(node, new QualifiedThisReference((TypeReference) toTree(node.astQualifier()), start(node), end(node)));
}
@Override
public boolean visitClassLiteral(lombok.ast.ClassLiteral node) {
return set(node, new ClassLiteralAccess(end(node), (TypeReference) toTree(node.astTypeReference())));
}
@Override
public boolean visitArrayAccess(lombok.ast.ArrayAccess node) {
ArrayReference ref = new ArrayReference(toExpression(node.astOperand()), toExpression(node.astIndexExpression()));
ref.sourceEnd = end(node);
return set(node, ref);
}
@Override
public boolean visitAssert(lombok.ast.Assert node) {
//TODO check the flags after more test have been added: asserts in constructors, methods etc.
bubblingFlags.add(BubblingFlags.ASSERT);
if (node.astMessage() == null) {
return set(node, new AssertStatement(toExpression(node.astAssertion()), start(node)));
}
return set(node, new AssertStatement(toExpression(node.astMessage()), toExpression(node.astAssertion()), start(node)));
}
@Override
public boolean visitDoWhile(lombok.ast.DoWhile node) {
return set(node, new DoStatement(toExpression(node.astCondition()), toStatement(node.astStatement()), start(node), end(node)));
}
@Override
public boolean visitContinue(lombok.ast.Continue node) {
return set(node, new ContinueStatement(toName(node.astLabel()), start(node), end(node)));
}
@Override
public boolean visitBreak(lombok.ast.Break node) {
return set(node, new BreakStatement(toName(node.astLabel()), start(node), end(node)));
}
@Override
public boolean visitForEach(lombok.ast.ForEach node) {
ForeachStatement forEach = new ForeachStatement((LocalDeclaration) toTree(node.astVariable()), start(node));
forEach.sourceEnd = end(node);
forEach.collection = toExpression(node.astIterable());
forEach.action = toStatement(node.astStatement());
return set(node, forEach);
}
@Override
public boolean visitVariableDeclaration(lombok.ast.VariableDeclaration node) {
List<AbstractVariableDeclaration> list = toList(AbstractVariableDeclaration.class, node.astDefinition());
if (list.size() > 0) setupJavadoc(list.get(0), node);
return set(node, list);
}
@Override
public boolean visitVariableDefinition(lombok.ast.VariableDefinition node) {
List<AbstractVariableDeclaration> values = Lists.newArrayList();
Annotation[] annotations = toArray(Annotation.class, node.astModifiers().astAnnotations());
int modifiers = toModifiers(node.astModifiers());
TypeReference base = (TypeReference) toTree(node.astTypeReference());
AbstractVariableDeclaration prevDecl = null, firstDecl = null;
for (lombok.ast.VariableDefinitionEntry entry : node.astVariables()) {
VariableKind kind = VariableKind.kind(node);
AbstractVariableDeclaration decl = kind.create();
decl.annotations = annotations;
decl.initialization = toExpression(entry.astInitializer());
decl.modifiers = modifiers;
decl.name = toName(entry.astName());
if (entry.astArrayDimensions() == 0 && !node.astVarargs()) {
decl.type = base;
} else if (entry.astArrayDimensions() > 0 || node.astVarargs()) {
decl.type = (TypeReference) toTree(entry.getEffectiveTypeReference());
decl.type.sourceStart = base.sourceStart;
Position ecjTypeSourcePos = getConversionPositionInfo(entry, "typeSourcePos");
if (ecjTypeSourcePos != null) {
decl.type.sourceEnd = ecjTypeSourcePos.getEnd() - 1;
} else {
// This makes no sense whatsoever but eclipse wants it this way.
if (firstDecl == null && (base.dimensions() > 0 || node.getParent() instanceof lombok.ast.ForEach)) {
decl.type.sourceEnd = posOfStructure(entry, "]", Integer.MAX_VALUE, false) - 1;
} else if (firstDecl != null) {
// This replicates an eclipse bug; the end pos of the type of b in: int[] a[][], b[]; is in fact the second closing ] of a.
decl.type.sourceEnd = firstDecl.type.sourceEnd;
} else decl.type.sourceEnd = base.sourceEnd;
// Yet another eclipse inconsistency.
if (kind == VariableKind.FIELD && base instanceof ArrayQualifiedTypeReference) {
long[] poss = ((ArrayQualifiedTypeReference)base).sourcePositions;
decl.type.sourceEnd = (int) poss[poss.length - 1];
}
}
if (node.astVarargs()) {
if (decl.type instanceof ArrayTypeReference) {
((ArrayTypeReference)decl.type).originalSourceEnd = decl.type.sourceEnd;
}
Position ecjTyperefPos = getConversionPositionInfo(node, "typeref");
decl.type.sourceEnd = ecjTyperefPos == null ? posOfStructure(node, "...", Integer.MAX_VALUE, false) - 1 : ecjTyperefPos.getEnd() - 1;
} else {
if (decl.type instanceof ArrayTypeReference) {
((ArrayTypeReference)decl.type).originalSourceEnd = decl.type.sourceEnd;
}
if (decl.type instanceof ArrayQualifiedTypeReference) {
((ArrayQualifiedTypeReference)decl.type).sourcePositions = ((QualifiedTypeReference)base).sourcePositions.clone();
}
}
}
if (node.astVarargs()) {
decl.type.bits |= ASTNode.IsVarArgs;
}
if (decl instanceof FieldDeclaration) {
if (bubblingFlags.remove(BubblingFlags.LOCALTYPE)) {
decl.bits |= ASTNode.HasLocalType;
}
}
decl.sourceStart = start(entry.astName());
decl.sourceEnd = end(entry.astName());
decl.declarationSourceStart = jstart(node);
switch (kind) {
case LOCAL:
int end;
if (node.getParent() instanceof lombok.ast.VariableDeclaration) end = end(node.getParent());
else {
if (entry.rawInitializer() != null) end = end(entry.rawInitializer());
else end = end(entry.astName());
}
decl.declarationSourceEnd = decl.declarationEnd = end;
break;
case ARGUMENT:
decl.declarationSourceEnd = decl.declarationEnd = end(entry.astName());
break;
case FIELD:
decl.declarationSourceEnd = decl.declarationEnd = end(node.getParent());
Position ecjPart1Pos = getConversionPositionInfo(entry, "varDeclPart1");
Position ecjPart2Pos = getConversionPositionInfo(entry, "varDeclPart2");
((FieldDeclaration)decl).endPart1Position = ecjPart1Pos == null ? end(node.rawTypeReference()) + 1 : ecjPart1Pos.getEnd() - 1;
((FieldDeclaration)decl).endPart2Position = ecjPart2Pos == null ? end(node.getParent()) : ecjPart2Pos.getEnd() - 1;
if (ecjPart2Pos == null && prevDecl instanceof FieldDeclaration) {
((FieldDeclaration)prevDecl).endPart2Position = start(entry) - 1;
}
break;
}
values.add(decl);
prevDecl = decl;
if (firstDecl == null) firstDecl = decl;
}
return set(node, values);
}
@Override
public boolean visitIf(lombok.ast.If node) {
if (node.astElseStatement() == null) {
return set(node, new IfStatement(toExpression(node.astCondition()), toStatement(node.astStatement()), start(node), end(node)));
}
return set(node, new IfStatement(toExpression(node.astCondition()), toStatement(node.astStatement()), toStatement(node.astElseStatement()), start(node), end(node)));
}
@Override
public boolean visitLabelledStatement(lombok.ast.LabelledStatement node) {
return set(node, new LabeledStatement(toName(node.astLabel()), toStatement(node.astStatement()), pos(node.astLabel()), end(node)));
}
@Override
public boolean visitFor(lombok.ast.For node) {
//TODO make test for modifiers on variable declarations
//TODO make test for empty for/foreach etc.
if(node.isVariableDeclarationBased()) {
return set(node, new ForStatement(toArray(Statement.class, node.astVariableDeclaration()),
toExpression(node.astCondition()),
toArray(Statement.class, node.astUpdates()),
toStatement(node.astStatement()),
true, start(node), end(node)));
}
return set(node, new ForStatement(toArray(Statement.class, node.astExpressionInits()),
toExpression(node.astCondition()),
toArray(Statement.class, node.astUpdates()),
toStatement(node.astStatement()),
false, start(node), end(node)));
}
@Override
public boolean visitSwitch(lombok.ast.Switch node) {
SwitchStatement value = new SwitchStatement();
value.sourceStart = start(node);
value.sourceEnd = end(node);
value.blockStart = start(node.rawBody());
value.expression = toExpression(node.astCondition());
value.statements = toArray(Statement.class, node.astBody().astContents());
if (value.statements == null) {
if (isUndocumented(node.astBody())) value.bits |= ASTNode.UndocumentedEmptyBlock;
} else {
for (Statement s : value.statements) {
if (s instanceof LocalDeclaration) {
value.explicitDeclarations++;
}
}
}
return set(node, value);
}
@Override
public boolean visitSynchronized(lombok.ast.Synchronized node) {
return set(node, new SynchronizedStatement(toExpression(node.astLock()), (Block) toTree(node.astBody()), start(node), end(node)));
}
@Override
public boolean visitTry(lombok.ast.Try node) {
TryStatement tryStatement = new TryStatement();
tryStatement.sourceStart = start(node);
tryStatement.sourceEnd = end(node);
tryStatement.tryBlock = (Block) toTree(node.astBody());
int catchSize = node.astCatches().size();
if (catchSize > 0) {
tryStatement.catchArguments = new Argument[catchSize];
tryStatement.catchBlocks = new Block[catchSize];
int i = 0;
for (lombok.ast.Catch c : node.astCatches()) {
tryStatement.catchArguments[i] = (Argument)toTree(c.astExceptionDeclaration());
tryStatement.catchBlocks[i] = (Block) toTree(c.astBody());
i++;
}
}
tryStatement.finallyBlock = (Block) toTree(node.astFinally());
return set(node, tryStatement);
}
@Override
public boolean visitThrow(lombok.ast.Throw node) {
return set(node, new ThrowStatement(toExpression(node.astThrowable()), start(node), end(node)));
}
@Override
public boolean visitWhile(lombok.ast.While node) {
return set(node, new WhileStatement(toExpression(node.astCondition()), toStatement(node.astStatement()), start(node), end(node)));
}
@Override
public boolean visitReturn(lombok.ast.Return node) {
return set(node, new ReturnStatement(toExpression(node.astValue()), start(node), end(node)));
}
@Override
public boolean visitAnnotation(lombok.ast.Annotation node) {
//TODO add test where the value is the result of string concatenation
TypeReference type = (TypeReference) toTree(node.astAnnotationTypeReference());
boolean isEcjNormal = Position.UNPLACED == getConversionPositionInfo(node, "isNormalAnnotation");
if (node.astElements().isEmpty() && countStructure(node, "(") == 0 && !isEcjNormal) {
MarkerAnnotation ann = new MarkerAnnotation(type, start(node));
ann.declarationSourceEnd = end(node);
return set(node, ann);
}
MemberValuePair[] values = toArray(MemberValuePair.class, node.astElements());
if (values != null && (values.length == 1 && values[0].name == null)) {
SingleMemberAnnotation ann = new SingleMemberAnnotation(type, start(node));
ann.declarationSourceEnd = end(node);
ann.memberValue = values[0].value;
return set(node, ann);
}
NormalAnnotation ann = new NormalAnnotation(type, start(node));
ann.declarationSourceEnd = end(node);
ann.memberValuePairs = values;
return set(node, ann);
}
@Override
public boolean visitAnnotationElement(lombok.ast.AnnotationElement node) {
//TODO make a test where the array initializer is the default value
MemberValuePair pair = new MemberValuePair(toName(node.astName()), start(node), end(node.astName()), null);
// giving the value to the constructor will set the ASTNode.IsAnnotationDefaultValue flag
pair.value = toExpression(node.astValue());
if (pair.name != null && pair.value instanceof ArrayInitializer) {
pair.value.bits |= ASTNode.IsAnnotationDefaultValue;
}
return set(node, pair);
}
@Override
public boolean visitCase(lombok.ast.Case node) {
// end and start args are switched around on CaseStatement, presumably because the API designer was drunk at the time.
return set(node, new CaseStatement(toExpression(node.astCondition()), end(node.rawCondition()), start(node)));
}
@Override
public boolean visitDefault(lombok.ast.Default node) {
// end and start args are switched around on CaseStatement, presumably because the API designer was drunk at the time.
return set(node, new CaseStatement(null, posOfStructure(node, "default", 0, false) - 1, start(node)));
}
@Override
public boolean visitComment(lombok.ast.Comment node) {
if (!node.isJavadoc()) {
throw new RuntimeException("Only javadoc expected here");
}
Node parent = node.getParent();
parent = parent == null ? null : parent.getParent();
while (parent != null && !(parent instanceof lombok.ast.TypeDeclaration)) parent = parent.getParent();
String typeName = null;
if (parent instanceof lombok.ast.TypeDeclaration) {
Identifier identifier = ((lombok.ast.TypeDeclaration)parent).astName();
if (identifier != null) typeName = identifier.astValue();
}
if (typeName == null) {
typeName = getTypeNameFromFileName(compilationResult.getFileName());
}
return set(node, new JustJavadocParser(reporter, typeName).parse(rawInput, node.getPosition().getStart(), node.getPosition().getEnd()));
}
@Override
public boolean visitEmptyStatement(lombok.ast.EmptyStatement node) {
return set(node, new EmptyStatement(start(node), end(node)));
}
@Override
public boolean visitEmptyDeclaration(lombok.ast.EmptyDeclaration node) {
return set(node, (ASTNode)null);
}
private int toModifiers(lombok.ast.Modifiers modifiers) {
return modifiers.getExplicitModifierFlags();
}
@Override
public boolean visitNode(lombok.ast.Node node) {
throw new UnsupportedOperationException(String.format("Unhandled node '%s' (%s)", node, node.getClass().getSimpleName()));
}
private char[][] chain(lombok.ast.StrictListAccessor<lombok.ast.Identifier, ?> parts) {
return chain(parts, parts.size());
}
private char[][] chain(Iterable<lombok.ast.Identifier> parts, int size) {
char[][] c = new char[size][];
int i = 0;
for (lombok.ast.Identifier part : parts) {
c[i++] = part.astValue().toCharArray();
}
return c;
}
private void updateRestrictionFlags(lombok.ast.Node node, NameReference ref) {
ref.bits &= ~ASTNode.RestrictiveFlagMASK;
ref.bits |= Binding.VARIABLE;
if (node.getParent() instanceof lombok.ast.MethodInvocation) {
if (((lombok.ast.MethodInvocation)node.getParent()).astOperand() == node) {
ref.bits |= Binding.TYPE;
}
}
if (node.getParent() instanceof lombok.ast.Select) {
if (((lombok.ast.Select)node.getParent()).astOperand() == node) {
ref.bits |= Binding.TYPE;
}
}
}
// Only works for TypeBody, EnumTypeBody and Block
private boolean isUndocumented(lombok.ast.Node block) {
if (block == null) return false;
if (rawInput == null) return false;
lombok.ast.Position pos = block.getPosition();
if (pos.isUnplaced() || pos.size() < 3) return true;
String content = rawInput.substring(pos.getStart() + 1, pos.getEnd() - 1);
return content.trim().isEmpty();
}
};
private static class JustJavadocParser extends JavadocParser {
private static final char[] GENERIC_JAVA_CLASS_SUFFIX = "class Y{}".toCharArray();
JustJavadocParser(ProblemReporter reporter, String mainTypeName) {
super(makeDummyParser(reporter, mainTypeName));
}
private static Parser makeDummyParser(ProblemReporter reporter, String mainTypeName) {
Parser parser = new Parser(reporter, false);
CompilationResult cr = new CompilationResult((mainTypeName + ".java").toCharArray(), 0, 1, 0);
parser.compilationUnit = new CompilationUnitDeclaration(reporter, cr, 0);
return parser;
}
Javadoc parse(String rawInput, int from, int to) {
char[] rawContent;
rawContent = new char[to + GENERIC_JAVA_CLASS_SUFFIX.length];
Arrays.fill(rawContent, 0, from, ' ');
System.arraycopy(rawInput.substring(from, to).toCharArray(), 0, rawContent, from, to - from);
// Eclipse crashes if there's no character following the javadoc.
System.arraycopy(GENERIC_JAVA_CLASS_SUFFIX, 0, rawContent, to, GENERIC_JAVA_CLASS_SUFFIX.length);
this.sourceLevel = ClassFileConstants.JDK1_6;
this.scanner.setSource(rawContent);
this.source = rawContent;
this.javadocStart = from;
this.javadocEnd = to;
this.reportProblems = false;
this.docComment = new Javadoc(this.javadocStart, this.javadocEnd);
commentParse();
this.docComment.valuePositions = -1;
this.docComment.sourceEnd--;
return docComment;
}
}
private static int jstart(lombok.ast.Node node) {
if (node == null) return 0;
if (node instanceof lombok.ast.JavadocContainer) {
lombok.ast.Node javadoc = ((lombok.ast.JavadocContainer)node).rawJavadoc();
if (javadoc != null) return start(javadoc);
}
if (node instanceof lombok.ast.VariableDefinition && node.getParent() instanceof lombok.ast.VariableDeclaration) {
lombok.ast.Node javadoc = ((lombok.ast.JavadocContainer)node.getParent()).rawJavadoc();
if (javadoc != null) return start(javadoc);
}
if (node instanceof lombok.ast.Modifiers && node.getParent() instanceof JavadocContainer) {
lombok.ast.Node javadoc = ((lombok.ast.JavadocContainer)node.getParent()).rawJavadoc();
if (javadoc != null) return start(javadoc);
}
return start(node);
}
private static int start(lombok.ast.Node node) {
if (node == null || node.getPosition().isUnplaced()) return 0;
return node.getPosition().getStart();
}
private static int end(lombok.ast.Node node) {
if (node == null || node.getPosition().isUnplaced()) return 0;
return node.getPosition().getEnd() - 1;
}
private static long pos(lombok.ast.Node n) {
return (((long)start(n)) << 32) | end(n);
}
private static long[] partsToPosArray(RawListAccessor<?, ?> parts) {
long[] pos = new long[parts.size()];
int idx = 0;
for (lombok.ast.Node n : parts) {
if (n instanceof lombok.ast.TypeReferencePart) {
pos[idx++] = pos(((lombok.ast.TypeReferencePart) n).astIdentifier());
} else {
pos[idx++] = pos(n);
}
}
return pos;
}
private int countStructure(lombok.ast.Node node, String structure) {
int result = 0;
if (sourceStructures != null && sourceStructures.containsKey(node)) {
for (SourceStructure struct : sourceStructures.get(node)) {
if (structure.equals(struct.getContent())) result++;
}
}
return result;
}
private int posOfStructure(lombok.ast.Node node, String structure, int idx, boolean atStart) {
int start = node.getPosition().getStart();
int end = node.getPosition().getEnd();
Integer result = null;
if (sourceStructures != null && sourceStructures.containsKey(node)) {
for (SourceStructure struct : sourceStructures.get(node)) {
if (structure.equals(struct.getContent())) {
result = atStart ? struct.getPosition().getStart() : struct.getPosition().getEnd();
if (idx-- <= 0) break;
}
}
}
if (result != null) return result;
return atStart ? start : end;
}
private static String getTypeNameFromFileName(char[] fileName) {
String f = new String(fileName);
int start = Math.max(f.lastIndexOf('/'), f.lastIndexOf('\\'));
int end = f.lastIndexOf('.');
if (end == -1) end = f.length();
return f.substring(start + 1, end);
}
}
diff --git a/src/javacTransformer/lombok/ast/javac/JcTreePrinter.java b/src/javacTransformer/lombok/ast/javac/JcTreePrinter.java
index 51c6400..0025c26 100644
--- a/src/javacTransformer/lombok/ast/javac/JcTreePrinter.java
+++ b/src/javacTransformer/lombok/ast/javac/JcTreePrinter.java
@@ -1,829 +1,828 @@
/*
* Copyright © 2010 Reinier Zwitserloot and Roel Spilker.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package lombok.ast.javac;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import lombok.ast.StringLiteral;
import com.google.common.collect.MapMaker;
import com.sun.tools.javac.code.BoundKind;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.TypeTags;
import com.sun.tools.javac.main.JavaCompiler;
import com.sun.tools.javac.main.OptionName;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCArrayAccess;
import com.sun.tools.javac.tree.JCTree.JCArrayTypeTree;
import com.sun.tools.javac.tree.JCTree.JCAssert;
import com.sun.tools.javac.tree.JCTree.JCAssign;
import com.sun.tools.javac.tree.JCTree.JCAssignOp;
import com.sun.tools.javac.tree.JCTree.JCBinary;
import com.sun.tools.javac.tree.JCTree.JCBlock;
import com.sun.tools.javac.tree.JCTree.JCBreak;
import com.sun.tools.javac.tree.JCTree.JCCase;
import com.sun.tools.javac.tree.JCTree.JCCatch;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.tree.JCTree.JCConditional;
import com.sun.tools.javac.tree.JCTree.JCContinue;
import com.sun.tools.javac.tree.JCTree.JCDoWhileLoop;
import com.sun.tools.javac.tree.JCTree.JCEnhancedForLoop;
import com.sun.tools.javac.tree.JCTree.JCErroneous;
import com.sun.tools.javac.tree.JCTree.JCExpressionStatement;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
import com.sun.tools.javac.tree.JCTree.JCForLoop;
import com.sun.tools.javac.tree.JCTree.JCIdent;
import com.sun.tools.javac.tree.JCTree.JCIf;
import com.sun.tools.javac.tree.JCTree.JCImport;
import com.sun.tools.javac.tree.JCTree.JCInstanceOf;
import com.sun.tools.javac.tree.JCTree.JCLabeledStatement;
import com.sun.tools.javac.tree.JCTree.JCLiteral;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
import com.sun.tools.javac.tree.JCTree.JCModifiers;
import com.sun.tools.javac.tree.JCTree.JCNewArray;
import com.sun.tools.javac.tree.JCTree.JCNewClass;
import com.sun.tools.javac.tree.JCTree.JCParens;
import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree;
import com.sun.tools.javac.tree.JCTree.JCReturn;
import com.sun.tools.javac.tree.JCTree.JCSkip;
import com.sun.tools.javac.tree.JCTree.JCSwitch;
import com.sun.tools.javac.tree.JCTree.JCSynchronized;
import com.sun.tools.javac.tree.JCTree.JCThrow;
import com.sun.tools.javac.tree.JCTree.JCTry;
import com.sun.tools.javac.tree.JCTree.JCTypeApply;
import com.sun.tools.javac.tree.JCTree.JCTypeCast;
import com.sun.tools.javac.tree.JCTree.JCTypeParameter;
import com.sun.tools.javac.tree.JCTree.JCUnary;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.tree.JCTree.JCWhileLoop;
import com.sun.tools.javac.tree.JCTree.JCWildcard;
import com.sun.tools.javac.tree.JCTree.LetExpr;
import com.sun.tools.javac.tree.JCTree.TypeBoundKind;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Options;
/**
* Diagnostic tool that turns a {@code JCTree} (javac) based tree into a hierarchical dump that should make
* it easy to analyse the exact structure of the AST.
*/
public class JcTreePrinter {
private final StringBuilder output = new StringBuilder();
private final boolean includePositions;
private final boolean includeObjectRefs;
private int indent;
private String rel;
private Map<JCTree, Integer> endPosTable;
private boolean modsOfEnum;
private final Map<Object, Integer> visited = new MapMaker().weakKeys().makeMap();
private int objectCounter = 0;
private static final Method GET_TAG_METHOD;
private static final Field TAG_FIELD;
//TODO Adopt the reflective printer principle used in the EcjTreePrinter. For example, we don't currently know if the type ref is shared or unique amongst
// JCVarDecls that all come from the same line: int[] x, y;
static {
Method m = null;
Field f = null;
try {
m = JCTree.class.getDeclaredMethod("getTag");
} catch (NoSuchMethodException e) {
try {
f = JCTree.class.getDeclaredField("tag");
} catch (NoSuchFieldException e1) {
e1.printStackTrace();
}
}
GET_TAG_METHOD = m;
TAG_FIELD = f;
}
static int getTag(JCTree tree) {
if (GET_TAG_METHOD != null) {
try {
return (Integer) GET_TAG_METHOD.invoke(tree);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getCause());
}
}
try {
return TAG_FIELD.getInt(tree);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public JcTreePrinter(boolean includePositions) {
this.includePositions = includePositions;
this.includeObjectRefs = true;
}
@Override
public String toString() {
return output.toString();
}
public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.out.println("Usage: Supply a file name to print.");
return;
}
Context context = new Context();
Options.instance(context).put(OptionName.ENCODING, "UTF-8");
JavaCompiler compiler = new JavaCompiler(context);
compiler.genEndPos = true;
compiler.keepComments = true;
@SuppressWarnings("deprecation") JCCompilationUnit cu = compiler.parse(args[0]);
JcTreePrinter printer = new JcTreePrinter(true);
printer.visit(cu);
System.out.println(printer);
}
private void printNode(JCTree tree) {
if (tree == null) {
printNode("NULL");
} else {
String suffix = "";
int objId;
Integer backRef = visited.get(tree);
if (backRef == null) {
objId = ++objectCounter;
visited.put(tree, objId);
} else {
objId = backRef;
}
if (includePositions) {
Integer endPos_ = null;
if (endPosTable != null) endPos_ = endPosTable.get(tree);
int endPos = endPos_ == null ? tree.getEndPosition(endPosTable) : endPos_;
int startPos = tree.pos;
if (tree instanceof JCTypeApply || tree instanceof JCWildcard || tree instanceof JCTypeParameter) {
// Javac itself actually has bugs in generating the right endpos. To make sure our tests that compare end pos don't fail,
// as we do set the end pos at the right place, we overwrite it with magic value -2 which means: javac screws this up.
endPos = -2;
}
// When there are no modifiers but an internal flag is set, javac screws up,
// and sets start to the beginning of the node, and end to the last non-whitespace thing before it;
// yes - that would make for negatively sized modifier nodes.
if (tree instanceof JCModifiers && endPos-tree.pos <= 0) {
startPos = -1;
endPos = -1;
}
// The end value of an annotation is end-of-annotation-type in older javac, and end-of-parenslist in new javac.
if (tree instanceof JCAnnotation) {
endPos = -2;
}
// Modifiers of enums never get their position set, but we do set the position.
if (modsOfEnum) {
startPos = -1;
endPos = -1;
modsOfEnum = false;
}
//In rare conditions, the end pos table is filled with a silly value, but start is -1.
if (startPos == -1 && endPos >= 0) endPos = -1;
/*Javac bug: sometimes the startpos of a binary expression is set to the wrong operator.*/ {
if (tree instanceof JCBinary && ((JCBinary)tree).rhs instanceof JCBinary) {
if (getTag(tree) != getTag(((JCBinary)tree).rhs)) {
startPos = -2;
}
}
if (tree instanceof JCBinary && ((JCBinary)tree).rhs instanceof JCInstanceOf) {
startPos = -2;
}
}
/* Javac bug: The end position of a "super.FOO" node which is itself the LHS of a select-like
concept (Select, Method Invocation, etcetera) are set to right after the dot following
it. This doesn't happen with 'this' or anything other than super. */ {
if (tree instanceof JCMethodInvocation) {
JCMethodInvocation invoke = (JCMethodInvocation) tree;
if (invoke.meth instanceof JCFieldAccess && ((JCFieldAccess) invoke.meth).selected instanceof JCIdent) {
JCIdent selected = (JCIdent) ((JCFieldAccess) invoke.meth).selected;
if (selected.name.toString().equals("super")) endPos = -2;
}
}
if (tree instanceof JCFieldAccess && ((JCFieldAccess) tree).selected instanceof JCIdent) {
JCIdent selected = (JCIdent) ((JCFieldAccess) tree).selected;
if (selected.name.toString().equals("super")) endPos = -2;
}
}
-
/* Javac bug: the 'JCAssign' starts at a dot (if present) in the expression instead of at the start of it, which is weird
and inconsistent. */ {
if (tree instanceof JCAssign && ((JCAssign) tree).rhs instanceof JCFieldAccess) {
startPos = -2;
}
}
suffix += String.format("(%d-%d)", startPos, endPos);
}
if (includeObjectRefs) {
suffix += String.format("(id: %d%s)", objId, backRef != null ? " BACKREF" : "");
}
printNode(String.format("%s%s", tree.getClass().getSimpleName(), suffix));
}
}
private void printNode(String nodeKind) {
printIndent();
if (rel != null)
output.append(rel).append(": ");
rel = null;
output.append("[").append(nodeKind).append("]\n");
indent++;
}
private void printIndent() {
for (int i = 0; i < indent; i++) {
output.append("\t");
}
}
private void property(String rel, Object val) {
printIndent();
if (rel != null)
output.append(rel).append(": ");
if (val instanceof JCTree)
output.append("!!JCTree-AS-PROP!!");
if (val == null) {
output.append("[NULL]\n");
} else {
String content;
if (val instanceof String) {
content = new StringLiteral().astValue(val.toString()).rawValue();
} else {
content = String.valueOf(val);
}
output.append("[").append(val.getClass().getSimpleName()).append(" ").append(content).append("]\n");
}
}
private void child(String rel, JCTree node) {
this.rel = rel;
if (node != null) {
node.accept(visitor);
} else {
printNode("NULL");
indent--;
}
}
private void children(String rel, List<? extends JCTree> nodes) {
this.rel = rel;
if (nodes == null) {
;
printNode("LISTNULL");
indent--;
} else if (nodes.isEmpty()) {
printNode("LISTEMPTY");
indent--;
} else {
int i = 0;
for (JCTree node : nodes) {
child(String.format("%s[%d]", rel, i++), node);
}
}
}
public void visit(JCTree tree) {
tree.accept(visitor);
}
private final JCTree.Visitor visitor = new JCTree.Visitor() {
@Override public void visitTopLevel(JCCompilationUnit tree) {
printNode(tree);
endPosTable = tree.endPositions;
child("pid", tree.pid);
children("defs", tree.defs);
indent--;
}
@Override public void visitImport(JCImport tree) {
printNode(tree);
property("staticImport", tree.staticImport);
child("qualid", tree.qualid);
indent--;
}
@Override public void visitClassDef(JCClassDecl tree) {
printNode(tree);
modsOfEnum = (tree.mods != null && (tree.mods.flags & Flags.ENUM) != 0);
child("mods", tree.mods);
property("name", tree.name);
children("typarams", tree.typarams);
child("extends", tree.extending);
children("implementing", tree.implementing);
children("defs", tree.defs);
indent--;
}
@Override public void visitMethodDef(JCMethodDecl tree) {
printNode(tree);
property("name", tree.name);
child("mods", tree.mods);
children("typarams", tree.typarams);
children("params", tree.params);
children("thrown", tree.thrown);
child("default", tree.defaultValue);
child("body", tree.body);
indent--;
}
@Override public void visitVarDef(JCVariableDecl tree) {
printNode(tree);
child("mods", tree.mods);
child("vartype", tree.vartype);
property("name", tree.name);
child("init", tree.init);
indent--;
}
@Override public void visitSkip(JCSkip tree) {
printNode(tree);
indent--;
}
@Override public void visitBlock(JCBlock tree) {
printNode(tree);
property("flags", "0x" + Long.toString(tree.flags, 0x10));
children("stats", tree.stats);
indent--;
}
@Override public void visitDoLoop(JCDoWhileLoop tree) {
printNode(tree);
child("body", tree.body);
child("cond", tree.cond);
indent--;
}
@Override public void visitWhileLoop(JCWhileLoop tree) {
printNode(tree);
child("cond", tree.cond);
child("body", tree.body);
indent--;
}
@Override public void visitForLoop(JCForLoop tree) {
printNode(tree);
children("init", tree.init);
child("cond", tree.cond);
children("step", tree.step);
child("body", tree.body);
indent--;
}
@Override public void visitForeachLoop(JCEnhancedForLoop tree) {
printNode(tree);
child("var", tree.var);
child("expr", tree.expr);
child("body", tree.body);
indent--;
}
@Override public void visitLabelled(JCLabeledStatement tree) {
printNode(tree);
property("label", tree.label);
child("body", tree.body);
indent--;
}
@Override public void visitSwitch(JCSwitch tree) {
printNode(tree);
child("selector", tree.selector);
children("cases", tree.cases);
indent--;
}
@Override public void visitCase(JCCase tree) {
printNode(tree);
child("pat", tree.pat);
children("stats", tree.stats);
indent--;
}
@Override public void visitSynchronized(JCSynchronized tree) {
printNode(tree);
child("lock", tree.lock);
child("body", tree.body);
indent--;
}
@Override public void visitTry(JCTry tree) {
printNode(tree);
child("body", tree.body);
children("catchers", tree.catchers);
child("finalizer", tree.finalizer);
indent--;
}
@Override public void visitCatch(JCCatch tree) {
printNode(tree);
child("param", tree.param);
child("body", tree.body);
indent--;
}
@Override public void visitConditional(JCConditional tree) {
printNode(tree);
child("cond", tree.cond);
child("truepart", tree.truepart);
child("falsepart", tree.falsepart);
indent--;
}
@Override public void visitIf(JCIf tree) {
printNode(tree);
child("cond", tree.cond);
child("thenpart", tree.thenpart);
child("elsepart", tree.elsepart);
indent--;
}
@Override public void visitExec(JCExpressionStatement tree) {
printNode(tree);
child("expr", tree.expr);
indent--;
}
@Override public void visitBreak(JCBreak tree) {
printNode(tree);
property("label", tree.label);
indent--;
}
@Override public void visitContinue(JCContinue tree) {
printNode(tree);
property("label", tree.label);
indent--;
}
@Override public void visitReturn(JCReturn tree) {
printNode(tree);
child("expr", tree.expr);
indent--;
}
@Override public void visitThrow(JCThrow tree) {
printNode(tree);
child("expr", tree.expr);
indent--;
}
@Override public void visitAssert(JCAssert tree) {
printNode(tree);
child("cond", tree.cond);
child("detail", tree.detail);
indent--;
}
@Override public void visitApply(JCMethodInvocation tree) {
printNode(tree);
children("typeargs", tree.typeargs);
child("meth", tree.meth);
children("args", tree.args);
indent--;
}
@Override public void visitNewClass(JCNewClass tree) {
printNode(tree);
child("encl", tree.encl);
children("typeargs", tree.typeargs);
child("clazz", tree.clazz);
children("args", tree.args);
child("def", tree.def);
indent--;
}
@Override public void visitNewArray(JCNewArray tree) {
printNode(tree);
child("elemtype", tree.elemtype);
children("dims", tree.dims);
children("elems", tree.elems);
indent--;
}
@Override public void visitParens(JCParens tree) {
printNode(tree);
child("expr", tree.expr);
indent--;
}
@Override public void visitAssign(JCAssign tree) {
printNode(tree);
child("lhs", tree.lhs);
child("rhs", tree.rhs);
indent--;
}
public String operatorName(int tag) {
switch (tag) {
case JCTree.POS:
return "+";
case JCTree.NEG:
return "-";
case JCTree.NOT:
return "!";
case JCTree.COMPL:
return "~";
case JCTree.PREINC:
return "++X";
case JCTree.PREDEC:
return "--X";
case JCTree.POSTINC:
return "X++";
case JCTree.POSTDEC:
return "X--";
case JCTree.NULLCHK:
return "<*nullchk*>";
case JCTree.OR:
return "||";
case JCTree.AND:
return "&&";
case JCTree.EQ:
return "==";
case JCTree.NE:
return "!=";
case JCTree.LT:
return "<";
case JCTree.GT:
return ">";
case JCTree.LE:
return "<=";
case JCTree.GE:
return ">=";
case JCTree.BITOR:
return "|";
case JCTree.BITXOR:
return "^";
case JCTree.BITAND:
return "&";
case JCTree.SL:
return "<<";
case JCTree.SR:
return ">>";
case JCTree.USR:
return ">>>";
case JCTree.PLUS:
return "+";
case JCTree.MINUS:
return "-";
case JCTree.MUL:
return "*";
case JCTree.DIV:
return "/";
case JCTree.MOD:
return "%";
case JCTree.PLUS_ASG:
return "+=";
case JCTree.MINUS_ASG:
return "-=";
case JCTree.MUL_ASG:
return "*=";
case JCTree.DIV_ASG:
return "/=";
case JCTree.MOD_ASG:
return "%=";
case JCTree.BITAND_ASG:
return "&=";
case JCTree.BITXOR_ASG:
return "^=";
case JCTree.BITOR_ASG:
return "|=";
case JCTree.SL_ASG:
return "<<=";
case JCTree.SR_ASG:
return ">>=";
case JCTree.USR_ASG:
return ">>>=";
case JCTree.TYPETEST:
return "instanceof";
default:
throw new Error("Unexpected operator: " + tag);
}
}
@Override public void visitAssignop(JCAssignOp tree) {
printNode(tree);
child("lhs", tree.lhs);
property("(operator)", operatorName(getTag(tree) - JCTree.ASGOffset) + "=");
child("rhs", tree.rhs);
indent--;
}
@Override public void visitUnary(JCUnary tree) {
printNode(tree);
child("arg", tree.arg);
property("(operator)", operatorName(getTag(tree)));
indent--;
}
@Override public void visitBinary(JCBinary tree) {
printNode(tree);
child("lhs", tree.lhs);
property("(operator)", operatorName(getTag(tree)));
child("rhs", tree.rhs);
indent--;
}
@Override public void visitTypeCast(JCTypeCast tree) {
printNode(tree);
child("clazz", tree.clazz);
child("expr", tree.expr);
indent--;
}
@Override public void visitTypeTest(JCInstanceOf tree) {
printNode(tree);
child("expr", tree.expr);
child("clazz", tree.clazz);
indent--;
}
@Override public void visitIndexed(JCArrayAccess tree) {
printNode(tree);
child("indexed", tree.indexed);
child("index", tree.index);
indent--;
}
@Override public void visitSelect(JCFieldAccess tree) {
printNode(tree);
child("selected", tree.selected);
property("name", tree.name);
indent--;
}
@Override public void visitIdent(JCIdent tree) {
printNode(tree);
property("name", tree.name);
indent--;
}
public String literalName(int typeTag) {
switch (typeTag) {
case TypeTags.BYTE:
return "BYTE";
case TypeTags.SHORT:
return "SHORT";
case TypeTags.INT:
return "INT";
case TypeTags.LONG:
return "LONG";
case TypeTags.FLOAT:
return "FLOAT";
case TypeTags.DOUBLE:
return "DOUBLE";
case TypeTags.CHAR:
return "CHAR";
case TypeTags.BOOLEAN:
return "BOOLEAN";
case TypeTags.VOID:
return "VOID";
case TypeTags.CLASS:
return "CLASS/STRING";
case TypeTags.BOT:
return "BOT";
default:
return "ERROR(" + typeTag + ")";
}
}
@Override public void visitLiteral(JCLiteral tree) {
printNode(tree);
property("typetag", literalName(tree.typetag));
property("value", tree.value);
indent--;
}
@Override public void visitTypeIdent(JCPrimitiveTypeTree tree) {
printNode(tree);
property("typetag", literalName(tree.typetag));
indent--;
}
@Override public void visitTypeArray(JCArrayTypeTree tree) {
printNode(tree);
child("elemtype", tree.elemtype);
indent--;
}
@Override public void visitTypeApply(JCTypeApply tree) {
printNode(tree);
child("clazz", tree.clazz);
children("arguments", tree.arguments);
indent--;
}
@Override public void visitTypeParameter(JCTypeParameter tree) {
printNode(tree);
property("name", tree.name);
children("bounds", tree.bounds);
indent--;
}
@Override public void visitWildcard(JCWildcard tree) {
printNode(tree);
Object o;
// In some javacs (older ones), JCWildcard.kind is a BoundKind, which is an enum. In newer ones its a TypeBoundKind which is a JCTree, i.e. has positions.
try {
o = tree.getClass().getField("kind").get(tree);
} catch (Exception e) {
throw new RuntimeException("There's no field at all named 'kind' in JCWildcard? This is not a javac I understand.", e);
}
if (o instanceof JCTree) {
child("kind", (JCTree)o);
} else if (o instanceof BoundKind) {
property("kind", String.valueOf(o));
}
child("inner", tree.inner);
indent--;
}
// In older javacs this method does not exist, so no @Override here
public void visitTypeBoundKind(TypeBoundKind tree) {
printNode(tree);
property("kind", String.valueOf(tree.kind));
indent--;
}
@Override public void visitErroneous(JCErroneous tree) {
printNode(tree);
children("errs", tree.errs);
indent--;
}
@Override public void visitLetExpr(LetExpr tree) {
printNode(tree);
children("defs", tree.defs);
child("expr", tree.expr);
indent--;
}
@Override public void visitModifiers(JCModifiers tree) {
printNode(tree);
children("annotations", tree.annotations);
property("flags", "0x" + Long.toString(tree.flags, 0x10));
indent--;
}
@Override public void visitAnnotation(JCAnnotation tree) {
printNode(tree);
child("annotationType", tree.annotationType);
children("args", tree.args);
indent--;
}
@Override public void visitTree(JCTree tree) {
String typeName = tree == null ? "NULL" : tree.getClass().getSimpleName();
printNode("UNKNOWN(" + typeName + ")");
indent--;
}
};
}
diff --git a/test/resources/alias/H003_Annotations.java b/test/resources/alias/H003_Annotations.java
index 37a2b42..d4795c5 100644
--- a/test/resources/alias/H003_Annotations.java
+++ b/test/resources/alias/H003_Annotations.java
@@ -1,15 +1,16 @@
public @ interface H003_Annotations {
int value() default 10;
}
+@ java . lang.annotation.Target ( java.lang.annotation.ElementType . TYPE )
@ interface ComplexAnnotation {
int x = 10;
String v1()[];
Class<?> clazz() default Object.class;
public abstract H003_Annotations ann();
String v2 ( ) [ ] default { "a" , "b" , "c" } ;
}
\ No newline at end of file
diff --git a/test/resources/idempotency/H003_Annotations.java b/test/resources/idempotency/H003_Annotations.java
index 213e802..06ebbc0 100644
--- a/test/resources/idempotency/H003_Annotations.java
+++ b/test/resources/idempotency/H003_Annotations.java
@@ -1,15 +1,16 @@
public @interface H003_Annotations {
int value() default 10;
}
[email protected](java.lang.annotation.ElementType.TYPE)
@interface ComplexAnnotation {
int x = 10;
String[] v1();
Class<?> clazz() default Object.class;
public abstract H003_Annotations ann();
String[] v2() default {"a", "b", "c"};
}
\ No newline at end of file
| false | false | null | null |
diff --git a/sql12/app/src/net/sourceforge/squirrel_sql/client/session/Session.java b/sql12/app/src/net/sourceforge/squirrel_sql/client/session/Session.java
index 4a0265038..7e0ece3aa 100755
--- a/sql12/app/src/net/sourceforge/squirrel_sql/client/session/Session.java
+++ b/sql12/app/src/net/sourceforge/squirrel_sql/client/session/Session.java
@@ -1,710 +1,718 @@
package net.sourceforge.squirrel_sql.client.session;
/*
* Copyright (C) 2001-2003 Colin Bell
* [email protected]
*
* Modifications copyright (C) 2001 Johan Compagner
* [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.event.EventListenerList;
import net.sourceforge.squirrel_sql.fw.id.IIdentifier;
import net.sourceforge.squirrel_sql.fw.sql.ISQLAlias;
import net.sourceforge.squirrel_sql.fw.sql.ISQLDriver;
import net.sourceforge.squirrel_sql.fw.sql.SQLConnection;
import net.sourceforge.squirrel_sql.fw.sql.SQLConnectionState;
import net.sourceforge.squirrel_sql.fw.util.BaseException;
import net.sourceforge.squirrel_sql.fw.util.IMessageHandler;
import net.sourceforge.squirrel_sql.fw.util.NullMessageHandler;
import net.sourceforge.squirrel_sql.fw.util.StringManager;
import net.sourceforge.squirrel_sql.fw.util.StringManagerFactory;
import net.sourceforge.squirrel_sql.fw.util.log.ILogger;
import net.sourceforge.squirrel_sql.fw.util.log.LoggerController;
import net.sourceforge.squirrel_sql.client.IApplication;
import net.sourceforge.squirrel_sql.client.mainframe.action.OpenConnectionCommand;
import net.sourceforge.squirrel_sql.client.plugin.IPlugin;
import net.sourceforge.squirrel_sql.client.session.event.ISessionListener;
import net.sourceforge.squirrel_sql.client.session.event.SessionEvent;
import net.sourceforge.squirrel_sql.client.session.mainpanel.IMainPanelTab;
import net.sourceforge.squirrel_sql.client.session.mainpanel.objecttree.ObjectTreePanel;
import net.sourceforge.squirrel_sql.client.session.properties.SessionProperties;
import net.sourceforge.squirrel_sql.client.session.sqlfilter.SQLFilterClauses;
import net.sourceforge.squirrel_sql.client.session.parser.ParserEventsProcessor;
import net.sourceforge.squirrel_sql.client.session.parser.IParserEventsProcessor;
import net.sourceforge.squirrel_sql.client.util.IdentifierFactory;
/**
* Think of a session as being the users view of the database. IE it includes
* the database connetion and the UI.
*
* @author <A HREF="mailto:[email protected]">Colin Bell</A>
*/
class Session implements ISession
{
/** Logger for this class. */
private static final ILogger s_log =
LoggerController.createLogger(Session.class);
/** Internationalized strings for this class. */
private static final StringManager s_stringMgr =
StringManagerFactory.getStringManager(Session.class);
/** Descriptive title for session. */
private String _title = "";
private SessionSheet _sessionSheet;
/** The <TT>IIdentifier</TT> that uniquely identifies this object. */
private IIdentifier _id = IdentifierFactory.getInstance().createIdentifier();
/** Application API. */
private IApplication _app;
/** Connection to database. */
private SQLConnection _conn;
/** Driver used to connect to database. */
private ISQLDriver _driver;
/** Alias describing how to connect to database. */
private ISQLAlias _alias;
private final String _user;
private final String _password;
/** Properties for this session. */
private SessionProperties _props;
private SQLFilterClauses _sqlFilterClauses;
/**
* Objects stored in session. Each entry is a <TT>Map</TT>
* keyed by <TT>IPlugin.getInternalName()</TT>. Each <TT>Map</TT>
* contains the objects saved for the plugin.
*/
private final Map _pluginObjects = new HashMap();
private IMessageHandler _msgHandler = NullMessageHandler.getInstance();
/** API for the object tree. */
private final IObjectTreeAPI _objectTreeAPI;
/** API object for the SQL panel. */
private final ISQLPanelAPI _sqlPanelAPI;
/** Xref info about the current connection. */
private final SchemaInfo _defaultSchemaInfo = new SchemaInfo();
private final Hashtable _schemaInfosByCatalogAndSchema = new Hashtable();
/** Set to <TT>true</TT> once session closed. */
private boolean _closed;
/**
* Collection of listeners to this object tree.
*/
private EventListenerList _listenerList = new EventListenerList();
private List _statusBarToBeAdded = new ArrayList();
private ParserEventsProcessor _parserEventsProcessor;
/**
* Create a new session.
*
* @param app Application API.
* @param driver JDBC driver for session.
* @param alias Defines URL to database.
* @param conn Connection to database.
* @param user User name connected with.
* @param password Password for <TT>user</TT>
*
* @throws IllegalArgumentException if any parameter is null.
*/
public Session(IApplication app, ISQLDriver driver, ISQLAlias alias,
SQLConnection conn, String user, String password)
{
super();
if (app == null)
{
throw new IllegalArgumentException("null IApplication passed");
}
if (driver == null)
{
throw new IllegalArgumentException("null ISQLDriver passed");
}
if (alias == null)
{
throw new IllegalArgumentException("null ISQLAlias passed");
}
if (conn == null)
{
throw new IllegalArgumentException("null SQLConnection passed");
}
_app = app;
_driver = driver;
_alias = alias;
_conn = conn;
_user = user;
_password = password;
_title = createTitle();
_props = (SessionProperties)_app.getSquirrelPreferences().getSessionProperties().clone();
_sqlFilterClauses = new SQLFilterClauses();
// Create the API objects that give access to various
// areas of the session.
_objectTreeAPI = new ObjectTreeAPI(this);
_sqlPanelAPI = new SQLPanelAPI(this);
_parserEventsProcessor = new ParserEventsProcessor(this);
// Start loading table/column info about the current database.
_app.getThreadPool().addTask(new Runnable()
{
public void run()
{
loadTableInfo();
}
});
}
/**
* Close this session.
*
* @throws SQLException
* Thrown if an error closing the SQL connection. The session
* will still be closed even though the connection may not have
* been.
*/
public void close() throws SQLException
{
if (!_closed)
{
s_log.debug("Closing session: " + _id);
try
{
_parserEventsProcessor.endProcessing();
}
catch(Exception e)
{
s_log.info("Error stopping parser event processor", e);
}
try
{
closeSQLConnection();
}
finally
{
// This is set here as SessionSheet.dispose() will attempt
// to close the session.
_closed = true;
fireSessionClosedEvent();
// Remove all listeners.
_listenerList = null;
if (_sessionSheet != null)
{
_sessionSheet.sessionHasClosed();
_sessionSheet = null;
}
}
s_log.debug("Successfully closed session: " + _id);
}
}
/**
* Return the unique identifier for this session.
*
* @return the unique identifier for this session.
*/
public IIdentifier getIdentifier()
{
return _id;
}
/**
* Retrieve whether this session has been closed.
*
* @return <TT>true</TT> if session closed else <TT>false</TT>.
*/
public boolean isClosed()
{
return _closed;
}
/**
* Return the Application API object.
*
* @return the Application API object.
*/
public IApplication getApplication()
{
return _app;
}
/**
* @return <TT>SQLConnection</TT> for this session.
*/
public SQLConnection getSQLConnection()
{
return _conn;
}
/**
* @return <TT>ISQLDriver</TT> for this session.
*/
public ISQLDriver getDriver()
{
return _driver;
}
/**
* @return <TT>ISQLAlias</TT> for this session.
*/
public ISQLAlias getAlias()
{
return _alias;
}
public SessionProperties getProperties()
{
return _props;
}
/**
* Retrieve the schema information object for this session.
*/
public SchemaInfo getSchemaInfo()
{
return _defaultSchemaInfo;
}
public SchemaInfo getSchemaInfo(String catalogName, String schemaName)
{
String key = catalogName + "," + schemaName;
SchemaInfo ret = (SchemaInfo) _schemaInfosByCatalogAndSchema.get(key);
if(null == ret)
{
ret = new SchemaInfo(getSQLConnection(), catalogName, schemaName);
_schemaInfosByCatalogAndSchema.put(key, ret);
}
return ret;
}
/**
* Return the API for the Object Tree.
*
* @param plugin Plugin requesting the API.
*
* @return the API object for the Object Tree.
*
* @throws IllegalArgumentException
* Thrown if null IPlugin passed.
*/
public IObjectTreeAPI getObjectTreeAPI(IPlugin plugin)
{
if (plugin == null)
{
throw new IllegalArgumentException("IPlugin == null");
}
return _objectTreeAPI;
}
/**
* Return the API object for the SQL panel.
*
* @param plugin Plugin requesting the API.
*
* @return the API object for the SQL panel.
*
* @throws IllegalArgumentException
* Thrown if null IPlugin passed.
*/
public ISQLPanelAPI getSQLPanelAPI(IPlugin plugin)
{
if (plugin == null)
{
throw new IllegalArgumentException("IPlugin == null");
}
return _sqlPanelAPI;
}
public synchronized Object getPluginObject(IPlugin plugin, String key)
{
if (plugin == null)
{
throw new IllegalArgumentException("Null IPlugin passed");
}
if (key == null)
{
throw new IllegalArgumentException("Null key passed");
}
Map map = (Map) _pluginObjects.get(plugin.getInternalName());
if (map == null)
{
map = new HashMap();
_pluginObjects.put(plugin.getInternalName(), map);
}
return map.get(key);
}
/**
* Add a listener to this session
*
* @param lis The listener to add.
*
* @throws IllegalArgumentException
* Thrown if a <TT>null</TT> listener passed.
*/
public void addSessionListener(ISessionListener lis)
{
_listenerList.add(ISessionListener.class, lis);
}
/**
* Remove a listener from this session
*
* @param lis The listener to remove.
*
* @throws IllegalArgumentException
* Thrown if a <TT>null</TT> listener passed.
*/
public void removeSessionListener(ISessionListener lis)
{
_listenerList.remove(ISessionListener.class, lis);
}
/**
* Add the passed action to the session toolbar.
*
* @param action Action to be added.
*/
public void addToToolbar(Action action)
{
_sessionSheet.addToToolbar(action);
}
public synchronized Object putPluginObject(IPlugin plugin, String key,
Object value)
{
if (plugin == null)
{
throw new IllegalArgumentException("Null IPlugin passed");
}
if (key == null)
{
throw new IllegalArgumentException("Null key passed");
}
Map map = (Map) _pluginObjects.get(plugin.getInternalName());
if (map == null)
{
map = new HashMap();
_pluginObjects.put(plugin.getInternalName(), map);
}
return map.put(key, value);
}
public synchronized void removePluginObject(IPlugin plugin, String key)
{
if (plugin == null)
{
throw new IllegalArgumentException("Null IPlugin passed");
}
if (key == null)
{
throw new IllegalArgumentException("Null key passed");
}
Map map = (Map) _pluginObjects.get(plugin.getInternalName());
if (map != null)
{
map.remove(key);
}
}
/**
* Return the object that handles the SQL entry
* component.
*
* @return <TT>ISQLEntryPanel</TT> object.
*/
public ISQLEntryPanel getSQLEntryPanel()
{
+ if (null == _sessionSheet)
+ {
+ return null;
+ }
return _sessionSheet.getSQLEntryPanel();
}
public ObjectTreePanel getObjectTreePanel()
{
+ if (null == _sessionSheet)
+ {
+ return null;
+ }
return _sessionSheet.getObjectTreePanel();
}
public synchronized void closeSQLConnection() throws SQLException
{
if (_conn != null)
{
try
{
_conn.close();
}
finally
{
_conn = null;
}
}
}
/**
* Reconnect to the database.
*/
public void reconnect()
{
SQLConnectionState connState = null;
if (_conn != null)
{
connState = new SQLConnectionState();
try
{
connState.saveState(_conn, _msgHandler);
}
catch (SQLException ex)
{
s_log.error("Unexpected SQLException", ex);
}
}
OpenConnectionCommand cmd = new OpenConnectionCommand(_app, _alias,
_user, _password, connState.getConnectionProperties());
try
{
closeSQLConnection();
}
catch (SQLException ex)
{
final String msg = s_stringMgr.getString("Session.error.connclose");
s_log.error(msg, ex);
_msgHandler.showErrorMessage(msg);
_msgHandler.showErrorMessage(ex);
}
try
{
cmd.execute();
_conn = cmd.getSQLConnection();
if (connState != null)
{
connState.restoreState(_conn, _msgHandler);
}
final String msg = s_stringMgr.getString("Session.reconn", _alias.getName());
_msgHandler.showMessage(msg);
getObjectTreeAPI(_app.getDummyAppPlugin()).refreshTree();
}
catch (SQLException ex)
{
_msgHandler.showErrorMessage(ex);
}
catch (BaseException ex)
{
_msgHandler.showErrorMessage(ex);
}
}
public IMessageHandler getMessageHandler()
{
return _msgHandler;
}
public void setMessageHandler(IMessageHandler handler)
{
_msgHandler = handler != null ? handler : NullMessageHandler.getInstance();
}
public synchronized void setSessionSheet(SessionSheet child)
{
_sessionSheet = child;
if (_sessionSheet != null)
{
final ListIterator it = _statusBarToBeAdded.listIterator();
while (it.hasNext())
{
addToStatusBar((JComponent)it.next());
it.remove();
}
}
}
public SessionSheet getSessionSheet()
{
return _sessionSheet;
}
/**
* Select a tab in the main tabbed pane.
*
* @param tabIndex The tab to select. @see ISession.IMainTabIndexes
*
* @throws IllegalArgumentException
* Thrown if an invalid <TT>tabId</TT> passed.
*/
public void selectMainTab(int tabIndex)
{
_sessionSheet.selectMainTab(tabIndex);
}
/**
* Add a tab to the main tabbed panel.
*
* @param tab The tab to be added.
*
* @throws IllegalArgumentException
* Thrown if a <TT>null</TT> <TT>IMainPanelTab</TT> passed.
*/
public void addMainTab(IMainPanelTab tab)
{
_sessionSheet.addMainTab(tab);
}
/**
* Add component to the session sheets status bar.
*
* @param comp Component to add.
*/
public synchronized void addToStatusBar(JComponent comp)
{
if (_sessionSheet != null)
{
_sessionSheet.addToStatusBar(comp);
}
else
{
_statusBarToBeAdded.add(comp);
}
}
/**
* Remove component from the session sheets status bar.
*
* @param comp Component to remove.
*/
public synchronized void removeFromStatusBar(JComponent comp)
{
if (_sessionSheet != null)
{
_sessionSheet.removeFromStatusBar(comp);
}
else
{
_statusBarToBeAdded.remove(comp);
}
}
public SQLFilterClauses getSQLFilterClauses()
{
return _sqlFilterClauses;
}
/**
* Retrieve the descriptive title of this session.
*
* @return The descriptive title of this session.
*/
public String getTitle()
{
return _title;
}
/**
* Fire a "session closed" event.
*/
protected void fireSessionClosedEvent()
{
Object[] listeners = _listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event.
SessionEvent evt = null;
for (int i = listeners.length - 2; i >= 0; i-=2 )
{
if (listeners[i] == ISessionListener.class)
{
// Lazily create the event.
if (evt == null)
{
evt = new SessionEvent(this);
}
((ISessionListener)listeners[i + 1]).sessionClosed(evt);
}
}
}
/**
* Set the descriptive title for this session.
*
* @param title The descriptive title for this session.
*/
void setTitle(String value)
{
_title = value != null ? value : "";
}
/**
* Load table information about the current database.
*/
private void loadTableInfo()
{
_defaultSchemaInfo.load(getSQLConnection());
}
// TODO: i18n
private String createTitle()
{
final StringBuffer title = new StringBuffer();
title.append(getAlias().getName());
String user = null;
try
{
user = getSQLConnection().getSQLMetaData().getUserName();
}
catch (SQLException ex)
{
s_log.error("Error occured retrieving user name from Connection", ex);
}
if (user != null && user.length() > 0)
{
title.append(" as ").append(user); // i18n
}
return title.toString();
}
public IParserEventsProcessor getParserEventsProcessor()
{
return _parserEventsProcessor;
}
}
| false | false | null | null |
diff --git a/apps/test/app/controllers/popups/PopupPersonaSolicitantePersonaJuridicaJuridicaTablaController.java b/apps/test/app/controllers/popups/PopupPersonaSolicitantePersonaJuridicaJuridicaTablaController.java
new file mode 100644
index 00000000..081e39fe
--- /dev/null
+++ b/apps/test/app/controllers/popups/PopupPersonaSolicitantePersonaJuridicaJuridicaTablaController.java
@@ -0,0 +1,9 @@
+
+package controllers.popups;
+
+import controllers.gen.popups.PopupPersonaSolicitantePersonaJuridicaJuridicaTablaControllerGen;
+
+public class PopupPersonaSolicitantePersonaJuridicaJuridicaTablaController extends PopupPersonaSolicitantePersonaJuridicaJuridicaTablaControllerGen {
+
+}
+
\ No newline at end of file
diff --git a/apps/test/app/models/Solicitud.java b/apps/test/app/models/Solicitud.java
index ef7886ac..b004e846 100644
--- a/apps/test/app/models/Solicitud.java
+++ b/apps/test/app/models/Solicitud.java
@@ -1,161 +1,179 @@
package models;
import java.util.*;
import javax.persistence.*;
import play.Logger;
import play.db.jpa.JPA;
import play.db.jpa.Model;
import play.data.validation.*;
import org.joda.time.DateTime;
import models.*;
import messages.Messages;
import validation.*;
import audit.Auditable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
// === IMPORT REGION START ===
// === IMPORT REGION END ===
@Entity
public class Solicitud extends SolicitudGenerica {
// Código de los atributos
@OneToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
public DireccionTest direccionTest;
@OneToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
public ComboTest comboTest;
@OneToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
public ValoresPorDefectoTest valoresPorDefectoTest;
@OneToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
public Fechas fechas;
@OneToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
public TestGrupo testGrupo;
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
@JoinTable(name="solicitud_tabladenombres")
public List<TablaDeNombres> tablaDeNombres;
@ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
public ComboTestRef comboError;
@ManyToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
@JoinTable(name="solicitud_comboerrormany")
public List<ComboTestRef> comboErrorMany;
@ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
public PaginasTab paginas;
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
@JoinTable(name="solicitud_popuppaginas")
public List<TablaPopUpPaginas> popupPaginas;
@OneToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
+ public Solicitante solicitantePersonaFisica;
+
+
+ @OneToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
+ public Solicitante solicitantePersonaJuridica;
+
+
+ @OneToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
public PersonaFisica amigo;
@OneToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
public SavePages savePages;
public Solicitud (){
init();
}
public void init(){
super.init();
if (direccionTest == null)
direccionTest = new DireccionTest();
else
direccionTest.init();
if (comboTest == null)
comboTest = new ComboTest();
else
comboTest.init();
if (valoresPorDefectoTest == null)
valoresPorDefectoTest = new ValoresPorDefectoTest();
else
valoresPorDefectoTest.init();
if (fechas == null)
fechas = new Fechas();
else
fechas.init();
if (testGrupo == null)
testGrupo = new TestGrupo();
else
testGrupo.init();
if (tablaDeNombres == null)
tablaDeNombres = new ArrayList<TablaDeNombres>();
if (comboError != null)
comboError.init();
if (comboErrorMany == null)
comboErrorMany = new ArrayList<ComboTestRef>();
if (paginas != null)
paginas.init();
if (popupPaginas == null)
popupPaginas = new ArrayList<TablaPopUpPaginas>();
+ if (solicitantePersonaFisica == null)
+ solicitantePersonaFisica = new Solicitante();
+ else
+ solicitantePersonaFisica.init();
+
+ if (solicitantePersonaJuridica == null)
+ solicitantePersonaJuridica = new Solicitante();
+ else
+ solicitantePersonaJuridica.init();
+
if (amigo == null)
amigo = new PersonaFisica();
else
amigo.init();
if (savePages == null)
savePages = new SavePages();
else
savePages.init();
}
public void savePagesPrepared () {
if ((savePages.paginaSolicitante == null) || (!savePages.paginaSolicitante))
Messages.error("La página Solicitante no fue guardada correctamente");
}
// === MANUAL REGION START ===
public Solicitud(Agente agente) {
super.init();
init();
this.save();
//Crea la participacion
Participacion p = new Participacion();
p.agente = agente;
p.solicitud = this;
p.tipo = "creador";
p.save();
}
// === MANUAL REGION END ===
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/com/android/exchange/adapter/EmailSyncAdapter.java b/src/com/android/exchange/adapter/EmailSyncAdapter.java
index a387510..8d59da4 100644
--- a/src/com/android/exchange/adapter/EmailSyncAdapter.java
+++ b/src/com/android/exchange/adapter/EmailSyncAdapter.java
@@ -1,700 +1,705 @@
/*
* Copyright (C) 2008-2009 Marc Blank
* Licensed to The Android Open Source Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.exchange.adapter;
import com.android.email.mail.Address;
import com.android.email.provider.AttachmentProvider;
import com.android.email.provider.EmailContent;
import com.android.email.provider.EmailProvider;
import com.android.email.provider.EmailContent.Account;
import com.android.email.provider.EmailContent.AccountColumns;
import com.android.email.provider.EmailContent.Attachment;
import com.android.email.provider.EmailContent.Mailbox;
import com.android.email.provider.EmailContent.Message;
import com.android.email.provider.EmailContent.MessageColumns;
import com.android.email.provider.EmailContent.SyncColumns;
import com.android.email.service.MailService;
import com.android.exchange.Eas;
import com.android.exchange.EasSyncService;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.RemoteException;
import android.webkit.MimeTypeMap;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
/**
* Sync adapter for EAS email
*
*/
public class EmailSyncAdapter extends AbstractSyncAdapter {
private static final int UPDATES_READ_COLUMN = 0;
private static final int UPDATES_MAILBOX_KEY_COLUMN = 1;
private static final int UPDATES_SERVER_ID_COLUMN = 2;
private static final int UPDATES_FLAG_COLUMN = 3;
private static final String[] UPDATES_PROJECTION =
{MessageColumns.FLAG_READ, MessageColumns.MAILBOX_KEY, SyncColumns.SERVER_ID,
MessageColumns.FLAG_FAVORITE};
+ private static final String[] MESSAGE_ID_SUBJECT_PROJECTION =
+ new String[] { Message.RECORD_ID, MessageColumns.SUBJECT };
+
String[] bindArguments = new String[2];
ArrayList<Long> mDeletedIdList = new ArrayList<Long>();
ArrayList<Long> mUpdatedIdList = new ArrayList<Long>();
public EmailSyncAdapter(Mailbox mailbox, EasSyncService service) {
super(mailbox, service);
}
@Override
public boolean parse(InputStream is) throws IOException {
EasEmailSyncParser p = new EasEmailSyncParser(is, this);
return p.parse();
}
public class EasEmailSyncParser extends AbstractSyncParser {
private static final String WHERE_SERVER_ID_AND_MAILBOX_KEY =
SyncColumns.SERVER_ID + "=? and " + MessageColumns.MAILBOX_KEY + "=?";
private String mMailboxIdAsString;
ArrayList<Message> newEmails = new ArrayList<Message>();
ArrayList<Long> deletedEmails = new ArrayList<Long>();
ArrayList<ServerChange> changedEmails = new ArrayList<ServerChange>();
public EasEmailSyncParser(InputStream in, EmailSyncAdapter adapter) throws IOException {
super(in, adapter);
mMailboxIdAsString = Long.toString(mMailbox.mId);
}
@Override
public void wipe() {
mContentResolver.delete(Message.CONTENT_URI,
Message.MAILBOX_KEY + "=" + mMailbox.mId, null);
mContentResolver.delete(Message.DELETED_CONTENT_URI,
Message.MAILBOX_KEY + "=" + mMailbox.mId, null);
mContentResolver.delete(Message.UPDATED_CONTENT_URI,
Message.MAILBOX_KEY + "=" + mMailbox.mId, null);
}
public void addData (Message msg) throws IOException {
ArrayList<Attachment> atts = new ArrayList<Attachment>();
while (nextTag(Tags.SYNC_APPLICATION_DATA) != END) {
switch (tag) {
case Tags.EMAIL_ATTACHMENTS:
case Tags.BASE_ATTACHMENTS: // BASE_ATTACHMENTS is used in EAS 12.0 and up
attachmentsParser(atts, msg);
break;
case Tags.EMAIL_TO:
msg.mTo = Address.pack(Address.parse(getValue()));
break;
case Tags.EMAIL_FROM:
Address[] froms = Address.parse(getValue());
if (froms != null && froms.length > 0) {
msg.mDisplayName = froms[0].toFriendly();
}
msg.mFrom = Address.pack(froms);
break;
case Tags.EMAIL_CC:
msg.mCc = Address.pack(Address.parse(getValue()));
break;
case Tags.EMAIL_REPLY_TO:
msg.mReplyTo = Address.pack(Address.parse(getValue()));
break;
case Tags.EMAIL_DATE_RECEIVED:
String date = getValue();
// 2009-02-11T18:03:03.627Z
GregorianCalendar cal = new GregorianCalendar();
cal.set(Integer.parseInt(date.substring(0, 4)), Integer.parseInt(date
.substring(5, 7)) - 1, Integer.parseInt(date.substring(8, 10)),
Integer.parseInt(date.substring(11, 13)), Integer.parseInt(date
.substring(14, 16)), Integer.parseInt(date
.substring(17, 19)));
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
msg.mTimeStamp = cal.getTimeInMillis();
break;
case Tags.EMAIL_SUBJECT:
msg.mSubject = getValue();
break;
case Tags.EMAIL_READ:
msg.mFlagRead = getValueInt() == 1;
break;
case Tags.BASE_BODY:
bodyParser(msg);
break;
case Tags.EMAIL_FLAG:
msg.mFlagFavorite = flagParser();
break;
case Tags.EMAIL_BODY:
String text = getValue();
msg.mText = text;
break;
default:
skipTag();
}
}
if (atts.size() > 0) {
msg.mAttachments = atts;
}
}
private void addParser(ArrayList<Message> emails) throws IOException {
Message msg = new Message();
msg.mAccountKey = mAccount.mId;
msg.mMailboxKey = mMailbox.mId;
msg.mFlagLoaded = Message.FLAG_LOADED_COMPLETE;
while (nextTag(Tags.SYNC_ADD) != END) {
switch (tag) {
case Tags.SYNC_SERVER_ID:
msg.mServerId = getValue();
break;
case Tags.SYNC_APPLICATION_DATA:
addData(msg);
break;
default:
skipTag();
}
}
emails.add(msg);
}
// For now, we only care about the "active" state
private Boolean flagParser() throws IOException {
Boolean state = false;
while (nextTag(Tags.EMAIL_FLAG) != END) {
switch (tag) {
case Tags.EMAIL_FLAG_STATUS:
state = getValueInt() == 2;
break;
default:
skipTag();
}
}
return state;
}
private void bodyParser(Message msg) throws IOException {
String bodyType = Eas.BODY_PREFERENCE_TEXT;
String body = "";
while (nextTag(Tags.EMAIL_BODY) != END) {
switch (tag) {
case Tags.BASE_TYPE:
bodyType = getValue();
break;
case Tags.BASE_DATA:
body = getValue();
break;
default:
skipTag();
}
}
// We always ask for TEXT or HTML; there's no third option
if (bodyType.equals(Eas.BODY_PREFERENCE_HTML)) {
msg.mHtml = body;
} else {
msg.mText = body;
}
}
private void attachmentsParser(ArrayList<Attachment> atts, Message msg) throws IOException {
while (nextTag(Tags.EMAIL_ATTACHMENTS) != END) {
switch (tag) {
case Tags.EMAIL_ATTACHMENT:
case Tags.BASE_ATTACHMENT: // BASE_ATTACHMENT is used in EAS 12.0 and up
attachmentParser(atts, msg);
break;
default:
skipTag();
}
}
}
private void attachmentParser(ArrayList<Attachment> atts, Message msg) throws IOException {
String fileName = null;
String length = null;
String location = null;
while (nextTag(Tags.EMAIL_ATTACHMENT) != END) {
switch (tag) {
// We handle both EAS 2.5 and 12.0+ attachments here
case Tags.EMAIL_DISPLAY_NAME:
case Tags.BASE_DISPLAY_NAME:
fileName = getValue();
break;
case Tags.EMAIL_ATT_NAME:
case Tags.BASE_FILE_REFERENCE:
location = getValue();
break;
case Tags.EMAIL_ATT_SIZE:
case Tags.BASE_ESTIMATED_DATA_SIZE:
length = getValue();
break;
default:
skipTag();
}
}
if ((fileName != null) && (length != null) && (location != null)) {
Attachment att = new Attachment();
att.mEncoding = "base64";
att.mSize = Long.parseLong(length);
att.mFileName = fileName;
att.mLocation = location;
att.mMimeType = getMimeTypeFromFileName(fileName);
atts.add(att);
msg.mFlagAttachment = true;
}
}
/**
* Try to determine a mime type from a file name, defaulting to application/x, where x
* is either the extension or (if none) octet-stream
* At the moment, this is somewhat lame, since many file types aren't recognized
* @param fileName the file name to ponder
* @return
*/
// Note: The MimeTypeMap method currently uses a very limited set of mime types
// A bug has been filed against this issue.
public String getMimeTypeFromFileName(String fileName) {
String mimeType;
int lastDot = fileName.lastIndexOf('.');
String extension = null;
if ((lastDot > 0) && (lastDot < fileName.length() - 1)) {
extension = fileName.substring(lastDot + 1).toLowerCase();
}
if (extension == null) {
// A reasonable default for now.
mimeType = "application/octet-stream";
} else {
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
if (mimeType == null) {
mimeType = "application/" + extension;
}
}
return mimeType;
}
private Cursor getServerIdCursor(String serverId, String[] projection) {
bindArguments[0] = serverId;
bindArguments[1] = mMailboxIdAsString;
return mContentResolver.query(Message.CONTENT_URI, projection,
WHERE_SERVER_ID_AND_MAILBOX_KEY, bindArguments, null);
}
private void deleteParser(ArrayList<Long> deletes, int entryTag) throws IOException {
while (nextTag(entryTag) != END) {
switch (tag) {
case Tags.SYNC_SERVER_ID:
String serverId = getValue();
// Find the message in this mailbox with the given serverId
- Cursor c = getServerIdCursor(serverId, Message.ID_COLUMN_PROJECTION);
+ Cursor c = getServerIdCursor(serverId, MESSAGE_ID_SUBJECT_PROJECTION);
try {
if (c.moveToFirst()) {
- userLog("Deleting ", serverId);
- deletes.add(c.getLong(Message.ID_COLUMNS_ID_COLUMN));
+ deletes.add(c.getLong(0));
+ if (Eas.USER_LOG) {
+ userLog("Deleting ", serverId + ", " + c.getString(1));
+ }
}
} finally {
c.close();
}
break;
default:
skipTag();
}
}
}
class ServerChange {
long id;
Boolean read;
Boolean flag;
ServerChange(long _id, Boolean _read, Boolean _flag) {
id = _id;
read = _read;
flag = _flag;
}
}
private void changeParser(ArrayList<ServerChange> changes) throws IOException {
String serverId = null;
Boolean oldRead = false;
Boolean read = null;
Boolean oldFlag = false;
Boolean flag = null;
long id = 0;
while (nextTag(Tags.SYNC_CHANGE) != END) {
switch (tag) {
case Tags.SYNC_SERVER_ID:
serverId = getValue();
Cursor c = getServerIdCursor(serverId, Message.LIST_PROJECTION);
try {
if (c.moveToFirst()) {
userLog("Changing ", serverId);
oldRead = c.getInt(Message.LIST_READ_COLUMN) == Message.READ;
oldFlag = c.getInt(Message.LIST_FAVORITE_COLUMN) == 1;
id = c.getLong(Message.LIST_ID_COLUMN);
}
} finally {
c.close();
}
break;
case Tags.EMAIL_READ:
read = getValueInt() == 1;
break;
case Tags.EMAIL_FLAG:
flag = flagParser();
break;
case Tags.SYNC_APPLICATION_DATA:
break;
default:
skipTag();
}
}
if (((read != null) && !oldRead.equals(read)) ||
((flag != null) && !oldFlag.equals(flag))) {
changes.add(new ServerChange(id, read, flag));
}
}
/* (non-Javadoc)
* @see com.android.exchange.adapter.EasContentParser#commandsParser()
*/
@Override
public void commandsParser() throws IOException {
while (nextTag(Tags.SYNC_COMMANDS) != END) {
if (tag == Tags.SYNC_ADD) {
addParser(newEmails);
incrementChangeCount();
} else if (tag == Tags.SYNC_DELETE || tag == Tags.SYNC_SOFT_DELETE) {
deleteParser(deletedEmails, tag);
incrementChangeCount();
} else if (tag == Tags.SYNC_CHANGE) {
changeParser(changedEmails);
incrementChangeCount();
} else
skipTag();
}
}
@Override
public void responsesParser() {
}
@Override
public void commit() {
int notifyCount = 0;
// Use a batch operation to handle the changes
// TODO New mail notifications? Who looks for these?
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
for (Message msg: newEmails) {
if (!msg.mFlagRead) {
notifyCount++;
}
msg.addSaveOps(ops);
}
for (Long id : deletedEmails) {
ops.add(ContentProviderOperation.newDelete(
ContentUris.withAppendedId(Message.CONTENT_URI, id)).build());
AttachmentProvider.deleteAllAttachmentFiles(mContext, mAccount.mId, id);
}
if (!changedEmails.isEmpty()) {
// Server wins in a conflict...
for (ServerChange change : changedEmails) {
ContentValues cv = new ContentValues();
if (change.read != null) {
cv.put(MessageColumns.FLAG_READ, change.read);
}
if (change.flag != null) {
cv.put(MessageColumns.FLAG_FAVORITE, change.flag);
}
ops.add(ContentProviderOperation.newUpdate(
ContentUris.withAppendedId(Message.CONTENT_URI, change.id))
.withValues(cv)
.build());
}
}
// We only want to update the sync key here
ContentValues mailboxValues = new ContentValues();
mailboxValues.put(Mailbox.SYNC_KEY, mMailbox.mSyncKey);
ops.add(ContentProviderOperation.newUpdate(
ContentUris.withAppendedId(Mailbox.CONTENT_URI, mMailbox.mId))
.withValues(mailboxValues).build());
addCleanupOps(ops);
// No commits if we're stopped
synchronized (mService.getSynchronizer()) {
if (mService.isStopped()) return;
try {
mContentResolver.applyBatch(EmailProvider.EMAIL_AUTHORITY, ops);
userLog(mMailbox.mDisplayName, " SyncKey saved as: ", mMailbox.mSyncKey);
} catch (RemoteException e) {
// There is nothing to be done here; fail by returning null
} catch (OperationApplicationException e) {
// There is nothing to be done here; fail by returning null
}
}
if (notifyCount > 0) {
// Use the new atomic add URI in EmailProvider
// We could add this to the operations being done, but it's not strictly
// speaking necessary, as the previous batch preserves the integrity of the
// database, whereas this is purely for notification purposes, and is itself atomic
ContentValues cv = new ContentValues();
cv.put(EmailContent.FIELD_COLUMN_NAME, AccountColumns.NEW_MESSAGE_COUNT);
cv.put(EmailContent.ADD_COLUMN_NAME, notifyCount);
Uri uri = ContentUris.withAppendedId(Account.ADD_TO_FIELD_URI, mAccount.mId);
mContentResolver.update(uri, cv, null, null);
MailService.actionNotifyNewMessages(mContext, mAccount.mId);
}
}
}
@Override
public String getCollectionName() {
return "Email";
}
private void addCleanupOps(ArrayList<ContentProviderOperation> ops) {
// If we've sent local deletions, clear out the deleted table
for (Long id: mDeletedIdList) {
ops.add(ContentProviderOperation.newDelete(
ContentUris.withAppendedId(Message.DELETED_CONTENT_URI, id)).build());
}
// And same with the updates
for (Long id: mUpdatedIdList) {
ops.add(ContentProviderOperation.newDelete(
ContentUris.withAppendedId(Message.UPDATED_CONTENT_URI, id)).build());
}
}
@Override
public void cleanup() {
if (!mDeletedIdList.isEmpty() || !mUpdatedIdList.isEmpty()) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
addCleanupOps(ops);
try {
mContext.getContentResolver()
.applyBatch(EmailProvider.EMAIL_AUTHORITY, ops);
} catch (RemoteException e) {
// There is nothing to be done here; fail by returning null
} catch (OperationApplicationException e) {
// There is nothing to be done here; fail by returning null
}
}
}
private String formatTwo(int num) {
if (num < 10) {
return "0" + (char)('0' + num);
} else
return Integer.toString(num);
}
/**
* Create date/time in RFC8601 format. Oddly enough, for calendar date/time, Microsoft uses
* a different format that excludes the punctuation (this is why I'm not putting this in a
* parent class)
*/
public String formatDateTime(Calendar calendar) {
StringBuilder sb = new StringBuilder();
//YYYY-MM-DDTHH:MM:SS.MSSZ
sb.append(calendar.get(Calendar.YEAR));
sb.append('-');
sb.append(formatTwo(calendar.get(Calendar.MONTH) + 1));
sb.append('-');
sb.append(formatTwo(calendar.get(Calendar.DAY_OF_MONTH)));
sb.append('T');
sb.append(formatTwo(calendar.get(Calendar.HOUR_OF_DAY)));
sb.append(':');
sb.append(formatTwo(calendar.get(Calendar.MINUTE)));
sb.append(':');
sb.append(formatTwo(calendar.get(Calendar.SECOND)));
sb.append(".000Z");
return sb.toString();
}
@Override
public boolean sendLocalChanges(Serializer s) throws IOException {
ContentResolver cr = mContext.getContentResolver();
// Never upsync from these folders
if (mMailbox.mType == Mailbox.TYPE_DRAFTS || mMailbox.mType == Mailbox.TYPE_OUTBOX) {
return false;
}
// Find any of our deleted items
Cursor c = cr.query(Message.DELETED_CONTENT_URI, Message.LIST_PROJECTION,
MessageColumns.MAILBOX_KEY + '=' + mMailbox.mId, null, null);
boolean first = true;
// We keep track of the list of deleted item id's so that we can remove them from the
// deleted table after the server receives our command
mDeletedIdList.clear();
try {
while (c.moveToNext()) {
String serverId = c.getString(Message.LIST_SERVER_ID_COLUMN);
// Keep going if there's no serverId
if (serverId == null) {
continue;
} else if (first) {
s.start(Tags.SYNC_COMMANDS);
first = false;
}
// Send the command to delete this message
s.start(Tags.SYNC_DELETE).data(Tags.SYNC_SERVER_ID, serverId).end();
mDeletedIdList.add(c.getLong(Message.LIST_ID_COLUMN));
}
} finally {
c.close();
}
// Find our trash mailbox, since deletions will have been moved there...
long trashMailboxId =
Mailbox.findMailboxOfType(mContext, mMailbox.mAccountKey, Mailbox.TYPE_TRASH);
// Do the same now for updated items
c = cr.query(Message.UPDATED_CONTENT_URI, Message.LIST_PROJECTION,
MessageColumns.MAILBOX_KEY + '=' + mMailbox.mId, null, null);
// We keep track of the list of updated item id's as we did above with deleted items
mUpdatedIdList.clear();
try {
while (c.moveToNext()) {
long id = c.getLong(Message.LIST_ID_COLUMN);
// Say we've handled this update
mUpdatedIdList.add(id);
// We have the id of the changed item. But first, we have to find out its current
// state, since the updated table saves the opriginal state
Cursor currentCursor = cr.query(ContentUris.withAppendedId(Message.CONTENT_URI, id),
UPDATES_PROJECTION, null, null, null);
try {
// If this item no longer exists (shouldn't be possible), just move along
if (!currentCursor.moveToFirst()) {
continue;
}
// Keep going if there's no serverId
String serverId = currentCursor.getString(UPDATES_SERVER_ID_COLUMN);
if (serverId == null) {
continue;
}
// If the message is now in the trash folder, it has been deleted by the user
if (currentCursor.getLong(UPDATES_MAILBOX_KEY_COLUMN) == trashMailboxId) {
if (first) {
s.start(Tags.SYNC_COMMANDS);
first = false;
}
// Send the command to delete this message
s.start(Tags.SYNC_DELETE).data(Tags.SYNC_SERVER_ID, serverId).end();
continue;
}
boolean flagChange = false;
boolean readChange = false;
int flag = 0;
// We can only send flag changes to the server in 12.0 or later
if (mService.mProtocolVersionDouble >= 12.0) {
flag = currentCursor.getInt(UPDATES_FLAG_COLUMN);
if (flag != c.getInt(Message.LIST_FAVORITE_COLUMN)) {
flagChange = true;
}
}
int read = currentCursor.getInt(UPDATES_READ_COLUMN);
if (read != c.getInt(Message.LIST_READ_COLUMN)) {
readChange = true;
}
if (!flagChange && !readChange) {
// In this case, we've got nothing to send to the server
continue;
}
if (first) {
s.start(Tags.SYNC_COMMANDS);
first = false;
}
// Send the change to "read" and "favorite" (flagged)
s.start(Tags.SYNC_CHANGE)
.data(Tags.SYNC_SERVER_ID, c.getString(Message.LIST_SERVER_ID_COLUMN))
.start(Tags.SYNC_APPLICATION_DATA);
if (readChange) {
s.data(Tags.EMAIL_READ, Integer.toString(read));
}
// "Flag" is a relatively complex concept in EAS 12.0 and above. It is not only
// the boolean "favorite" that we think of in Gmail, but it also represents a
// follow up action, which can include a subject, start and due dates, and even
// recurrences. We don't support any of this as yet, but EAS 12.0 and higher
// require that a flag contain a status, a type, and four date fields, two each
// for start date and end (due) date.
if (flagChange) {
if (flag != 0) {
// Status 2 = set flag
s.start(Tags.EMAIL_FLAG).data(Tags.EMAIL_FLAG_STATUS, "2");
// "FollowUp" is the standard type
s.data(Tags.EMAIL_FLAG_TYPE, "FollowUp");
long now = System.currentTimeMillis();
Calendar calendar =
GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.setTimeInMillis(now);
// Flags are required to have a start date and end date (duplicated)
// First, we'll set the current date/time in GMT as the start time
String utc = formatDateTime(calendar);
s.data(Tags.TASK_START_DATE, utc).data(Tags.TASK_UTC_START_DATE, utc);
// And then we'll use one week from today for completion date
calendar.setTimeInMillis(now + 1*WEEKS);
utc = formatDateTime(calendar);
s.data(Tags.TASK_DUE_DATE, utc).data(Tags.TASK_UTC_DUE_DATE, utc);
s.end();
} else {
s.tag(Tags.EMAIL_FLAG);
}
}
s.end().end(); // SYNC_APPLICATION_DATA, SYNC_CHANGE
} finally {
currentCursor.close();
}
}
} finally {
c.close();
}
if (!first) {
s.end(); // SYNC_COMMANDS
}
return false;
}
}
| false | false | null | null |
diff --git a/plugins/SPIMAcquisition/spim/SPIMAcquisition.java b/plugins/SPIMAcquisition/spim/SPIMAcquisition.java
index f3ca97775..7990d521a 100644
--- a/plugins/SPIMAcquisition/spim/SPIMAcquisition.java
+++ b/plugins/SPIMAcquisition/spim/SPIMAcquisition.java
@@ -1,817 +1,817 @@
package spim;
import ij.IJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.process.ByteProcessor;
import ij.process.ImageProcessor;
import ij.process.ShortProcessor;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Dictionary;
import java.util.Hashtable;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import mmcorej.CMMCore;
import org.micromanager.MMStudioMainFrame;
import org.micromanager.api.MMPlugin;
import org.micromanager.api.ScriptInterface;
public class SPIMAcquisition implements MMPlugin {
// TODO: read these from the properties
protected int motorMin = 1, motorMax = 8000,
twisterMin = -180, twisterMax = 180;
protected ScriptInterface app;
protected CMMCore mmc;
protected MMStudioMainFrame gui;
protected String xyStageLabel, zStageLabel, twisterLabel,
laserLabel, cameraLabel;
protected JFrame frame;
protected IntegerField xPosition, yPosition, zPosition, rotation,
zFrom, zTo, stepsPerRotation, degreesPerStep,
laserPower, exposure;
protected MotorSlider xSlider, ySlider, zSlider, rotationSlider,
laserSlider, exposureSlider;
protected JCheckBox liveCheckbox, registrationCheckbox,
multipleAngleCheckbox, continuousCheckbox;
protected JButton ohSnap;
protected boolean updateLiveImage;
// MMPlugin stuff
/**
* The menu name is stored in a static string, so Micro-Manager
* can obtain it without instantiating the plugin
*/
public static String menuName = "Acquire SPIM image";
/**
* The main app calls this method to remove the module window
*/
@Override
public void dispose() {
if (frame == null)
return;
frame.dispose();
frame = null;
runToX.interrupt();
runToY.interrupt();
runToZ.interrupt();
runToAngle.interrupt();
}
/**
* The main app passes its ScriptInterface to the module. This
* method is typically called after the module is instantiated.
* @param app - ScriptInterface implementation
*/
@Override
public void setApp(ScriptInterface app) {
this.app = app;
mmc = app.getMMCore();
gui = MMStudioMainFrame.getInstance();
}
/**
* Open the module window
*/
@Override
public void show() {
initUI();
configurationChanged();
frame.setVisible(true);
}
/**
* The main app calls this method when hardware settings change.
* This call signals to the module that it needs to update whatever
* information it needs from the MMCore.
*/
@Override
public void configurationChanged() {
zStageLabel = null;
xyStageLabel = null;
twisterLabel = null;
for (String label : mmc.getLoadedDevices().toArray()) try {
String driver = mmc.getDeviceNameInLibrary(label);
if (driver.equals("Picard Twister"))
twisterLabel = label;
else if (driver.equals("Picard Z Stage")) { // TODO: read this from the to-be-added property
zStageLabel = label;
}
else if (driver.equals("Picard XY Stage"))
xyStageLabel = label;
// testing
else if (driver.equals("DStage")) {
if (label.equals("DStage"))
zStageLabel = label;
else
twisterLabel = label;
}
else if (driver.equals("DXYStage"))
xyStageLabel = label;
} catch (Exception e) {
IJ.handleException(e);
}
cameraLabel = mmc.getCameraDevice();
updateUI();
}
/**
* Returns a very short (few words) description of the module.
*/
@Override
public String getDescription() {
return "Open Source SPIM acquisition";
}
/**
* Returns verbose information about the module.
* This may even include a short help instructions.
*/
@Override
public String getInfo() {
// TODO: be more verbose
return "See https://wiki.mpi-cbg.de/wiki/spiminabriefcase/";
}
/**
* Returns version string for the module.
* There is no specific required format for the version
*/
@Override
public String getVersion() {
return "0.01";
}
/**
* Returns copyright information
*/
@Override
public String getCopyright() {
return "Copyright Johannes Schindelin (2011)\n"
+ "GPLv2 or later";
}
// UI stuff
protected void initUI() {
if (frame != null)
return;
frame = new JFrame("SPIM in a Briefcase");
JPanel left = new JPanel();
left.setLayout(new BoxLayout(left, BoxLayout.PAGE_AXIS));
left.setBorder(BorderFactory.createTitledBorder("Position/Angle"));
xSlider = new MotorSlider(motorMin, motorMax, 1) {
@Override
public void valueChanged(int value) {
runToX.run(value);
maybeUpdateImage();
}
};
ySlider = new MotorSlider(motorMin, motorMax, 1) {
@Override
public void valueChanged(int value) {
runToY.run(value);
maybeUpdateImage();
}
};
zSlider = new MotorSlider(motorMin, motorMax, 1) {
@Override
public void valueChanged(int value) {
runToZ.run(value);
maybeUpdateImage();
}
};
rotationSlider = new MotorSlider(twisterMin, twisterMax, 0) {
@Override
public void valueChanged(int value) {
runToAngle.run(value * 200 / 360);
maybeUpdateImage();
}
};
xPosition = new IntegerSliderField(xSlider);
yPosition = new IntegerSliderField(ySlider);
zPosition = new IntegerSliderField(zSlider);
rotation = new IntegerSliderField(rotationSlider);
zFrom = new IntegerField(1) {
@Override
public void valueChanged(int value) {
if (value < motorMin)
setText("" + motorMin);
else if (value > motorMax)
setText("" + motorMax);
}
};
zTo = new IntegerField(motorMax) {
@Override
public void valueChanged(int value) {
if (value < motorMin)
setText("" + motorMin);
else if (value > motorMax)
setText("" + motorMax);
}
};
stepsPerRotation = new IntegerField(4) {
@Override
public void valueChanged(int value) {
degreesPerStep.setText("" + (360 / value));
}
};
degreesPerStep = new IntegerField(90) {
@Override
public void valueChanged(int value) {
stepsPerRotation.setText("" + (360 / value));
}
};
addLine(left, Justification.LEFT, "x:", xPosition, "y:", yPosition, "z:", zPosition, "angle:", rotation);
addLine(left, Justification.STRETCH, "x:", xSlider);
addLine(left, Justification.RIGHT, new LimitedRangeCheckbox("Limit range", xSlider, 500, 2500));
addLine(left, Justification.STRETCH, "y:", ySlider);
addLine(left, Justification.RIGHT, new LimitedRangeCheckbox("Limit range", ySlider, 500, 2500));
addLine(left, Justification.STRETCH, "z:", zSlider);
addLine(left, Justification.RIGHT, new LimitedRangeCheckbox("Limit range", zSlider, 500, 2500));
addLine(left, Justification.RIGHT, "from z:", zFrom, "to z:", zTo);
addLine(left, Justification.STRETCH, "rotation:", rotationSlider);
addLine(left, Justification.RIGHT, "steps/rotation:", stepsPerRotation, "degrees/step:", degreesPerStep);
JPanel right = new JPanel();
right.setLayout(new BoxLayout(right, BoxLayout.PAGE_AXIS));
right.setBorder(BorderFactory.createTitledBorder("Acquisition"));
// TODO: find out correct values
laserSlider = new MotorSlider(0, 1000, 1000) {
@Override
public void valueChanged(int value) {
// TODO
}
};
// TODO: find out correct values
exposureSlider = new MotorSlider(10, 1000, 10) {
@Override
public void valueChanged(int value) {
try {
mmc.setExposure(value);
} catch (Exception e) {
IJ.handleException(e);
}
}
};
laserPower = new IntegerSliderField(laserSlider);
exposure = new IntegerSliderField(exposureSlider);
liveCheckbox = new JCheckBox("Update Live View");
liveCheckbox.setSelected(true);
updateLiveImage = true;
liveCheckbox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
updateLiveImage = e.getStateChange() == ItemEvent.SELECTED;
}
});
registrationCheckbox = new JCheckBox("Perform SPIM registration");
registrationCheckbox.setSelected(false);
registrationCheckbox.setEnabled(false);
multipleAngleCheckbox = new JCheckBox("Multiple Rotation Angles");
multipleAngleCheckbox.setSelected(false);
multipleAngleCheckbox.setEnabled(false);
continuousCheckbox = new JCheckBox("Continuous z motion");
continuousCheckbox.setEnabled(true);
ohSnap = new JButton("Oh snap!");
ohSnap.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final int zStart = zFrom.getValue();
final int zEnd = zTo.getValue();
final boolean isContinuous = continuousCheckbox.isSelected();
new Thread() {
@Override
public void run() {
try {
ImagePlus image = isContinuous ?
snapContinuousStack(zStart, zEnd) : snapStack(zStart, zEnd);
image.show();
} catch (Exception e) {
IJ.handleException(e);
}
}
}.start();
}
});
addLine(right, Justification.RIGHT, "laser power:", laserPower, "exposure:", exposure);
addLine(right, Justification.STRETCH, "laser:", laserSlider);
addLine(right, Justification.STRETCH, "exposure:", exposureSlider);
addLine(right, Justification.RIGHT, liveCheckbox);
addLine(right, Justification.RIGHT, registrationCheckbox);
addLine(right, Justification.RIGHT, multipleAngleCheckbox);
addLine(right, Justification.RIGHT, continuousCheckbox);
addLine(right, Justification.RIGHT, ohSnap);
Container panel = frame.getContentPane();
panel.setLayout(new GridLayout(1, 2));
panel.add(left);
panel.add(right);
frame.pack();
}
protected void updateUI() {
xPosition.setEnabled(xyStageLabel != null);
yPosition.setEnabled(xyStageLabel != null);
zPosition.setEnabled(zStageLabel != null);
rotation.setEnabled(twisterLabel != null);
xSlider.setEnabled(xyStageLabel != null);
ySlider.setEnabled(xyStageLabel != null);
zSlider.setEnabled(zStageLabel != null);
zFrom.setEnabled(zStageLabel != null);
zTo.setEnabled(zStageLabel != null);
rotationSlider.setEnabled(twisterLabel != null);
stepsPerRotation.setEnabled(twisterLabel != null);
degreesPerStep.setEnabled(twisterLabel != null);
laserPower.setEnabled(laserLabel != null);
exposure.setEnabled(cameraLabel != null);
laserSlider.setEnabled(laserLabel != null);
exposureSlider.setEnabled(cameraLabel != null);
liveCheckbox.setEnabled(cameraLabel != null);
ohSnap.setEnabled(zStageLabel != null && cameraLabel != null);
if (xyStageLabel != null) try {
int x = (int)mmc.getXPosition(xyStageLabel);
int y = (int)mmc.getYPosition(xyStageLabel);
xPosition.setText("" + x);
yPosition.setText("" + y);
xSlider.setValue(x);
ySlider.setValue(y);
} catch (Exception e) {
IJ.handleException(e);
}
if (zStageLabel != null) try {
int z = (int)mmc.getPosition(zStageLabel);
zPosition.setText("" + z);
zSlider.setValue(z);
} catch (Exception e) {
IJ.handleException(e);
}
if (twisterLabel != null) try {
// TODO: how to handle 200 steps per 360 degrees?
int angle = (int)mmc.getPosition(twisterLabel);
rotation.setText("" + angle);
rotationSlider.setValue(angle);
} catch (Exception e) {
IJ.handleException(e);
}
if (laserLabel != null) try {
// TODO: get current laser power
} catch (Exception e) {
IJ.handleException(e);
}
if (cameraLabel != null) try {
// TODO: get current exposure
} catch (Exception e) {
IJ.handleException(e);
}
}
// UI helpers
protected enum Justification {
LEFT, STRETCH, RIGHT
};
protected static void addLine(Container container, Justification justification, Object... objects) {
JPanel panel = new JPanel();
if (justification == Justification.STRETCH)
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
else
panel.setLayout(new FlowLayout(justification == Justification.LEFT ? FlowLayout.LEADING : FlowLayout.TRAILING));
for (Object object : objects) {
Component component = (object instanceof String) ?
new JLabel((String)object) :
(Component)object;
panel.add(component);
}
container.add(panel);
}
protected static abstract class MotorSlider extends JSlider implements ChangeListener {
protected JTextField updating;
protected Color background;
public MotorSlider(int min, int max, int current) {
super(JSlider.HORIZONTAL, min, max, Math.min(max, Math.max(min, current)));
setMinorTickSpacing((int)((max - min) / 40));
setMajorTickSpacing((int)((max - min) / 5));
setPaintTrack(true);
setPaintTicks(true);
if (min == 1)
setLabelTable(makeLabelTable(min, max, 5));
setPaintLabels(true);
addChangeListener(this);
}
@Override
public void stateChanged(ChangeEvent e) {
final int value = getValue();
if (getValueIsAdjusting()) {
if (updating != null) {
if (background == null)
background = updating.getBackground();
updating.setBackground(Color.YELLOW);
updating.setText("" + value);
}
}
else
new Thread() {
@Override
public void run() {
if (updating != null)
updating.setBackground(background);
valueChanged(value);
}
}.start();
}
public abstract void valueChanged(int value);
}
protected static class LimitedRangeCheckbox extends JPanel implements ItemListener {
protected JTextField min, max;
protected JCheckBox checkbox;
protected MotorSlider slider;
protected Dictionary originalLabels, limitedLabels;
protected int originalMin, originalMax;
protected int limitedMin, limitedMax;
public LimitedRangeCheckbox(String label, MotorSlider slider, int min, int max) {
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
checkbox = new JCheckBox(label);
add(checkbox);
this.min = new JTextField("" + min);
add(this.min);
add(new JLabel(" to "));
this.max = new JTextField("" + max);
add(this.max);
this.slider = slider;
originalLabels = slider.getLabelTable();
originalMin = slider.getMinimum();
originalMax = slider.getMaximum();
limitedMin = min;
limitedMax = max;
checkbox.setSelected(false);
checkbox.addItemListener(this);
}
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
limitedMin = getValue(min, limitedMin);
limitedMax = getValue(max, limitedMax);
limitedLabels = makeLabelTable(limitedMin, limitedMax, 5);
int current = slider.getValue();
if (current < limitedMin)
slider.setValue(limitedMin);
else if (current > limitedMax)
slider.setValue(limitedMax);
slider.setMinimum(limitedMin);
slider.setMaximum(limitedMax);
slider.setLabelTable(limitedLabels);
}
else {
slider.setMinimum(originalMin);
slider.setMaximum(originalMax);
slider.setLabelTable(originalLabels);
}
}
protected static int getValue(JTextField text, int defaultValue) {
try {
return Integer.parseInt(text.getText());
} catch (Exception e) {
return defaultValue;
}
}
}
protected static Dictionary makeLabelTable(int min, int max, int count) {
int spacing = (int)((max - min) / count);
spacing = 100 * ((spacing + 50) / 100); // round to nearest 100
Hashtable<Integer, JLabel> table = new Hashtable<Integer, JLabel>();
table.put(min, new JLabel("" + min));
for (int i = max; i > min; i -= spacing)
table.put(i, new JLabel("" + i));
return table;
}
protected static abstract class IntegerField extends JTextField {
public IntegerField(int value) {
this(value, 4);
}
public IntegerField(int value, int columns) {
super(columns);
setText("" + value);
addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() != KeyEvent.VK_ENTER)
return;
valueChanged(getValue());
}
});
addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
valueChanged(getValue());
}
});
}
public int getValue() {
String typed = getText();
if(!typed.matches("\\d+"))
return 0;
return Integer.parseInt(typed);
}
public abstract void valueChanged(int value);
}
protected static class IntegerSliderField extends IntegerField {
protected JSlider slider;
public IntegerSliderField(JSlider slider) {
super(slider.getValue());
this.slider = slider;
if (slider instanceof MotorSlider)
((MotorSlider)slider).updating = this;
}
@Override
public void valueChanged(int value) {
if (slider != null)
slider.setValue(value);
}
}
// Accessing the devices
protected void maybeUpdateImage() {
if (cameraLabel != null && updateLiveImage)
gui.updateImage();
}
protected abstract static class RunTo extends Thread {
protected int goal, current = Integer.MAX_VALUE;
@Override
public void run() {
for (;;) try {
if (goal != current) synchronized (this) {
if (get() == goal) {
current = goal;
done();
notifyAll();
}
}
Thread.currentThread().sleep(50);
} catch (Exception e) {
return;
}
}
public void run(int value) {
synchronized (this) {
if (goal == value) {
done();
return;
}
goal = value;
try {
set(goal);
} catch (Exception e) {
return;
}
synchronized (this) {
if (!isAlive())
start();
try {
wait();
} catch (InterruptedException e) {
return;
}
}
}
}
public abstract int get() throws Exception ;
public abstract void set(int value) throws Exception;
public abstract void done();
}
protected RunTo runToX = new RunTo() {
@Override
public int get() throws Exception {
return (int)mmc.getXPosition(xyStageLabel);
}
@Override
public void set(int value) throws Exception {
mmc.setXYPosition(xyStageLabel, value, mmc.getYPosition(xyStageLabel));
}
@Override
public void done() {
xPosition.setText("" + goal);
}
};
protected RunTo runToY = new RunTo() {
@Override
public int get() throws Exception {
return (int)mmc.getYPosition(xyStageLabel);
}
@Override
public void set(int value) throws Exception {
mmc.setXYPosition(xyStageLabel, mmc.getXPosition(xyStageLabel), value);
}
@Override
public void done() {
yPosition.setText("" + goal);
}
};
protected RunTo runToZ = new RunTo() {
@Override
public int get() throws Exception {
return (int)mmc.getPosition(zStageLabel);
}
@Override
public void set(int value) throws Exception {
mmc.setPosition(zStageLabel, value);
}
@Override
public void done() {
zPosition.setText("" + goal);
}
};
protected RunTo runToAngle = new RunTo() {
@Override
public int get() throws Exception {
return (int)mmc.getPosition(twisterLabel);
}
@Override
public void set(int value) throws Exception {
mmc.setPosition(twisterLabel, value);
}
@Override
public void done() {
rotation.setText("" + goal);
}
};
protected ImageProcessor snapSlice() throws Exception {
mmc.snapImage();
int width = (int)mmc.getImageWidth();
int height = (int)mmc.getImageHeight();
if (mmc.getBytesPerPixel() == 1) {
byte[] pixels = (byte[])mmc.getImage();
return new ByteProcessor(width, height, pixels, null);
} else if (mmc.getBytesPerPixel() == 2){
short[] pixels = (short[])mmc.getImage();
return new ShortProcessor(width, height, pixels, null);
} else
return null;
}
protected void snapAndShowContinuousStack(final int zStart, final int zEnd) throws Exception {
// Cannot run this on the EDT
if (SwingUtilities.isEventDispatchThread()) {
new Thread() {
public void run() {
try {
snapAndShowContinuousStack(zStart, zEnd);
} catch (Exception e) {
IJ.handleException(e);
}
}
}.start();
return;
}
snapContinuousStack(zStart, zEnd).show();
}
protected ImagePlus snapContinuousStack(int zStart, int zEnd) throws Exception {
String meta = getMetaData();
ImageStack stack = null;
zSlider.setValue(zStart);
runToZ.run(zStart);
IJ.wait(50); // wait 50 milliseconds for the state to settle
zSlider.setValue(zEnd);
int zStep = (zStart < zEnd ? +1 : -1);
for (int z = zStart; z * zStep <= zEnd * zStep; z = z + zStep) {
- while (z != (int)mmc.getPosition(zStageLabel))
+ while (z * zStep < (int)mmc.getPosition(zStageLabel) * zStep)
Thread.yield();
ImageProcessor ip = snapSlice();
if (stack == null)
stack = new ImageStack(ip.getWidth(), ip.getHeight());
stack.addSlice("z: " + z, ip);
}
ImagePlus result = new ImagePlus("SPIM!", stack);
result.setProperty("Info", meta);
return result;
}
protected ImagePlus snapStack(int zStart, int zEnd) throws Exception {
String meta = getMetaData();
ImageStack stack = null;
int zStep = (zStart < zEnd ? +1 : -1);
- for (int z = zStart; z <= zEnd; z = z + zStep) {
+ for (int z = zStart; z * zStep <= zEnd * zStep; z = z + zStep) {
zSlider.setValue(z);
runToZ.run(z);
ImageProcessor ip = snapSlice();
if (stack == null)
stack = new ImageStack(ip.getWidth(), ip.getHeight());
stack.addSlice("z: " + z, ip);
}
ImagePlus result = new ImagePlus("SPIM!", stack);
result.setProperty("Info", meta);
return result;
}
protected String getMetaData() throws Exception {
String meta = "";
if (xyStageLabel != "")
meta += "x motor position: " + mmc.getXPosition(xyStageLabel) + "\n"
+ "y motor position: " + mmc.getYPosition(xyStageLabel) + "\n";
if (zStageLabel != "")
meta += "z motor position: " + mmc.getPosition(zStageLabel) + "\n";
if (twisterLabel != "")
meta += "twister position: " + mmc.getPosition(twisterLabel) + "\n"
+ "twister angle: " + (360.0 / 200.0 * mmc.getPosition(twisterLabel)) + "\n";
return meta;
}
}
| false | false | null | null |
diff --git a/src/euphonia/core/Migration.java b/src/euphonia/core/Migration.java
index 4efc53e..2148b0a 100644
--- a/src/euphonia/core/Migration.java
+++ b/src/euphonia/core/Migration.java
@@ -1,367 +1,368 @@
package euphonia.core;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import euphonia.core.transformation.Transformation;
public class Migration
{
private static final Log log = LogFactory.getLog(Migration.class);
private List<Table> tables = new ArrayList<Table>();
private Table lastTable;
private Field lastField;
private boolean incremental = false;
private String sourceDatabase, targetDatabase;
private DBMS sourceDBMS, targetDBMS;
protected boolean addTable(Table table)
{
return tables.add(table);
}
public Table table(String name)
{
Table table = new Table(name, this);
lastTable = table;
return table;
}
public Field field(String name)
{
this.lastField = new Field(name, lastTable, this);
return lastField;
}
public Migration run()
{
DatabaseConnection source = ConnectionFactory.getConnection(sourceDBMS)
.open(sourceDatabase, null, null);
DatabaseConnection target = ConnectionFactory.getConnection(targetDBMS)
.open(targetDatabase, null, null);
try
{
for (Table table: tables)
runTable(source, target, table);
}
finally
{
source.close();
target.close();
}
return this;
}
private void runTable(DatabaseConnection source, DatabaseConnection target, Table table)
{
readDataFromSourceTable(table, source);
- deleteFromTargetTable(table, target);
+ if (incremental)
+ deleteFromTargetTable(table, target);
writeDataToTargetTable(table, target);
}
private void writeDataToTargetTable(Table table, DatabaseConnection target)
{
StringBuilder sql = createInsertQuery(table);
try
{
PreparedStatement ps = target.getConnection().prepareStatement(sql.toString());
try
{
for (int count = 1; count <= table.recordCount(); count++)
{
ps.clearParameters();
int paramCount = 1;
for (Field field: table.fields())
{
log.debug("Including value " + table.getValue(field.sourceName, count-1) +
" for field " + field + " in table " + table);
ps.setObject(paramCount, field.copy(table.getValue(field.sourceName, count-1)));
paramCount++;
}
ps.execute();
}
}
finally
{
ps.close();
}
}
catch (SQLException e)
{
throw new RuntimeException(e);
}
}
private StringBuilder createInsertQuery(Table table)
{
StringBuilder sql = new StringBuilder()
.append("insert into ")
.append(table.targetName)
.append(" (");
for (Field field: table.fields())
sql.append(field.targetName).append(',');
sql.delete(sql.length()-1, sql.length());
sql.append(") VALUES(");
for (int i = 0; i < table.fieldCount(); i++)
sql.append("?,");
sql.delete(sql.length()-1, sql.length());
sql.append(')');
log.debug(sql);
return sql;
}
private void readDataFromSourceTable(Table table, DatabaseConnection source)
{
try
{
ResultSet result = source.executeQuery("select * from " + table.sourceName);
try
{
ResultSetMetaData metadata = result.getMetaData();
Map<String, Integer> columns = loadColumns(metadata);
while (result.next())
{
for (Field field: table.fields())
{
Integer index = columns.get(field.sourceName.toUpperCase());
field.sourceType = metadata.getColumnTypeName(index);
table.putValue(field.sourceName, result.getObject(field.sourceName));
}
}
}
finally
{
result.close();
}
}
catch (SQLException e)
{
throw new RuntimeException(e);
}
}
private Map<String, Integer> loadColumns(ResultSetMetaData metadata)
throws SQLException
{
Map<String, Integer> columns = new HashMap<String, Integer>();
for (int i = 1; i <= metadata.getColumnCount(); i++)
columns.put(metadata.getColumnName(i).toUpperCase(), i);
return columns;
}
private void deleteFromTargetTable(Table table, DatabaseConnection target)
{
target.execute("delete from " + table.targetName);
}
private boolean sourceWasLast = false;
public Migration from(String databaseSource)
{
this.sourceDatabase = databaseSource;
sourceWasLast = true;
return this;
}
public Migration to(String databaseTarget)
{
this.targetDatabase = databaseTarget;
sourceWasLast = false;
return this;
}
public Migration in(DBMS sgbd)
{
if (sourceWasLast)
this.sourceDBMS = sgbd;
else
this.targetDBMS = sgbd;
return this;
}
public Migration allFields()
{
try
{
DatabaseConnection source = ConnectionFactory.getConnection(sourceDBMS)
.open(sourceDatabase, null, null);
try
{
String tableName = lastTable.sourceName;
ResultSet result = source.executeQuery("select * from " + tableName);
try
{
ResultSetMetaData metadata = result.getMetaData();
for (int i = 1; i <= metadata.getColumnCount(); i++)
{
String columnName = metadata.getColumnName(i);
this.field(columnName).to(columnName);
}
}
finally
{
result.close();
}
}
finally
{
source.close();
}
return this;
}
catch (SQLException e)
{
throw new RuntimeException(e);
}
}
public Migration withTransformation(Transformation transformation)
{
lastField.transformation(transformation);
return this;
}
public Migration incremental()
{
incremental = true;
return this;
}
}
class Table
{
String sourceName;
private Migration migration;
String targetName;
private Map<String, List<Object>> sourceMap = new HashMap<String, List<Object>>();
private List<Field> fields = new ArrayList<Field>();
protected void addField(Field field)
{
fields.add(field);
sourceMap.put(field.sourceName, new ArrayList<Object>());
}
protected int recordCount()
{
return sourceMap.get(sourceMap.keySet().iterator().next()).size();
}
protected int fieldCount()
{
return fields.size();
}
protected Iterable<Field> fields()
{
return fields;
}
protected Object getValue(String field, int index)
{
return sourceMap.get(field).get(index);
}
protected void putValue(String field, Object value)
{
sourceMap.get(field).add(value);
}
public Table(String name, Migration migration)
{
this.sourceName = name;
this.migration = migration;
migration.addTable(this);
}
public Migration to(String targetName)
{
this.targetName = targetName;
return migration;
}
@Override
public String toString()
{
return new StringBuilder()
.append('(')
.append(sourceName)
.append(',')
.append(targetName)
.append(')')
.toString();
}
}
class Field
{
String sourceName;
String sourceType;
Migration migration;
String targetName;
Transformation transformation;
public Field(String name, Table table, Migration migration)
{
this.sourceName = name;
this.migration = migration;
table.addField(this);
}
public Object copy(Object value)
{
return transformation == null ? value : transformation.transform(value);
}
public Field transformation(Transformation transformation)
{
this.transformation = transformation;
return this;
}
public Transformation transformation()
{
return transformation;
}
public Migration to(String targetName)
{
this.targetName = targetName;
return migration;
}
@Override
public String toString()
{
return new StringBuilder()
.append('(')
.append(sourceName)
.append(',')
.append(targetName)
.append(')')
.toString();
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/MyParser.java b/MyParser.java
index 6554747..f26e5d6 100644
--- a/MyParser.java
+++ b/MyParser.java
@@ -1,1187 +1,1181 @@
//---------------------------------------------------------------------
//
//---------------------------------------------------------------------
import java_cup.runtime.*;
import java.util.Vector;
class MyParser extends parser
{
//----------------------------------------------------------------
// Instance variables
//----------------------------------------------------------------
private Lexer m_lexer;
private ErrorPrinter m_errors;
private int m_nNumErrors;
private String m_strLastLexeme;
private boolean m_bSyntaxError = true;
private int m_nSavedLineNum;
private SymbolTable m_symtab;
private boolean m_inStructdef = false;
private String m_structId;
private Scope m_currentStructdef;
private int m_whileLevel;
//----------------------------------------------------------------
//
//----------------------------------------------------------------
public MyParser(Lexer lexer, ErrorPrinter errors)
{
m_lexer = lexer;
m_symtab = new SymbolTable();
m_errors = errors;
m_nNumErrors = 0;
m_whileLevel = 0;
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
public boolean Ok()
{
return (m_nNumErrors == 0);
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
public Symbol scan()
{
Token t = m_lexer.GetToken();
// We'll save the last token read for error messages.
// Sometimes, the token is lost reading for the next
// token which can be null.
m_strLastLexeme = t.GetLexeme();
switch(t.GetCode()) {
case sym.T_ID:
case sym.T_ID_U:
case sym.T_STR_LITERAL:
case sym.T_FLOAT_LITERAL:
case sym.T_INT_LITERAL:
case sym.T_CHAR_LITERAL:
return (new Symbol(t.GetCode(), t.GetLexeme()));
default:
return (new Symbol(t.GetCode()));
}
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
public void syntax_error(Symbol s)
{
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
public void report_fatal_error(Symbol s)
{
m_nNumErrors++;
if(m_bSyntaxError) {
m_nNumErrors++;
// It is possible that the error was detected
// at the end of a line - in which case, s will
// be null. Instead, we saved the last token
// read in to give a more meaningful error
// message.
m_errors.print(Formatter.toString(ErrorMsg.syntax_error, m_strLastLexeme));
}
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
public void unrecovered_syntax_error(Symbol s)
{
report_fatal_error(s);
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
public void DisableSyntaxError()
{
m_bSyntaxError = false;
}
public void EnableSyntaxError()
{
m_bSyntaxError = true;
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
public String GetFile()
{
return (m_lexer.getEPFilename());
}
public int GetLineNum()
{
return (m_lexer.getLineNumber());
}
public void SaveLineNum()
{
m_nSavedLineNum = m_lexer.getLineNumber();
}
public int GetSavedLineNum()
{
return (m_nSavedLineNum);
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void DoProgramStart()
{
// Opens the global scope.
m_symtab.openScope();
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void DoProgramEnd()
{
m_symtab.closeScope();
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void DoVarDecl(Type type, Vector<IdValueTuple> lstIDs)
{
for(int i = 0; i < lstIDs.size(); i++) {
String id = lstIDs.elementAt(i).getId();
STO value = lstIDs.elementAt(i).getValue();
STO arrayIndex = lstIDs.elementAt(i).getArrayIndex();
Type ptrType = lstIDs.elementAt(i).getPointerType();
// Check for var already existing in localScope
if(m_symtab.accessLocal(id) != null) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id));
}
Type finalType = type;
VarSTO stoVar;
// Do Array checks if type = ArrayType
if(arrayIndex != null && type != null) {
// Check 10
ArrayType arrType = DoArrayDecl(type, arrayIndex);
if (arrType != null) {
// Check 11b
if(value.isArrEle()) {
ArrEleSTO elements = (ArrEleSTO) value;
Vector<STO> stos = elements.getArrayElements();
// # elements not exceed array size
if(stos.size() >= ((ConstSTO) arrayIndex).getIntValue()) {
m_nNumErrors++;
m_errors.print(ErrorMsg.error11_TooManyInitExpr);
break;
}
for(STO sto : stos) {
if (!sto.isConst()) {
m_nNumErrors++;
m_errors.print(ErrorMsg.error11_NonConstInitExpr);
break;
}
if (!sto.getType().isAssignable(type)) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error3b_Assign, sto.getType().getName(), type.getName()));
break;
}
}
// Add it array
arrType.setElementList(elements);
}
}
// Override type with new arrayType that encompasses the value stored in finalType
finalType = arrType;
}
if(ptrType != null) {
((PtrGrpType) ptrType).setBottomPtrType(type);
finalType = ((PtrGrpType) ptrType).getBottomPtrType();
}
stoVar = new VarSTO(id, finalType);
m_symtab.insert(stoVar);
if(!value.isNull()) {
DoAssignExpr(stoVar, value);
}
}
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
ArrayType DoArrayDecl(Type type, STO indexSTO) {
boolean errorFlag = false;
int size = 0;
if(!indexSTO.isError()) {
// Do Array checks if type = ArrayType
if(!indexSTO.getType().isEquivalent(new IntType())) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error10i_Array, indexSTO.getType().getName()));
errorFlag = true;
}
if(!indexSTO.isConst()) {
m_nNumErrors++;
m_errors.print(ErrorMsg.error10c_Array);
errorFlag = true;
}
else if (((ConstSTO)indexSTO).getIntValue() <= 0) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error10z_Array, ((ConstSTO)indexSTO).getIntValue()));
errorFlag = true;
}
if (errorFlag == false) {
size = ((ConstSTO)indexSTO).getIntValue();
}
}
return new ArrayType(type, size);
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void DoExternDecl(Type type, Vector<String> lstIDs)
{
for(int i = 0; i < lstIDs.size(); i++) {
String id = lstIDs.elementAt(i);
if(m_symtab.accessLocal(id) != null) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id));
}
VarSTO sto = new VarSTO(id, type);
m_symtab.insert(sto);
}
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void DoConstDecl(Type type, Vector<IdValueTuple> lstIDs)
{
// Check for previous errors
for(int i = 0; i < lstIDs.size(); i++) {
if(lstIDs.elementAt(i).getValue().isError())
return;
//return lstIDs.elementAt(i).value;
}
for(int i = 0; i < lstIDs.size(); i++) {
String id = lstIDs.elementAt(i).getId();
STO value = lstIDs.elementAt(i).getValue();
// Check for constant already existing in localScope
if(m_symtab.accessLocal(id) != null) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id));
return;
}
// Check #8a - init value not known at compiler time
if(!value.isConst()) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error8_CompileTime, id));
return;
}
// Check #8b
if(!value.getType().isAssignable(type)) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error8_Assign, value.getType().getName(), type.getName()));
return;
}
STO sto = new ConstSTO(id, type, ((ConstSTO)value).getValue());
m_symtab.insert(sto);
}
}
/*
DoVarDecl(Type type, Vector<IdValueTuple> lstIDs)
{
for(int i = 0; i < lstIDs.size(); i++)
{
String id = lstIDs.elementAt(i).getId();
STO value = lstIDs.elementAt(i).getValue();
// Check for var already existing in localScope
if(m_symtab.accessLocal(id) != null)
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id));
}
VarSTO stoVar = new VarSTO(id, type);
m_symtab.insert(stoVar);
if(!value.isNull())
{
DoAssignExpr(stoVar, value);
}
}
}
*/
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void DoTypedefDecl(Type type, Vector<String> lstIDs)
{
for(int i = 0; i < lstIDs.size(); i++) {
String id = lstIDs.elementAt(i);
if(m_symtab.accessLocal(id) != null) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id));
}
// Do Array checks if type = ArrayType
/* if(type.isArray()) {
STO stoResult = ((ArrayType)type);
}*/
type.setName(id);
TypedefSTO sto = new TypedefSTO(id, type, false, false);
m_symtab.insert(sto);
}
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void DoStructdefDeclStart(String id)
{
m_inStructdef = true;
m_structId = id;
m_currentStructdef = new Scope();
// TODO: Need to add the name of the struct type to scope so we can look for the type for function pointers done inside struct
if(m_symtab.accessLocal(id) != null) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id));
} else {
TypedefSTO sto = new TypedefSTO(m_structId, new StructType(m_structId), false, false);
m_symtab.insert(sto);
}
}
STO DoStructdefField(String id, Type type)
//void DoStructdefField(String id, STO thisSTO)
{
// Check for duplicate names
// Check 13a
if(m_currentStructdef.accessLocal(id) != null) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error13a_Struct, id));
//return new ErrorSTO("Error- Field declared second time in struct");
}
// Check 13b
// Check that the type is not this same type of struct and that it's not a pointer in that case
else if((type.getName().equals(id)) && (!type.isPointer())) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error13b_Struct, id));
// return new ErrorSTO("Error- Size of field cannot be determined at compile time.");
}
VarSTO var = new VarSTO(id, type);
m_currentStructdef.InsertLocal(var);
return var;
// create the STO
// m_currentStructdef.InsertLocal(thisSTO);
// return thisSTO;
}
void DoStructdefDeclFinish(String id, Vector<STO> fieldList)
{
// check for struct in scope
// old line if(m_currentStructdef.accessLocal(id) != null) {
if(m_symtab.accessLocal(id) != null) {
// get size of struct
int size = 0;
for(STO sto : fieldList) {
if(sto.isFunc()) continue;
- System.out.println(sto.getType().getName() +" "+sto.getName() +" "+sto.getType().getSize());
size += sto.getType().getSize();
}
// get TypedefSTO of StructType
TypedefSTO sto = (TypedefSTO) m_symtab.accessLocal(id);
- System.out.println(sto.getName());
sto.getType().setSize(size);
((StructType) sto.getType()).setFields(fieldList);
- System.out.println("Size:"+m_symtab.access(id).getType().getSize());
- //TypedefSTO sto = new TypedefSTO(id, new StructType("StructType", size, fieldList), false, false);
-
- //m_symtab.insert(sto);
}
m_inStructdef = false;
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
STO DoFuncDecl_1(Type returnType, String id, Boolean retByRef)
{
STO accessedSTO;
if(m_inStructdef)
accessedSTO = m_currentStructdef.access(id);
else
accessedSTO = m_symtab.accessLocal(id);
// Check for func already existing in localScope
if(accessedSTO != null) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id));
}
FuncSTO sto = new FuncSTO(id, retByRef);
// Set return type
sto.setReturnType(returnType);
if(m_inStructdef)
m_currentStructdef.InsertLocal(sto);
else
m_symtab.insert(sto);
m_symtab.openScope();
m_symtab.setFunc(sto);
// Set the function's level
sto.setLevel(m_symtab.getLevel());
return sto;
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void DoFuncDecl_2()
{
FuncSTO stoFunc;
if((stoFunc = m_symtab.getFunc()) == null) {
m_nNumErrors++;
m_errors.print("internal: DoFuncDecl_2 says no proc!");
return;
}
// Check #6c - no return statement for non-void type function
if(!stoFunc.getReturnType().isVoid()) {
if(!stoFunc.getHasReturnStatement()) {
m_nNumErrors++;
m_errors.print(ErrorMsg.error6c_Return_missing);
}
}
m_symtab.closeScope();
m_symtab.setFunc(null);
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void DoFormalParams(Vector<ParamSTO> params)
{
FuncSTO stoFunc;
if((stoFunc = m_symtab.getFunc()) == null) {
m_nNumErrors++;
m_errors.print("internal: DoFormalParams says no proc!");
return;
}
// Insert parameters
stoFunc.setParameters(params);
// Add parameters to local scope
for(STO thisParam: params) {
/* Not sure if want this check
if(m_symtab.accessLocal(id) != null)
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id));
}
*/
m_symtab.insert(thisParam);
}
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void DoBlockOpen()
{
// Open a scope.
m_symtab.openScope();
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void DoBlockClose()
{
m_symtab.closeScope();
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
STO DoAssignExpr(STO stoDes, STO stoValue)
{
// Check for previous errors in line and short circuit
if(stoDes.isError()) {
return stoDes;
}
if(stoValue.isError()) {
return stoValue;
}
// Check #3a - illegal assignment - not modifiable L-value
if(!stoDes.isModLValue()) {
m_nNumErrors++;
m_errors.print(ErrorMsg.error3a_Assign);
return (new ErrorSTO("DoAssignExpr Error - not mod-L-Value"));
}
if(!stoValue.getType().isAssignable(stoDes.getType())) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error3b_Assign, stoValue.getType().getName(), stoDes.getType().getName()));
return (new ErrorSTO("DoAssignExpr Error - bad types"));
}
return stoDes;
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
STO DoFuncCall(STO sto, Vector<STO> args)
{
// Check for previous errors
if(sto.isError())
return sto;
for(int i = 0; i < args.size(); i++) {
if(args.elementAt(i).isError())
return args.elementAt(i);
}
if(!sto.isFunc()) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.not_function, sto.getName()));
return (new ErrorSTO(sto.getName()));
}
// We know it's a function, do function call checks
FuncSTO stoFunc =(FuncSTO)sto;
// Check #5
// Check #5a - # args = # params
if((stoFunc.getNumOfParams() != args.size())) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error5n_Call, args.size(), stoFunc.getNumOfParams()));
return (new ErrorSTO("DoFuncCall - # args"));
}
// Now we check each arg individually, accepting one error per arg
boolean error_flag = false;
for(int i = 0; i < args.size(); i++) {
// For readability and shorter lines
ParamSTO thisParam = stoFunc.getParameters().elementAt(i);
STO thisArg = args.elementAt(i);
// Check #5b - non-assignable arg for pass-by-value param
if(!thisParam.isPassByReference()) {
if(!thisArg.getType().isAssignable(thisParam.getType())) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error5a_Call, thisArg.getType().getName(), thisParam.getName(), thisParam.getType().getName()));
error_flag = true;
continue;
}
}
else {
// Check #5c - arg type not equivalent to pass-by-ref param type
if(!thisArg.getType().isEquivalent(thisParam.getType())) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error5r_Call, thisArg.getType().getName(), thisParam.getName(), thisParam.getType().getName()));
error_flag = true;
continue;
}
// Check #5d - arg not modifiable l-value for pass by ref param
if(!thisArg.isModLValue()) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error5c_Call, thisParam.getName(), thisArg.getType().getName()));
error_flag = true;
continue;
}
}
}
if(error_flag) {
// Error occured in at least one arg, return error
return (new ErrorSTO("DoFuncCall - Check 5"));
}
else {
// Func call legal, return function return type
return (new ExprSTO(stoFunc.getName() + " return type", stoFunc.getReturnType()));
}
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
STO DoDesignator2_Dot(STO sto, String strID)
{
STO returnSTO = null;
// Good place to do the struct checks
if(sto.isError()) {
return sto;
}
// Check #14a
// type of struct is not a struct type
if(!sto.getType().isStruct()) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error14t_StructExp, sto.getType().getName()));
return new ErrorSTO("Struct Error - not a struct");
}
// Check #14b
if((m_inStructdef) && ((m_structId == sto.getType().getName()) || sto.getName().equals("this"))) {
if(m_currentStructdef.accessLocal(strID) == null) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error14b_StructExpThis, strID));
return new ErrorSTO("Struct Error - field not in Struct");
}
else {
returnSTO = m_currentStructdef.accessLocal(strID);
}
}
else {
// Check #14a
boolean found_flag = false; // type of struct does not contain the field or function
Vector<STO> fieldList = ((StructType)sto.getType()).getFields();
for(STO thisSTO: fieldList) {
if(thisSTO.getName().equals(strID)) {
found_flag = true;
returnSTO = thisSTO;
}
}
if(!found_flag) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error14f_StructExp, strID, sto.getType().getName()));
return new ErrorSTO("Struct Error - field not found in type");
}
}
return returnSTO;
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
STO DoDesignator2_Arrow(STO sto, String strID)
{
STO returnSTO = null;
// Good place to do the struct checks
if(sto.isError()) {
return sto;
}
// Check 15b
// if it's a pointer but not a struct pointer
if(sto.getType().isPtrGrp()) {
if(!((PtrGrpType) sto.getType()).getPointsToType().isStruct()) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error15_ReceiverArrow, sto.getType().getName()));
return new ErrorSTO("Pointer Error - Doesn't point to struct pointer");
}
}
// If it's not a pointer
else {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error15_ReceiverArrow, sto.getType().getName()));
return new ErrorSTO("Pointer Error - Doesn't point to struct pointer");
}
// It's a pointer, check if the field is valid
// Check 14a
StructType structType = (StructType) ((PtrGrpType) sto.getType()).getPointsToType();
// if the struct we're accessing is the struct being defined
if((m_inStructdef) && (m_structId == structType.getName())) {
if(m_currentStructdef.accessLocal(strID) == null) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error14b_StructExpThis, strID));
return new ErrorSTO("Struct Error - field not in Struct");
}
else {
returnSTO = m_currentStructdef.accessLocal(strID);
}
}
// The struct we're accessing isn't the current struct
else {
boolean found_flag = false; // type of struct does not contain the field or function
Vector<STO> fieldList = structType.getFields();
for(STO thisSTO: fieldList) {
if(thisSTO.getName().equals(strID)) {
found_flag = true;
returnSTO = thisSTO;
}
}
if(!found_flag) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error14f_StructExp, strID, structType.getName()));
return new ErrorSTO("Struct Error - field not found in type");
}
}
return returnSTO;
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
STO DoDesignator2_Array(STO desSTO, STO indexSTO)
{
// desSTO: the identifier
// indexSTO: the expression inside the []
if(desSTO.isError()) {
return desSTO;
}
// Check #11a
// bullet 1 - desSTO is not array or pointer type
if((!desSTO.getType().isArray()) && (!desSTO.getType().isPointer())) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error11t_ArrExp, desSTO.getType().getName()));
return new ErrorSTO("Desig2_Array() - Not array or ptr");
}
// bullet 2 - index expression type is not equiv to int
if(!indexSTO.getType().isEquivalent(new IntType())) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error11i_ArrExp, indexSTO.getType().getName()));
return new ErrorSTO("Desig2_Array() - index not equiv to int");
}
// bullet 3 - index expr is constant, error if indexExpr outside bounds of array dimension
// except when desSTO is pointer type
if(indexSTO.isConst()) {
if(((ConstSTO)indexSTO).getIntValue() >= (((ArrayType)desSTO.getType()).getDimensionSize()) || ((ConstSTO)indexSTO).getIntValue() < 0) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error11b_ArrExp, ((ConstSTO)indexSTO).getIntValue(), ((ArrayType)desSTO.getType()).getDimensionSize()));
return new ErrorSTO("Desig2_Array() - index is constant, out of bounds");
}
}
// Checks are complete, now we need to return an ExprSTO with the type of the array elements
desSTO = new VarSTO(((ArrayType)desSTO.getType()).getElementType().getName(),((ArrayType)desSTO.getType()).getElementType());
//TODO: Double check what the name of exprSTO should be.
return desSTO;
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
STO DoDesignator3_GlobalID(String strID)
{
STO sto;
if((sto = m_symtab.accessGlobal(strID)) == null) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error0g_Scope, strID));
sto = new ErrorSTO(strID);
}
return (sto);
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
STO DoDesignator3_ID(String strID)
{
STO sto;
if((sto = m_symtab.access(strID)) == null) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.undeclared_id, strID));
sto = new ErrorSTO(strID);
}
return (sto);
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
STO DoQualIdent(String strID)
{
STO sto;
if((sto = m_symtab.access(strID)) == null) {
if(m_inStructdef) {
if(!m_structId.equals(strID)) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.undeclared_id, strID));
return (new ErrorSTO(strID));
}
}
}
if(!sto.isTypedef()) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.not_type, sto.getName()));
return (new ErrorSTO(sto.getName()));
}
return (sto);
}
//----------------------------------------------------------------
// DoBinaryOp
//----------------------------------------------------------------
STO DoBinaryOp(BinaryOp op, STO operand1, STO operand2)
{
// Check for previous errors in line and short circuit
if(operand1.isError()) {
return operand1;
}
if(operand2.isError()) {
return operand2;
}
// Use BinaryOp.checkOperands() to perform error checks
STO resultSTO = op.checkOperands(operand1, operand2);
// If operands are constants, do the op
if((!resultSTO.isError()) && (resultSTO.isConst())) {
resultSTO = op.doOperation((ConstSTO)operand1, (ConstSTO)operand2, resultSTO.getType());
}
// Process/Print errors
if(resultSTO.isError()) {
m_nNumErrors++;
m_errors.print(resultSTO.getName());
}
return resultSTO;
}
//----------------------------------------------------------------
// DoUnaryOp
//----------------------------------------------------------------
STO DoUnaryOp(UnaryOp op, STO operand)
{
// Check for previous errors in line and short circuit
if(operand.isError()) {
return operand;
}
// Use UnaryOp.checkOperand() to perform error checks
STO resultSTO = op.checkOperand(operand);
// If operand is a constant, do the op
if((!resultSTO.isError()) && (resultSTO.isConst())) {
resultSTO = op.doOperation((ConstSTO)operand, resultSTO.getType());
}
// Process/Print errors
if(resultSTO.isError()) {
m_nNumErrors++;
m_errors.print(resultSTO.getName());
}
return resultSTO;
}
//----------------------------------------------------------------
// DoWhileExpr
//----------------------------------------------------------------
STO DoWhileExpr(STO stoExpr)
{
// Check for previous errors in line and short circuit
if(stoExpr.isError()) {
return stoExpr;
}
// Check #4 - while expr - int or bool
if((!stoExpr.getType().isInt()) &&(!stoExpr.getType().isBool())) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error4_Test, stoExpr.getType().getName()));
return (new ErrorSTO("DoWhile error"));
}
whileLevelUp();
return stoExpr;
}
//----------------------------------------------------------------
// DoIfExpr
//----------------------------------------------------------------
STO DoIfExpr(STO stoExpr)
{
// Check for previous errors in line and short circuit
if(stoExpr.isError()) {
return stoExpr;
}
// Check #4 - if expr - int or bool
if((!stoExpr.getType().isInt()) &&(!stoExpr.getType().isBool())) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error4_Test, stoExpr.getType().getName()));
return (new ErrorSTO("DoIf error"));
}
return stoExpr;
}
//----------------------------------------------------------------
// DoReturnStmt_1
//----------------------------------------------------------------
STO DoReturnStmt_1()
{
FuncSTO stoFunc;
if((stoFunc = m_symtab.getFunc()) == null) {
m_nNumErrors++;
m_errors.print("internal: DoReturnStmt_1 says no proc!");
return (new ErrorSTO("DoReturnStmt_1 Error"));
}
// Check #6a - no expr on non-void rtn
if(!stoFunc.getReturnType().isVoid()) {
m_nNumErrors++;
m_errors.print(ErrorMsg.error6a_Return_expr);
return (new ErrorSTO("DoReturnStmt_1 Error"));
}
// valid return statement, set func.hasReturnStatement if at right level
if(stoFunc.getLevel() == m_symtab.getLevel()) {
stoFunc.setHasReturnStatement(true);
}
return (new ExprSTO(stoFunc.getName() + " Return", new VoidType()));
}
//----------------------------------------------------------------
// DoReturnStmt_2
//----------------------------------------------------------------
STO DoReturnStmt_2(STO stoExpr)
{
FuncSTO stoFunc;
// Check for previous errors in line and short circuit
if(stoExpr.isError()) {
return stoExpr;
}
if((stoFunc = m_symtab.getFunc()) == null) {
m_nNumErrors++;
m_errors.print("internal: DoReturnStmt_2 says no proc!");
return (new ErrorSTO("DoReturnStmt_2 Error"));
}
// Check #6b - 1st bullet - rtn by val - rtn expr type not assignable to return
if(!stoFunc.getReturnByRef()) {
if(!stoExpr.getType().isAssignable(stoFunc.getReturnType())) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg. error6a_Return_type, stoExpr.getType().getName(), stoFunc.getReturnType().getName()));
return (new ErrorSTO("DoReturnStmt_2 Error"));
}
}
else {
// Check #6b - 2nd bullet - rtn by ref - rtn expr type not equivalent to return type
if(!stoExpr.getType().isEquivalent(stoFunc.getReturnType())) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error6b_Return_equiv, stoExpr.getType().getName(), stoFunc.getReturnType().getName()));
return (new ErrorSTO("DoReturnStmt_2 Error"));
}
// Check #6b - 3rd bullet - rtn by ref - rtn expr not modLValue
if(!stoExpr.isModLValue()) {
m_nNumErrors++;
m_errors.print(ErrorMsg.error6b_Return_modlval);
return (new ErrorSTO("DoReturnStmt_2 Error"));
}
}
// valid return statement, set func.hasReturnStatement if at right level
if(stoFunc.getLevel() == m_symtab.getLevel()) {
stoFunc.setHasReturnStatement(true);
}
return stoExpr;
}
//----------------------------------------------------------------
// DoExitStmt
//----------------------------------------------------------------
STO DoExitStmt(STO stoExpr)
{
// Check for previous errors in line and short circuit
if(stoExpr.isError()) {
return stoExpr;
}
// Check #7 - exit value assignable to int
if(!stoExpr.getType().isAssignable(new IntType())) {
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error7_Exit, stoExpr.getType().getName()));
}
return stoExpr;
}
//----------------------------------------------------------------
// DoBreakStmt
//----------------------------------------------------------------
void DoBreakStmt()
{
// Check #12 - break statement in while loop
if(m_whileLevel <= 0) {
m_nNumErrors++;
m_errors.print(ErrorMsg.error12_Break);
}
}
//----------------------------------------------------------------
// DoBreakStmt
//----------------------------------------------------------------
void DoContinueStmt()
{
// Check #12 - continue statement in while loop
if(m_whileLevel <= 0) {
m_nNumErrors++;
m_errors.print(ErrorMsg.error12_Continue);
}
}
void whileLevelUp()
{
m_whileLevel++;
}
void whileLevelDown()
{
m_whileLevel--;
}
STO DoSizeOf(STO sto, Type type)
{
int size = 0;
//Either type or type is null
if (sto == null) {
size = type.getSize();
} else if (type == null){
if (sto.getIsAddressable() && sto.getType() != null) {
size = sto.getType().getSize();
} else {
m_nNumErrors++;
m_errors.print(ErrorMsg.error19_Sizeof);
}
} else {
m_nNumErrors++;
m_errors.print(ErrorMsg.error19_Sizeof);
}
return new ConstSTO("ConstInt", new IntType("int",4), (double)size);
}
//----------------------------------------------------------------
// DoBuildType
//----------------------------------------------------------------
Type DoBuildType(Type subType, Type ptrType, STO arrayIndex)
{
Type returnType = subType;
// TODO: Possibly check arrayIndex for errorSTO
// TODO: Do type null check here if decided needed
// Check if arrayIndex is null - this means it is not an array
if(arrayIndex != null) {
returnType = DoArrayDecl(subType, arrayIndex);
// TODO: Might need to do something else here if arrayType isn't valid
}
if(ptrType != null) {
((PtrGrpType) ptrType).setBottomPtrType(returnType);
returnType = ptrType;
}
return returnType;
}
}
| false | false | null | null |
diff --git a/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java b/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java
index d876abaa..5b6a5eb1 100644
--- a/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java
+++ b/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java
@@ -1,11077 +1,11077 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.site.tool;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Random;
import java.util.Set;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.alias.api.Alias;
import org.sakaiproject.alias.cover.AliasService;
import org.sakaiproject.archive.api.ImportMetadata;
import org.sakaiproject.archive.cover.ArchiveService;
import org.sakaiproject.authz.api.AuthzGroup;
import org.sakaiproject.authz.api.AuthzPermissionException;
import org.sakaiproject.authz.api.GroupNotDefinedException;
import org.sakaiproject.authz.api.Member;
import org.sakaiproject.authz.api.PermissionsHelper;
import org.sakaiproject.authz.api.Role;
import org.sakaiproject.authz.cover.AuthzGroupService;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.cheftool.Context;
import org.sakaiproject.cheftool.JetspeedRunData;
import org.sakaiproject.cheftool.PagedResourceActionII;
import org.sakaiproject.cheftool.PortletConfig;
import org.sakaiproject.cheftool.RunData;
import org.sakaiproject.cheftool.VelocityPortlet;
import org.sakaiproject.cheftool.api.Menu;
import org.sakaiproject.cheftool.api.MenuItem;
import org.sakaiproject.cheftool.menu.MenuEntry;
import org.sakaiproject.cheftool.menu.MenuImpl;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.content.cover.ContentHostingService;
import org.sakaiproject.email.cover.EmailService;
import org.sakaiproject.entity.api.EntityProducer;
import org.sakaiproject.entity.api.EntityPropertyNotDefinedException;
import org.sakaiproject.entity.api.EntityPropertyTypeException;
import org.sakaiproject.entity.api.EntityTransferrer;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.entity.cover.EntityManager;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.id.cover.IdManager;
import org.sakaiproject.javax.PagingPosition;
import org.sakaiproject.mailarchive.api.MailArchiveService;
import org.sakaiproject.site.api.Course;
import org.sakaiproject.site.api.CourseMember;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SitePage;
import org.sakaiproject.site.api.Term;
import org.sakaiproject.site.api.ToolConfiguration;
import org.sakaiproject.site.api.SiteService.SortType;
import org.sakaiproject.site.cover.CourseManagementService;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.util.SubjectAffiliates;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.api.TimeBreakdown;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.Tool;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserAlreadyDefinedException;
import org.sakaiproject.user.api.UserEdit;
import org.sakaiproject.user.api.UserIdInvalidException;
import org.sakaiproject.user.api.UserNotDefinedException;
import org.sakaiproject.user.api.UserPermissionException;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.sakaiproject.util.ArrayUtil;
import org.sakaiproject.util.FileItem;
import org.sakaiproject.util.ParameterParser;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.SortedIterator;
import org.sakaiproject.util.StringUtil;
import org.sakaiproject.util.Validator;
import org.sakaiproject.importer.api.ImportService;
import org.sakaiproject.importer.api.ImportDataSource;
import org.sakaiproject.importer.api.SakaiArchive;
/**
* <p>SiteAction controls the interface for worksite setup.</p>
*/
public class SiteAction extends PagedResourceActionII
{
/** Our logger. */
private static Log M_log = LogFactory.getLog(SiteAction.class);
private ImportService importService = org.sakaiproject.importer.cover.ImportService.getInstance();
/** portlet configuration parameter values**/
/** Resource bundle using current language locale */
private static ResourceLoader rb = new ResourceLoader("sitesetupgeneric");
private static final String SITE_MODE_SITESETUP = "sitesetup";
private static final String SITE_MODE_SITEINFO= "siteinfo";
private static final String STATE_SITE_MODE = "site_mode";
protected final static String[] TEMPLATE =
{
"-list",//0
"-type",
"-newSiteInformation",
"-newSiteFeatures",
"-addRemoveFeature",
"-addParticipant",
"-removeParticipants",
"-changeRoles",
"-siteDeleteConfirm",
"-publishUnpublish",
"-newSiteConfirm",//10
"-newSitePublishUnpublish",
"-siteInfo-list",//12
"-siteInfo-editInfo",
"-siteInfo-editInfoConfirm",
"-addRemoveFeatureConfirm",//15
"-publishUnpublish-sendEmail",
"-publishUnpublish-confirm",
"-siteInfo-editAccess",
"-addParticipant-sameRole",
"-addParticipant-differentRole",//20
"-addParticipant-notification",
"-addParticipant-confirm",
"-siteInfo-editAccess-globalAccess",
"-siteInfo-editAccess-globalAccess-confirm",
"-changeRoles-confirm",//25
"-modifyENW",
"-importSites",
"-siteInfo-import",
"-siteInfo-duplicate",
"",//30
"",//31
"",//32
"",//33
"",//34
"",//35
"-newSiteCourse",//36
"-newSiteCourseManual",//37
"",//38
"",//39
"",//40
"",//41
"-gradtoolsConfirm",//42
"-siteInfo-editClass",//43
"-siteInfo-addCourseConfirm",//44
"-siteInfo-importMtrlMaster", //45 -- htripath for import material from a file
"-siteInfo-importMtrlCopy", //46
"-siteInfo-importMtrlCopyConfirm",
"-siteInfo-importMtrlCopyConfirmMsg", //48
"-siteInfo-group", //49
"-siteInfo-groupedit", //50
"-siteInfo-groupDeleteConfirm" //51
};
/** Name of state attribute for Site instance id */
private static final String STATE_SITE_INSTANCE_ID = "site.instance.id";
/** Name of state attribute for Site Information */
private static final String STATE_SITE_INFO = "site.info";
/** Name of state attribute for CHEF site type */
private static final String STATE_SITE_TYPE = "site-type";
/** Name of state attribute for poissible site types */
private static final String STATE_SITE_TYPES = "site_types";
private static final String STATE_DEFAULT_SITE_TYPE = "default_site_type";
private static final String STATE_PUBLIC_CHANGEABLE_SITE_TYPES = "changeable_site_types";
private static final String STATE_PUBLIC_SITE_TYPES = "public_site_types";
private static final String STATE_PRIVATE_SITE_TYPES = "private_site_types";
private static final String STATE_DISABLE_JOINABLE_SITE_TYPE = "disable_joinable_site_types";
//Names of state attributes corresponding to properties of a site
private final static String PROP_SITE_CONTACT_EMAIL = "contact-email";
private final static String PROP_SITE_CONTACT_NAME = "contact-name";
private final static String PROP_SITE_TERM = "term";
/** Name of the state attribute holding the site list column list is sorted by */
private static final String SORTED_BY = "site.sorted.by";
/** the list of criteria for sorting */
private static final String SORTED_BY_TITLE = "title";
private static final String SORTED_BY_DESCRIPTION = "description";
private static final String SORTED_BY_TYPE = "type";
private static final String SORTED_BY_STATUS = "status";
private static final String SORTED_BY_CREATION_DATE = "creationdate";
private static final String SORTED_BY_JOINABLE = "joinable";
private static final String SORTED_BY_PARTICIPANT_NAME = "participant_name";
private static final String SORTED_BY_PARTICIPANT_UNIQNAME = "participant_uniqname";
private static final String SORTED_BY_PARTICIPANT_ROLE = "participant_role";
private static final String SORTED_BY_PARTICIPANT_ID = "participant_id";
private static final String SORTED_BY_PARTICIPANT_COURSE = "participant_course";
private static final String SORTED_BY_PARTICIPANT_CREDITS = "participant_credits";
private static final String SORTED_BY_MEMBER_NAME = "member_name";
/** Name of the state attribute holding the site list column to sort by */
private static final String SORTED_ASC = "site.sort.asc";
/** State attribute for list of sites to be deleted. */
private static final String STATE_SITE_REMOVALS = "site.removals";
/** Name of the state attribute holding the site list View selected */
private static final String STATE_VIEW_SELECTED = "site.view.selected";
/** Names of lists related to tools */
private static final String STATE_TOOL_REGISTRATION_LIST = "toolRegistrationList";
private static final String STATE_TOOL_REGISTRATION_SELECTED_LIST = "toolRegistrationSelectedList";
private static final String STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST = "toolRegistrationOldSelectedList";
private static final String STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME = "toolRegistrationOldSelectedHome";
private static final String STATE_TOOL_EMAIL_ADDRESS = "toolEmailAddress";
private static final String STATE_TOOL_HOME_SELECTED = "toolHomeSelected";
private static final String STATE_PROJECT_TOOL_LIST = "projectToolList";
private final static String STATE_NEWS_TITLES = "newstitles";
private final static String STATE_NEWS_URLS = "newsurls";
private final static String NEWS_DEFAULT_TITLE = ServerConfigurationService.getString("news.title");
private final static String NEWS_DEFAULT_URL = ServerConfigurationService.getString("news.feedURL");
private final static String STATE_WEB_CONTENT_TITLES = "webcontenttitles";
private final static String STATE_WEB_CONTENT_URLS = "wcUrls";
private final static String WEB_CONTENT_DEFAULT_TITLE = "Web Content";
private final static String WEB_CONTENT_DEFAULT_URL = "http://";
private final static String STATE_SITE_QUEST_UNIQNAME = "site_quest_uniqname";
// %%% get rid of the IdAndText tool lists and just use ToolConfiguration or ToolRegistration lists
// %%% same for CourseItems
// Names for other state attributes that are lists
private final static String STATE_WORKSITE_SETUP_PAGE_LIST = "wSetupPageList"; // the list of site pages consistent with Worksite Setup page patterns
/** The name of the state form field containing additional information for a course request */
private static final String FORM_ADDITIONAL = "form.additional";
/** %%% in transition from putting all form variables in state*/
private final static String FORM_TITLE = "form_title";
private final static String FORM_DESCRIPTION = "form_description";
private final static String FORM_HONORIFIC = "form_honorific";
private final static String FORM_INSTITUTION = "form_institution";
private final static String FORM_SUBJECT = "form_subject";
private final static String FORM_PHONE = "form_phone";
private final static String FORM_EMAIL = "form_email";
private final static String FORM_REUSE = "form_reuse";
private final static String FORM_RELATED_CLASS = "form_related_class";
private final static String FORM_RELATED_PROJECT = "form_related_project";
private final static String FORM_NAME = "form_name";
private final static String FORM_SHORT_DESCRIPTION = "form_short_description";
private final static String FORM_ICON_URL = "iconUrl";
/** site info edit form variables */
private final static String FORM_SITEINFO_TITLE = "siteinfo_title";
private final static String FORM_SITEINFO_TERM = "siteinfo_term";
private final static String FORM_SITEINFO_DESCRIPTION = "siteinfo_description";
private final static String FORM_SITEINFO_SHORT_DESCRIPTION = "siteinfo_short_description";
private final static String FORM_SITEINFO_SKIN = "siteinfo_skin";
private final static String FORM_SITEINFO_INCLUDE = "siteinfo_include";
private final static String FORM_SITEINFO_ICON_URL = "siteinfo_icon_url";
private final static String FORM_SITEINFO_CONTACT_NAME = "siteinfo_contact_name";
private final static String FORM_SITEINFO_CONTACT_EMAIL = "siteinfo_contact_email";
private final static String FORM_WILL_NOTIFY = "form_will_notify";
/** Context action */
private static final String CONTEXT_ACTION = "SiteAction";
/** The name of the Attribute for display template index */
private static final String STATE_TEMPLATE_INDEX = "site.templateIndex";
/** State attribute for state initialization. */
private static final String STATE_INITIALIZED = "site.initialized";
/** The action for menu */
private static final String STATE_ACTION = "site.action";
/** The user copyright string */
private static final String STATE_MY_COPYRIGHT = "resources.mycopyright";
/** The copyright character */
private static final String COPYRIGHT_SYMBOL = "copyright (c)";
/** The null/empty string */
private static final String NULL_STRING = "";
/** The state attribute alerting user of a sent course request */
private static final String REQUEST_SENT = "site.request.sent";
/** The state attributes in the make public vm */
private static final String STATE_JOINABLE = "state_joinable";
private static final String STATE_JOINERROLE = "state_joinerRole";
/** the list of selected user */
private static final String STATE_SELECTED_USER_LIST = "state_selected_user_list";
private static final String STATE_SELECTED_PARTICIPANT_ROLES = "state_selected_participant_roles";
private static final String STATE_SELECTED_PARTICIPANTS = "state_selected_participants";
private static final String STATE_PARTICIPANT_LIST = "state_participant_list";
private static final String STATE_ADD_PARTICIPANTS = "state_add_participants";
/** for changing participant roles*/
private static final String STATE_CHANGEROLE_SAMEROLE = "state_changerole_samerole";
private static final String STATE_CHANGEROLE_SAMEROLE_ROLE = "state_changerole_samerole_role";
/** for remove user */
private static final String STATE_REMOVEABLE_USER_LIST = "state_removeable_user_list";
private static final String STATE_IMPORT = "state_import";
private static final String STATE_IMPORT_SITES = "state_import_sites";
private static final String STATE_IMPORT_SITE_TOOL = "state_import_site_tool";
/** for navigating between sites in site list */
private static final String STATE_SITES = "state_sites";
private static final String STATE_PREV_SITE = "state_prev_site";
private static final String STATE_NEXT_SITE = "state_next_site";
/** for course information */
private final static String STATE_TERM_COURSE_LIST = "state_term_course_list";
private final static String STATE_TERM_SELECTED = "state_term_selected";
private final static String STATE_FUTURE_TERM_SELECTED = "state_future_term_selected";
private final static String STATE_ADD_CLASS_PROVIDER = "state_add_class_provider";
private final static String STATE_ADD_CLASS_PROVIDER_CHOSEN = "state_add_class_provider_chosen";
private final static String STATE_ADD_CLASS_MANUAL = "state_add_class_manual";
private final static String STATE_AUTO_ADD = "state_auto_add";
private final static String STATE_MANUAL_ADD_COURSE_NUMBER = "state_manual_add_course_number";
private final static String STATE_MANUAL_ADD_COURSE_FIELDS = "state_manual_add_course_fields";
public final static String PROP_SITE_REQUEST_COURSE = "site-request-course-sections";
public final static String SITE_PROVIDER_COURSE_LIST = "site_provider_course_list";
public final static String SITE_MANUAL_COURSE_LIST = "site_manual_course_list";
private final static String STATE_SUBJECT_AFFILIATES = "site.subject.affiliates";
private final static String STATE_ICONS = "icons";
//site template used to create a UM Grad Tools student site
public static final String SITE_GTS_TEMPLATE = "!gtstudent";
//the type used to identify a UM Grad Tools student site
public static final String SITE_TYPE_GRADTOOLS_STUDENT = "GradToolsStudent";
//list of UM Grad Tools site types for editing
public static final String GRADTOOLS_SITE_TYPES = "gradtools_site_types";
public static final String SITE_DUPLICATED = "site_duplicated";
public static final String SITE_DUPLICATED_NAME = "site_duplicated_named";
// used for site creation wizard title
public static final String SITE_CREATE_TOTAL_STEPS = "site_create_total_steps";
public static final String SITE_CREATE_CURRENT_STEP = "site_create_current_step";
// types of site whose title can be editable
public static final String TITLE_EDITABLE_SITE_TYPE = "title_editable_site_type";
// types of site where site view roster permission is editable
public static final String EDIT_VIEW_ROSTER_SITE_TYPE = "edit_view_roster_site_type";
//htripath : for import material from file - classic import
private static final String ALL_ZIP_IMPORT_SITES= "allzipImports";
private static final String FINAL_ZIP_IMPORT_SITES= "finalzipImports";
private static final String DIRECT_ZIP_IMPORT_SITES= "directzipImports";
private static final String CLASSIC_ZIP_FILE_NAME="classicZipFileName" ;
private static final String SESSION_CONTEXT_ID="sessionContextId";
// page size for worksite setup tool
private static final String STATE_PAGESIZE_SITESETUP = "state_pagesize_sitesetup";
// page size for site info tool
private static final String STATE_PAGESIZE_SITEINFO = "state_pagesize_siteinfo";
// group info
private static final String STATE_GROUP_INSTANCE_ID = "state_group_instance_id";
private static final String STATE_GROUP_TITLE = "state_group_title";
private static final String STATE_GROUP_DESCRIPTION = "state_group_description";
private static final String STATE_GROUP_MEMBERS = "state_group_members";
private static final String STATE_GROUP_REMOVE = "state_group_remove";
private static final String GROUP_PROP_WSETUP_CREATED = "group_prop_wsetup_created";
private static final String IMPORT_DATA_SOURCE = "import_data_source";
private static final String EMAIL_CHAR = "@";
// Special tool id for Home page
private static final String HOME_TOOL_ID = "home";
// the string marks the protocol part in url
private static final String PROTOCOL_STRING = "://";
/**
* Populate the state object, if needed.
*/
protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData rundata)
{
super.initState(state, portlet, rundata);
PortletConfig config = portlet.getPortletConfig();
// types of sites that can either be public or private
String changeableTypes = StringUtil.trimToNull(config.getInitParameter("publicChangeableSiteTypes"));
if (state.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES) == null)
{
if (changeableTypes != null)
{
state.setAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES, new ArrayList(Arrays.asList(changeableTypes.split(","))));
}
else
{
state.setAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES, new Vector());
}
}
// type of sites that are always public
String publicTypes = StringUtil.trimToNull(config.getInitParameter("publicSiteTypes"));
if (state.getAttribute(STATE_PUBLIC_SITE_TYPES) == null)
{
if (publicTypes != null)
{
state.setAttribute(STATE_PUBLIC_SITE_TYPES, new ArrayList(Arrays.asList(publicTypes.split(","))));
}
else
{
state.setAttribute(STATE_PUBLIC_SITE_TYPES, new Vector());
}
}
// types of sites that are always private
String privateTypes = StringUtil.trimToNull(config.getInitParameter("privateSiteTypes"));
if (state.getAttribute(STATE_PRIVATE_SITE_TYPES) == null)
{
if (privateTypes != null)
{
state.setAttribute(STATE_PRIVATE_SITE_TYPES, new ArrayList(Arrays.asList(privateTypes.split(","))));
}
else
{
state.setAttribute(STATE_PRIVATE_SITE_TYPES, new Vector());
}
}
// default site type
String defaultType = StringUtil.trimToNull(config.getInitParameter("defaultSiteType"));
if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) == null)
{
if (defaultType != null)
{
state.setAttribute(STATE_DEFAULT_SITE_TYPE, defaultType);
}
else
{
state.setAttribute(STATE_PRIVATE_SITE_TYPES, new Vector());
}
}
// certain type(s) of site cannot get its "joinable" option set
if (state.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE) == null)
{
if (ServerConfigurationService.getStrings("wsetup.disable.joinable") != null)
{
state.setAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE, new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("wsetup.disable.joinable"))));
}
else
{
state.setAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE, new Vector());
}
}
if (state.getAttribute(STATE_TOP_PAGE_MESSAGE) == null)
{
state.setAttribute(STATE_TOP_PAGE_MESSAGE, new Integer(0));
}
// affiliates if any
if (state.getAttribute(STATE_SUBJECT_AFFILIATES) == null)
{
setupSubjectAffiliates(state);
}
//skins if any
if (state.getAttribute(STATE_ICONS) == null)
{
setupIcons(state);
}
if (state.getAttribute(GRADTOOLS_SITE_TYPES) == null)
{
List gradToolsSiteTypes = new Vector();
if (ServerConfigurationService.getStrings("gradToolsSiteType") != null)
{
gradToolsSiteTypes = new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("gradToolsSiteType")));
}
state.setAttribute(GRADTOOLS_SITE_TYPES, gradToolsSiteTypes);
}
if (ServerConfigurationService.getStrings("titleEditableSiteType") != null)
{
state.setAttribute(TITLE_EDITABLE_SITE_TYPE, new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("titleEditableSiteType"))));
}
else
{
state.setAttribute(TITLE_EDITABLE_SITE_TYPE, new Vector());
}
if (state.getAttribute(EDIT_VIEW_ROSTER_SITE_TYPE) == null)
{
List siteTypes = new Vector();
if (ServerConfigurationService.getStrings("editViewRosterSiteType") != null)
{
siteTypes = new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("editViewRosterSiteType")));
}
state.setAttribute(EDIT_VIEW_ROSTER_SITE_TYPE, siteTypes);
}
//get site tool mode from tool registry
String site_mode = portlet.getPortletConfig().getInitParameter(STATE_SITE_MODE);
state.setAttribute(STATE_SITE_MODE, site_mode);
} // initState
/**
* cleanState removes the current site instance and it's properties from state
*/
private void cleanState(SessionState state)
{
state.removeAttribute(STATE_SITE_INSTANCE_ID);
state.removeAttribute(STATE_SITE_INFO);
state.removeAttribute(STATE_SITE_TYPE);
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
state.removeAttribute(STATE_TOOL_HOME_SELECTED);
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.removeAttribute(STATE_JOINABLE);
state.removeAttribute(STATE_JOINERROLE);
state.removeAttribute(STATE_NEWS_TITLES);
state.removeAttribute(STATE_NEWS_URLS);
state.removeAttribute(STATE_WEB_CONTENT_TITLES);
state.removeAttribute(STATE_WEB_CONTENT_URLS);
state.removeAttribute(STATE_SITE_QUEST_UNIQNAME);
state.removeAttribute(STATE_IMPORT);
state.removeAttribute(STATE_IMPORT_SITES);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
// remove those state attributes related to course site creation
state.removeAttribute(STATE_TERM_COURSE_LIST);
state.removeAttribute(STATE_TERM_SELECTED);
state.removeAttribute(STATE_FUTURE_TERM_SELECTED);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
state.removeAttribute(STATE_ADD_CLASS_MANUAL);
state.removeAttribute(STATE_AUTO_ADD);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(SITE_CREATE_TOTAL_STEPS);
state.removeAttribute(SITE_CREATE_CURRENT_STEP);
} // cleanState
/**
* Fire up the permissions editor
*/
public void doPermissions(RunData data, Context context)
{
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.permissions.helper");
SessionState state = ((JetspeedRunData)data).getPortletSessionState(((JetspeedRunData)data).getJs_peid());
String contextString = ToolManager.getCurrentPlacement().getContext();
String siteRef = SiteService.siteReference(contextString);
// if it is in Worksite setup tool, pass the selected site's reference
if (state.getAttribute(STATE_SITE_MODE) != null && ((String) state.getAttribute(STATE_SITE_MODE)).equals(SITE_MODE_SITESETUP))
{
if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null)
{
Site s = getStateSite(state);
if (s != null)
{
siteRef = s.getReference();
}
}
}
// setup for editing the permissions of the site for this tool, using the roles of this site, too
state.setAttribute(PermissionsHelper.TARGET_REF, siteRef);
// ... with this description
state.setAttribute(PermissionsHelper.DESCRIPTION, rb.getString("setperfor") + " "
+ SiteService.getSiteDisplay(contextString));
// ... showing only locks that are prpefixed with this
state.setAttribute(PermissionsHelper.PREFIX, "site.");
} // doPermissions
/**
* Build the context for normal display
*/
public String buildMainPanelContext ( VelocityPortlet portlet,
Context context,
RunData data,
SessionState state)
{
context.put("tlang",rb);
// TODO: what is all this doing? if we are in helper mode, we are already setup and don't get called here now -ggolden
/*
String helperMode = (String) state.getAttribute(PermissionsAction.STATE_MODE);
if (helperMode != null)
{
Site site = getStateSite(state);
if (site != null)
{
if (site.getType() != null && ((List) state.getAttribute(EDIT_VIEW_ROSTER_SITE_TYPE)).contains(site.getType()))
{
context.put("editViewRoster", Boolean.TRUE);
}
else
{
context.put("editViewRoster", Boolean.FALSE);
}
}
else
{
context.put("editViewRoster", Boolean.FALSE);
}
// for new, don't show site.del in Permission page
context.put("hiddenLock", "site.del");
String template = PermissionsAction.buildHelperContext(portlet, context, data, state);
if (template == null)
{
addAlert(state, rb.getString("theisa"));
}
else
{
return template;
}
}
*/
String template = null;
context.put ("action", CONTEXT_ACTION);
//updatePortlet(state, portlet, data);
if (state.getAttribute (STATE_INITIALIZED) == null)
{
init (portlet, data, state);
}
int index = Integer.valueOf((String)state.getAttribute(STATE_TEMPLATE_INDEX)).intValue();
template = buildContextForTemplate(index, portlet, context, data, state);
return template;
} // buildMainPanelContext
/**
* Build the context for each template using template_index parameter passed in a form hidden field.
* Each case is associated with a template. (Not all templates implemented). See String[] TEMPLATES.
* @param index is the number contained in the template's template_index
*/
private String buildContextForTemplate (int index, VelocityPortlet portlet,
Context context,
RunData data,
SessionState state)
{
String realmId = "";
String site_type = "";
String sortedBy = "";
String sortedAsc = "";
ParameterParser params = data.getParameters ();
context.put("tlang",rb);
context.put("alertMessage", state.getAttribute(STATE_MESSAGE));
// If cleanState() has removed SiteInfo, get a new instance into state
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null)
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
else
{
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
// Lists used in more than one template
// Access
List roles = new Vector();
// the hashtables for News and Web Content tools
Hashtable newsTitles = new Hashtable();
Hashtable newsUrls = new Hashtable();
Hashtable wcTitles = new Hashtable();
Hashtable wcUrls = new Hashtable();
List toolRegistrationList = new Vector();
List toolRegistrationSelectedList = new Vector();
ResourceProperties siteProperties = null;
// for showing site creation steps
if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) != null)
{
context.put("totalSteps", state.getAttribute(SITE_CREATE_TOTAL_STEPS));
}
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null)
{
context.put("step", state.getAttribute(SITE_CREATE_CURRENT_STEP));
}
String hasGradSites = ServerConfigurationService.getString("withDissertation", Boolean.FALSE.toString());
Site site = getStateSite(state);
switch (index)
{
case 0:
/* buildContextForTemplate chef_site-list.vm
*
*/
// site types
List sTypes = (List) state.getAttribute(STATE_SITE_TYPES);
//make sure auto-updates are enabled
Hashtable views = new Hashtable();
if (SecurityService.isSuperUser())
{
views.put(rb.getString("java.allmy"), rb.getString("java.allmy"));
views.put(rb.getString("java.my") + " " + rb.getString("java.sites"), rb.getString("java.my"));
for(int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++)
{
String type = (String) sTypes.get(sTypeIndex);
views.put(type + " " + rb.getString("java.sites"), type);
}
if (hasGradSites.equalsIgnoreCase("true"))
{
views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb.getString("java.gradtools"));
}
if(state.getAttribute(STATE_VIEW_SELECTED) == null)
{
state.setAttribute(STATE_VIEW_SELECTED, rb.getString("java.allmy"));
}
context.put("superUser", Boolean.TRUE);
}
else
{
context.put("superUser", Boolean.FALSE);
views.put(rb.getString("java.allmy"), rb.getString("java.allmy"));
// if there is a GradToolsStudent choice inside
boolean remove = false;
if (hasGradSites.equalsIgnoreCase("true"))
{
try
{
//the Grad Tools site option is only presented to GradTools Candidates
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
//am I a grad student?
if (!isGradToolsCandidate(userId))
{
// not a gradstudent
remove = true;
}
}
catch(Exception e)
{
remove = true;
}
}
else
{
// not support for dissertation sites
remove=true;
}
//do not show this site type in views
//sTypes.remove(new String(SITE_TYPE_GRADTOOLS_STUDENT));
for(int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++)
{
String type = (String) sTypes.get(sTypeIndex);
if(!type.equals(SITE_TYPE_GRADTOOLS_STUDENT))
{
views.put(type + " "+rb.getString("java.sites"), type);
}
}
if (!remove)
{
views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb.getString("java.gradtools"));
}
//default view
if(state.getAttribute(STATE_VIEW_SELECTED) == null)
{
state.setAttribute(STATE_VIEW_SELECTED, rb.getString("java.allmy"));
}
}
context.put("views", views);
if(state.getAttribute(STATE_VIEW_SELECTED) != null)
{
context.put("viewSelected", (String) state.getAttribute(STATE_VIEW_SELECTED));
}
String search = (String) state.getAttribute(STATE_SEARCH);
context.put("search_term", search);
sortedBy = (String) state.getAttribute (SORTED_BY);
if (sortedBy == null)
{
state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString());
sortedBy = SortType.TITLE_ASC.toString();
}
sortedAsc = (String) state.getAttribute (SORTED_ASC);
if (sortedAsc == null)
{
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if(sortedBy!=null) context.put ("currentSortedBy", sortedBy);
if(sortedAsc!=null) context.put ("currentSortAsc", sortedAsc);
String portalUrl = ServerConfigurationService.getPortalUrl();
context.put("portalUrl", portalUrl);
List sites = prepPage(state);
state.setAttribute(STATE_SITES, sites);
context.put("sites", sites);
context.put("totalPageNumber", new Integer(totalPageNumber(state)));
context.put("searchString", state.getAttribute(STATE_SEARCH));
context.put("form_search", FORM_SEARCH);
context.put("formPageNumber", FORM_PAGE_NUMBER);
context.put("prev_page_exists", state.getAttribute(STATE_PREV_PAGE_EXISTS));
context.put("next_page_exists", state.getAttribute(STATE_NEXT_PAGE_EXISTS));
context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE));
// put the service in the context (used for allow update calls on each site)
context.put("service", SiteService.getInstance());
context.put("sortby_title", SortType.TITLE_ASC.toString());
context.put("sortby_type", SortType.TYPE_ASC.toString());
context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString());
context.put("sortby_publish", SortType.PUBLISHED_ASC.toString());
context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString());
// top menu bar
Menu bar = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null))
{
bar.add( new MenuEntry(rb.getString("java.new"), "doNew_site"));
}
bar.add( new MenuEntry(rb.getString("java.revise"), null, true, MenuItem.CHECKED_NA, "doGet_site", "sitesForm"));
bar.add( new MenuEntry(rb.getString("java.delete"), null, true, MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm"));
context.put("menu", bar);
// default to be no pageing
context.put("paged", Boolean.FALSE);
Menu bar2 = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
// add the search commands
addSearchMenus(bar2, state);
context.put("menu2", bar2);
pagingInfoToContext(state, context);
return (String)getContext(data).get("template") + TEMPLATE[0];
case 1:
/* buildContextForTemplate chef_site-type.vm
*
*/
if (hasGradSites.equalsIgnoreCase("true"))
{
context.put("withDissertation", Boolean.TRUE);
try
{
//the Grad Tools site option is only presented to UM grad students
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
//am I a UM grad student?
Boolean isGradStudent = new Boolean(isGradToolsCandidate(userId));
context.put("isGradStudent", isGradStudent);
//if I am a UM grad student, do I already have a Grad Tools site?
boolean noGradToolsSite = true;
if(hasGradToolsStudentSite(userId))
noGradToolsSite = false;
context.put("noGradToolsSite", new Boolean(noGradToolsSite));
}
catch(Exception e)
{
if(Log.isWarnEnabled())
{
M_log.warn("buildContextForTemplate chef_site-type.vm " + e);
}
}
}
else
{
context.put("withDissertation", Boolean.FALSE);
}
List types = (List) state.getAttribute(STATE_SITE_TYPES);
context.put("siteTypes", types);
// put selected/default site type into context
if (siteInfo.site_type != null && siteInfo.site_type.length() >0)
{
context.put("typeSelected", siteInfo.site_type);
}
else if (types.size() > 0)
{
context.put("typeSelected", types.get(0));
}
List termsForSiteCreation = getAvailableTerms();
if (termsForSiteCreation.size() > 0)
{
context.put("termList", termsForSiteCreation);
}
if (state.getAttribute(STATE_TERM_SELECTED) != null)
{
context.put("selectedTerm", state.getAttribute(STATE_TERM_SELECTED));
}
return (String)getContext(data).get("template") + TEMPLATE[1];
case 2:
/* buildContextForTemplate chef_site-newSiteInformation.vm
*
*/
context.put("siteTypes", state.getAttribute(STATE_SITE_TYPES));
String siteType = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("titleEditableSiteType", state.getAttribute(TITLE_EDITABLE_SITE_TYPE));
context.put("type", siteType);
if (siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
context.put ("selectedProviderCourse", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
int number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
context.put ("manualAddNumber", new Integer(number - 1));
context.put ("manualAddFields", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("back", "37");
}
else
{
context.put("back", "36");
}
context.put ("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null)
{
context.put("selectedIcon", siteInfo.getIconUrl());
}
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null)
{
context.put(FORM_ICON_URL, siteInfo.iconUrl);
}
context.put ("back", "1");
}
context.put (FORM_TITLE,siteInfo.title);
context.put(FORM_SHORT_DESCRIPTION, siteInfo.short_description);
context.put (FORM_DESCRIPTION,siteInfo.description);
// defalt the site contact person to the site creator
if (siteInfo.site_contact_name.equals(NULL_STRING) && siteInfo.site_contact_email.equals(NULL_STRING))
{
User user = UserDirectoryService.getCurrentUser();
siteInfo.site_contact_name = user.getDisplayName();
siteInfo.site_contact_email = user.getEmail();
}
context.put("form_site_contact_name", siteInfo.site_contact_name);
context.put("form_site_contact_email", siteInfo.site_contact_email);
// those manual inputs
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String)getContext(data).get("template") + TEMPLATE[2];
case 3:
/* buildContextForTemplate chef_site-newSiteFeatures.vm
*
*/
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType!=null && siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
}
context.put("defaultTools", ServerConfigurationService.getToolsRequired(siteType));
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// If this is the first time through, check for tools
// which should be selected by default.
List defaultSelectedTools = ServerConfigurationService.getDefaultTools(siteType);
if (toolRegistrationSelectedList == null) {
toolRegistrationSelectedList = new Vector(defaultSelectedTools);
}
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST) ); // %%% use ToolRegistrations for template list
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService.getServerName());
// The "Home" tool checkbox needs special treatment to be selected by
// default.
Boolean checkHome = (Boolean)state.getAttribute(STATE_TOOL_HOME_SELECTED);
if (checkHome == null) {
if ((defaultSelectedTools != null) && defaultSelectedTools.contains(HOME_TOOL_ID)) {
checkHome = Boolean.TRUE;
}
}
context.put("check_home", checkHome);
//titles for news tools
context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES));
//titles for web content tools
context.put("wcTitles", state.getAttribute(STATE_WEB_CONTENT_TITLES));
//urls for news tools
context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS));
//urls for web content tools
context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS));
context.put("sites", SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null));
context.put("import", state.getAttribute(STATE_IMPORT));
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
return (String)getContext(data).get("template") + TEMPLATE[3];
case 4:
/* buildContextForTemplate chef_site-addRemoveFeatures.vm
*
*/
context.put("SiteTitle", site.getTitle());
String type = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("defaultTools", ServerConfigurationService.getToolsRequired(type));
boolean myworkspace_site = false;
//Put up tool lists filtered by category
List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES);
if (siteTypes.contains(type))
{
myworkspace_site = false;
}
if (SiteService.isUserSite(site.getId()) || (type!=null && type.equalsIgnoreCase("myworkspace")))
{
myworkspace_site = true;
type="myworkspace";
}
context.put ("myworkspace_site", new Boolean(myworkspace_site));
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST));
//titles for news tools
context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES));
//titles for web content tools
context.put("wcTitles", state.getAttribute(STATE_WEB_CONTENT_TITLES));
//urls for news tools
context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS));
//urls for web content tools
context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS));
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
//get the email alias when an Email Archive tool has been selected
String channelReference = mailArchiveChannelReference(site.getId());
List aliases = AliasService.getAliases(channelReference, 1, 1);
if (aliases.size() > 0)
{
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases.get(0)).getId());
}
else
{
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
}
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null)
{
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService.getServerName());
context.put("backIndex", "12");
return (String)getContext(data).get("template") + TEMPLATE[4];
case 5:
/* buildContextForTemplate chef_site-addParticipant.vm
*
*/
context.put("title", site.getTitle());
roles = getRoles(state);
context.put("roles", roles);
// Note that (for now) these strings are in both sakai.properties and sitesetupgeneric.properties
context.put("noEmailInIdAccountName", ServerConfigurationService.getString("noEmailInIdAccountName"));
context.put("noEmailInIdAccountLabel", ServerConfigurationService.getString("noEmailInIdAccountLabel"));
context.put("emailInIdAccountName", ServerConfigurationService.getString("emailInIdAccountName"));
context.put("emailInIdAccountLabel", ServerConfigurationService.getString("emailInIdAccountLabel"));
if(state.getAttribute("noEmailInIdAccountValue")!=null)
{
context.put("noEmailInIdAccountValue", (String)state.getAttribute("noEmailInIdAccountValue"));
}
if(state.getAttribute("emailInIdAccountValue")!=null)
{
context.put("emailInIdAccountValue", (String)state.getAttribute("emailInIdAccountValue"));
}
if(state.getAttribute("form_same_role") != null)
{
context.put("form_same_role", ((Boolean) state.getAttribute("form_same_role")).toString());
}
else
{
context.put("form_same_role", Boolean.TRUE.toString());
}
context.put("backIndex", "12");
return (String)getContext(data).get("template") + TEMPLATE[5];
case 6:
/* buildContextForTemplate chef_site-removeParticipants.vm
*
*/
context.put("title", site.getTitle());
realmId = SiteService.siteReference(site.getId());
try
{
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
try
{
List removeableList = (List) state.getAttribute(STATE_REMOVEABLE_USER_LIST);
List removeableParticipants = new Vector();
for (int k = 0; k < removeableList.size(); k++)
{
User user = UserDirectoryService.getUser((String) removeableList.get(k));
Participant participant = new Participant();
participant.name = user.getSortName();
participant.uniqname = user.getId();
Role r = realm.getUserRole(user.getId());
if (r != null)
{
participant.role = r.getId();
}
removeableParticipants.add(participant);
}
context.put("removeableList", removeableParticipants);
}
catch (UserNotDefinedException ee)
{
}
}
catch (GroupNotDefinedException e)
{
}
context.put("backIndex", "18");
return (String)getContext(data).get("template") + TEMPLATE[6];
case 7:
/* buildContextForTemplate chef_site-changeRoles.vm
*
*/
context.put("same_role", state.getAttribute(STATE_CHANGEROLE_SAMEROLE));
roles = getRoles(state);
context.put("roles", roles);
context.put("currentRole", state.getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE));
context.put("participantSelectedList", state.getAttribute(STATE_SELECTED_PARTICIPANTS));
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("siteTitle", site.getTitle());
return (String)getContext(data).get("template") + TEMPLATE[7];
case 8:
/* buildContextForTemplate chef_site-siteDeleteConfirm.vm
*
*/
String site_title = NULL_STRING;
String[] removals = (String[]) state.getAttribute(STATE_SITE_REMOVALS);
List remove = new Vector();
String user = SessionManager.getCurrentSessionUserId();
String workspace = SiteService.getUserSiteId(user);
if( removals != null && removals.length != 0 )
{
for (int i = 0; i < removals.length; i++ )
{
String id = (String) removals[i];
if(!(id.equals(workspace)))
{
try
{
site_title = SiteService.getSite(id).getTitle();
}
catch (IdUnusedException e)
{
M_log.warn("SiteAction.doSite_delete_confirmed - IdUnusedException " + id);
addAlert(state, rb.getString("java.sitewith")+" " + id + " "+rb.getString("java.couldnt")+" ");
}
if(SiteService.allowRemoveSite(id))
{
try
{
Site removeSite = SiteService.getSite(id);
remove.add(removeSite);
}
catch (IdUnusedException e)
{
M_log.warn("SiteAction.buildContextForTemplate chef_site-siteDeleteConfirm.vm: IdUnusedException");
}
}
else
{
addAlert(state, site_title + " "+rb.getString("java.couldntdel") + " ");
}
}
else
{
addAlert(state, rb.getString("java.yourwork"));
}
}
if(remove.size() == 0)
{
addAlert(state, rb.getString("java.click"));
}
}
context.put("removals", remove);
return (String)getContext(data).get("template") + TEMPLATE[8];
case 9:
/* buildContextForTemplate chef_site-publishUnpublish.vm
*
*/
context.put("publish", Boolean.valueOf(((SiteInfo)state.getAttribute(STATE_SITE_INFO)).getPublished()));
context.put("backIndex", "12");
return (String)getContext(data).get("template") + TEMPLATE[9];
case 10:
/* buildContextForTemplate chef_site-newSiteConfirm.vm
*
*/
siteInfo = (SiteInfo)state.getAttribute(STATE_SITE_INFO);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put ("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
context.put ("selectedProviderCourse", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
int number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
context.put ("manualAddNumber", new Integer(number - 1));
context.put ("manualAddFields", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
context.put ("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null)
{
context.put("selectedIcon", siteInfo.getIconUrl());
}
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType!=null && siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null)
{
context.put("iconUrl", siteInfo.iconUrl);
}
}
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
context.put("siteContactName", siteInfo.site_contact_name);
context.put("siteContactEmail", siteInfo.site_contact_email);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use Tool
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService.getServerName());
context.put("include", new Boolean(siteInfo.include));
context.put("published", new Boolean(siteInfo.published));
context.put("joinable", new Boolean(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
context.put("newsTitles", (Hashtable) state.getAttribute(STATE_NEWS_TITLES));
context.put("wcTitles", (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES));
// back to edit access page
context.put("back", "18");
context.put("importSiteTools", state.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("siteService", SiteService.getInstance());
// those manual inputs
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String)getContext(data).get("template") + TEMPLATE[10];
case 11:
/* buildContextForTemplate chef_site-newSitePublishUnpublish.vm
*
*/
return (String)getContext(data).get("template") + TEMPLATE[11];
case 12:
/* buildContextForTemplate chef_site-siteInfo-list.vm
*
*/
context.put("userDirectoryService", UserDirectoryService.getInstance());
try
{
siteProperties = site.getProperties();
siteType = site.getType();
if (siteType != null)
{
state.setAttribute(STATE_SITE_TYPE, siteType);
}
boolean isMyWorkspace = false;
if (SiteService.isUserSite(site.getId()))
{
if (SiteService.getSiteUserId(site.getId()).equals(SessionManager.getCurrentSessionUserId()))
{
isMyWorkspace = true;
context.put("siteUserId", SiteService.getSiteUserId(site.getId()));
}
}
context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace));
String siteId = site.getId();
if (state.getAttribute(STATE_ICONS)!= null)
{
List skins = (List)state.getAttribute(STATE_ICONS);
for (int i = 0; i < skins.size(); i++)
{
Icon s = (Icon)skins.get(i);
if(!StringUtil.different(s.getUrl(), site.getIconUrl()))
{
context.put("siteUnit", s.getName());
break;
}
}
}
context.put("siteIcon", site.getIconUrl());
context.put("siteTitle", site.getTitle());
context.put("siteDescription", site.getDescription());
context.put("siteJoinable", new Boolean(site.isJoinable()));
if(site.isPublished())
{
context.put("published", Boolean.TRUE);
}
else
{
context.put("published", Boolean.FALSE);
context.put("owner", site.getCreatedBy().getSortName());
}
Time creationTime = site.getCreatedTime();
if (creationTime != null)
{
context.put("siteCreationDate", creationTime.toStringLocalFull());
}
boolean allowUpdateSite = SiteService.allowUpdateSite(siteId);
context.put("allowUpdate", Boolean.valueOf(allowUpdateSite));
boolean allowUpdateGroupMembership = SiteService.allowUpdateGroupMembership(siteId);
context.put("allowUpdateGroupMembership", Boolean.valueOf(allowUpdateGroupMembership));
boolean allowUpdateSiteMembership = SiteService.allowUpdateSiteMembership(siteId);
context.put("allowUpdateSiteMembership", Boolean.valueOf(allowUpdateSiteMembership));
if (allowUpdateSite)
{
// top menu bar
Menu b = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (!isMyWorkspace)
{
b.add( new MenuEntry(rb.getString("java.editsite"), "doMenu_edit_site_info"));
}
b.add( new MenuEntry(rb.getString("java.edittools"), "doMenu_edit_site_tools"));
if (!isMyWorkspace
&& (ServerConfigurationService.getString("wsetup.group.support") == ""
|| ServerConfigurationService.getString("wsetup.group.support").equalsIgnoreCase(Boolean.TRUE.toString())))
{
// show the group toolbar unless configured to not support group
b.add( new MenuEntry(rb.getString("java.group"), "doMenu_group"));
}
if (!isMyWorkspace)
{
List gradToolsSiteTypes = (List) state.getAttribute(GRADTOOLS_SITE_TYPES);
boolean isGradToolSite = false;
if (siteType != null && gradToolsSiteTypes.contains(siteType))
{
isGradToolSite = true;
}
if (siteType == null
|| siteType != null && !isGradToolSite)
{
// hide site access for GRADTOOLS type of sites
b.add( new MenuEntry(rb.getString("java.siteaccess"), "doMenu_edit_site_access"));
}
b.add( new MenuEntry(rb.getString("java.addp"), "doMenu_siteInfo_addParticipant"));
if (siteType != null && siteType.equals("course"))
{
b.add( new MenuEntry(rb.getString("java.editc"), "doMenu_siteInfo_editClass"));
}
if (siteType == null || siteType != null && !isGradToolSite)
{
// hide site duplicate and import for GRADTOOLS type of sites
b.add( new MenuEntry(rb.getString("java.duplicate"), "doMenu_siteInfo_duplicate"));
List updatableSites = SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null);
// import link should be visible even if only one site
if (updatableSites.size() > 0)
{
b.add( new MenuEntry(rb.getString("java.import"), "doMenu_siteInfo_import"));
// a configuration param for showing/hiding import from file choice
String importFromFile = ServerConfigurationService.getString("site.setup.import.file", Boolean.TRUE.toString());
if (importFromFile.equalsIgnoreCase("true"))
{
//htripath: June 4th added as per Kris and changed desc of above
b.add(new MenuEntry(rb.getString("java.importFile"), "doAttachmentsMtrlFrmFile"));
}
}
}
}
// if the page order helper is available, not stealthed and not hidden, show the link
if (ToolManager.getTool("sakai-site-pageorder-helper") != null
&& !ServerConfigurationService
.getString("[email protected]")
.contains("sakai-site-pageorder-helper")
&& !ServerConfigurationService
.getString("[email protected]")
.contains("sakai-site-pageorder-helper"))
{
b.add(new MenuEntry(rb.getString("java.orderpages"), "doPageOrderHelper"));
}
context.put("menu", b);
}
if (allowUpdateGroupMembership)
{
// show Manage Groups menu
Menu b = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (!isMyWorkspace
&& (ServerConfigurationService.getString("wsetup.group.support") == ""
|| ServerConfigurationService.getString("wsetup.group.support").equalsIgnoreCase(Boolean.TRUE.toString())))
{
// show the group toolbar unless configured to not support group
b.add( new MenuEntry(rb.getString("java.group"), "doMenu_group"));
}
context.put("menu", b);
}
if (allowUpdateSiteMembership)
{
// show add participant menu
Menu b = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (!isMyWorkspace)
{
// show the Add Participant menu
b.add( new MenuEntry(rb.getString("java.addp"), "doMenu_siteInfo_addParticipant"));
}
context.put("menu", b);
}
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP))
{
// editing from worksite setup tool
context.put("fromWSetup", Boolean.TRUE);
if (state.getAttribute(STATE_PREV_SITE) != null)
{
context.put("prevSite", state.getAttribute(STATE_PREV_SITE));
}
if (state.getAttribute(STATE_NEXT_SITE) != null)
{
context.put("nextSite", state.getAttribute(STATE_NEXT_SITE));
}
}
else
{
context.put("fromWSetup", Boolean.FALSE);
}
//allow view roster?
boolean allowViewRoster = SiteService.allowViewRoster(siteId);
if (allowViewRoster)
{
context.put("viewRoster", Boolean.TRUE);
}
else
{
context.put("viewRoster", Boolean.FALSE);
}
//set participant list
if (allowUpdateSite || allowViewRoster || allowUpdateSiteMembership)
{
List participants = new Vector();
participants = getParticipantList(state);
sortedBy = (String) state.getAttribute (SORTED_BY);
sortedAsc = (String) state.getAttribute (SORTED_ASC);
if(sortedBy==null)
{
state.setAttribute(SORTED_BY, SORTED_BY_PARTICIPANT_NAME);
sortedBy = SORTED_BY_PARTICIPANT_NAME;
}
if (sortedAsc==null)
{
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if(sortedBy!=null) context.put ("currentSortedBy", sortedBy);
if(sortedAsc!=null) context.put ("currentSortAsc", sortedAsc);
Iterator sortedParticipants = null;
if (sortedBy != null)
{
sortedParticipants = new SortedIterator (participants.iterator (), new SiteComparator (sortedBy, sortedAsc));
participants.clear();
while (sortedParticipants.hasNext())
{
participants.add(sortedParticipants.next());
}
}
context.put("participantListSize", new Integer(participants.size()));
context.put("participantList", prepPage(state));
pagingInfoToContext(state, context);
}
context.put("include", Boolean.valueOf(site.isPubView()));
// site contact information
String contactName = siteProperties.getProperty(PROP_SITE_CONTACT_NAME);
String contactEmail = siteProperties.getProperty(PROP_SITE_CONTACT_EMAIL);
if (contactName == null && contactEmail == null)
{
User u = site.getCreatedBy();
String email = u.getEmail();
if (email != null)
{
contactEmail = u.getEmail();
}
contactName = u.getDisplayName();
}
if (contactName != null)
{
context.put("contactName", contactName);
}
if (contactEmail != null)
{
context.put("contactEmail", contactEmail);
}
if (siteType != null && siteType.equalsIgnoreCase("course"))
{
context.put("isCourseSite", Boolean.TRUE);
List providerCourseList = getProviderCourseList(StringUtil.trimToNull(getExternalRealmId(state)));
if (providerCourseList != null)
{
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
context.put("providerCourseList", providerCourseList);
}
String manualCourseListString = site.getProperties().getProperty(PROP_SITE_REQUEST_COURSE);
if (manualCourseListString != null)
{
List manualCourseList = new Vector();
if (manualCourseListString.indexOf("+") != -1)
{
manualCourseList = new ArrayList(Arrays.asList(manualCourseListString.split("\\+")));
}
else
{
manualCourseList.add(manualCourseListString);
}
state.setAttribute(SITE_MANUAL_COURSE_LIST, manualCourseList);
context.put("manualCourseList", manualCourseList);
}
context.put("term", siteProperties.getProperty(PROP_SITE_TERM));
}
else
{
context.put("isCourseSite", Boolean.FALSE);
}
}
catch (Exception e)
{
M_log.warn(this + " site info list: " + e.toString());
}
roles = getRoles(state);
context.put("roles", roles);
// will have the choice to active/inactive user or not
String activeInactiveUser = ServerConfigurationService.getString("activeInactiveUser", Boolean.FALSE.toString());
if (activeInactiveUser.equalsIgnoreCase("true"))
{
context.put("activeInactiveUser", Boolean.TRUE);
// put realm object into context
realmId = SiteService.siteReference(site.getId());
try
{
context.put("realm", AuthzGroupService.getAuthzGroup(realmId));
}
catch (GroupNotDefinedException e)
{
M_log.warn(this + " IdUnusedException " + realmId);
}
}
else
{
context.put("activeInactiveUser", Boolean.FALSE);
}
context.put("groupsWithMember", site.getGroupsWithMember(UserDirectoryService.getCurrentUser().getId()));
return (String)getContext(data).get("template") + TEMPLATE[12];
case 13:
/* buildContextForTemplate chef_site-siteInfo-editInfo.vm
*
*/
siteProperties = site.getProperties();
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("titleEditableSiteType", state.getAttribute(TITLE_EDITABLE_SITE_TYPE));
context.put("type", site.getType());
List terms = CourseManagementService.getTerms();
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course"))
{
context.put("isCourseSite", Boolean.TRUE);
context.put("skins", state.getAttribute(STATE_ICONS));
if (state.getAttribute(FORM_SITEINFO_SKIN) != null)
{
context.put("selectedIcon",state.getAttribute(FORM_SITEINFO_SKIN));
}
else if (site.getIconUrl() != null)
{
context.put("selectedIcon",site.getIconUrl());
}
if (terms != null && terms.size() >0)
{
context.put("termList", terms);
}
if (state.getAttribute(FORM_SITEINFO_TERM) == null)
{
String currentTerm = site.getProperties().getProperty(PROP_SITE_TERM);
if (currentTerm != null)
{
state.setAttribute(FORM_SITEINFO_TERM, currentTerm);
}
}
if (state.getAttribute(FORM_SITEINFO_TERM) != null)
{
context.put("selectedTerm", state.getAttribute(FORM_SITEINFO_TERM));
}
}
else
{
context.put("isCourseSite", Boolean.FALSE);
if (state.getAttribute(FORM_SITEINFO_ICON_URL) == null && StringUtil.trimToNull(site.getIconUrl()) != null)
{
state.setAttribute(FORM_SITEINFO_ICON_URL, site.getIconUrl());
}
if (state.getAttribute(FORM_SITEINFO_ICON_URL) != null)
{
context.put("iconUrl", state.getAttribute(FORM_SITEINFO_ICON_URL));
}
}
context.put("description", state.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("short_description", state.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("form_site_contact_name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("form_site_contact_email", state.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
//Display of appearance icon/url list with course site based on
// "disable.course.site.skin.selection" value set with sakai.properties file.
if ((ServerConfigurationService.getString("disable.course.site.skin.selection")).equals("true")){
context.put("disableCourseSelection", Boolean.TRUE);
}
return (String)getContext(data).get("template") + TEMPLATE[13];
case 14:
/* buildContextForTemplate chef_site-siteInfo-editInfoConfirm.vm
*
*/
siteProperties = site.getProperties();
siteType = (String)state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course"))
{
context.put("isCourseSite", Boolean.TRUE);
context.put("siteTerm", state.getAttribute(FORM_SITEINFO_TERM));
}
else
{
context.put("isCourseSite", Boolean.FALSE);
}
context.put("oTitle", site.getTitle());
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("description", state.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("oDescription", site.getDescription());
context.put("short_description", state.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("oShort_description", site.getShortDescription());
context.put("skin", state.getAttribute(FORM_SITEINFO_SKIN));
context.put("oSkin", site.getIconUrl());
context.put("skins", state.getAttribute(STATE_ICONS));
context.put("oIcon", site.getIconUrl());
context.put("icon", state.getAttribute(FORM_SITEINFO_ICON_URL));
context.put("include", state.getAttribute(FORM_SITEINFO_INCLUDE));
context.put("oInclude", Boolean.valueOf(site.isPubView()));
context.put("name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("oName", siteProperties.getProperty(PROP_SITE_CONTACT_NAME));
context.put("email", state.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
context.put("oEmail", siteProperties.getProperty(PROP_SITE_CONTACT_EMAIL));
return (String)getContext(data).get("template") + TEMPLATE[14];
case 15:
/* buildContextForTemplate chef_site-addRemoveFeatureConfirm.vm
*
*/
context.put("title", site.getTitle());
site_type = (String)state.getAttribute(STATE_SITE_TYPE);
myworkspace_site = false;
if (SiteService.isUserSite(site.getId()))
{
if (SiteService.getSiteUserId(site.getId()).equals(SessionManager.getCurrentSessionUserId()))
{
myworkspace_site = true;
site_type = "myworkspace";
}
}
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("selectedTools", orderToolIds(state, (String) state.getAttribute(STATE_SITE_TYPE), (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST)));
context.put("oldSelectedTools", state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
context.put("oldSelectedHome", state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME));
context.put("continueIndex", "12");
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null)
{
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService.getServerName());
context.put("newsTitles", (Hashtable) state.getAttribute(STATE_NEWS_TITLES));
context.put("wcTitles", (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES));
if (fromENWModifyView(state))
{
context.put("back", "26");
}
else
{
context.put("back", "4");
}
return (String)getContext(data).get("template") + TEMPLATE[15];
case 16:
/* buildContextForTemplate chef_site-publishUnpublish-sendEmail.vm
*
*/
context.put("title", site.getTitle());
context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY));
return (String)getContext(data).get("template") + TEMPLATE[16];
case 17:
/* buildContextForTemplate chef_site-publishUnpublish-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("continueIndex", "12");
SiteInfo sInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (sInfo.getPublished())
{
context.put("publish", Boolean.TRUE);
context.put("backIndex", "16");
}
else
{
context.put("publish", Boolean.FALSE);
context.put("backIndex", "9");
}
context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY));
return (String)getContext(data).get("template") + TEMPLATE[17];
case 18:
/* buildContextForTemplate chef_siteInfo-editAccess.vm
*
*/
List publicChangeableSiteTypes = (List) state.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES);
List unJoinableSiteTypes = (List) state.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE);
if (site != null)
{
//editing existing site
context.put("site", site);
siteType = state.getAttribute(STATE_SITE_TYPE)!=null?(String)state.getAttribute(STATE_SITE_TYPE):null;
if ( siteType != null
&& publicChangeableSiteTypes.contains(siteType))
{
context.put ("publicChangeable", Boolean.TRUE);
}
else
{
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(site.isPubView()));
if ( siteType != null && !unJoinableSiteTypes.contains(siteType))
{
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
if (state.getAttribute(STATE_JOINABLE) == null)
{
state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site.isJoinable()));
}
if (state.getAttribute(STATE_JOINERROLE) == null
|| state.getAttribute(STATE_JOINABLE) != null && ((Boolean) state.getAttribute(STATE_JOINABLE)).booleanValue())
{
state.setAttribute(STATE_JOINERROLE, site.getJoinerRole());
}
if (state.getAttribute(STATE_JOINABLE) != null)
{
context.put("joinable", state.getAttribute(STATE_JOINABLE));
}
if (state.getAttribute(STATE_JOINERROLE) != null)
{
context.put("joinerRole", state.getAttribute(STATE_JOINERROLE));
}
}
else
{
//site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
context.put("roles", getRoles(state));
context.put("back", "12");
}
else
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if ( siteInfo.site_type != null
&& publicChangeableSiteTypes.contains(siteInfo.site_type))
{
context.put ("publicChangeable", Boolean.TRUE);
}
else
{
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(siteInfo.getInclude()));
context.put("published", Boolean.valueOf(siteInfo.getPublished()));
if ( siteInfo.site_type != null && !unJoinableSiteTypes.contains(siteInfo.site_type))
{
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
context.put("joinable", Boolean.valueOf(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
}
else
{
// site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
// use the type's template, if defined
String realmTemplate = "!site.template";
if (siteInfo.site_type != null)
{
realmTemplate = realmTemplate + "." + siteInfo.site_type;
}
try
{
AuthzGroup r = AuthzGroupService.getAuthzGroup(realmTemplate);
context.put("roles", r.getRoles());
}
catch (GroupNotDefinedException e)
{
try
{
AuthzGroup rr = AuthzGroupService.getAuthzGroup("!site.template");
context.put("roles", rr.getRoles());
}
catch (GroupNotDefinedException ee)
{
}
}
// new site, go to confirmation page
context.put("continue", "10");
if (fromENWModifyView(state))
{
context.put("back", "26");
}
else if (state.getAttribute(STATE_IMPORT) != null)
{
context.put("back", "27");
}
else
{
context.put("back", "3");
}
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType!=null && siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
}
}
return (String)getContext(data).get("template") + TEMPLATE[18];
case 19:
/* buildContextForTemplate chef_site-addParticipant-sameRole.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("participantList", state.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("form_selectedRole", state.getAttribute("form_selectedRole"));
return (String)getContext(data).get("template") + TEMPLATE[19];
case 20:
/* buildContextForTemplate chef_site-addParticipant-differentRole.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("participantList", state.getAttribute(STATE_ADD_PARTICIPANTS));
return (String)getContext(data).get("template") + TEMPLATE[20];
case 21:
/* buildContextForTemplate chef_site-addParticipant-notification.vm
*
*/
context.put("title", site.getTitle());
context.put("sitePublished", Boolean.valueOf(site.isPublished()));
if (state.getAttribute("form_selectedNotify") == null)
{
state.setAttribute("form_selectedNotify", Boolean.FALSE);
}
context.put("notify", state.getAttribute("form_selectedNotify"));
boolean same_role = state.getAttribute("form_same_role")==null?true:((Boolean) state.getAttribute("form_same_role")).booleanValue();
if (same_role)
{
context.put("backIndex", "19");
}
else
{
context.put("backIndex", "20");
}
return (String)getContext(data).get("template") + TEMPLATE[21];
case 22:
/* buildContextForTemplate chef_site-addParticipant-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("participants", state.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("notify", state.getAttribute("form_selectedNotify"));
context.put("roles", getRoles(state));
context.put("same_role", state.getAttribute("form_same_role"));
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("selectedRole", state.getAttribute("form_selectedRole"));
return (String)getContext(data).get("template") + TEMPLATE[22];
case 23:
/* buildContextForTemplate chef_siteInfo-editAccess-globalAccess.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
if (state.getAttribute("form_joinable") == null)
{
state.setAttribute("form_joinable", new Boolean(site.isJoinable()));
}
context.put("form_joinable", state.getAttribute("form_joinable"));
if (state.getAttribute("form_joinerRole") == null)
{
state.setAttribute("form_joinerRole", site.getJoinerRole());
}
context.put("form_joinerRole", state.getAttribute("form_joinerRole"));
return (String)getContext(data).get("template") + TEMPLATE[23];
case 24:
/* buildContextForTemplate chef_siteInfo-editAccess-globalAccess-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("form_joinable", state.getAttribute("form_joinable"));
context.put("form_joinerRole", state.getAttribute("form_joinerRole"));
return (String)getContext(data).get("template") + TEMPLATE[24];
case 25:
/* buildContextForTemplate chef_changeRoles-confirm.vm
*
*/
Boolean sameRole = (Boolean) state.getAttribute(STATE_CHANGEROLE_SAMEROLE);
context.put("sameRole", sameRole);
if (sameRole.booleanValue())
{
// same role
context.put("currentRole", state.getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE));
}
else
{
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
}
roles = getRoles(state);
context.put("roles", roles);
context.put("participantSelectedList", state.getAttribute(STATE_SELECTED_PARTICIPANTS));
if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) != null)
{
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
}
context.put("siteTitle", site.getTitle());
return (String)getContext(data).get("template") + TEMPLATE[25];
case 26:
/* buildContextForTemplate chef_site-modifyENW.vm
*
*/
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
boolean existingSite = site != null? true:false;
if (existingSite)
{
// revising a existing site's tool
context.put("existingSite", Boolean.TRUE);
context.put("back", "4");
context.put("continue", "15");
context.put("function", "eventSubmit_doAdd_remove_features");
}
else
{
// new site
context.put("existingSite", Boolean.FALSE);
context.put("function", "eventSubmit_doAdd_features");
if (state.getAttribute(STATE_IMPORT) != null)
{
context.put("back", "27");
}
else
{
// new site, go to edit access page
context.put("back", "3");
}
context.put("continue", "18");
}
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
String emailId = (String) state.getAttribute(STATE_TOOL_EMAIL_ADDRESS);
if (emailId != null)
{
context.put("emailId", emailId);
}
//titles for news tools
newsTitles = (Hashtable) state.getAttribute(STATE_NEWS_TITLES);
if (newsTitles == null)
{
newsTitles = new Hashtable();
newsTitles.put("sakai.news", NEWS_DEFAULT_TITLE);
state.setAttribute(STATE_NEWS_TITLES, newsTitles);
}
context.put("newsTitles", newsTitles);
//urls for news tools
newsUrls = (Hashtable) state.getAttribute(STATE_NEWS_URLS);
if (newsUrls == null)
{
newsUrls = new Hashtable();
newsUrls.put("sakai.news", NEWS_DEFAULT_URL);
state.setAttribute(STATE_NEWS_URLS, newsUrls);
}
context.put("newsUrls", newsUrls);
// titles for web content tools
wcTitles = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES);
if (wcTitles == null)
{
wcTitles = new Hashtable();
wcTitles.put("sakai.iframe", WEB_CONTENT_DEFAULT_TITLE);
state.setAttribute(STATE_WEB_CONTENT_TITLES, wcTitles);
}
context.put("wcTitles", wcTitles);
//URLs for web content tools
wcUrls = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_URLS);
if (wcUrls == null)
{
wcUrls = new Hashtable();
wcUrls.put("sakai.iframe", WEB_CONTENT_DEFAULT_URL);
state.setAttribute(STATE_WEB_CONTENT_URLS, wcUrls);
}
context.put("wcUrls", wcUrls);
context.put("serverName", ServerConfigurationService.getServerName());
context.put("oldSelectedTools", state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
return (String)getContext(data).get("template") + TEMPLATE[26];
case 27:
/* buildContextForTemplate chef_site-importSites.vm
*
*/
existingSite = site != null? true:false;
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (existingSite)
{
// revising a existing site's tool
context.put("continue", "12");
context.put("back", "28");
context.put("totalSteps", "2");
context.put("step", "2");
context.put("currentSite", site);
}
else
{
// new site, go to edit access page
context.put("back", "3");
if (fromENWModifyView(state))
{
context.put("continue", "26");
}
else
{
context.put("continue", "18");
}
}
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put ("selectedTools", orderToolIds(state, site_type, getToolsAvailableForImport(state))); // String toolId's
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
context.put("importSitesTools", state.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("importSupportedTools", importTools());
return (String)getContext(data).get("template") + TEMPLATE[27];
case 28:
/* buildContextForTemplate chef_siteinfo-import.vm
*
*/
context.put("currentSite", site);
context.put("importSiteList", state.getAttribute(STATE_IMPORT_SITES));
context.put("sites", SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null));
return (String)getContext(data).get("template") + TEMPLATE[28];
case 29:
/* buildContextForTemplate chef_siteinfo-duplicate.vm
*
*/
context.put("siteTitle", site.getTitle());
String sType = site.getType();
if (sType != null && sType.equals("course"))
{
context.put("isCourseSite", Boolean.TRUE);
context.put("currentTermId", site.getProperties().getProperty(PROP_SITE_TERM));
context.put("termList", getAvailableTerms());
}
else
{
context.put("isCourseSite", Boolean.FALSE);
}
if (state.getAttribute(SITE_DUPLICATED) == null)
{
context.put("siteDuplicated", Boolean.FALSE);
}
else
{
context.put("siteDuplicated", Boolean.TRUE);
context.put("duplicatedName", state.getAttribute(SITE_DUPLICATED_NAME));
}
return (String)getContext(data).get("template") + TEMPLATE[29];
case 36:
/*
* buildContextForTemplate chef_site-newSiteCourse.vm
*/
if (site != null)
{
context.put("site", site);
context.put("siteTitle", site.getTitle());
terms = CourseManagementService.getTerms();
if (terms != null && terms.size() >0)
{
context.put("termList", terms);
}
List providerCourseList = (List) state.getAttribute(SITE_PROVIDER_COURSE_LIST);
context.put("providerCourseList", providerCourseList);
context.put("manualCourseList", state.getAttribute(SITE_MANUAL_COURSE_LIST));
Term t = (Term) state.getAttribute(STATE_TERM_SELECTED);
context.put ("term", t);
if (t != null)
{
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
List courses = CourseManagementService.getInstructorCourses(userId, t.getYear(), t.getTerm());
if (courses != null && courses.size() > 0)
{
Vector notIncludedCourse = new Vector();
// remove included sites
for (Iterator i = courses.iterator(); i.hasNext(); )
{
Course c = (Course) i.next();
if (!providerCourseList.contains(c.getId()))
{
notIncludedCourse.add(c);
}
}
state.setAttribute(STATE_TERM_COURSE_LIST, notIncludedCourse);
}
else
{
state.removeAttribute(STATE_TERM_COURSE_LIST);
}
}
// step number used in UI
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer("1"));
}
else
{
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
context.put ("selectedProviderCourse", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if(state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
context.put("selectedManualCourse", Boolean.TRUE);
}
context.put ("term", (Term) state.getAttribute(STATE_TERM_SELECTED));
}
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP))
{
context.put("backIndex", "1");
}
else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO))
{
context.put("backIndex", "");
}
context.put("termCourseList", (List) state.getAttribute(STATE_TERM_COURSE_LIST));
return (String)getContext(data).get("template") + TEMPLATE[36];
case 37:
/*
* buildContextForTemplate chef_site-newSiteCourseManual.vm
*/
if (site != null)
{
context.put("site", site);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
}
buildInstructorSectionsList(state, params, context);
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("form_requiredFieldsSizes", CourseManagementService.getCourseIdRequiredFieldsSizes());
context.put("form_additional", siteInfo.additional);
context.put("form_title", siteInfo.title);
context.put("form_description", siteInfo.description);
context.put("noEmailInIdAccountName", ServerConfigurationService.getString("noEmailInIdAccountName", ""));
context.put("value_uniqname", state.getAttribute(STATE_SITE_QUEST_UNIQNAME));
int number = 1;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
context.put("currentNumber", new Integer(number));
}
context.put("currentNumber", new Integer(number));
context.put("listSize", new Integer(number-1));
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
List l = (List) state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
context.put ("selectedProviderCourse", l);
context.put("size", new Integer(l.size()-1));
}
if (site != null)
{
context.put("back", "36");
}
else
{
if (state.getAttribute(STATE_AUTO_ADD) != null)
{
context.put("autoAdd", Boolean.TRUE);
context.put("back", "36");
}
else
{
context.put("back", "1");
}
}
context.put("isFutureTerm", state.getAttribute(STATE_FUTURE_TERM_SELECTED));
context.put("weeksAhead", ServerConfigurationService.getString("roster.available.weeks.before.term.start", "0"));
return (String)getContext(data).get("template") + TEMPLATE[37];
case 42:
/* buildContextForTemplate chef_site-gradtoolsConfirm.vm
*
*/
siteInfo = (SiteInfo)state.getAttribute(STATE_SITE_INFO);
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
toolRegistrationList = (Vector) state.getAttribute(STATE_PROJECT_TOOL_LIST);
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
context.put (STATE_TOOL_REGISTRATION_LIST, toolRegistrationList ); // %%% use Tool
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService.getServerName());
context.put("include", new Boolean(siteInfo.include));
return (String)getContext(data).get("template") + TEMPLATE[42];
case 43:
/* buildContextForTemplate chef_siteInfo-editClass.vm
*
*/
bar = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null))
{
bar.add( new MenuEntry(rb.getString("java.addclasses"), "doMenu_siteInfo_addClass"));
}
context.put("menu", bar);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
return (String)getContext(data).get("template") + TEMPLATE[43];
case 44:
/* buildContextForTemplate chef_siteInfo-addCourseConfirm.vm
*
*/
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
context.put("providerAddCourses", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
int addNumber = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue() -1;
context.put("manualAddNumber", new Integer(addNumber));
context.put("requestFields", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("backIndex", "37");
}
else
{
context.put("backIndex", "36");
}
//those manual inputs
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String)getContext(data).get("template") + TEMPLATE[44];
//htripath - import materials from classic
case 45:
/* buildContextForTemplate chef_siteInfo-importMtrlMaster.vm
*
*/
return (String)getContext(data).get("template") + TEMPLATE[45];
case 46:
/* buildContextForTemplate chef_siteInfo-importMtrlCopy.vm
*
*/
// this is for list display in listbox
context.put("allZipSites", state.getAttribute(ALL_ZIP_IMPORT_SITES));
context.put("finalZipSites", state.getAttribute(FINAL_ZIP_IMPORT_SITES));
//zip file
//context.put("zipreffile",state.getAttribute(CLASSIC_ZIP_FILE_NAME));
return (String)getContext(data).get("template") + TEMPLATE[46];
case 47:
/* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String)getContext(data).get("template") + TEMPLATE[47];
case 48:
/* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String)getContext(data).get("template") + TEMPLATE[48];
case 49:
/* buildContextForTemplate chef_siteInfo-group.vm
*
*/
context.put("site", site);
bar = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (SiteService.allowUpdateSite(site.getId()) || SiteService.allowUpdateGroupMembership(site.getId()))
{
- bar.add( new MenuEntry(rb.getString("java.new"), "doGroup_new"));
+ bar.add( new MenuEntry(rb.getString("editgroup.new"), "doGroup_new"));
}
context.put("menu", bar);
// the group list
sortedBy = (String) state.getAttribute (SORTED_BY);
sortedAsc = (String) state.getAttribute (SORTED_ASC);
if(sortedBy!=null) context.put ("currentSortedBy", sortedBy);
if(sortedAsc!=null) context.put ("currentSortAsc", sortedAsc);
// only show groups created by WSetup tool itself
Collection groups = (Collection) site.getGroups();
List groupsByWSetup = new Vector();
for(Iterator gIterator = groups.iterator(); gIterator.hasNext();)
{
Group gNext = (Group) gIterator.next();
String gProp = gNext.getProperties().getProperty(GROUP_PROP_WSETUP_CREATED);
if (gProp != null && gProp.equals(Boolean.TRUE.toString()))
{
groupsByWSetup.add(gNext);
}
}
if (sortedBy != null && sortedAsc != null)
{
context.put("groups", new SortedIterator (groupsByWSetup.iterator (), new SiteComparator (sortedBy, sortedAsc)));
}
return (String)getContext(data).get("template") + TEMPLATE[49];
case 50:
/* buildContextForTemplate chef_siteInfo-groupedit.vm
*
*/
Group g = getStateGroup(state);
if (g != null)
{
context.put("group", g);
context.put("newgroup", Boolean.FALSE);
}
else
{
context.put("newgroup", Boolean.TRUE);
}
if (state.getAttribute(STATE_GROUP_TITLE) != null)
{
context.put("title", state.getAttribute(STATE_GROUP_TITLE));
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) != null)
{
context.put("description", state.getAttribute(STATE_GROUP_DESCRIPTION));
}
Iterator siteMembers = new SortedIterator (getParticipantList(state).iterator (), new SiteComparator (SORTED_BY_PARTICIPANT_NAME, Boolean.TRUE.toString()));
if (siteMembers != null && siteMembers.hasNext())
{
context.put("generalMembers", siteMembers);
}
Set groupMembersSet = (Set) state.getAttribute(STATE_GROUP_MEMBERS);
if (state.getAttribute(STATE_GROUP_MEMBERS) != null)
{
context.put("groupMembers", new SortedIterator(groupMembersSet.iterator(), new SiteComparator (SORTED_BY_MEMBER_NAME, Boolean.TRUE.toString())));
}
context.put("groupMembersClone", groupMembersSet);
context.put("userDirectoryService", UserDirectoryService.getInstance());
return (String)getContext(data).get("template") + TEMPLATE[50];
case 51:
/* buildContextForTemplate chef_siteInfo-groupDeleteConfirm.vm
*
*/
context.put("site", site);
context.put("removeGroupIds", new ArrayList(Arrays.asList((String[])state.getAttribute(STATE_GROUP_REMOVE))));
return (String)getContext(data).get("template") + TEMPLATE[51];
}
// should never be reached
return (String)getContext(data).get("template") + TEMPLATE[0];
} // buildContextForTemplate
// obtain a list of available terms
private List getAvailableTerms()
{
List terms = CourseManagementService.getTerms();
List termsForSiteCreation = new Vector();
if (terms != null && terms.size() >0)
{
for (int i=0; i<terms.size();i++)
{
Term t = (Term) terms.get(i);
if (!t.getEndTime().before(TimeService.newTime()))
{
// don't show those terms which have ended already
termsForSiteCreation.add(t);
}
}
}
return termsForSiteCreation;
}
/**
* Launch the Page Order Helper Tool -- for ordering, adding and customizing pages
* @see case 12
*
*/
public void doPageOrderHelper(RunData data)
{
SessionState state = ((JetspeedRunData)data)
.getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//pass in the siteId of the site to be ordered (so it can configure sites other then the current site)
SessionManager.getCurrentToolSession()
.setAttribute(HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId());
//launch the helper
startHelper(data.getRequest(), "sakai-site-pageorder-helper");
}
//htripath: import materials from classic
/**
* Master import -- for import materials from a file
* @see case 45
*
*/
public void doAttachmentsMtrlFrmFile(RunData data)
{
SessionState state =
((JetspeedRunData) data).getPortletSessionState(
((JetspeedRunData) data).getJs_peid());
//state.setAttribute(FILE_UPLOAD_MAX_SIZE, ServerConfigurationService.getString("content.upload.max", "1"));
state.setAttribute(STATE_TEMPLATE_INDEX, "45");
} // doImportMtrlFrmFile
/**
* Handle File Upload request
* @see case 46
* @throws Exception
*/
public void doUpload_Mtrl_Frm_File(RunData data)
{
SessionState state =
((JetspeedRunData) data).getPortletSessionState(
((JetspeedRunData) data).getJs_peid());
List allzipList = new Vector();
List finalzipList = new Vector();
List directcopyList = new Vector();
// see if the user uploaded a file
FileItem fileFromUpload = null;
String fileName = null;
fileFromUpload = data.getParameters().getFileItem("file");
String max_file_size_mb = ServerConfigurationService.getString("content.upload.max", "1");
int max_bytes = 1024 * 1024;
try
{
max_bytes = Integer.parseInt(max_file_size_mb) * 1024 * 1024;
}
catch(Exception e)
{
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1024 * 1024;
}
if(fileFromUpload == null)
{
// "The user submitted a file to upload but it was too big!"
addAlert(state, rb.getString("importFile.size") + " " + max_file_size_mb + "MB " + rb.getString("importFile.exceeded"));
}
else if (fileFromUpload.getFileName() == null || fileFromUpload.getFileName().length() == 0)
{
addAlert(state, rb.getString("importFile.choosefile"));
}
else
{
byte[] fileData = fileFromUpload.get();
if(fileData.length >= max_bytes)
{
addAlert(state, rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("importFile.exceeded"));
}
else if(fileData.length > 0)
{
if (importService.isValidArchive(fileData)) {
ImportDataSource importDataSource = importService.parseFromFile(fileData);
Log.info("chef","Getting import items from manifest.");
List lst = importDataSource.getItemCategories();
if (lst != null && lst.size() > 0)
{
Iterator iter = lst.iterator();
while (iter.hasNext())
{
ImportMetadata importdata = (ImportMetadata) iter.next();
// Log.info("chef","Preparing import item '" + importdata.getId() + "'");
if ((!importdata.isMandatory())
&& (importdata.getFileName().endsWith(".xml")))
{
allzipList.add(importdata);
}
else
{
directcopyList.add(importdata);
}
}
}
//set Attributes
state.setAttribute(ALL_ZIP_IMPORT_SITES, allzipList);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, finalzipList);
state.setAttribute(DIRECT_ZIP_IMPORT_SITES, directcopyList);
state.setAttribute(CLASSIC_ZIP_FILE_NAME, fileName);
state.setAttribute(IMPORT_DATA_SOURCE, importDataSource);
state.setAttribute(STATE_TEMPLATE_INDEX, "46");
} else { // uploaded file is not a valid archive
}
}
}
} // doImportMtrlFrmFile
/**
* Handle addition to list request
* @param data
*/
public void doAdd_MtrlSite(RunData data)
{
SessionState state =
((JetspeedRunData) data).getPortletSessionState(
((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
List zipList = (List) state.getAttribute(ALL_ZIP_IMPORT_SITES);
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
List importSites = new ArrayList(Arrays.asList(params
.getStrings("addImportSelected")));
for (int i = 0; i < importSites.size(); i++)
{
String value = (String) importSites.get(i);
fnlList.add(removeItems(value, zipList));
}
state.setAttribute(ALL_ZIP_IMPORT_SITES, zipList);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList);
state.setAttribute(STATE_TEMPLATE_INDEX, "46");
} // doAdd_MtrlSite
/**
* Helper class for Add and remove
* @param value
* @param items
* @return
*/
public ImportMetadata removeItems(String value, List items)
{
ImportMetadata result = null;
for (int i = 0; i < items.size(); i++)
{
ImportMetadata item = (ImportMetadata) items.get(i);
if (value.equals(item.getId()))
{
result = (ImportMetadata) items.remove(i);
break;
}
}
return result;
}
/**
* Handle the request for remove
* @param data
*/
public void doRemove_MtrlSite(RunData data)
{
SessionState state =
((JetspeedRunData) data).getPortletSessionState(
((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
List zipList = (List) state.getAttribute(ALL_ZIP_IMPORT_SITES);
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
List importSites = new ArrayList(Arrays.asList(params
.getStrings("removeImportSelected")));
for (int i = 0; i < importSites.size(); i++)
{
String value = (String) importSites.get(i);
zipList.add(removeItems(value, fnlList));
}
state.setAttribute(ALL_ZIP_IMPORT_SITES, zipList);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList);
state.setAttribute(STATE_TEMPLATE_INDEX, "46");
} // doAdd_MtrlSite
/**
* Handle the request for copy
* @param data
*/
public void doCopyMtrlSite(RunData data)
{
SessionState state =
((JetspeedRunData) data).getPortletSessionState(
((JetspeedRunData) data).getJs_peid());
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList);
state.setAttribute(STATE_TEMPLATE_INDEX, "47");
} // doCopy_MtrlSite
/**
* Handle the request for Save
* @param data
* @throws ImportException
*/
public void doSaveMtrlSite(RunData data)
{
SessionState state =
((JetspeedRunData) data).getPortletSessionState(
((JetspeedRunData) data).getJs_peid());
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
List directList = (List) state.getAttribute(DIRECT_ZIP_IMPORT_SITES);
ImportDataSource importDataSource = (ImportDataSource) state.getAttribute(IMPORT_DATA_SOURCE);
// combine the selected import items with the mandatory import items
fnlList.addAll(directList);
Log.info("chef","doSaveMtrlSite() about to import " + fnlList.size() + " top level items");
Log.info("chef", "doSaveMtrlSite() the importDataSource is " + importDataSource.getClass().getName());
if (importDataSource instanceof SakaiArchive) {
Log.info("chef","doSaveMtrlSite() our data source is a Sakai format");
((SakaiArchive)importDataSource).buildSourceFolder(fnlList);
Log.info("chef","doSaveMtrlSite() source folder is " + ((SakaiArchive)importDataSource).getSourceFolder());
ArchiveService.merge(((SakaiArchive)importDataSource).getSourceFolder(), siteId, null);
} else {
importService.doImportItems(importDataSource.getItemsForCategories(fnlList), siteId);
}
//remove attributes
state.removeAttribute(ALL_ZIP_IMPORT_SITES);
state.removeAttribute(FINAL_ZIP_IMPORT_SITES);
state.removeAttribute(DIRECT_ZIP_IMPORT_SITES);
state.removeAttribute(CLASSIC_ZIP_FILE_NAME);
state.removeAttribute(SESSION_CONTEXT_ID);
state.removeAttribute(IMPORT_DATA_SOURCE);
state.setAttribute(STATE_TEMPLATE_INDEX, "48");
//state.setAttribute(STATE_TEMPLATE_INDEX, "28");
} // doSave_MtrlSite
public void doSaveMtrlSiteMsg(RunData data)
{
SessionState state =
((JetspeedRunData) data).getPortletSessionState(
((JetspeedRunData) data).getJs_peid());
//remove attributes
state.removeAttribute(ALL_ZIP_IMPORT_SITES);
state.removeAttribute(FINAL_ZIP_IMPORT_SITES);
state.removeAttribute(DIRECT_ZIP_IMPORT_SITES);
state.removeAttribute(CLASSIC_ZIP_FILE_NAME);
state.removeAttribute(SESSION_CONTEXT_ID);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
//htripath-end
/**
* Handle the site search request.
**/
public void doSite_search(RunData data, Context context)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// read the search form field into the state object
String search = StringUtil.trimToNull(data.getParameters().getString(FORM_SEARCH));
// set the flag to go to the prev page on the next list
if (search == null)
{
state.removeAttribute(STATE_SEARCH);
}
else
{
state.setAttribute(STATE_SEARCH, search);
}
} // doSite_search
/**
* Handle a Search Clear request.
**/
public void doSite_search_clear(RunData data, Context context)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// clear the search
state.removeAttribute(STATE_SEARCH);
} // doSite_search_clear
private void coursesIntoContext(SessionState state, Context context, Site site)
{
List providerCourseList = getProviderCourseList(StringUtil.trimToNull(getExternalRealmId(state)));
if (providerCourseList != null && providerCourseList.size() > 0)
{
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
context.put("providerCourseList", providerCourseList);
}
String manualCourseListString = StringUtil.trimToNull(site.getProperties().getProperty(PROP_SITE_REQUEST_COURSE));
if (manualCourseListString != null)
{
List manualCourseList = new Vector();
if (manualCourseListString.indexOf("+") != -1)
{
manualCourseList = new ArrayList(Arrays.asList(manualCourseListString.split("\\+")));
}
else
{
manualCourseList.add(manualCourseListString);
}
state.setAttribute(SITE_MANUAL_COURSE_LIST, manualCourseList);
context.put("manualCourseList", manualCourseList);
}
}
/**
* buildInstructorSectionsList
* Build the CourseListItem list for this Instructor for the requested Term
*
*/
private void buildInstructorSectionsList(SessionState state, ParameterParser params, Context context)
{
//Site information
// The sections of the specified term having this person as Instructor
context.put ("providerCourseSectionList", state.getAttribute("providerCourseSectionList"));
context.put ("manualCourseSectionList", state.getAttribute("manualCourseSectionList"));
context.put ("term", (Term) state.getAttribute(STATE_TERM_SELECTED));
context.put ("termList", CourseManagementService.getTerms());
context.put(STATE_TERM_COURSE_LIST, (List) state.getAttribute(STATE_TERM_COURSE_LIST));
context.put("tlang",rb);
} // buildInstructorSectionsList
/**
* getProviderCourseList
* a course site/realm id in one of three formats,
* for a single section, for multiple sections of the same course, or
* for a cross-listing having multiple courses. getProviderCourseList
* parses a realm id into year, term, campus_code, catalog_nbr, section components.
* @param id is a String representation of the course realm id (external id).
*/
private List getProviderCourseList(String id)
{
Vector rv = new Vector();
if(id == null || id == NULL_STRING)
{
return rv;
}
String course_part = NULL_STRING;
String section_part = NULL_STRING;
String key = NULL_STRING;
try
{
//Break Provider Id into course_nbr parts
List course_nbrs = new ArrayList(Arrays.asList(id.split("\\+")));
//Iterate through course_nbrs
for (ListIterator i = course_nbrs.listIterator(); i.hasNext(); )
{
String course_nbr = (String) i.next();
//Course_nbr pattern will be for either one section or more than one section
if (course_nbr.indexOf("[") == -1)
{
// This course_nbr matches the pattern for one section
try
{
rv.add(course_nbr);
}
catch (Exception e)
{
M_log.warn(this + ": cannot find class " + course_nbr);
}
}
else
{
// This course_nbr matches the pattern for more than one section
course_part = course_nbr.substring(0, course_nbr.indexOf("[")); // includes trailing ","
section_part = course_nbr.substring(course_nbr.indexOf("[")+1, course_nbr.indexOf("]"));
String[] sect = section_part.split(",");
for (int j = 0; j < sect.length; j++)
{
key = course_part + sect[j];
try
{
rv.add(key);
}
catch (Exception e)
{
M_log.warn(this + ": cannot find class " + key);
}
}
}
}
}
catch (Exception ee)
{
M_log.warn(ee.getMessage());
}
return rv;
} // getProviderCourseList
/**
* {@inheritDoc}
*/
protected int sizeResources(SessionState state)
{
int size = 0;
String search = "";
String userId = SessionManager.getCurrentSessionUserId();
//if called from the site list page
if(((String)state.getAttribute(STATE_TEMPLATE_INDEX)).equals("0"))
{
search = StringUtil.trimToNull((String) state.getAttribute(STATE_SEARCH));
if (SecurityService.isSuperUser())
{
// admin-type of user
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null)
{
if (view.equals(rb.getString("java.allmy")))
{
//search for non-user sites, using the criteria
size = SiteService.countSites(org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, null, search, null);
}
else if (view.equals(rb.getString("java.my")))
{
//search for a specific user site for the particular user id in the criteria - exact match only
try
{
SiteService.getSite(SiteService.getUserSiteId(search));
size++;
}
catch (IdUnusedException e) {}
}
else if (view.equalsIgnoreCase(rb.getString("java.gradtools")))
{
//search for gradtools sites
size = SiteService.countSites(org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, state.getAttribute(GRADTOOLS_SITE_TYPES), search, null);
}
else
{
//search for specific type of sites
size = SiteService.countSites(org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, view, search, null);
}
}
}
else
{
Site userWorkspaceSite = null;
try
{
userWorkspaceSite = SiteService.getSite(SiteService.getUserSiteId(userId));
}
catch (IdUnusedException e)
{
M_log.warn("Cannot find user " + SessionManager.getCurrentSessionUserId() + "'s My Workspace site.");
}
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view!= null)
{
if (view.equals(rb.getString("java.allmy")))
{
view = null;
//add my workspace if any
if (userWorkspaceSite != null)
{
if (search!=null)
{
if (userId.indexOf(search) != -1)
{
size++;
}
}
else
{
size++;
}
}
size += SiteService.countSites(org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, null, search, null);
}
else if (view.equalsIgnoreCase(rb.getString("java.gradtools")))
{
//search for gradtools sites
size += SiteService.countSites(org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, state.getAttribute(GRADTOOLS_SITE_TYPES), search, null);
}
else
{
// search for specific type of sites
size += SiteService.countSites(org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, view, search, null);
}
}
}
}
//for SiteInfo list page
else if (state.getAttribute(STATE_TEMPLATE_INDEX).toString().equals("12"))
{
List l = (List) state.getAttribute(STATE_PARTICIPANT_LIST);
size = (l!= null)?l.size():0;
}
return size;
} // sizeResources
/**
* {@inheritDoc}
*/
protected List readResourcesPage(SessionState state, int first, int last)
{
String search = StringUtil.trimToNull((String) state.getAttribute(STATE_SEARCH));
//if called from the site list page
if(((String)state.getAttribute(STATE_TEMPLATE_INDEX)).equals("0"))
{
// get sort type
SortType sortType = null;
String sortBy = (String) state.getAttribute(SORTED_BY);
boolean sortAsc = (new Boolean((String) state.getAttribute(SORTED_ASC))).booleanValue();
if (sortBy.equals(SortType.TITLE_ASC.toString()))
{
sortType=sortAsc?SortType.TITLE_ASC:SortType.TITLE_DESC;
}
else if (sortBy.equals(SortType.TYPE_ASC.toString()))
{
sortType=sortAsc?SortType.TYPE_ASC:SortType.TYPE_DESC;
}
else if (sortBy.equals(SortType.CREATED_BY_ASC.toString()))
{
sortType=sortAsc?SortType.CREATED_BY_ASC:SortType.CREATED_BY_DESC;
}
else if (sortBy.equals(SortType.CREATED_ON_ASC.toString()))
{
sortType=sortAsc?SortType.CREATED_ON_ASC:SortType.CREATED_ON_DESC;
}
else if (sortBy.equals(SortType.PUBLISHED_ASC.toString()))
{
sortType=sortAsc?SortType.PUBLISHED_ASC:SortType.PUBLISHED_DESC;
}
if (SecurityService.isSuperUser())
{
// admin-type of user
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null)
{
if (view.equals(rb.getString("java.allmy")))
{
//search for non-user sites, using the criteria
return SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
null, search, null, sortType, new PagingPosition(first, last));
}
else if (view.equalsIgnoreCase(rb.getString("java.my")))
{
//search for a specific user site for the particular user id in the criteria - exact match only
List rv = new Vector();
try
{
Site userSite = SiteService.getSite(SiteService.getUserSiteId(search));
rv.add(userSite);
}
catch (IdUnusedException e) {}
return rv;
}
else if (view.equalsIgnoreCase(rb.getString("java.gradtools")))
{
//search for gradtools sites
return SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
state.getAttribute(GRADTOOLS_SITE_TYPES), search, null, sortType, new PagingPosition(first, last));
}
else
{
//search for a specific site
return SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.ANY,
view, search, null, sortType, new PagingPosition(first, last));
}
}
}
else
{
List rv = new Vector();
Site userWorkspaceSite = null;
String userId = SessionManager.getCurrentSessionUserId();
try
{
userWorkspaceSite = SiteService.getSite(SiteService.getUserSiteId(userId));
}
catch (IdUnusedException e)
{
M_log.warn("Cannot find user " + SessionManager.getCurrentSessionUserId() + "'s My Workspace site.");
}
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view!= null)
{
if (view.equals(rb.getString("java.allmy")))
{
view = null;
//add my workspace if any
if (userWorkspaceSite != null)
{
if (search!=null)
{
if (userId.indexOf(search) != -1)
{
rv.add(userWorkspaceSite);
}
}
else
{
rv.add(userWorkspaceSite);
}
}
rv.addAll(SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
null, search, null, sortType, new PagingPosition(first, last)));
}
else if (view.equalsIgnoreCase(rb.getString("java.gradtools")))
{
//search for a specific user site for the particular user id in the criteria - exact match only
rv.addAll(SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
state.getAttribute(GRADTOOLS_SITE_TYPES), search, null, sortType, new PagingPosition(first, last)));
}
else
{
rv.addAll(SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
view, search, null, sortType, new PagingPosition(first, last)));
}
}
return rv;
}
}
//if in Site Info list view
else if (state.getAttribute(STATE_TEMPLATE_INDEX).toString().equals("12"))
{
List participants = (state.getAttribute(STATE_PARTICIPANT_LIST) != null)?(List) state.getAttribute(STATE_PARTICIPANT_LIST):new Vector();
PagingPosition page = new PagingPosition(first, last);
page.validate(participants.size());
participants = participants.subList(page.getFirst()-1, page.getLast());
return participants;
}
return null;
} // readResourcesPage
/**
* get the selected tool ids from import sites
*/
private boolean select_import_tools(ParameterParser params, SessionState state)
{
// has the user selected any tool for importing?
boolean anyToolSelected = false;
Hashtable importTools = new Hashtable();
// the tools for current site
List selectedTools = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // String toolId's
for (int i=0; i<selectedTools.size(); i++)
{
// any tools chosen from import sites?
String toolId = (String) selectedTools.get(i);
if (params.getStrings(toolId) != null)
{
importTools.put(toolId, new ArrayList(Arrays.asList(params.getStrings(toolId))));
if (!anyToolSelected)
{
anyToolSelected = true;
}
}
}
state.setAttribute(STATE_IMPORT_SITE_TOOL, importTools);
return anyToolSelected;
} // select_import_tools
/**
* Is it from the ENW edit page?
* @return ture if the process went through the ENW page; false, otherwise
*/
private boolean fromENWModifyView(SessionState state)
{
boolean fromENW = false;
List oTools = (List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
List toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
for (int i=0; i<toolList.size() && !fromENW; i++)
{
String toolId = (String) toolList.get(i);
if (toolId.equals("sakai.mailbox") || toolId.indexOf("sakai.news") != -1 || toolId.indexOf("sakai.iframe") != -1)
{
if (oTools == null)
{
// if during site creation proces
fromENW = true;
}
else if (!oTools.contains(toolId))
{
//if user is adding either EmailArchive tool, News tool or Web Content tool, go to the Customize page for the tool
fromENW = true;
}
}
}
return fromENW;
}
/**
* doNew_site is called when the Site list tool bar New... button is clicked
*
*/
public void doNew_site ( RunData data )
throws Exception
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// start clean
cleanState(state);
List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES);
if (siteTypes != null)
{
if (siteTypes.size() == 1)
{
String siteType = (String) siteTypes.get(0);
if (!siteType.equals(ServerConfigurationService.getString("courseSiteType", "")))
{
// if only one site type is allowed and the type isn't course type
// skip the select site type step
setNewSiteType(state, siteType);
state.setAttribute (STATE_TEMPLATE_INDEX, "2");
}
else
{
state.setAttribute (STATE_TEMPLATE_INDEX, "1");
}
}
else
{
state.setAttribute (STATE_TEMPLATE_INDEX, "1");
}
}
} // doNew_site
/**
* doMenu_site_delete is called when the Site list tool bar Delete button is clicked
*
*/
public void doMenu_site_delete ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
if (params.getStrings ("selectedMembers") == null)
{
addAlert(state, rb.getString("java.nosites"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
String[] removals = (String[]) params.getStrings ("selectedMembers");
state.setAttribute(STATE_SITE_REMOVALS, removals );
//present confirm delete template
state.setAttribute(STATE_TEMPLATE_INDEX, "8");
} // doMenu_site_delete
public void doSite_delete_confirmed ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
if (params.getStrings ("selectedMembers") == null)
{
M_log.warn("SiteAction.doSite_delete_confirmed selectedMembers null");
state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // return to the site list
return;
}
List chosenList = new ArrayList(Arrays.asList(params.getStrings ("selectedMembers"))); // Site id's of checked sites
if(!chosenList.isEmpty())
{
for (ListIterator i = chosenList.listIterator(); i.hasNext(); )
{
String id = (String)i.next();
String site_title = NULL_STRING;
try
{
site_title = SiteService.getSite(id).getTitle();
}
catch (IdUnusedException e)
{
M_log.warn("SiteAction.doSite_delete_confirmed - IdUnusedException " + id);
addAlert(state,rb.getString("java.sitewith") + " " + id + " "+ rb.getString("java.couldnt")+" ");
}
if(SiteService.allowRemoveSite(id))
{
try
{
Site site = SiteService.getSite(id);
site_title = site.getTitle();
SiteService.removeSite(site);
}
catch (IdUnusedException e)
{
M_log.warn("SiteAction.doSite_delete_confirmed - IdUnusedException " + id);
addAlert(state, rb.getString("java.sitewith")+" " + site_title + "(" + id + ") "+ rb.getString("java.couldnt")+" ");
}
catch (PermissionException e)
{
M_log.warn("SiteAction.doSite_delete_confirmed - PermissionException, site " + site_title + "(" + id + ").");
addAlert(state, site_title + " "+ rb.getString("java.dontperm")+" ");
}
}
else
{
M_log.warn("SiteAction.doSite_delete_confirmed - allowRemoveSite failed for site " + id);
addAlert(state, site_title + " "+ rb.getString("java.dontperm") +" ");
}
}
}
state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // return to the site list
// TODO: hard coding this frame id is fragile, portal dependent, and needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
} // doSite_delete_confirmed
/**
* get the Site object based on SessionState attribute values
* @return Site object related to current state; null if no such Site object could be found
*/
protected Site getStateSite(SessionState state)
{
Site site = null;
if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null)
{
try
{
site = SiteService.getSite((String) state.getAttribute(STATE_SITE_INSTANCE_ID));
}
catch (Exception ignore)
{
}
}
return site;
} // getStateSite
/**
* get the Group object based on SessionState attribute values
* @return Group object related to current state; null if no such Group object could be found
*/
protected Group getStateGroup(SessionState state)
{
Group group = null;
Site site = getStateSite(state);
if (site != null && state.getAttribute(STATE_GROUP_INSTANCE_ID) != null)
{
try
{
group = site.getGroup((String) state.getAttribute(STATE_GROUP_INSTANCE_ID));
}
catch (Exception ignore)
{
}
}
return group;
} // getStateGroup
/**
* do called when "eventSubmit_do" is in the request parameters to c
* is called from site list menu entry Revise... to get a locked site as editable and to go to the correct template to begin
* DB version of writes changes to disk at site commit whereas XML version writes at server shutdown
*/
public void doGet_site ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
//check form filled out correctly
if (params.getStrings ("selectedMembers") == null)
{
addAlert(state, rb.getString("java.nosites"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
List chosenList = new ArrayList(Arrays.asList(params.getStrings ("selectedMembers"))); // Site id's of checked sites
String siteId = "";
if(!chosenList.isEmpty())
{
if(chosenList.size() != 1)
{
addAlert(state, rb.getString("java.please"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
siteId = (String) chosenList.get(0);
getReviseSite(state, siteId);
state.setAttribute(SORTED_BY, SORTED_BY_PARTICIPANT_NAME);
state.setAttribute (SORTED_ASC, Boolean.TRUE.toString());
}
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP))
{
state.setAttribute(STATE_PAGESIZE_SITESETUP, state.getAttribute(STATE_PAGESIZE));
}
Hashtable h = (Hashtable) state.getAttribute(STATE_PAGESIZE_SITEINFO);
if (!h.containsKey(siteId))
{
// when first entered Site Info, set the participant list size to 200 as default
state.setAttribute(STATE_PAGESIZE, new Integer(200));
// update
h.put(siteId, new Integer(200));
state.setAttribute(STATE_PAGESIZE_SITEINFO, h);
}
else
{
//restore the page size in site info tool
state.setAttribute(STATE_PAGESIZE, h.get(siteId));
}
} // doGet_site
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doMenu_site_reuse ( RunData data )
throws Exception
{
// called from chef_site-list.vm after a site has been selected from list
// create a new Site object based on selected Site object and put in state
//
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.setAttribute (STATE_TEMPLATE_INDEX, "1");
} // doMenu_site_reuse
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doMenu_site_revise ( RunData data )
throws Exception
{
// called from chef_site-list.vm after a site has been selected from list
// get site as Site object, check SiteCreationStatus and SiteType of site, put in state, and set STATE_TEMPLATE_INDEX correctly
// set mode to state_mode_site_type
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.setAttribute (STATE_TEMPLATE_INDEX, "1");
} // doMenu_site_revise
/**
* doView_sites is called when "eventSubmit_doView_sites" is in the request parameters
*/
public void doView_sites ( RunData data )
throws Exception
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
state.setAttribute (STATE_VIEW_SELECTED, params.getString("view"));
state.setAttribute (STATE_TEMPLATE_INDEX, "0");
resetPaging(state);
} // doView_sites
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doView ( RunData data )
throws Exception
{
// called from chef_site-list.vm with a select option to build query of sites
//
//
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.setAttribute (STATE_TEMPLATE_INDEX, "1");
} // doView
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doSite_type ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
int index = Integer.valueOf(params.getString ("template-index")).intValue();
actionForTemplate("continue", index, params, state);
String type = StringUtil.trimToNull(params.getString ("itemType"));
int totalSteps = 0;
if (type == null)
{
addAlert(state, rb.getString("java.select")+" ");
}
else
{
setNewSiteType(state, type);
if (type.equalsIgnoreCase("course"))
{
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
String termId = params.getString("selectTerm");
Term t = CourseManagementService.getTerm(termId);
state.setAttribute(STATE_TERM_SELECTED, t);
if (t != null)
{
List courses = CourseManagementService.getInstructorCourses(userId, t.getYear(), t.getTerm());
// future term? roster information is not available yet?
int weeks = 0;
Calendar c = (Calendar) Calendar.getInstance().clone();
try
{
weeks = Integer.parseInt(ServerConfigurationService.getString("roster.available.weeks.before.term.start", "0"));
c.add(Calendar.DATE, weeks*7);
}
catch (Exception ignore)
{
}
if ((courses == null || courses != null && courses.size() == 0)
&& c.getTimeInMillis() < t.getStartTime().getTime())
{
//if a future term is selected
state.setAttribute(STATE_FUTURE_TERM_SELECTED, Boolean.TRUE);
}
else
{
state.setAttribute(STATE_FUTURE_TERM_SELECTED, Boolean.FALSE);
}
if (courses != null && courses.size() > 0)
{
state.setAttribute(STATE_TERM_COURSE_LIST, courses);
state.setAttribute (STATE_TEMPLATE_INDEX, "36");
state.setAttribute(STATE_AUTO_ADD, Boolean.TRUE);
totalSteps = 6;
}
else
{
state.removeAttribute(STATE_TERM_COURSE_LIST);
state.setAttribute (STATE_TEMPLATE_INDEX, "37");
totalSteps = 5;
}
}
else
{
state.setAttribute (STATE_TEMPLATE_INDEX, "37");
totalSteps = 5;
}
}
else if (type.equals("project"))
{
totalSteps = 4;
state.setAttribute (STATE_TEMPLATE_INDEX, "2");
}
else if (type.equals (SITE_TYPE_GRADTOOLS_STUDENT))
{
//if a GradTools site use pre-defined site info and exclude from public listing
SiteInfo siteInfo = new SiteInfo();
if(state.getAttribute(STATE_SITE_INFO) != null)
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
User currentUser = UserDirectoryService.getCurrentUser();
siteInfo.title = rb.getString("java.grad")+" - " + currentUser.getId();
siteInfo.description = rb.getString("java.gradsite")+" " + currentUser.getDisplayName();
siteInfo.short_description = rb.getString("java.grad")+" - " + currentUser.getId();
siteInfo.include = false;
state.setAttribute(STATE_SITE_INFO, siteInfo);
//skip directly to confirm creation of site
state.setAttribute (STATE_TEMPLATE_INDEX, "42");
}
else
{
state.setAttribute (STATE_TEMPLATE_INDEX, "2");
}
}
if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) == null)
{
state.setAttribute(SITE_CREATE_TOTAL_STEPS, new Integer(totalSteps));
}
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) == null)
{
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(1));
}
} // doSite_type
/**
* cleanEditGroupParams
* clean the state parameters used by editing group process
*
*/
public void cleanEditGroupParams ( SessionState state )
{
state.removeAttribute(STATE_GROUP_INSTANCE_ID);
state.removeAttribute(STATE_GROUP_TITLE);
state.removeAttribute(STATE_GROUP_DESCRIPTION);
state.removeAttribute(STATE_GROUP_MEMBERS);
state.removeAttribute(STATE_GROUP_REMOVE);
} //cleanEditGroupParams
/**
* doGroup_edit
*
*/
public void doGroup_update ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
Set gMemberSet = (Set) state.getAttribute(STATE_GROUP_MEMBERS);
Site site = getStateSite(state);
String title = StringUtil.trimToNull(params.getString(rb.getString("group.title")));
state.setAttribute(STATE_GROUP_TITLE, title);
String description = StringUtil.trimToZero(params.getString(rb.getString("group.description")));
state.setAttribute(STATE_GROUP_DESCRIPTION, description);
boolean found = false;
String option = params.getString("option");
if (option.equals("add"))
{
// add selected members into it
if (params.getStrings("generallist") != null)
{
List addMemberIds = new ArrayList(Arrays.asList(params.getStrings("generallist")));
for (int i=0; i<addMemberIds.size(); i++)
{
String aId = (String) addMemberIds.get(i);
found = false;
for(Iterator iSet = gMemberSet.iterator(); !found && iSet.hasNext();)
{
if (((Member) iSet.next()).getUserEid().equals(aId))
{
found = true;
}
}
if (!found)
{
try
{
User u = UserDirectoryService.getUser(aId);
gMemberSet.add(site.getMember(u.getId()));
}
catch (UserNotDefinedException e)
{
try
{
User u2 = UserDirectoryService.getUserByEid(aId);
gMemberSet.add(site.getMember(u2.getId()));
}
catch (UserNotDefinedException ee)
{
M_log.warn(this + ee.getMessage() + aId);
}
}
}
}
}
state.setAttribute(STATE_GROUP_MEMBERS, gMemberSet);
}
else if (option.equals("remove"))
{
// update the group member list by remove selected members from it
if (params.getStrings("grouplist") != null)
{
List removeMemberIds = new ArrayList(Arrays.asList(params.getStrings("grouplist")));
for (int i=0; i<removeMemberIds.size(); i++)
{
found = false;
for(Iterator iSet = gMemberSet.iterator(); !found && iSet.hasNext();)
{
Member mSet = (Member) iSet.next();
if (mSet.getUserId().equals((String) removeMemberIds.get(i)))
{
found = true;
gMemberSet.remove(mSet);
}
}
}
}
state.setAttribute(STATE_GROUP_MEMBERS, gMemberSet);
}
else if (option.equals("cancel"))
{
// cancel from the update the group member process
doCancel(data);
cleanEditGroupParams(state);
}
else if (option.equals("save"))
{
Group group = null;
if (site != null && state.getAttribute(STATE_GROUP_INSTANCE_ID) != null)
{
try
{
group = site.getGroup((String) state.getAttribute(STATE_GROUP_INSTANCE_ID));
}
catch (Exception ignore)
{
}
}
if (title == null)
{
addAlert(state, rb.getString("editgroup.titlemissing"));
}
else
{
if (group == null)
{
// when adding a group, check whether the group title has been used already
boolean titleExist = false;
for (Iterator iGroups = site.getGroups().iterator(); !titleExist && iGroups.hasNext(); )
{
Group iGroup = (Group) iGroups.next();
if (iGroup.getTitle().equals(title))
{
// found same title
titleExist = true;
}
}
if (titleExist)
{
addAlert(state, rb.getString("group.title.same"));
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (group == null)
{
// adding new group
group = site.addGroup();
group.getProperties().addProperty(GROUP_PROP_WSETUP_CREATED, Boolean.TRUE.toString());
}
if (group != null)
{
group.setTitle(title);
group.setDescription(description);
// save the modification to group members
// remove those no longer included in the group
Set members = group.getMembers();
for(Iterator iMembers = members.iterator(); iMembers.hasNext();)
{
found = false;
String mId = ((Member)iMembers.next()).getUserId();
for(Iterator iMemberSet = gMemberSet.iterator(); !found && iMemberSet.hasNext();)
{
if (mId.equals(((Member) iMemberSet.next()).getUserId()))
{
found = true;
}
}
if (!found)
{
group.removeMember(mId);
}
}
// add those seleted members
for(Iterator iMemberSet = gMemberSet.iterator(); iMemberSet.hasNext();)
{
String memberId = ((Member) iMemberSet.next()).getUserId();
if (group.getUserRole(memberId) == null)
{
Role r = site.getUserRole(memberId);
Member m = site.getMember(memberId);
// for every member added through the "Manage Groups" interface, he should be defined as non-provided
group.addMember(memberId, r!= null?r.getId():"", m!=null?m.isActive():true, false);
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
try
{
SiteService.save(site);
}
catch (IdUnusedException e)
{
}
catch (PermissionException e)
{
}
// return to group list view
state.setAttribute (STATE_TEMPLATE_INDEX, "49");
cleanEditGroupParams(state);
}
}
}
}
} // doGroup_updatemembers
/**
* doGroup_new
*
*/
public void doGroup_new ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
if (state.getAttribute(STATE_GROUP_TITLE) == null)
{
state.setAttribute(STATE_GROUP_TITLE, "");
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) == null)
{
state.setAttribute(STATE_GROUP_DESCRIPTION, "");
}
if (state.getAttribute(STATE_GROUP_MEMBERS) == null)
{
state.setAttribute(STATE_GROUP_MEMBERS, new HashSet());
}
state.setAttribute (STATE_TEMPLATE_INDEX, "50");
} // doGroup_new
/**
* doGroup_edit
*
*/
public void doGroup_edit ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
String groupId = data.getParameters ().getString("groupId");
state.setAttribute(STATE_GROUP_INSTANCE_ID, groupId);
Site site = getStateSite(state);
if (site != null)
{
Group g = site.getGroup(groupId);
if (g != null)
{
if (state.getAttribute(STATE_GROUP_TITLE) == null)
{
state.setAttribute(STATE_GROUP_TITLE, g.getTitle());
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) == null)
{
state.setAttribute(STATE_GROUP_DESCRIPTION, g.getDescription());
}
if (state.getAttribute(STATE_GROUP_MEMBERS) == null)
{
// double check the member existance
Set gMemberSet = g.getMembers();
Set rvGMemberSet = new HashSet();
for(Iterator iSet = gMemberSet.iterator(); iSet.hasNext();)
{
Member member = (Member) iSet.next();
try
{
UserDirectoryService.getUser(member.getUserId());
((Set) rvGMemberSet).add(member);
}
catch (UserNotDefinedException e)
{
// cannot find user
M_log.warn(this + rb.getString("user.notdefined") + member.getUserId());
}
}
state.setAttribute(STATE_GROUP_MEMBERS, rvGMemberSet);
}
}
}
state.setAttribute (STATE_TEMPLATE_INDEX, "50");
} // doGroup_edit
/**
* doGroup_remove_prep
* Go to confirmation page before deleting group(s)
*
*/
public void doGroup_remove_prep ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
String[] removeGroupIds = data.getParameters ().getStrings("removeGroups");
if (removeGroupIds.length > 0)
{
state.setAttribute(STATE_GROUP_REMOVE, removeGroupIds);
state.setAttribute (STATE_TEMPLATE_INDEX, "51");
}
} // doGroup_remove_prep
/**
* doGroup_remove_confirmed
* Delete selected groups after confirmation
*
*/
public void doGroup_remove_confirmed ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
String[] removeGroupIds = (String[]) state.getAttribute(STATE_GROUP_REMOVE);
Site site = getStateSite(state);
for (int i=0; i<removeGroupIds.length; i++)
{
if (site != null)
{
Group g = site.getGroup(removeGroupIds[i]);
if (g != null)
{
site.removeGroup(g);
}
}
}
try
{
SiteService.save(site);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("editgroup.site.notfound.alert"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("editgroup.site.permission.alert"));
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
cleanEditGroupParams(state);
state.setAttribute (STATE_TEMPLATE_INDEX, "49");
}
} // doGroup_remove_confirmed
/**
* doMenu_edit_site_info
* The menu choice to enter group view
*
*/
public void doMenu_group ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// reset sort criteria
state.setAttribute(SORTED_BY, rb.getString("group.title"));
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
state.setAttribute (STATE_TEMPLATE_INDEX, "49");
} // doMenu_group
/**
* dispatch to different functions based on the option value in the parameter
*/
public void doManual_add_course ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
String option = params.getString("option");
if (option.equalsIgnoreCase("change") || option.equalsIgnoreCase("add"))
{
readCourseSectionInfo(state, params);
String uniqname = StringUtil.trimToNull(params.getString("uniqname"));
state.setAttribute(STATE_SITE_QUEST_UNIQNAME, uniqname);
if (getStateSite(state) == null)
{
// creating new site
updateSiteInfo(params, state);
}
if (option.equalsIgnoreCase("add"))
{
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null
&& !((Boolean) state.getAttribute(STATE_FUTURE_TERM_SELECTED)).booleanValue())
{
// if a future term is selected, do not check authorization uniqname
if (uniqname == null)
{
addAlert(state, rb.getString("java.author") + " " + ServerConfigurationService.getString("noEmailInIdAccountName") + ". ");
}
else
{
try
{
UserDirectoryService.getUserByEid(uniqname);
}
catch (UserNotDefinedException e)
{
addAlert(state, rb.getString("java.validAuthor1")+" "+ ServerConfigurationService.getString("noEmailInIdAccountName") + " "+ rb.getString("java.validAuthor2"));
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (getStateSite(state) == null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
}
else
{
state.setAttribute(STATE_TEMPLATE_INDEX, "44");
}
}
updateCurrentStep(state, true);
}
}
else if (option.equalsIgnoreCase("back"))
{
doBack(data);
if (state.getAttribute(STATE_MESSAGE) == null)
{
updateCurrentStep(state, false);
}
}
else if (option.equalsIgnoreCase("cancel"))
{
if (getStateSite(state) == null)
{
doCancel_create(data);
}
else
{
doCancel(data);
}
}
} // doManual_add_course
/**
* read the input information of subject, course and section in the manual site creation page
*/
private void readCourseSectionInfo (SessionState state, ParameterParser params)
{
int oldNumber = 1;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
oldNumber = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
}
// read the user input
int validInputSites = 0;
boolean validInput = true;
List requiredFields = CourseManagementService.getCourseIdRequiredFields();
List multiCourseInputs = new Vector();
for (int i = 0; i < oldNumber; i++)
{
List aCourseInputs = new Vector();
int emptyInputNum = 0;
// iterate through all required fields
for (int k = 0; k<requiredFields.size(); k++)
{
String field = (String) requiredFields.get(k);
String fieldInput = StringUtil.trimToZero(params.getString(field + i));
aCourseInputs.add(fieldInput);
if (fieldInput.length() == 0)
{
// is this an empty String input?
emptyInputNum++;
}
}
// add to the multiCourseInput vector
multiCourseInputs.add(i, aCourseInputs);
// is any input invalid?
if (emptyInputNum == 0)
{
// valid if all the inputs are not empty
validInputSites++;
}
else if (emptyInputNum == requiredFields.size())
{
// ignore if all inputs are empty
}
else
{
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null
&& ((Boolean) state.getAttribute(STATE_FUTURE_TERM_SELECTED)).booleanValue())
{
// if future term selected, then not all fields are required %%%
validInputSites++;
}
else
{
validInput = false;
}
}
}
//how many more course/section to include in the site?
String option = params.getString("option");
if (option.equalsIgnoreCase("change"))
{
if (params.getString("number") != null)
{
int newNumber = Integer.parseInt(params.getString("number"));
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer(oldNumber + newNumber));
for (int j = 0; j<newNumber; j++)
{
// add a new course input
List aCourseInputs = new Vector();
// iterate through all required fields
for (int m = 0; m<requiredFields.size(); m++)
{
aCourseInputs.add("");
}
multiCourseInputs.add(aCourseInputs);
}
}
}
state.setAttribute(STATE_MANUAL_ADD_COURSE_FIELDS, multiCourseInputs);
if (!option.equalsIgnoreCase("change"))
{
if (!validInput || validInputSites == 0)
{
// not valid input
addAlert(state, rb.getString("java.miss"));
}
else
{
// valid input, adjust the add course number
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer(validInputSites));
}
}
// set state attributes
state.setAttribute(FORM_ADDITIONAL, StringUtil.trimToZero(params.getString("additional")));
SiteInfo siteInfo = new SiteInfo();
if(state.getAttribute(STATE_SITE_INFO) != null)
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
List providerCourseList = (List) state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
//store the manually requested sections in one site property
if ((providerCourseList == null || providerCourseList.size() == 0) && multiCourseInputs.size() > 0)
{
String courseId = CourseManagementService.getCourseId((Term) state.getAttribute(STATE_TERM_SELECTED), (List) multiCourseInputs.get(0));
String title = "";
try
{
title = CourseManagementService.getCourseName(courseId);
}
catch (IdUnusedException e)
{
// ignore
}
siteInfo.title = appendTermInSiteTitle(state, title);
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
} // readCourseSectionInfo
/**
* set the site type for new site
*
* @param type The type String
*/
private void setNewSiteType(SessionState state, String type)
{
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
//start out with fresh site information
SiteInfo siteInfo = new SiteInfo();
siteInfo.site_type = type;
siteInfo.published = true;
state.setAttribute(STATE_SITE_INFO, siteInfo);
// get registered tools list
Set categories = new HashSet();
categories.add(type);
Set toolRegistrations = ToolManager.findTools(categories, null);
List tools = new Vector();
SortedIterator i = new SortedIterator(toolRegistrations.iterator(), new ToolComparator());
for (; i.hasNext();)
{
// form a new Tool
Tool tr = (Tool) i.next();
MyTool newTool = new MyTool();
newTool.title = tr.getTitle();
newTool.id = tr.getId();
newTool.description = tr.getDescription();
tools.add(newTool);
}
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, tools);
state.setAttribute (STATE_SITE_TYPE, type);
}
/**
* Set the field on which to sort the list of students
*
*/
public void doSort_roster ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//get the field on which to sort the student list
ParameterParser params = data.getParameters ();
String criterion = params.getString ("criterion");
// current sorting sequence
String asc = "";
if (!criterion.equals (state.getAttribute (SORTED_BY)))
{
state.setAttribute (SORTED_BY, criterion);
asc = Boolean.TRUE.toString ();
state.setAttribute (SORTED_ASC, asc);
}
else
{
// current sorting sequence
asc = (String) state.getAttribute (SORTED_ASC);
//toggle between the ascending and descending sequence
if (asc.equals (Boolean.TRUE.toString ()))
{
asc = Boolean.FALSE.toString ();
}
else
{
asc = Boolean.TRUE.toString ();
}
state.setAttribute (SORTED_ASC, asc);
}
} //doSort_roster
/**
* Set the field on which to sort the list of sites
*
*/
public void doSort_sites ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//call this method at the start of a sort for proper paging
resetPaging(state);
//get the field on which to sort the site list
ParameterParser params = data.getParameters ();
String criterion = params.getString ("criterion");
// current sorting sequence
String asc = "";
if (!criterion.equals (state.getAttribute (SORTED_BY)))
{
state.setAttribute (SORTED_BY, criterion);
asc = Boolean.TRUE.toString ();
state.setAttribute (SORTED_ASC, asc);
}
else
{
// current sorting sequence
asc = (String) state.getAttribute (SORTED_ASC);
//toggle between the ascending and descending sequence
if (asc.equals (Boolean.TRUE.toString ()))
{
asc = Boolean.FALSE.toString ();
}
else
{
asc = Boolean.TRUE.toString ();
}
state.setAttribute (SORTED_ASC, asc);
}
state.setAttribute(SORTED_BY, criterion);
} //doSort_sites
/**
* doContinue is called when "eventSubmit_doContinue" is in the request parameters
*/
public void doContinue ( RunData data )
{
// Put current form data in state and continue to the next template, make any permanent changes
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
int index = Integer.valueOf(params.getString ("template-index")).intValue();
// Let actionForTemplate know to make any permanent changes before continuing to the next template
String direction = "continue";
actionForTemplate(direction, index, params, state);
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (index == 9)
{
// go to the send site publish email page if "publish" option is chosen
SiteInfo sInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (sInfo.getPublished())
{
state.setAttribute(STATE_TEMPLATE_INDEX, "16");
}
else
{
state.setAttribute(STATE_TEMPLATE_INDEX, "17");
}
}
else if (params.getString ("continue") != null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString ("continue"));
}
}
}// doContinue
/**
* doBack is called when "eventSubmit_doBack" is in the request parameters
* Pass parameter to actionForTemplate to request action for backward direction
*/
public void doBack ( RunData data )
{
// Put current form data in state and return to the previous template
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
int currentIndex = Integer.parseInt((String)state.getAttribute(STATE_TEMPLATE_INDEX));
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString ("back"));
// Let actionForTemplate know not to make any permanent changes before continuing to the next template
String direction = "back";
actionForTemplate(direction, currentIndex, params, state);
}// doBack
/**
* doFinish is called when a site has enough information to be saved as an unpublished site
*/
public void doFinish ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString ("continue"));
int index = Integer.valueOf(params.getString ("template-index")).intValue();
actionForTemplate("continue", index, params, state);
addNewSite(params, state);
addFeatures(state);
Site site = getStateSite(state);
// for course sites
String siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course"))
{
String siteId = site.getId();
ResourcePropertiesEdit rp = site.getPropertiesEdit();
Term term = null;
if (state.getAttribute(STATE_TERM_SELECTED) != null)
{
term = (Term) state.getAttribute(STATE_TERM_SELECTED);
rp.addProperty(PROP_SITE_TERM, term.getId());
}
List providerCourseList = (List) state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
int manualAddNumber = 0;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
manualAddNumber = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
}
String realm = SiteService.siteReference(siteId);
if ((providerCourseList != null) && (providerCourseList.size() != 0))
{
String providerRealm = buildExternalRealm(siteId, state, providerCourseList);
try
{
AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realm);
realmEdit.setProviderGroupId(providerRealm);
AuthzGroupService.save(realmEdit);
}
catch (GroupNotDefinedException e)
{
M_log.warn(this + " IdUnusedException, not found, or not an AuthzGroup object");
addAlert(state, rb.getString("java.realm"));
return;
}
// catch (AuthzPermissionException e)
// {
// M_log.warn(this + " PermissionException, user does not have permission to edit AuthzGroup object.");
// addAlert(state, rb.getString("java.notaccess"));
// return;
// }
catch (Exception e)
{
addAlert(state, this + rb.getString("java.problem"));
return;
}
addSubjectAffliates(state, providerCourseList);
sendSiteNotification(state, providerCourseList);
}
if (manualAddNumber != 0)
{
// set the manual sections to the site property
String manualSections = "";
List manualCourseInputs = (List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
for (int j = 0; j < manualAddNumber; j++)
{
manualSections = manualSections.concat(CourseManagementService.getCourseId(term, (List) manualCourseInputs.get(j))).concat("+");
}
// trim the trailing plus sign
if (manualSections.endsWith("+"))
{
manualSections = manualSections.substring(0, manualSections.lastIndexOf("+"));
}
rp.addProperty(PROP_SITE_REQUEST_COURSE, manualSections);
// send request
sendSiteRequest(state, "new", manualAddNumber, manualCourseInputs);
}
}
// commit site
commitSite(site);
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
//now that the site exists, we can set the email alias when an Email Archive tool has been selected
String alias = StringUtil.trimToNull((String) state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
if (alias != null)
{
String channelReference = mailArchiveChannelReference(siteId);
try
{
AliasService.setAlias(alias, channelReference);
}
catch (IdUsedException ee)
{
addAlert(state, rb.getString("java.alias")+" " + alias + " "+rb.getString("java.exists"));
}
catch (IdInvalidException ee)
{
addAlert(state, rb.getString("java.alias")+" " + alias + " "+rb.getString("java.isinval"));
}
catch (PermissionException ee)
{
addAlert(state, rb.getString("java.addalias")+" ");
}
}
// TODO: hard coding this frame id is fragile, portal dependent, and needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
resetPaging(state);
// clean state variables
cleanState(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
}
}// doFinish
private void addSubjectAffliates(SessionState state, List providerCourseList)
{
Vector subjAffiliates = new Vector();
Vector affiliates = new Vector();
String subject = "";
String affiliate = "";
//get all subject and campus pairs for this site
for (ListIterator i = providerCourseList.listIterator(); i.hasNext(); )
{
String courseId = (String) i.next();
try
{
Course c = CourseManagementService.getCourse(courseId);
if(c.getSubject() != null && c.getSubject() != "") subject = c.getSubject();
subjAffiliates.add(subject);
}
catch (IdUnusedException e)
{
// M_log.warn(this + " cannot find course " + courseId + ". ");
}
}
// remove duplicates
Collection noDups = new HashSet(subjAffiliates);
// get affliates for subjects
for (Iterator i = noDups.iterator(); i.hasNext(); )
{
subject = (String)i.next();
Collection uniqnames = getSubjectAffiliates(state, subject);
try
{
affiliates.addAll(uniqnames);
}
catch(Exception ignore){}
}
// remove duplicates
Collection addAffiliates = new HashSet(affiliates);
// try to add uniqnames with appropriate role
for (Iterator i = addAffiliates.iterator(); i.hasNext(); )
{
affiliate = (String)i.next();
try
{
User user = UserDirectoryService.getUserByEid(affiliate);
String realmId = "/site/" + (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
if (AuthzGroupService.allowUpdate(realmId))
{
try
{
AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realmId);
Role role = realmEdit.getRole("Affiliate");
realmEdit.addMember(user.getId(), role.getId(), true, false);
AuthzGroupService.save(realmEdit);
}
catch(Exception ignore) {}
}
}
catch(Exception ignore)
{
M_log.warn(this + " cannot find affiliate " + affiliate);
}
}
} //addSubjectAffliates
/**
* @params - SessionState state
* @params - String subject is the University's Subject code
* @return - Collection of uniqnames of affiliates for this subject
*/
private Collection getSubjectAffiliates(SessionState state, String subject)
{
Collection rv = null;
List allAffiliates = (Vector) state.getAttribute(STATE_SUBJECT_AFFILIATES);
//iterate through the subjects looking for this subject
for (Iterator i = allAffiliates.iterator(); i.hasNext(); )
{
SubjectAffiliates sa = (SubjectAffiliates)i.next();
if(subject.equals(sa.getCampus() + "_" + sa.getSubject())) return sa.getUniqnames();
}
return rv;
} //getSubjectAffiliates
/**
* buildExternalRealm creates a site/realm id in one of three formats,
* for a single section, for multiple sections of the same course, or
* for a cross-listing having multiple courses
* @param sectionList is a Vector of CourseListItem
* @param id The site id
*/
private String buildExternalRealm(String id, SessionState state, List providerIdList)
{
String realm = SiteService.siteReference(id);
if (!AuthzGroupService.allowUpdate(realm))
{
addAlert(state, rb.getString("java.rosters"));
return null;
}
return CourseManagementService.getProviderId(providerIdList);
} // buildExternalRealm
/**
* Notification sent when a course site needs to be set up by Support
*
*/
private void sendSiteRequest(SessionState state, String request, int requestListSize, List requestFields)
{
User cUser = UserDirectoryService.getCurrentUser();
boolean sendEmailToRequestee = false;
StringBuffer buf = new StringBuffer();
// get the request email from configuration
String requestEmail = ServerConfigurationService.getString("setup.request", null);
if (requestEmail == null)
{
M_log.warn(this + " - no 'setup.request' in configuration");
}
else
{
String noEmailInIdAccountName = ServerConfigurationService.getString("noEmailInIdAccountName", "");
SiteInfo siteInfo = (SiteInfo)state.getAttribute(STATE_SITE_INFO);
Site site = getStateSite(state);
String id = site.getId();
String title = site.getTitle();
Time time = TimeService.newTime();
String local_time = time.toStringLocalTime();
String local_date = time.toStringLocalDate();
Term term = null;
boolean termExist = false;
if (state.getAttribute(STATE_TERM_SELECTED) != null)
{
termExist = true;
term = (Term) state.getAttribute(STATE_TERM_SELECTED);
}
String productionSiteName = ServerConfigurationService.getServerName();
String from = NULL_STRING;
String to = NULL_STRING;
String headerTo = NULL_STRING;
String replyTo = NULL_STRING;
String message_subject = NULL_STRING;
String content = NULL_STRING;
String sessionUserName = cUser.getDisplayName();
String additional = NULL_STRING;
if (request.equals("new"))
{
additional = siteInfo.getAdditional();
}
else
{
additional = (String)state.getAttribute(FORM_ADDITIONAL);
}
boolean isFutureTerm = false;
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null && ((Boolean) state.getAttribute(STATE_FUTURE_TERM_SELECTED)).booleanValue())
{
isFutureTerm = true;
}
// message subject
if (termExist)
{
message_subject = rb.getString("java.sitereqfrom")+" " + sessionUserName + " " + rb.getString("java.for") + " " + term.getId();
}
else
{
message_subject = rb.getString("java.official")+" " + sessionUserName;
}
// there is no offical instructor for future term sites
String requestId = (String) state.getAttribute(STATE_SITE_QUEST_UNIQNAME);
if (!isFutureTerm)
{
//To site quest account - the instructor of record's
if (requestId != null)
{
try
{
User instructor = UserDirectoryService.getUser(requestId);
from = requestEmail;
to = instructor.getEmail();
headerTo = instructor.getEmail();
replyTo = requestEmail;
buf.append(rb.getString("java.hello")+" \n\n");
buf.append(rb.getString("java.receiv")+" " + sessionUserName + ", ");
buf.append(rb.getString("java.who")+"\n");
if (termExist)
{
buf.append(term.getTerm() + " " + term.getYear() + "\n");
}
// what are the required fields shown in the UI
List requiredFields = CourseManagementService.getCourseIdRequiredFields();
for (int i = 0; i < requestListSize; i++)
{
List requiredFieldList = (List) requestFields.get(i);
for (int j = 0; j < requiredFieldList.size(); j++)
{
String requiredField = (String) requiredFields.get(j);
buf.append(requiredField +"\t" + requiredFieldList.get(j) + "\n");
}
}
buf.append("\n" + rb.getString("java.sitetitle")+"\t" + title + "\n");
buf.append(rb.getString("java.siteid")+"\t" + id);
buf.append("\n\n"+rb.getString("java.according")+" " + sessionUserName + " "+rb.getString("java.record"));
buf.append(" " + rb.getString("java.canyou")+" " + sessionUserName + " "+ rb.getString("java.assoc")+"\n\n");
buf.append(rb.getString("java.respond")+" " + sessionUserName + rb.getString("java.appoint")+"\n\n");
buf.append(rb.getString("java.thanks")+"\n");
buf.append(productionSiteName + " "+rb.getString("java.support"));
content = buf.toString();
// send the email
EmailService.send(from, to, message_subject, content, headerTo, replyTo, null);
// email has been sent successfully
sendEmailToRequestee = true;
}
catch (UserNotDefinedException ee)
{
} // try
}
}
//To Support
from = cUser.getEmail();
to = requestEmail;
headerTo = requestEmail;
replyTo = cUser.getEmail();
buf.setLength(0);
buf.append(rb.getString("java.to")+"\t\t" + productionSiteName + " "+rb.getString("java.supp")+"\n");
buf.append("\n"+rb.getString("java.from")+"\t" + sessionUserName + "\n");
if (request.equals("new"))
{
buf.append(rb.getString("java.subj")+"\t"+rb.getString("java.sitereq")+"\n");
}
else
{
buf.append(rb.getString("java.subj")+"\t"+rb.getString("java.sitechreq")+"\n");
}
buf.append(rb.getString("java.date")+"\t" + local_date + " " + local_time + "\n\n");
if (request.equals("new"))
{
buf.append(rb.getString("java.approval") + " " + productionSiteName + " "+rb.getString("java.coursesite")+" ");
}
else
{
buf.append(rb.getString("java.approval2")+" " + productionSiteName + " "+rb.getString("java.coursesite")+" ");
}
if (termExist)
{
buf.append(term.getTerm() + " " + term.getYear());
}
if (requestListSize >1)
{
buf.append(" "+rb.getString("java.forthese")+" " + requestListSize + " "+rb.getString("java.sections")+"\n\n");
}
else
{
buf.append(" "+rb.getString("java.forthis")+"\n\n");
}
//what are the required fields shown in the UI
List requiredFields = CourseManagementService.getCourseIdRequiredFields();
for (int i = 0; i < requestListSize; i++)
{
List requiredFieldList = (List) requestFields.get(i);
for (int j = 0; j < requiredFieldList.size(); j++)
{
String requiredField = (String) requiredFields.get(j);
buf.append(requiredField +"\t" + requiredFieldList.get(j) + "\n");
}
}
buf.append(rb.getString("java.name")+"\t" + sessionUserName + " (" + noEmailInIdAccountName + " " + cUser.getEid() + ")\n");
buf.append(rb.getString("java.email")+"\t" + replyTo + "\n\n");
buf.append(rb.getString("java.sitetitle")+"\t" + title + "\n");
buf.append(rb.getString("java.siteid")+"\t" + id + "\n");
buf.append(rb.getString("java.siteinstr")+"\n" + additional + "\n\n");
if (!isFutureTerm)
{
if (sendEmailToRequestee)
{
buf.append(rb.getString("java.authoriz")+" " + requestId + " "+rb.getString("java.asreq"));
}
else
{
buf.append(rb.getString("java.thesiteemail")+" " + requestId + " "+rb.getString("java.asreq"));
}
}
content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo, replyTo, null);
//To the Instructor
from = requestEmail;
to = cUser.getEmail();
headerTo = to;
replyTo = to;
buf.setLength(0);
buf.append(rb.getString("java.isbeing")+" ");
buf.append(rb.getString("java.meantime")+"\n\n");
buf.append(rb.getString("java.copy")+"\n\n");
buf.append(content);
buf.append("\n"+rb.getString("java.wish")+" " + requestEmail);
content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo, replyTo, null);
state.setAttribute(REQUEST_SENT, new Boolean(true));
} // if
} // sendSiteRequest
/**
* Notification sent when a course site is set up automatcally
*
*/
private void sendSiteNotification(SessionState state, List notifySites)
{
// get the request email from configuration
String requestEmail = ServerConfigurationService.getString("setup.request", null);
if (requestEmail == null)
{
M_log.warn(this + " - no 'setup.request' in configuration");
}
else
{
// send emails
Site site = getStateSite(state);
String id = site.getId();
String title = site.getTitle();
Time time = TimeService.newTime();
String local_time = time.toStringLocalTime();
String local_date = time.toStringLocalDate();
String term_name = "";
if (state.getAttribute(STATE_TERM_SELECTED) != null)
{
term_name = ((Term) state.getAttribute(STATE_TERM_SELECTED)).getId();
}
String message_subject = rb.getString("java.official")+ " " + UserDirectoryService.getCurrentUser().getDisplayName() + " " + rb.getString("java.for") + " " + term_name;
String from = NULL_STRING;
String to = NULL_STRING;
String headerTo = NULL_STRING;
String replyTo = NULL_STRING;
String sender = UserDirectoryService.getCurrentUser().getDisplayName();
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
try
{
userId = UserDirectoryService.getUserEid(userId);
}
catch (UserNotDefinedException e)
{
M_log.warn(this + rb.getString("user.notdefined") + " " + userId);
}
//To Support
from = UserDirectoryService.getCurrentUser().getEmail();
to = requestEmail;
headerTo = requestEmail;
replyTo = UserDirectoryService.getCurrentUser().getEmail();
StringBuffer buf = new StringBuffer();
buf.append("\n"+rb.getString("java.fromwork")+" " + ServerConfigurationService.getServerName() + " "+rb.getString("java.supp")+":\n\n");
buf.append(rb.getString("java.off")+" '" + title + "' (id " + id + "), " +rb.getString("java.wasset")+" ");
buf.append(sender + " (" + userId + ", " + rb.getString("java.email2")+ " " + replyTo + ") ");
buf.append(rb.getString("java.on")+" " + local_date + " " + rb.getString("java.at")+ " " + local_time + " ");
buf.append(rb.getString("java.for")+" " + term_name + ", ");
int nbr_sections = notifySites.size();
if (nbr_sections >1)
{
buf.append(rb.getString("java.withrost")+" " + Integer.toString(nbr_sections) + " "+rb.getString("java.sections")+"\n\n");
}
else
{
buf.append(" "+rb.getString("java.withrost2")+"\n\n");
}
for (int i = 0; i < nbr_sections; i++)
{
String course = (String) notifySites.get(i);
buf.append(rb.getString("java.course2")+" " + course + "\n");
}
String content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo, replyTo, null);
} // if
} // sendSiteNotification
/**
* doCancel called when "eventSubmit_doCancel_create" is in the request parameters to c
*/
public void doCancel_create ( RunData data )
{
// Don't put current form data in state, just return to the previous template
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
removeAddClassContext(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} // doCancel_create
/**
* doCancel called when "eventSubmit_doCancel" is in the request parameters to c
* int index = Integer.valueOf(params.getString ("template-index")).intValue();
*/
public void doCancel ( RunData data )
{
// Don't put current form data in state, just return to the previous template
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
state.removeAttribute(STATE_MESSAGE);
String currentIndex = (String)state.getAttribute(STATE_TEMPLATE_INDEX);
String backIndex = params.getString("back");
state.setAttribute(STATE_TEMPLATE_INDEX, backIndex);
if (currentIndex.equals("4"))
{
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
state.removeAttribute(STATE_MESSAGE);
removeEditToolState(state);
}
else if (currentIndex.equals("5"))
{
//remove related state variables
removeAddParticipantContext(state);
params = data.getParameters ();
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("back"));
}
else if (currentIndex.equals("6"))
{
state.removeAttribute(STATE_REMOVEABLE_USER_LIST);
}
else if (currentIndex.equals("9"))
{
state.removeAttribute(FORM_WILL_NOTIFY);
}
else if (currentIndex.equals("17") || currentIndex.equals("16"))
{
state.removeAttribute(FORM_WILL_NOTIFY);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
else if (currentIndex.equals("13") || currentIndex.equals("14"))
{
// clean state attributes
state.removeAttribute(FORM_SITEINFO_TITLE);
state.removeAttribute(FORM_SITEINFO_DESCRIPTION);
state.removeAttribute(FORM_SITEINFO_SHORT_DESCRIPTION);
state.removeAttribute(FORM_SITEINFO_SKIN);
state.removeAttribute(FORM_SITEINFO_INCLUDE);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
else if (currentIndex.equals("15"))
{
params = data.getParameters ();
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("cancelIndex"));
removeEditToolState(state);
}
//htripath: added 'currentIndex.equals("45")' for import from file cancel
else if (currentIndex.equals("19") || currentIndex.equals("20") || currentIndex.equals("21") || currentIndex.equals("22")|| currentIndex.equals("45"))
{
// from adding participant pages
//remove related state variables
removeAddParticipantContext(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
else if (currentIndex.equals("23") || currentIndex.equals("24"))
{
// from change global access
state.removeAttribute("form_joinable");
state.removeAttribute("form_joinerRole");
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
else if (currentIndex.equals("7") || currentIndex.equals("25"))
{
//from change role
removeChangeRoleContext(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
else if (currentIndex.equals("3"))
{
//from adding class
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP))
{
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
}
else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO))
{
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
}
else if (currentIndex.equals("27") || currentIndex.equals("28"))
{
// from import
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP))
{
// worksite setup
if (getStateSite(state) == null)
{
//in creating new site process
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
}
else
{
// in editing site process
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
}
else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO))
{
// site info
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
}
else if (currentIndex.equals("26"))
{
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP)
&& getStateSite(state) == null)
{
//from creating site
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
}
else
{
//from revising site
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
removeEditToolState(state);
}
else if (currentIndex.equals("37") || currentIndex.equals("44"))
{
// cancel back to edit class view
state.setAttribute(STATE_TEMPLATE_INDEX, "43");
removeAddClassContext(state);
}
} // doCancel
/**
* doMenu_customize is called when "eventSubmit_doBack" is in the request parameters
* Pass parameter to actionForTemplate to request action for backward direction
*/
public void doMenu_customize ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.setAttribute(STATE_TEMPLATE_INDEX, "15");
}// doMenu_customize
/**
* doBack_to_list cancels an outstanding site edit, cleans state and returns to the site list
*
*/
public void doBack_to_list ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
Site site = getStateSite(state);
if (site != null)
{
Hashtable h = (Hashtable) state.getAttribute(STATE_PAGESIZE_SITEINFO);
h.put(site.getId(), state.getAttribute(STATE_PAGESIZE));
state.setAttribute(STATE_PAGESIZE_SITEINFO, h);
}
//restore the page size for Worksite setup tool
if (state.getAttribute(STATE_PAGESIZE_SITESETUP) != null)
{
state.setAttribute(STATE_PAGESIZE, state.getAttribute(STATE_PAGESIZE_SITESETUP));
state.removeAttribute(STATE_PAGESIZE_SITESETUP);
}
cleanState(state);
setupFormNamesAndConstants(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} // doBack_to_list
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doAdd_custom_link ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
if ((params.getString("name")) == null || (params.getString("url") == null))
{
Tool tr = ToolManager.getTool("sakai.iframe");
Site site = getStateSite(state);
SitePage page = site.addPage();
page.setTitle(params.getString("name")); // the visible label on the tool menu
ToolConfiguration tool = page.addTool();
tool.setTool("sakai.iframe", tr);
tool.setTitle(params.getString("name"));
commitSite(site);
}
else
{
addAlert(state, rb.getString("java.reqmiss"));
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("template-index"));
}
} // doAdd_custom_link
/**
* doAdd_remove_features is called when Make These Changes is clicked in chef_site-addRemoveFeatures
*/
public void doAdd_remove_features ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
List existTools = (List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
ParameterParser params = data.getParameters ();
String option = params.getString("option");
// dispatch
if (option.equalsIgnoreCase("addNews"))
{
updateSelectedToolList(state, params, false);
insertTool(state, "sakai.news", STATE_NEWS_TITLES, NEWS_DEFAULT_TITLE, STATE_NEWS_URLS, NEWS_DEFAULT_URL, Integer.parseInt(params.getString("newsNum")));
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
}
else if (option.equalsIgnoreCase("addWC"))
{
updateSelectedToolList(state, params, false);
insertTool(state, "sakai.iframe", STATE_WEB_CONTENT_TITLES, WEB_CONTENT_DEFAULT_TITLE, STATE_WEB_CONTENT_URLS, WEB_CONTENT_DEFAULT_URL, Integer.parseInt(params.getString("wcNum")));
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
}
else if (option.equalsIgnoreCase("save"))
{
List idsSelected = new Vector();
boolean goToENWPage = false;
boolean homeSelected = false;
// Add new pages and tools, if any
if (params.getStrings ("selectedTools") == null)
{
addAlert(state, rb.getString("atleastonetool"));
}
else
{
List l = new ArrayList(Arrays.asList(params.getStrings ("selectedTools"))); // toolId's & titles of chosen tools
for (int i = 0; i < l.size(); i++)
{
String toolId = (String) l.get(i);
if (toolId.equals(HOME_TOOL_ID))
{
homeSelected = true;
}
else if (toolId.equals("sakai.mailbox") || toolId.indexOf("sakai.news") != -1 || toolId.indexOf("sakai.iframe") != -1)
{
// if user is adding either EmailArchive tool, News tool or Web Content tool, go to the Customize page for the tool
if (!existTools.contains(toolId))
{
goToENWPage = true;
}
if (toolId.equals("sakai.mailbox"))
{
//get the email alias when an Email Archive tool has been selected
String channelReference = mailArchiveChannelReference((String) state.getAttribute(STATE_SITE_INSTANCE_ID));
List aliases = AliasService.getAliases(channelReference, 1, 1);
if (aliases.size() > 0)
{
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases.get(0)).getId());
}
}
}
idsSelected.add(toolId);
}
state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(homeSelected));
}
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idsSelected); // List of ToolRegistration toolId's
if (state.getAttribute(STATE_MESSAGE)== null)
{
if (goToENWPage)
{
// go to the configuration page for Email Archive, News and Web Content tools
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
}
else
{
// go to confirmation page
state.setAttribute(STATE_TEMPLATE_INDEX, "15");
}
}
}
else if (option.equalsIgnoreCase("continue"))
{
// continue
doContinue(data);
}
else if (option.equalsIgnoreCase("Back"))
{
//back
doBack(data);
}
else if (option.equalsIgnoreCase("Cancel"))
{
//cancel
doCancel(data);
}
} // doAdd_remove_features
/**
* doSave_revised_features
*/
public void doSave_revised_features ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
getRevisedFeatures(params, state);
Site site = getStateSite(state);
String id = site.getId();
//now that the site exists, we can set the email alias when an Email Archive tool has been selected
String alias = StringUtil.trimToNull((String) state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
if (alias != null)
{
String channelReference = mailArchiveChannelReference(id);
try
{
AliasService.setAlias(alias, channelReference);
}
catch (IdUsedException ee)
{
}
catch (IdInvalidException ee)
{
addAlert(state, rb.getString("java.alias")+" " + alias + " "+rb.getString("java.isinval"));
}
catch (PermissionException ee)
{
addAlert(state, rb.getString("java.addalias")+" ");
}
}
if (state.getAttribute(STATE_MESSAGE)== null)
{
// clean state variables
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_NEWS_TITLES);
state.removeAttribute(STATE_NEWS_URLS);
state.removeAttribute(STATE_WEB_CONTENT_TITLES);
state.removeAttribute(STATE_WEB_CONTENT_URLS);
state.setAttribute(STATE_SITE_INSTANCE_ID, id);
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString ("continue"));
}
// refresh the whole page
scheduleTopRefresh();
} // doSave_revised_features
/**
* doMenu_add_participant
*/
public void doMenu_add_participant ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.setAttribute (STATE_TEMPLATE_INDEX, "5");
} // doMenu_add_participant
/**
* doMenu_siteInfo_addParticipant
*/
public void doMenu_siteInfo_addParticipant ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.removeAttribute(STATE_SELECTED_USER_LIST);
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute (STATE_TEMPLATE_INDEX, "5");
}
} // doMenu_siteInfo_addParticipant
/**
* doMenu_siteInfo_removeParticipant
*/
public void doMenu_siteInfo_removeParticipant( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
if (params.getStrings ("selectedUser") == null)
{
addAlert(state, rb.getString("java.nousers"));
}
else
{
List removeUser = Arrays.asList(params.getStrings ("selectedUser"));
// all or some selected user(s) can be removed, go to confirmation page
if (removeUser.size() > 0)
{
state.setAttribute (STATE_TEMPLATE_INDEX, "6");
}
else
{
addAlert(state, rb.getString("java.however"));
}
state.setAttribute (STATE_REMOVEABLE_USER_LIST, removeUser);
}
} // doMenu_siteInfo_removeParticipant
/**
* doMenu_siteInfo_changeRole
*/
public void doMenu_siteInfo_changeRole ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
if (params.getStrings ("selectedUser") == null)
{
state.removeAttribute(STATE_SELECTED_USER_LIST);
addAlert(state, rb.getString("java.nousers2"));
}
else
{
state.setAttribute (STATE_CHANGEROLE_SAMEROLE, Boolean.TRUE);
List selectedUserIds = Arrays.asList(params.getStrings ("selectedUser"));
state.setAttribute (STATE_SELECTED_USER_LIST, selectedUserIds);
// get roles for selected participants
setSelectedParticipantRoles(state);
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute (STATE_TEMPLATE_INDEX, "7");
}
}
} // doMenu_siteInfo_changeRole
/**
* doMenu_siteInfo_globalAccess
*/
public void doMenu_siteInfo_globalAccess(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "23");
}
} //doMenu_siteInfo_globalAccess
/**
* doMenu_siteInfo_cancel_access
*/
public void doMenu_siteInfo_cancel_access( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} // doMenu_siteInfo_cancel_access
/**
* doMenu_siteInfo_import
*/
public void doMenu_siteInfo_import ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//get the tools
siteToolsIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute (STATE_TEMPLATE_INDEX, "28");
}
} // doMenu_siteInfo_import
/**
* doMenu_siteInfo_editClass
*/
public void doMenu_siteInfo_editClass( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.setAttribute (STATE_TEMPLATE_INDEX, "43");
} // doMenu_siteInfo_editClass
/**
* doMenu_siteInfo_addClass
*/
public void doMenu_siteInfo_addClass( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
Site site = getStateSite(state);
state.setAttribute(STATE_TERM_SELECTED, CourseManagementService.getTerm(site.getProperties().getProperty(PROP_SITE_TERM)));
state.setAttribute (STATE_TEMPLATE_INDEX, "36");
} // doMenu_siteInfo_addClass
/**
* first step of adding class
*/
public void doAdd_class_select( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
String option = params.getString("option");
if (option.equalsIgnoreCase("change"))
{
// change term
String termId = params.getString("selectTerm");
Term t = CourseManagementService.getTerm(termId);
state.setAttribute(STATE_TERM_SELECTED, t);
}
else if (option.equalsIgnoreCase("cancel"))
{
// cancel
state.removeAttribute(STATE_TERM_SELECTED);
removeAddClassContext(state);
state.setAttribute (STATE_TEMPLATE_INDEX, "43");
}
else if (option.equalsIgnoreCase("add"))
{
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
Term t = (Term) state.getAttribute(STATE_TERM_SELECTED);
if (t != null)
{
List courses = CourseManagementService.getInstructorCourses(userId, t.getYear(), t.getTerm());
// future term? roster information is not available yet?
int weeks = 0;
try
{
weeks = Integer.parseInt(ServerConfigurationService.getString("roster.available.weeks.before.term.start", "0"));
}
catch (Exception ignore)
{
}
if ((courses == null || courses != null && courses.size() == 0)
&& System.currentTimeMillis() + weeks*7*24*60*60*1000 < t.getStartTime().getTime())
{
//if a future term is selected
state.setAttribute(STATE_FUTURE_TERM_SELECTED, Boolean.TRUE);
}
else
{
state.setAttribute(STATE_FUTURE_TERM_SELECTED, Boolean.FALSE);
}
}
// continue
doContinue(data);
}
} // doAdd_class_select
/**
* doMenu_siteInfo_duplicate
*/
public void doMenu_siteInfo_duplicate ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute (STATE_TEMPLATE_INDEX, "29");
}
} // doMenu_siteInfo_import
/**
* doMenu_change_roles
*/
public void doMenu_change_roles ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
if (params.getStrings ("removeUser") != null)
{
state.setAttribute(STATE_SELECTED_USER_LIST, new ArrayList(Arrays.asList(params.getStrings ("removeUser"))));
state.setAttribute (STATE_TEMPLATE_INDEX, "7");
}
else
{
addAlert(state, rb.getString("java.nousers2"));
}
} // doMenu_change_roles
/**
* doMenu_edit_site_info
*
*/
public void doMenu_edit_site_info ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
Site Site = getStateSite(state);
ResourceProperties siteProperties = Site.getProperties();
state.setAttribute(FORM_SITEINFO_TITLE, Site.getTitle());
String site_type = (String)state.getAttribute(STATE_SITE_TYPE);
if(site_type != null && !site_type.equalsIgnoreCase("myworkspace"))
{
state.setAttribute(FORM_SITEINFO_INCLUDE, Boolean.valueOf(Site.isPubView()).toString());
}
state.setAttribute(FORM_SITEINFO_DESCRIPTION, Site.getDescription());
state.setAttribute(FORM_SITEINFO_SHORT_DESCRIPTION, Site.getShortDescription());
state.setAttribute(FORM_SITEINFO_SKIN, Site.getIconUrl());
if (Site.getIconUrl() != null)
{
state.setAttribute(FORM_SITEINFO_SKIN, Site.getIconUrl());
}
// site contact information
String contactName = siteProperties.getProperty(PROP_SITE_CONTACT_NAME);
String contactEmail = siteProperties.getProperty(PROP_SITE_CONTACT_EMAIL);
if (contactName == null && contactEmail == null)
{
String creatorId = siteProperties.getProperty(ResourceProperties.PROP_CREATOR);
try
{
User u = UserDirectoryService.getUser(creatorId);
String email = u.getEmail();
if (email != null)
{
contactEmail = u.getEmail();
}
contactName = u.getDisplayName();
}
catch (UserNotDefinedException e)
{
}
}
if (contactName != null)
{
state.setAttribute(FORM_SITEINFO_CONTACT_NAME, contactName);
}
if (contactEmail != null)
{
state.setAttribute(FORM_SITEINFO_CONTACT_EMAIL, contactEmail);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "13");
}
} // doMenu_edit_site_info
/**
* doMenu_edit_site_tools
*
*/
public void doMenu_edit_site_tools ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// get the tools
siteToolsIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "4");
}
} // doMenu_edit_site_tools
/**
* doMenu_edit_site_access
*
*/
public void doMenu_edit_site_access ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
} // doMenu_edit_site_access
/**
* doMenu_publish_site
*
*/
public void doMenu_publish_site ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// get the site properties
sitePropertiesIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "9");
}
} // doMenu_publish_site
/**
* Back to worksite setup's list view
*
*/
public void doBack_to_site_list ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.removeAttribute(STATE_SITE_TYPE);
state.removeAttribute(STATE_SITE_INSTANCE_ID);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} // doBack_to_site_list
/**
* doSave_site_info
*
*/
public void doSave_siteInfo ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
Site Site = getStateSite(state);
ResourcePropertiesEdit siteProperties = Site.getPropertiesEdit();
String site_type = (String)state.getAttribute(STATE_SITE_TYPE);
List titleEditableSiteType = (List) state.getAttribute(TITLE_EDITABLE_SITE_TYPE);
if (titleEditableSiteType.contains(Site.getType()))
{
Site.setTitle((String) state.getAttribute(FORM_SITEINFO_TITLE));
}
Site.setDescription((String) state.getAttribute(FORM_SITEINFO_DESCRIPTION));
Site.setShortDescription((String) state.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
if(site_type != null)
{
if (site_type.equals("course"))
{
//set icon url for course
String skin = (String) state.getAttribute(FORM_SITEINFO_SKIN);
setAppearance(state, Site, skin);
}
else
{
//set icon url for others
String iconUrl = (String) state.getAttribute(FORM_SITEINFO_ICON_URL);
Site.setIconUrl(iconUrl);
}
}
// site contact information
String contactName = (String) state.getAttribute(FORM_SITEINFO_CONTACT_NAME);
if (contactName != null)
{
siteProperties.addProperty(PROP_SITE_CONTACT_NAME, contactName);
}
String contactEmail = (String) state.getAttribute(FORM_SITEINFO_CONTACT_EMAIL);
if (contactEmail != null)
{
siteProperties.addProperty(PROP_SITE_CONTACT_EMAIL, contactEmail);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
try
{
SiteService.save(Site);
}
catch (IdUnusedException e)
{
// TODO:
}
catch (PermissionException e)
{
// TODO:
}
// clean state attributes
state.removeAttribute(FORM_SITEINFO_TITLE);
state.removeAttribute(FORM_SITEINFO_DESCRIPTION);
state.removeAttribute(FORM_SITEINFO_SHORT_DESCRIPTION);
state.removeAttribute(FORM_SITEINFO_SKIN);
state.removeAttribute(FORM_SITEINFO_INCLUDE);
state.removeAttribute(FORM_SITEINFO_CONTACT_NAME);
state.removeAttribute(FORM_SITEINFO_CONTACT_EMAIL);
// back to site info view
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
//refresh the whole page
scheduleTopRefresh();
}
} // doSave_siteInfo
/**
* init
*
*/
private void init (VelocityPortlet portlet, RunData data, SessionState state)
{
state.setAttribute(STATE_ACTION, "SiteAction");
setupFormNamesAndConstants(state);
if (state.getAttribute(STATE_PAGESIZE_SITEINFO) == null)
{
state.setAttribute(STATE_PAGESIZE_SITEINFO, new Hashtable());
}
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP))
{
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
}
else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO))
{
String siteId = ToolManager.getCurrentPlacement().getContext();
getReviseSite(state, siteId);
Hashtable h = (Hashtable) state.getAttribute(STATE_PAGESIZE_SITEINFO);
if (!h.containsKey(siteId))
{
// update
h.put(siteId, new Integer(200));
state.setAttribute(STATE_PAGESIZE_SITEINFO, h);
state.setAttribute(STATE_PAGESIZE, new Integer(200));
}
}
if (state.getAttribute(STATE_SITE_TYPES) == null)
{
PortletConfig config = portlet.getPortletConfig();
// all site types
String t = StringUtil.trimToNull(config.getInitParameter("siteTypes"));
if (t != null)
{
state.setAttribute(STATE_SITE_TYPES, new ArrayList(Arrays.asList(t.split(","))));
}
else
{
state.setAttribute(STATE_SITE_TYPES, new Vector());
}
}
} // init
public void doNavigate_to_site ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
String siteId = StringUtil.trimToNull(data.getParameters().getString("option"));
if (siteId != null)
{
getReviseSite(state, siteId);
}
else
{
doBack_to_list(data);
}
} // doNavigate_to_site
/**
* Get site information for revise screen
*/
private void getReviseSite(SessionState state, String siteId)
{
if (state.getAttribute(STATE_SELECTED_USER_LIST) == null)
{
state.setAttribute(STATE_SELECTED_USER_LIST, new Vector());
}
List sites = (List) state.getAttribute(STATE_SITES);
try
{
Site site = SiteService.getSite(siteId);
state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId());
if (sites != null)
{
int pos = -1;
for (int index=0;index<sites.size() && pos==-1;index++)
{
if (((Site) sites.get(index)).getId().equals(siteId))
{
pos = index;
}
}
// has any previous site in the list?
if (pos > 0)
{
state.setAttribute(STATE_PREV_SITE, sites.get(pos-1));
}
else
{
state.removeAttribute(STATE_PREV_SITE);
}
//has any next site in the list?
if (pos < sites.size()-1)
{
state.setAttribute(STATE_NEXT_SITE,sites.get(pos+1));
}
else
{
state.removeAttribute(STATE_NEXT_SITE);
}
}
String type = site.getType();
if (type == null)
{
if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null)
{
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
}
}
state.setAttribute(STATE_SITE_TYPE, type);
}
catch (IdUnusedException e)
{
M_log.warn(this + e.toString());
}
//one site has been selected
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} // getReviseSite
/**
* doUpdate_participant
*
*/
public void doUpdate_participant(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
Site s = getStateSite(state);
String realmId = SiteService.siteReference(s.getId());
if (AuthzGroupService.allowUpdate(realmId) || SiteService.allowUpdateSiteMembership(s.getId()))
{
try
{
AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realmId);
// does the site has maintain type user(s) before updating participants?
String maintainRoleString = realmEdit.getMaintainRole();
boolean hadMaintainUser = realmEdit.getUsersHasRole(maintainRoleString).isEmpty();
// update participant roles
List participants = (List) state.getAttribute(STATE_PARTICIPANT_LIST);;
// remove all roles and then add back those that were checked
for (int i=0; i<participants.size(); i++)
{
String id = null;
// added participant
Participant participant = (Participant) participants.get(i);
id = participant.getUniqname();
if (id != null)
{
//get the newly assigned role
String inputRoleField = "role" + id;
String roleId = params.getString(inputRoleField);
// only change roles when they are different than before
if (roleId!= null)
{
// get the grant active status
boolean activeGrant = true;
String activeGrantField = "activeGrant" + id;
if (params.getString(activeGrantField) != null)
{
activeGrant = params.getString(activeGrantField).equalsIgnoreCase("true")?true:false;
}
boolean fromProvider = !participant.isRemoveable();
if(fromProvider && !roleId.equals(participant.getProviderRole()))
{
fromProvider=false;
}
realmEdit.addMember(id, roleId, activeGrant, fromProvider);
}
}
}
//remove selected users
if (params.getStrings ("selectedUser") != null)
{
List removals = new ArrayList(Arrays.asList(params.getStrings ("selectedUser")));
state.setAttribute(STATE_SELECTED_USER_LIST, removals);
for(int i = 0; i<removals.size(); i++)
{
String rId = (String) removals.get(i);
try
{
User user = UserDirectoryService.getUser(rId);
Participant selected = new Participant();
selected.name = user.getDisplayName();
selected.uniqname = user.getId();
realmEdit.removeMember(user.getId());
}
catch (UserNotDefinedException e)
{
M_log.warn(this + " IdUnusedException " + rId + ". ");
}
}
}
if (hadMaintainUser && realmEdit.getUsersHasRole(maintainRoleString).isEmpty())
{
// if after update, the "had maintain type user" status changed, show alert message and don't save the update
addAlert(state, rb.getString("sitegen.siteinfolist.nomaintainuser") + maintainRoleString + ".");
}
else
{
AuthzGroupService.save(realmEdit);
}
}
catch (GroupNotDefinedException e)
{
addAlert(state, rb.getString("java.problem2"));
M_log.warn(this + " IdUnusedException " + s.getTitle() + "(" + realmId + "). ");
}
catch(AuthzPermissionException e)
{
addAlert(state, rb.getString("java.changeroles"));
M_log.warn(this + " PermissionException " + s.getTitle() + "(" + realmId + "). ");
}
}
} // doUpdate_participant
/**
* doUpdate_site_access
*
*/
public void doUpdate_site_access(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
Site sEdit = getStateSite(state);
ParameterParser params = data.getParameters ();
String publishUnpublish = params.getString("publishunpublish");
String include = params.getString("include");
String joinable = params.getString("joinable");
if (sEdit != null)
{
// editing existing site
//publish site or not
if (publishUnpublish != null&& publishUnpublish.equalsIgnoreCase("publish"))
{
sEdit.setPublished(true);
}
else
{
sEdit.setPublished(false);
}
//site public choice
if (include != null)
{
// if there is pubview input, use it
sEdit.setPubView(include.equalsIgnoreCase("true")?true:false);
}
else if (state.getAttribute(STATE_SITE_TYPE) != null)
{
String type = (String) state.getAttribute(STATE_SITE_TYPE);
List publicSiteTypes = (List) state.getAttribute(STATE_PUBLIC_SITE_TYPES);
List privateSiteTypes = (List) state.getAttribute(STATE_PRIVATE_SITE_TYPES);
if (publicSiteTypes.contains(type))
{
//sites are always public
sEdit.setPubView(true);
}
else if (privateSiteTypes.contains(type))
{
//site are always private
sEdit.setPubView(false);
}
}
else
{
sEdit.setPubView(false);
}
//publish site or not
if (joinable != null && joinable.equalsIgnoreCase("true"))
{
state.setAttribute(STATE_JOINABLE, Boolean.TRUE);
sEdit.setJoinable(true);
String joinerRole = StringUtil.trimToNull(params.getString("joinerRole"));
if (joinerRole!= null)
{
state.setAttribute(STATE_JOINERROLE, joinerRole);
sEdit.setJoinerRole(joinerRole);
}
else
{
state.setAttribute(STATE_JOINERROLE, "");
addAlert(state, rb.getString("java.joinsite")+" ");
}
}
else
{
state.setAttribute(STATE_JOINABLE, Boolean.FALSE);
state.removeAttribute(STATE_JOINERROLE);
sEdit.setJoinable(false);
sEdit.setJoinerRole(null);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
commitSite(sEdit);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
// TODO: hard coding this frame id is fragile, portal dependent, and needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
state.removeAttribute(STATE_JOINABLE);
state.removeAttribute(STATE_JOINERROLE);
}
}
else
{
// adding new site
if(state.getAttribute(STATE_SITE_INFO) != null)
{
SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (publishUnpublish != null&& publishUnpublish.equalsIgnoreCase("publish"))
{
siteInfo.published = true;
}
else
{
siteInfo.published = false;
}
//site public choice
if (include != null)
{
siteInfo.include = include.equalsIgnoreCase("true")?true:false;
}
else if (StringUtil.trimToNull(siteInfo.site_type) != null)
{
String type = StringUtil.trimToNull(siteInfo.site_type);
List publicSiteTypes = (List) state.getAttribute(STATE_PUBLIC_SITE_TYPES);
List privateSiteTypes = (List) state.getAttribute(STATE_PRIVATE_SITE_TYPES);
if (publicSiteTypes.contains(type))
{
//sites are always public
siteInfo.include = true;
}
else if (privateSiteTypes.contains(type))
{
//site are always private
siteInfo.include = false;
}
}
else
{
siteInfo.include = false;
}
//joinable site or not
if (joinable != null && joinable.equalsIgnoreCase("true"))
{
siteInfo.joinable = true;
String joinerRole = StringUtil.trimToNull(params.getString("joinerRole"));
if (joinerRole!= null)
{
siteInfo.joinerRole = joinerRole;
}
else
{
addAlert(state, rb.getString("java.joinsite")+" ");
}
}
else
{
siteInfo.joinable = false;
siteInfo.joinerRole = null;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "10");
updateCurrentStep(state, true);
}
}
// if editing an existing site, refresh the whole page so that the publish/unpublish icon could be updated
if (sEdit != null)
{
scheduleTopRefresh();
}
} // doUpdate_site_access
/**
* remove related state variable for changing participants roles
* @param state SessionState object
*/
private void removeChangeRoleContext(SessionState state)
{
// remove related state variables
state.removeAttribute(STATE_CHANGEROLE_SAMEROLE);
state.removeAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE);
state.removeAttribute(STATE_ADD_PARTICIPANTS);
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.removeAttribute(STATE_SELECTED_PARTICIPANT_ROLES);
} // removeChangeRoleContext
/**
/* Actions for vm templates under the "chef_site" root. This method is called by doContinue.
* Each template has a hidden field with the value of template-index that becomes the value of
* index for the switch statement here. Some cases not implemented.
*/
private void actionForTemplate ( String direction, int index, ParameterParser params, SessionState state)
{
// Continue - make any permanent changes, Back - keep any data entered on the form
boolean forward = direction.equals("continue") ? true : false;
SiteInfo siteInfo = new SiteInfo();
switch (index)
{
case 0:
/* actionForTemplate chef_site-list.vm
*
*/
break;
case 1:
/* actionForTemplate chef_site-type.vm
*
*/
break;
case 2:
/* actionForTemplate chef_site-newSiteInformation.vm
*
*/
if(state.getAttribute(STATE_SITE_INFO) != null)
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
//defaults to be true
siteInfo.include=true;
state.setAttribute(STATE_SITE_INFO, siteInfo);
updateSiteInfo(params, state);
// alerts after clicking Continue but not Back
if(forward)
{
if (StringUtil.trimToNull(siteInfo.title) == null)
{
addAlert(state, rb.getString("java.reqfields"));
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
return;
}
}
updateSiteAttributes(state);
if (state.getAttribute(STATE_MESSAGE) == null)
{
updateCurrentStep(state, forward);
}
break;
case 3:
/* actionForTemplate chef_site-newSiteFeatures.vm
*
*/
if (forward)
{
getFeatures(params, state);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
updateCurrentStep(state, forward);
}
break;
case 4:
/* actionForTemplate chef_site-addRemoveFeature.vm
*
*/
break;
case 5:
/* actionForTemplate chef_site-addParticipant.vm
*
*/
if(forward)
{
checkAddParticipant(params, state);
}
else
{
// remove related state variables
removeAddParticipantContext(state);
}
break;
case 6:
/* actionForTemplate chef_site-removeParticipants.vm
*
*/
break;
case 7:
/* actionForTemplate chef_site-changeRoles.vm
*
*/
if (forward)
{
if (!((Boolean) state.getAttribute(STATE_CHANGEROLE_SAMEROLE)).booleanValue())
{
getSelectedRoles(state, params, STATE_SELECTED_USER_LIST);
}
else
{
String role = params.getString("role_to_all");
if (role == null)
{
addAlert(state, rb.getString("java.pleasechoose")+" ");
}
else
{
state.setAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE, role);
}
}
}
else
{
removeChangeRoleContext(state);
}
break;
case 8:
/* actionForTemplate chef_site-siteDeleteConfirm.vm
*
*/
break;
case 9:
/* actionForTemplate chef_site-publishUnpublish.vm
*
*/
updateSiteInfo(params, state);
break;
case 10:
/* actionForTemplate chef_site-newSiteConfirm.vm
*
*/
if (!forward)
{
if (state.getAttribute(STATE_MESSAGE) == null)
{
updateCurrentStep(state, false);
}
}
break;
case 11:
/* actionForTemplate chef_site_newsitePublishUnpublish.vm
*
*/
break;
case 12:
/* actionForTemplate chef_site_siteInfo-list.vm
*
*/
break;
case 13:
/* actionForTemplate chef_site_siteInfo-editInfo.vm
*
*/
if (forward)
{
Site Site = getStateSite(state);
List titleEditableSiteType = (List) state.getAttribute(TITLE_EDITABLE_SITE_TYPE);
if (titleEditableSiteType.contains(Site.getType()))
{
// site titel is editable and could not be null
String title = StringUtil.trimToNull(params.getString("title"));
state.setAttribute(FORM_SITEINFO_TITLE, title);
if (title == null)
{
addAlert(state, rb.getString("java.specify")+" ");
}
}
String description = StringUtil.trimToNull(params.getString("description"));
state.setAttribute(FORM_SITEINFO_DESCRIPTION, description);
String short_description = StringUtil.trimToNull(params.getString("short_description"));
state.setAttribute(FORM_SITEINFO_SHORT_DESCRIPTION, short_description);
String skin = params.getString("skin");
if (skin != null)
{
// if there is a skin input for course site
skin = StringUtil.trimToNull(skin);
state.setAttribute(FORM_SITEINFO_SKIN, skin);
}
else
{
// if ther is a icon input for non-course site
String icon = StringUtil.trimToNull(params.getString("icon"));
if (icon != null)
{
if (icon.endsWith(PROTOCOL_STRING))
{
addAlert(state, rb.getString("alert.protocol"));
}
state.setAttribute(FORM_SITEINFO_ICON_URL, icon);
}
else
{
state.removeAttribute(FORM_SITEINFO_ICON_URL);
}
}
// site contact information
String contactName = StringUtil.trimToZero(params.getString ("siteContactName"));
state.setAttribute(FORM_SITEINFO_CONTACT_NAME, contactName);
String email = StringUtil.trimToZero(params.getString ("siteContactEmail"));
String[] parts = email.split("@");
if(email.length() > 0 && (email.indexOf("@") == -1 || parts.length != 2 || parts[0].length() == 0 || !Validator.checkEmailLocal(parts[0])))
{
// invalid email
addAlert(state, email + " "+rb.getString("java.invalid") + rb.getString("java.theemail"));
}
state.setAttribute(FORM_SITEINFO_CONTACT_EMAIL, email);
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "14");
}
}
break;
case 14:
/* actionForTemplate chef_site_siteInfo-editInfoConfirm.vm
*
*/
break;
case 15:
/* actionForTemplate chef_site_siteInfo-addRemoveFeatureConfirm.vm
*
*/
break;
case 16:
/* actionForTemplate chef_site_siteInfo-publishUnpublish-sendEmail.vm
*
*/
if (forward)
{
String notify = params.getString("notify");
if (notify != null)
{
state.setAttribute(FORM_WILL_NOTIFY, new Boolean(notify));
}
}
break;
case 17:
/* actionForTemplate chef_site_siteInfo--publishUnpublish-confirm.vm
*
*/
if (forward)
{
boolean oldStatus = getStateSite(state).isPublished();
boolean newStatus = ((SiteInfo) state.getAttribute(STATE_SITE_INFO)).getPublished();
saveSiteStatus(state, newStatus);
if (oldStatus == false || newStatus == true)
{
// if site's status been changed from unpublish to publish and notification is selected, send out notification to participants.
if (((Boolean) state.getAttribute(FORM_WILL_NOTIFY)).booleanValue())
{
// %%% place holder for sending email
}
}
// commit site edit
Site site = getStateSite(state);
try
{
SiteService.save(site);
}
catch (IdUnusedException e)
{
// TODO:
}
catch (PermissionException e)
{
// TODO:
}
// TODO: hard coding this frame id is fragile, portal dependent, and needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
}
break;
case 18:
/* actionForTemplate chef_siteInfo-editAccess.vm
*
*/
if (!forward)
{
if (state.getAttribute(STATE_MESSAGE) == null)
{
updateCurrentStep(state, false);
}
}
case 19:
/* actionForTemplate chef_site-addParticipant-sameRole.vm
*
*/
String roleId = StringUtil.trimToNull(params.getString("selectRole"));
if (roleId == null && forward)
{
addAlert(state, rb.getString("java.pleasesel")+" ");
}
else
{
state.setAttribute("form_selectedRole", params.getString("selectRole"));
}
break;
case 20:
/* actionForTemplate chef_site-addParticipant-differentRole.vm
*
*/
if (forward)
{
getSelectedRoles(state, params, STATE_ADD_PARTICIPANTS);
}
break;
case 21:
/* actionForTemplate chef_site-addParticipant-notification.vm
*
' */
if (params.getString("notify") == null)
{
if (forward)
addAlert(state, rb.getString("java.pleasechoice")+" ");
}
else
{
state.setAttribute("form_selectedNotify", new Boolean(params.getString("notify")));
}
break;
case 22:
/* actionForTemplate chef_site-addParticipant-confirm.vm
*
*/
break;
case 23:
/* actionForTemplate chef_siteInfo-editAccess-globalAccess.vm
*
*/
if (forward)
{
String joinable = params.getString("joinable");
state.setAttribute("form_joinable", Boolean.valueOf(joinable));
String joinerRole = params.getString("joinerRole");
state.setAttribute("form_joinerRole", joinerRole);
if (joinable.equals("true"))
{
if (joinerRole == null)
{
addAlert(state, rb.getString("java.pleasesel")+" ");
}
}
}
else
{
}
break;
case 24:
/* actionForTemplate chef_site-siteInfo-editAccess-globalAccess-confirm.vm
*
*/
break;
case 25:
/* actionForTemplate chef_site-changeRoles-confirm.vm
*
*/
break;
case 26:
/* actionForTemplate chef_site-modifyENW.vm
*
*/
updateSelectedToolList(state, params, forward);
if (state.getAttribute(STATE_MESSAGE) == null)
{
updateCurrentStep(state, forward);
}
break;
case 27:
/* actionForTemplate chef_site-importSites.vm
*
*/
if (forward)
{
Site existingSite = getStateSite(state);
if (existingSite != null)
{
// revising a existing site's tool
if (select_import_tools(params, state))
{
Hashtable importTools = (Hashtable) state.getAttribute(STATE_IMPORT_SITE_TOOL);
List selectedTools = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
importToolIntoSite(selectedTools, importTools, existingSite);
existingSite = getStateSite(state); // refresh site for WC and News
if (state.getAttribute(STATE_MESSAGE) == null)
{
commitSite(existingSite);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
}
}
else
{
// show alert and remain in current page
addAlert(state, rb.getString("java.toimporttool"));
}
}
else
{
// new site
select_import_tools(params, state);
}
}
else
{
// read form input about import tools
select_import_tools(params, state);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
updateCurrentStep(state, forward);
}
break;
case 28:
/* actionForTemplate chef_siteinfo-import.vm
*
*/
if (forward)
{
if (params.getStrings("importSites") == null)
{
addAlert(state, rb.getString("java.toimport")+" ");
state.removeAttribute(STATE_IMPORT_SITES);
}
else
{
List importSites = new ArrayList(Arrays.asList(params.getStrings("importSites")));
Hashtable sites = new Hashtable();
for (index = 0; index < importSites.size(); index ++)
{
try
{
Site s = SiteService.getSite((String) importSites.get(index));
sites.put(s, new Vector());
}
catch (IdUnusedException e)
{
}
}
state.setAttribute(STATE_IMPORT_SITES, sites);
}
}
break;
case 29:
/* actionForTemplate chef_siteinfo-duplicate.vm
*
*/
if (forward)
{
if (state.getAttribute(SITE_DUPLICATED) == null)
{
if (StringUtil.trimToNull(params.getString("title")) == null)
{
addAlert(state, rb.getString("java.dupli")+" ");
}
else
{
String title = params.getString("title");
state.setAttribute(SITE_DUPLICATED_NAME, title);
try
{
String oSiteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
String nSiteId = IdManager.createUuid();
Site site = SiteService.addSite(nSiteId, getStateSite(state));
try
{
SiteService.save(site);
}
catch (IdUnusedException e)
{
// TODO:
}
catch (PermissionException e)
{
// TODO:
}
try
{
site = SiteService.getSite(nSiteId);
// set title
site.setTitle(title);
// import tool content
List pageList = site.getPages();
if (!((pageList == null) || (pageList.size() == 0)))
{
for (ListIterator i = pageList.listIterator(); i.hasNext(); )
{
SitePage page = (SitePage) i.next();
List pageToolList = page.getTools();
String toolId = ((ToolConfiguration)pageToolList.get(0)).getTool().getId();
if (toolId.equalsIgnoreCase("sakai.resources"))
{
// handle resource tool specially
transferCopyEntities(toolId, ContentHostingService.getSiteCollection(oSiteId), ContentHostingService.getSiteCollection(nSiteId));
}
else
{
// other tools
transferCopyEntities(toolId, oSiteId, nSiteId);
}
}
}
}
catch (Exception e1)
{
//if goes here, IdService or SiteService has done something wrong.
M_log.warn(this + "Exception" + e1 + ":"+ nSiteId + "when duplicating site");
}
if (site.getType().equals("course"))
{
// for course site, need to read in the input for term information
String termId = StringUtil.trimToNull(params.getString("selectTerm"));
if (termId != null)
{
site.getPropertiesEdit().addProperty(PROP_SITE_TERM, termId);
}
}
try
{
SiteService.save(site);
}
catch (IdUnusedException e)
{
// TODO:
}
catch (PermissionException e)
{
// TODO:
}
// TODO: hard coding this frame id is fragile, portal dependent, and needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
state.setAttribute(SITE_DUPLICATED, Boolean.TRUE);
}
catch (IdInvalidException e)
{
addAlert(state, rb.getString("java.siteinval"));
}
catch (IdUsedException e)
{
addAlert(state, rb.getString("java.sitebeenused")+" ");
}
catch (PermissionException e)
{
addAlert(state, rb.getString("java.allowcreate")+" ");
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// site duplication confirmed
state.removeAttribute(SITE_DUPLICATED);
state.removeAttribute(SITE_DUPLICATED_NAME);
// return to the list view
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
}
break;
case 33:
break;
case 36:
/*
* actionForTemplate chef_site-newSiteCourse.vm
*/
if (forward)
{
List providerChosenList = new Vector();
if (params.getStrings("providerCourseAdd") == null)
{
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
if (params.getString("manualAdds") == null)
{
addAlert(state, rb.getString("java.manual")+" ");
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// The list of courses selected from provider listing
if (params.getStrings("providerCourseAdd") != null)
{
providerChosenList = new ArrayList(Arrays.asList(params.getStrings("providerCourseAdd"))); // list of course ids
state.setAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN, providerChosenList);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
siteInfo = new SiteInfo();
if(state.getAttribute(STATE_SITE_INFO) != null)
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
if (providerChosenList.size() >= 1)
{
siteInfo.title = getCourseTab(state, (String) providerChosenList.get(0));
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
if (params.getString("manualAdds") != null)
{
// if creating a new site
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer(1));
}
else
{
// no manual add
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(STATE_SITE_QUEST_UNIQNAME);
if (getStateSite(state) != null)
{
// if revising a site, go to the confirmation page of adding classes
state.setAttribute(STATE_TEMPLATE_INDEX, "44");
}
else
{
// if creating a site, go the the site information entry page
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
}
}
}
}
//next step
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(2));
}
break;
case 38:
break;
case 39:
break;
case 42:
/* actionForTemplate chef_site-gradtoolsConfirm.vm
*
*/
break;
case 43:
/* actionForTemplate chef_site-editClass.vm
*
*/
if (forward)
{
if (params.getStrings("providerClassDeletes") == null && params.getStrings("manualClassDeletes") == null &&
!direction.equals("back"))
{
addAlert(state, rb.getString("java.classes"));
}
if (params.getStrings("providerClassDeletes") != null)
{
// build the deletions list
List providerCourseList = (List) state.getAttribute(SITE_PROVIDER_COURSE_LIST);
List providerCourseDeleteList = new ArrayList(Arrays.asList(params.getStrings("providerClassDeletes")));
for (ListIterator i = providerCourseDeleteList.listIterator(); i.hasNext(); )
{
providerCourseList.remove((String) i.next());
}
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
}
if (params.getStrings("manualClassDeletes") != null)
{
// build the deletions list
List manualCourseList = (List) state.getAttribute(SITE_MANUAL_COURSE_LIST);
List manualCourseDeleteList = new ArrayList(Arrays.asList(params.getStrings("manualClassDeletes")));
for (ListIterator i = manualCourseDeleteList.listIterator(); i.hasNext(); )
{
manualCourseList.remove((String) i.next());
}
state.setAttribute(SITE_MANUAL_COURSE_LIST, manualCourseList);
}
updateCourseClasses (state, new Vector(), new Vector());
}
break;
case 44:
if (forward)
{
List providerList = (state.getAttribute(SITE_PROVIDER_COURSE_LIST) == null)?new Vector():(List) state.getAttribute(SITE_PROVIDER_COURSE_LIST);
List addProviderList = (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) == null)?new Vector():(List) state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
providerList.addAll(addProviderList);
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerList);
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
// if manually added course
List manualList = (state.getAttribute(SITE_MANUAL_COURSE_LIST) == null)?new Vector():(List) state.getAttribute(SITE_MANUAL_COURSE_LIST);
int manualAddNumber = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
List manualAddFields = (List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
Term t = (Term) state.getAttribute(STATE_TERM_SELECTED);
for (int m=0; m<manualAddNumber && t!=null; m++)
{
String manualAddClassId = CourseManagementService.getCourseId(t, (List) manualAddFields.get(m));
manualList.add(manualAddClassId);
}
state.setAttribute(SITE_MANUAL_COURSE_LIST, manualList);
}
updateCourseClasses(state, (List) state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN), (List) state.getAttribute(SITE_MANUAL_COURSE_LIST));
removeAddClassContext(state);
}
break;
case 49:
if (!forward)
{
state.removeAttribute(SORTED_BY);
state.removeAttribute(SORTED_ASC);
}
break;
}
}// actionFor Template
/**
* update current step index within the site creation wizard
* @param state The SessionState object
* @param forward Moving forward or backward?
*/
private void updateCurrentStep(SessionState state, boolean forward)
{
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null)
{
int currentStep = ((Integer) state.getAttribute(SITE_CREATE_CURRENT_STEP)).intValue();
if (forward)
{
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(currentStep+1));
}
else
{
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(currentStep-1));
}
}
}
/**
* remove related state variable for adding class
* @param state SessionState object
*/
private void removeAddClassContext(SessionState state)
{
// remove related state variables
state.removeAttribute(STATE_ADD_CLASS_MANUAL);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(STATE_SITE_QUEST_UNIQNAME);
state.removeAttribute(STATE_AUTO_ADD);
state.removeAttribute(SITE_CREATE_TOTAL_STEPS);
state.removeAttribute(SITE_CREATE_CURRENT_STEP);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
} // removeAddClassContext
private void updateCourseClasses (SessionState state, List notifyClasses, List requestClasses)
{
List providerCourseSectionList = (List) state.getAttribute(SITE_PROVIDER_COURSE_LIST);
List manualCourseSectionList = (List) state.getAttribute(SITE_MANUAL_COURSE_LIST);
Site site = getStateSite(state);
String id = site.getId();
String realmId = SiteService.siteReference(id);
if ((providerCourseSectionList == null) || (providerCourseSectionList.size() == 0))
{
//no section access so remove Provider Id
try
{
AuthzGroup realmEdit1 = AuthzGroupService.getAuthzGroup(realmId);
realmEdit1.setProviderGroupId(NULL_STRING);
AuthzGroupService.save(realmEdit1);
}
catch (GroupNotDefinedException e)
{
M_log.warn(this + " IdUnusedException, " + site.getTitle() + "(" + realmId + ") not found, or not an AuthzGroup object");
addAlert(state, rb.getString("java.cannotedit"));
return;
}
catch (AuthzPermissionException e)
{
M_log.warn(this + " PermissionException, user does not have permission to edit AuthzGroup object " + site.getTitle() + "(" + realmId + "). ");
addAlert(state, rb.getString("java.notaccess"));
return;
}
}
if ((providerCourseSectionList != null) && (providerCourseSectionList.size() != 0))
{
// section access so rewrite Provider Id
String externalRealm = buildExternalRealm(id, state, providerCourseSectionList);
try
{
AuthzGroup realmEdit2 = AuthzGroupService.getAuthzGroup(realmId);
realmEdit2.setProviderGroupId(externalRealm);
AuthzGroupService.save(realmEdit2);
}
catch (GroupNotDefinedException e)
{
M_log.warn(this + " IdUnusedException, " + site.getTitle() + "(" + realmId + ") not found, or not an AuthzGroup object");
addAlert(state, rb.getString("java.cannotclasses"));
return;
}
catch (AuthzPermissionException e)
{
M_log.warn(this + " PermissionException, user does not have permission to edit AuthzGroup object " + site.getTitle() + "(" + realmId + "). ");
addAlert(state, rb.getString("java.notaccess"));
return;
}
}
if ((manualCourseSectionList != null) && (manualCourseSectionList.size() != 0))
{
// store the manually requested sections in one site property
String manualSections = "";
for (int j = 0; j < manualCourseSectionList.size(); )
{
manualSections = manualSections + (String) manualCourseSectionList.get(j);
j++;
if (j < manualCourseSectionList.size())
{
manualSections = manualSections + "+";
}
}
ResourcePropertiesEdit rp = site.getPropertiesEdit();
rp.addProperty(PROP_SITE_REQUEST_COURSE, manualSections);
}
else
{
ResourcePropertiesEdit rp = site.getPropertiesEdit();
rp.removeProperty(PROP_SITE_REQUEST_COURSE);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
commitSite(site);
}
else
{
}
if (requestClasses != null && requestClasses.size() > 0 && state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
try
{
// send out class request notifications
sendSiteRequest( state,
"change",
((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue(),
(List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
catch (Exception e)
{
M_log.warn(this + e.toString());
}
}
if (notifyClasses != null && notifyClasses.size() > 0)
{
try
{
// send out class access confirmation notifications
sendSiteNotification(state, notifyClasses);
}
catch (Exception e)
{
M_log.warn(this + e.toString());
}
}
} // updateCourseClasses
/**
* Sets selected roles for multiple users
* @param params The ParameterParser object
* @param listName The state variable
*/
private void getSelectedRoles(SessionState state, ParameterParser params, String listName)
{
Hashtable pSelectedRoles = (Hashtable) state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES);
if (pSelectedRoles == null)
{
pSelectedRoles = new Hashtable();
}
List userList = (List) state.getAttribute(listName);
for (int i = 0; i < userList.size(); i++)
{
String userId = null;
if(listName.equalsIgnoreCase(STATE_ADD_PARTICIPANTS))
{
userId = ((Participant) userList.get(i)).getUniqname();
}
else if (listName.equalsIgnoreCase(STATE_SELECTED_USER_LIST))
{
userId = (String) userList.get(i);
}
if (userId != null)
{
String rId = StringUtil.trimToNull(params.getString("role" + userId));
if (rId == null)
{
addAlert(state, rb.getString("java.rolefor")+" " + userId + ". ");
pSelectedRoles.remove(userId);
}
else
{
pSelectedRoles.put(userId, rId);
}
}
}
state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, pSelectedRoles);
} // getSelectedRoles
/**
* dispatch function for changing participants roles
*/
public void doSiteinfo_edit_role(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
String option = params.getString("option");
// dispatch
if (option.equalsIgnoreCase("same_role_true"))
{
state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.TRUE);
state.setAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE, params.getString("role_to_all"));
}
else if (option.equalsIgnoreCase("same_role_false"))
{
state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.FALSE);
state.removeAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE);
if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) == null)
{
state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, new Hashtable());
}
}
else if (option.equalsIgnoreCase("continue"))
{
doContinue(data);
}
else if (option.equalsIgnoreCase("back"))
{
doBack(data);
}
else if (option.equalsIgnoreCase("cancel"))
{
doCancel(data);
}
} // doSiteinfo_edit_globalAccess
/**
* dispatch function for changing site global access
*/
public void doSiteinfo_edit_globalAccess(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
String option = params.getString("option");
// dispatch
if (option.equalsIgnoreCase("joinable"))
{
state.setAttribute("form_joinable", Boolean.TRUE);
state.setAttribute("form_joinerRole", getStateSite(state).getJoinerRole());
}
else if (option.equalsIgnoreCase("unjoinable"))
{
state.setAttribute("form_joinable", Boolean.FALSE);
state.removeAttribute("form_joinerRole");
}
else if (option.equalsIgnoreCase("continue"))
{
doContinue(data);
}
else if (option.equalsIgnoreCase("cancel"))
{
doCancel(data);
}
} // doSiteinfo_edit_globalAccess
/**
* save changes to site global access
*/
public void doSiteinfo_save_globalAccess(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
Site s = getStateSite(state);
boolean joinable = ((Boolean) state.getAttribute("form_joinable")).booleanValue();
s.setJoinable(joinable);
if (joinable)
{
// set the joiner role
String joinerRole = (String) state.getAttribute("form_joinerRole");
s.setJoinerRole(joinerRole);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
//release site edit
commitSite(s);
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
} // doSiteinfo_save_globalAccess
/**
* updateSiteAttributes
*
*/
private void updateSiteAttributes (SessionState state)
{
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null)
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
else
{
M_log.warn("SiteAction.updateSiteAttributes STATE_SITE_INFO == null");
return;
}
Site site = getStateSite(state);
if (site != null)
{
if (StringUtil.trimToNull(siteInfo.title) != null)
{
site.setTitle(siteInfo.title);
}
if (siteInfo.description != null)
{
site.setDescription(siteInfo.description);
}
site.setPublished(siteInfo.published);
setAppearance(state, site, siteInfo.iconUrl);
site.setJoinable(siteInfo.joinable);
if (StringUtil.trimToNull(siteInfo.joinerRole) != null)
{
site.setJoinerRole(siteInfo.joinerRole);
}
// Make changes and then put changed site back in state
String id = site.getId();
try
{
SiteService.save(site);
}
catch (IdUnusedException e)
{
// TODO:
}
catch (PermissionException e)
{
// TODO:
}
if (SiteService.allowUpdateSite(id))
{
try
{
SiteService.getSite(id);
state.setAttribute(STATE_SITE_INSTANCE_ID, id);
}
catch (IdUnusedException e)
{
M_log.warn("SiteAction.commitSite IdUnusedException " + siteInfo.getTitle() + "(" + id + ") not found");
}
}
// no permission
else
{
addAlert(state, rb.getString("java.makechanges"));
M_log.warn("SiteAction.commitSite PermissionException " + siteInfo.getTitle() + "(" + id + ")");
}
}
} // updateSiteAttributes
/**
* %%% legacy properties, to be removed
*/
private void updateSiteInfo (ParameterParser params, SessionState state)
{
SiteInfo siteInfo = new SiteInfo();
if(state.getAttribute(STATE_SITE_INFO) != null)
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
siteInfo.site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (params.getString ("title") != null)
{
siteInfo.title = params.getString ("title");
}
if (params.getString ("description") != null)
{
siteInfo.description = params.getString ("description");
}
if (params.getString ("short_description") != null)
{
siteInfo.short_description = params.getString ("short_description");
}
if (params.getString ("additional") != null)
{
siteInfo.additional = params.getString ("additional");
}
if (params.getString ("iconUrl") != null)
{
siteInfo.iconUrl = params.getString ("iconUrl");
}
else
{
siteInfo.iconUrl = params.getString ("skin");
}
if (params.getString ("joinerRole") != null)
{
siteInfo.joinerRole = params.getString ("joinerRole");
}
if (params.getString ("joinable") != null)
{
boolean joinable = params.getBoolean("joinable");
siteInfo.joinable = joinable;
if(!joinable) siteInfo.joinerRole = NULL_STRING;
}
if (params.getString ("itemStatus") != null)
{
siteInfo.published = Boolean.valueOf(params.getString ("itemStatus")).booleanValue();
}
// site contact information
String name = StringUtil.trimToZero(params.getString ("siteContactName"));
siteInfo.site_contact_name = name;
String email = StringUtil.trimToZero(params.getString ("siteContactEmail"));
if (email != null)
{
String[] parts = email.split("@");
if(email.length() > 0 && (email.indexOf("@") == -1 || parts.length != 2 || parts[0].length() == 0 || !Validator.checkEmailLocal(parts[0])))
{
// invalid email
addAlert(state, email + " "+rb.getString("java.invalid") + rb.getString("java.theemail"));
}
siteInfo.site_contact_email = email;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
} // updateSiteInfo
/**
* getExternalRealmId
*
*/
private String getExternalRealmId (SessionState state)
{
String realmId = SiteService.siteReference((String) state.getAttribute(STATE_SITE_INSTANCE_ID));
String rv = null;
try
{
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
rv = realm.getProviderGroupId();
}
catch (GroupNotDefinedException e)
{
M_log.warn("SiteAction.getExternalRealmId, site realm not found");
}
return rv;
} // getExternalRealmId
/**
* getParticipantList
*
*/
private List getParticipantList(SessionState state)
{
List members = new Vector();
List participants = new Vector();
String realmId = SiteService.siteReference((String) state.getAttribute(STATE_SITE_INSTANCE_ID));
List providerCourseList = null;
providerCourseList = getProviderCourseList(StringUtil.trimToNull(getExternalRealmId(state)));
if (providerCourseList != null && providerCourseList.size() > 0)
{
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
}
if (providerCourseList != null)
{
for (int k = 0; k < providerCourseList.size(); k++)
{
String courseId = (String) providerCourseList.get(k);
try
{
members.addAll(CourseManagementService.getCourseMembers(courseId));
}
catch (Exception e)
{
// M_log.warn(this + " Cannot find course " + courseId);
}
}
}
try
{
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
Set grants = realm.getMembers();
//Collections.sort(users);
for (Iterator i = grants.iterator(); i.hasNext();)
{
Member g = (Member) i.next();
String userString = g.getUserEid();
Role r = g.getRole();
boolean alreadyInList = false;
for (Iterator p = members.iterator(); p.hasNext() && !alreadyInList;)
{
CourseMember member = (CourseMember) p.next();
String memberUniqname = member.getUniqname();
if (userString.equalsIgnoreCase(memberUniqname))
{
alreadyInList = true;
if (r != null)
{
member.setRole(r.getId());
}
try
{
User user = UserDirectoryService.getUserByEid(memberUniqname);
Participant participant = new Participant();
participant.name = user.getSortName();
participant.uniqname = user.getId();
participant.role = member.getRole();
participant.providerRole = member.getProviderRole();
participant.course = member.getCourse();
participant.section = member.getSection();
participant.credits = member.getCredits();
participant.regId = member.getId();
participant.removeable = false;
participants.add(participant);
}
catch (UserNotDefinedException e)
{
// deal with missing user quietly without throwing a warning message
}
}
}
if (!alreadyInList)
{
try
{
User user = UserDirectoryService.getUserByEid(userString);
Participant participant = new Participant();
participant.name = user.getSortName();
participant.uniqname = user.getId();
if (r != null)
{
participant.role = r.getId();
}
participants.add(participant);
}
catch (UserNotDefinedException e)
{
// deal with missing user quietly without throwing a warning message
}
}
}
}
catch (GroupNotDefinedException e)
{
M_log.warn(this + " IdUnusedException " + realmId);
}
state.setAttribute(STATE_PARTICIPANT_LIST, participants);
return participants;
} // getParticipantList
/**
* getRoles
*
*/
private List getRoles (SessionState state)
{
List roles = new Vector();
String realmId = SiteService.siteReference((String) state.getAttribute(STATE_SITE_INSTANCE_ID));
try
{
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
roles.addAll(realm.getRoles());
Collections.sort(roles);
}
catch (GroupNotDefinedException e)
{
M_log.warn("SiteAction.getRoles IdUnusedException " + realmId);
}
return roles;
} // getRoles
private void addSynopticTool(SitePage page, String toolId, String toolTitle, String layoutHint)
{
// Add synoptic announcements tool
ToolConfiguration tool = page.addTool();
Tool reg = ToolManager.getTool(toolId);
tool.setTool(toolId, reg);
tool.setTitle(toolTitle);
tool.setLayoutHints(layoutHint);
}
private void getRevisedFeatures(ParameterParser params, SessionState state)
{
Site site = getStateSite(state);
//get the list of Worksite Setup configured pages
List wSetupPageList = (List)state.getAttribute(STATE_WORKSITE_SETUP_PAGE_LIST);
WorksiteSetupPage wSetupPage = new WorksiteSetupPage();
WorksiteSetupPage wSetupHome = new WorksiteSetupPage();
List pageList = new Vector();
//declare some flags used in making decisions about Home, whether to add, remove, or do nothing
boolean homeInChosenList = false;
boolean homeInWSetupPageList = false;
List chosenList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
//if features were selected, diff wSetupPageList and chosenList to get page adds and removes
// boolean values for adding synoptic views
boolean hasAnnouncement = false;
boolean hasChat = false;
boolean hasDiscussion = false;
boolean hasEmail = false;
boolean hasNewSiteInfo = false;
//Special case - Worksite Setup Home comes from a hardcoded checkbox on the vm template rather than toolRegistrationList
//see if Home was chosen
for (ListIterator j = chosenList.listIterator(); j.hasNext(); )
{
String choice = (String) j.next();
if(choice.equalsIgnoreCase(HOME_TOOL_ID))
{
homeInChosenList = true;
}
else if (choice.equals("sakai.mailbox"))
{
hasEmail = true;
String alias = StringUtil.trimToNull((String) state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
if (alias != null)
{
if (!Validator.checkEmailLocal(alias))
{
addAlert(state, rb.getString("java.theemail"));
}
else
{
try
{
String channelReference = mailArchiveChannelReference(site.getId());
//first, clear any alias set to this channel
AliasService.removeTargetAliases(channelReference); // check to see whether the alias has been used
try
{
String target = AliasService.getTarget(alias);
if (target != null)
{
addAlert(state, rb.getString("java.emailinuse")+" ");
}
}
catch (IdUnusedException ee)
{
try
{
AliasService.setAlias(alias, channelReference);
}
catch (IdUsedException exception) {}
catch (IdInvalidException exception) {}
catch (PermissionException exception) {}
}
}
catch (PermissionException exception) {}
}
}
}
else if (choice.equals("sakai.announcements"))
{
hasAnnouncement = true;
}
else if (choice.equals("sakai.chat"))
{
hasChat = true;
}
else if (choice.equals("sakai.discussion"))
{
hasDiscussion = true;
}
}
//see if Home and/or Help in the wSetupPageList (can just check title here, because we checked patterns before adding to the list)
for (ListIterator i = wSetupPageList.listIterator(); i.hasNext(); )
{
wSetupPage = (WorksiteSetupPage) i.next();
if(wSetupPage.getToolId().equals(HOME_TOOL_ID)){ homeInWSetupPageList = true; }
}
if (homeInChosenList)
{
SitePage page = null;
// Were the synoptic views of Announcement, Discussioin, Chat existing before the editing
boolean hadAnnouncement=false,hadDiscussion=false,hadChat=false;
if (homeInWSetupPageList)
{
if (!SiteService.isUserSite(site.getId()))
{
//for non-myworkspace site, if Home is chosen and Home is in the wSetupPageList, remove synoptic tools
WorksiteSetupPage homePage = new WorksiteSetupPage();
for (ListIterator i = wSetupPageList.listIterator(); i.hasNext(); )
{
WorksiteSetupPage comparePage = (WorksiteSetupPage) i.next();
if((comparePage.getToolId()).equals(HOME_TOOL_ID)) { homePage = comparePage; }
}
page = site.getPage(homePage.getPageId());
List toolList = page.getTools();
List removeToolList = new Vector();
// get those synoptic tools
for (ListIterator iToolList = toolList.listIterator(); iToolList.hasNext(); )
{
ToolConfiguration tool = (ToolConfiguration) iToolList.next();
if (tool.getTool().getId().equals("sakai.synoptic.announcement"))
{
hadAnnouncement = true;
if (!hasAnnouncement)
{
removeToolList.add(tool);// if Announcement tool isn't selected, remove the synotic Announcement
}
}
if (tool.getTool().getId().equals("sakai.synoptic.discussion"))
{
hadDiscussion = true;
if (!hasDiscussion)
{
removeToolList.add(tool);// if Discussion tool isn't selected, remove the synoptic Discussion
}
}
if (tool.getTool().getId().equals("sakai.synoptic.chat"))
{
hadChat = true;
if (!hasChat)
{
removeToolList.add(tool);// if Chat tool isn't selected, remove the synoptic Chat
}
}
}
// remove those synoptic tools
for (ListIterator rToolList = removeToolList.listIterator(); rToolList.hasNext(); )
{
page.removeTool((ToolConfiguration) rToolList.next());
}
}
}
else
{
//if Home is chosen and Home is not in wSetupPageList, add Home to site and wSetupPageList
page = site.addPage();
page.setTitle(rb.getString("java.home"));
wSetupHome.pageId = page.getId();
wSetupHome.pageTitle = page.getTitle();
wSetupHome.toolId = HOME_TOOL_ID;
wSetupPageList.add(wSetupHome);
//Add worksite information tool
ToolConfiguration tool = page.addTool();
Tool reg = ToolManager.getTool("sakai.iframe.site");
tool.setTool("sakai.iframe.site", reg);
tool.setTitle(rb.getString("java.workinfo"));
tool.setLayoutHints("0,0");
}
if (!SiteService.isUserSite(site.getId()))
{
//add synoptical tools to home tool in non-myworkspace site
try
{
if (hasAnnouncement && !hadAnnouncement)
{
//Add synoptic announcements tool
addSynopticTool(page, "sakai.synoptic.announcement", rb.getString("java.recann"), "0,1");
}
if (hasDiscussion && !hadDiscussion)
{
//Add synoptic discussion tool
addSynopticTool(page, "sakai.synoptic.discussion", rb.getString("java.recdisc"), "1,1");
}
if (hasChat&& !hadChat)
{
//Add synoptic chat tool
addSynopticTool(page, "sakai.synoptic.chat", rb.getString("java.recent"), "2,1");
}
if (hasAnnouncement || hasDiscussion || hasChat )
{
page.setLayout(SitePage.LAYOUT_DOUBLE_COL);
}
else
{
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
}
}
catch (Exception e)
{
M_log.warn("SiteAction.getFeatures Exception " + e.getMessage());
}
}
} // add Home
//if Home is in wSetupPageList and not chosen, remove Home feature from wSetupPageList and site
if (!homeInChosenList && homeInWSetupPageList)
{
//remove Home from wSetupPageList
WorksiteSetupPage removePage = new WorksiteSetupPage();
for (ListIterator i = wSetupPageList.listIterator(); i.hasNext(); )
{
WorksiteSetupPage comparePage = (WorksiteSetupPage) i.next();
if(comparePage.getToolId().equals(HOME_TOOL_ID)) { removePage = comparePage; }
}
SitePage siteHome = site.getPage(removePage.getPageId());
site.removePage(siteHome);
wSetupPageList.remove(removePage);
}
//declare flags used in making decisions about whether to add, remove, or do nothing
boolean inChosenList;
boolean inWSetupPageList;
Hashtable newsTitles = (Hashtable) state.getAttribute(STATE_NEWS_TITLES);
Hashtable wcTitles = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES);
Hashtable newsUrls = (Hashtable) state.getAttribute(STATE_NEWS_URLS);
Hashtable wcUrls = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_URLS);
Set categories = new HashSet();
categories.add((String) state.getAttribute(STATE_SITE_TYPE));
Set toolRegistrationList = ToolManager.findTools(categories, null);
// first looking for any tool for removal
Vector removePageIds = new Vector();
for (ListIterator k = wSetupPageList.listIterator(); k.hasNext(); )
{
wSetupPage = (WorksiteSetupPage)k.next();
String pageToolId = wSetupPage.getToolId();
// use page id + tool id for multiple News and Web Content tool
if (pageToolId.indexOf("sakai.news") != -1 || pageToolId.indexOf("sakai.iframe") != -1)
{
pageToolId = wSetupPage.getPageId() + pageToolId;
}
inChosenList = false;
for (ListIterator j = chosenList.listIterator(); j.hasNext(); )
{
String toolId = (String) j.next();
if(pageToolId.equals(toolId))
{
inChosenList = true;
}
}
if (!inChosenList)
{
removePageIds.add(wSetupPage.getPageId());
}
}
for (int i = 0; i < removePageIds.size(); i++)
{
//if the tool exists in the wSetupPageList, remove it from the site
String removeId = (String) removePageIds.get(i);
SitePage sitePage = site.getPage(removeId);
site.removePage(sitePage);
// and remove it from wSetupPageList
for (ListIterator k = wSetupPageList.listIterator(); k.hasNext(); )
{
wSetupPage = (WorksiteSetupPage)k.next();
if (!wSetupPage.getPageId().equals(removeId))
{
wSetupPage = null;
}
}
if (wSetupPage != null)
{
wSetupPageList.remove(wSetupPage);
}
}
// then looking for any tool to add
for (ListIterator j = orderToolIds(state, (String) state.getAttribute(STATE_SITE_TYPE), chosenList).listIterator(); j.hasNext(); )
{
String toolId = (String) j.next();
//Is the tool in the wSetupPageList?
inWSetupPageList = false;
for (ListIterator k = wSetupPageList.listIterator(); k.hasNext(); )
{
wSetupPage = (WorksiteSetupPage)k.next();
String pageToolId = wSetupPage.getToolId();
// use page Id + toolId for multiple News and Web Content tool
if (pageToolId.indexOf("sakai.news") != -1 || pageToolId.indexOf("sakai.iframe") != -1)
{
pageToolId = wSetupPage.getPageId() + pageToolId;
}
if(pageToolId.equals(toolId))
{
inWSetupPageList = true;
// but for News and Web Content tool, need to change the title
if (toolId.indexOf("sakai.news") != -1)
{
SitePage pEdit = (SitePage) site.getPage(wSetupPage.pageId);
pEdit.setTitle((String) newsTitles.get(toolId));
List toolList = pEdit.getTools();
for (ListIterator jTool = toolList.listIterator(); jTool.hasNext(); )
{
ToolConfiguration tool = (ToolConfiguration) jTool.next();
if (tool.getTool().getId().equals("sakai.news"))
{
// set News tool title
tool.setTitle((String) newsTitles.get(toolId));
// set News tool url
String urlString = (String) newsUrls.get(toolId);
try
{
URL url = new URL(urlString);
// update the tool config
tool.getPlacementConfig().setProperty("channel-url", (String) url.toExternalForm());
}
catch (MalformedURLException e)
{
addAlert(state, rb.getString("java.invurl")+" " + urlString + ". ");
}
}
}
}
else if (toolId.indexOf("sakai.iframe") != -1)
{
SitePage pEdit = (SitePage) site.getPage(wSetupPage.pageId);
pEdit.setTitle((String) wcTitles.get(toolId));
List toolList = pEdit.getTools();
for (ListIterator jTool = toolList.listIterator(); jTool.hasNext(); )
{
ToolConfiguration tool = (ToolConfiguration) jTool.next();
if (tool.getTool().getId().equals("sakai.iframe"))
{
// set Web Content tool title
tool.setTitle((String) wcTitles.get(toolId));
// set Web Content tool url
String wcUrl = StringUtil.trimToNull((String) wcUrls.get(toolId));
if (wcUrl != null && !wcUrl.equals(WEB_CONTENT_DEFAULT_URL))
{
// if url is not empty and not consists only of "http://"
tool.getPlacementConfig().setProperty("source", wcUrl);
}
}
}
}
}
}
if (inWSetupPageList)
{
// if the tool already in the list, do nothing so to save the option settings
}
else
{
// if in chosen list but not in wSetupPageList, add it to the site (one tool on a page)
// if Site Info tool is being newly added
if (toolId.equals("sakai.siteinfo"))
{
hasNewSiteInfo = true;
}
Tool toolRegFound = null;
for (Iterator i = toolRegistrationList.iterator(); i.hasNext(); )
{
Tool toolReg = (Tool) i.next();
if ((toolId.indexOf("assignment") != -1 && toolId.equals(toolReg.getId()))
|| (toolId.indexOf("assignment") == -1 && toolId.indexOf(toolReg.getId()) != -1))
{
toolRegFound = toolReg;
}
}
if (toolRegFound != null)
{
// we know such a tool, so add it
WorksiteSetupPage addPage = new WorksiteSetupPage();
SitePage page = site.addPage();
addPage.pageId = page.getId();
if (toolId.indexOf("sakai.news") != -1)
{
// set News tool title
page.setTitle((String) newsTitles.get(toolId));
}
else if (toolId.indexOf("sakai.iframe") != -1)
{
// set Web Content tool title
page.setTitle((String) wcTitles.get(toolId));
}
else
{
// other tools with default title
page.setTitle(toolRegFound.getTitle());
}
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
ToolConfiguration tool = page.addTool();
tool.setTool(toolRegFound.getId(), toolRegFound);
addPage.toolId = toolId;
wSetupPageList.add(addPage);
//set tool title
if (toolId.indexOf("sakai.news") != -1)
{
// set News tool title
tool.setTitle((String) newsTitles.get(toolId));
//set News tool url
String urlString = (String) newsUrls.get(toolId);
try
{
URL url = new URL(urlString);
// update the tool config
tool.getPlacementConfig().setProperty("channel-url", (String) url.toExternalForm());
}
catch(MalformedURLException e)
{
// display message
addAlert(state, "Invalid URL " + urlString + ". ");
// remove the page because of invalid url
site.removePage(page);
}
}
else if (toolId.indexOf("sakai.iframe") != -1)
{
// set Web Content tool title
tool.setTitle((String) wcTitles.get(toolId));
// set Web Content tool url
String wcUrl = StringUtil.trimToNull((String) wcUrls.get(toolId));
if (wcUrl != null && !wcUrl.equals(WEB_CONTENT_DEFAULT_URL))
{
// if url is not empty and not consists only of "http://"
tool.getPlacementConfig().setProperty("source", wcUrl);
}
}
else
{
tool.setTitle(toolRegFound.getTitle());
}
}
}
} // for
if (homeInChosenList)
{
//Order tools - move Home to the top - first find it
SitePage homePage = null;
pageList = site.getPages();
if (pageList != null && pageList.size() != 0)
{
for (ListIterator i = pageList.listIterator(); i.hasNext(); )
{
SitePage page = (SitePage)i.next();
if (rb.getString("java.home").equals(page.getTitle()))//if ("Home".equals(page.getTitle()))
{
homePage = page;
break;
}
}
}
// if found, move it
if (homePage != null)
{
// move home from it's index to the first position
int homePosition = pageList.indexOf(homePage);
for (int n = 0; n < homePosition; n++)
{
homePage.moveUp();
}
}
}
// if Site Info is newly added, more it to the last
if (hasNewSiteInfo)
{
SitePage siteInfoPage = null;
pageList = site.getPages();
String[] toolIds = {"sakai.siteinfo"};
if (pageList != null && pageList.size() != 0)
{
for (ListIterator i = pageList.listIterator(); siteInfoPage==null && i.hasNext(); )
{
SitePage page = (SitePage)i.next();
int s = page.getTools(toolIds).size();
if (s > 0)
{
siteInfoPage = page;
}
}
}
// if found, move it
if (siteInfoPage != null)
{
// move home from it's index to the first position
int siteInfoPosition = pageList.indexOf(siteInfoPage);
for (int n = siteInfoPosition; n<pageList.size(); n++)
{
siteInfoPage.moveDown();
}
}
}
// if there is no email tool chosen
if (!hasEmail)
{
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
}
//commit
commitSite(site);
} // getRevisedFeatures
/**
* getFeatures gets features for a new site
*
*/
private void getFeatures(ParameterParser params, SessionState state)
{
List idsSelected = new Vector();
boolean goToENWPage = false;
boolean homeSelected = false;
// Add new pages and tools, if any
if (params.getStrings ("selectedTools") == null)
{
addAlert(state, rb.getString("atleastonetool"));
}
else
{
List l = new ArrayList(Arrays.asList(params.getStrings ("selectedTools"))); // toolId's & titles of chosen tools
for (int i = 0; i < l.size(); i++)
{
String toolId = (String) l.get(i);
if (toolId.equals("sakai.mailbox") || toolId.indexOf("sakai.news") != -1 || toolId.indexOf("sakai.iframe") != -1)
{
goToENWPage = true;
}
else if (toolId.equals(HOME_TOOL_ID))
{
homeSelected = true;
}
idsSelected.add(toolId);
}
state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(homeSelected));
}
String importString = params.getString("import");
if (importString!= null && importString.equalsIgnoreCase(Boolean.TRUE.toString()))
{
state.setAttribute(STATE_IMPORT, Boolean.TRUE);
List importSites = new Vector();
if (params.getStrings("importSites") != null)
{
importSites = new ArrayList(Arrays.asList(params.getStrings("importSites")));
}
if (importSites.size() == 0)
{
addAlert(state, rb.getString("java.toimport")+" ");
}
else
{
Hashtable sites = new Hashtable();
for (int index = 0; index < importSites.size(); index ++)
{
try
{
Site s = SiteService.getSite((String) importSites.get(index));
if (!sites.containsKey(s))
{
sites.put(s, new Vector());
}
}
catch (IdUnusedException e)
{
}
}
state.setAttribute(STATE_IMPORT_SITES, sites);
}
}
else
{
state.removeAttribute(STATE_IMPORT);
}
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idsSelected); // List of ToolRegistration toolId's
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (state.getAttribute(STATE_IMPORT) != null)
{
// go to import tool page
state.setAttribute(STATE_TEMPLATE_INDEX, "27");
}
else if (goToENWPage)
{
// go to the configuration page for Email Archive, News and Web Content tools
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
}
else
{
// go to edit access page
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
int totalSteps = 4;
if (state.getAttribute(STATE_SITE_TYPE) != null && ((String) state.getAttribute(STATE_SITE_TYPE)).equalsIgnoreCase("course"))
{
totalSteps = 5;
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null && state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
totalSteps++;
}
}
if (state.getAttribute(STATE_IMPORT) != null)
{
totalSteps++;
}
if (goToENWPage)
{
totalSteps++;
}
state.setAttribute(SITE_CREATE_TOTAL_STEPS, new Integer(totalSteps));
}
} // getFeatures
/**
* addFeatures adds features to a new site
*
*/
private void addFeatures(SessionState state)
{
List toolRegistrationList = (Vector)state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
Site site = getStateSite(state);
List pageList = new Vector();
int moves = 0;
boolean hasHome = false;
boolean hasAnnouncement = false;
boolean hasChat = false;
boolean hasDiscussion = false;
boolean hasSiteInfo = false;
List chosenList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// tools to be imported from other sites?
Hashtable importTools = null;
if (state.getAttribute(STATE_IMPORT_SITE_TOOL) != null)
{
importTools = (Hashtable) state.getAttribute(STATE_IMPORT_SITE_TOOL);
}
//for tools other than home
if (chosenList.contains(HOME_TOOL_ID))
{
// add home tool later
hasHome = true;
}
// order the id list
chosenList = orderToolIds(state, site.getType(), chosenList);
// titles for news tools
Hashtable newsTitles = (Hashtable) state.getAttribute(STATE_NEWS_TITLES);
// urls for news tools
Hashtable newsUrls = (Hashtable) state.getAttribute(STATE_NEWS_URLS);
// titles for web content tools
Hashtable wcTitles = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES);
// urls for web content tools
Hashtable wcUrls = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_URLS);
if (chosenList.size() > 0)
{
Tool toolRegFound = null;
for (ListIterator i = chosenList.listIterator(); i.hasNext(); )
{
String toolId = (String) i.next();
// find the tool in the tool registration list
toolRegFound = null;
for (int j = 0; j < toolRegistrationList.size() && toolRegFound == null; j++)
{
MyTool tool = (MyTool) toolRegistrationList.get(j);
if ((toolId.indexOf("assignment") != -1 && toolId.equals(tool.getId()))
|| (toolId.indexOf("assignment") == -1 && toolId.indexOf(tool.getId()) != -1))
{
toolRegFound = ToolManager.getTool(tool.getId());
}
}
if (toolRegFound != null)
{
if (toolId.indexOf("sakai.news") != -1)
{
// adding multiple news tool
String newsTitle = (String) newsTitles.get(toolId);
SitePage page = site.addPage();
page.setTitle(newsTitle); // the visible label on the tool menu
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
ToolConfiguration tool = page.addTool();
tool.setTool("sakai.news", ToolManager.getTool("sakai.news"));
tool.setTitle(newsTitle);
tool.setLayoutHints("0,0");
String urlString = (String) newsUrls.get(toolId);
//update the tool config
tool.getPlacementConfig().setProperty("channel-url", urlString);
}
else if (toolId.indexOf("sakai.iframe") != -1)
{
// adding multiple web content tool
String wcTitle = (String) wcTitles.get(toolId);
SitePage page = site.addPage();
page.setTitle(wcTitle); // the visible label on the tool menu
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
ToolConfiguration tool = page.addTool();
tool.setTool("sakai.iframe", ToolManager.getTool("sakai.iframe"));
tool.setTitle(wcTitle);
tool.setLayoutHints("0,0");
String wcUrl = StringUtil.trimToNull((String) wcUrls.get(toolId));
if (wcUrl != null && !wcUrl.equals(WEB_CONTENT_DEFAULT_URL))
{
// if url is not empty and not consists only of "http://"
tool.getPlacementConfig().setProperty("source", wcUrl);
}
}
else
{
SitePage page = site.addPage();
page.setTitle(toolRegFound.getTitle()); // the visible label on the tool menu
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
ToolConfiguration tool = page.addTool();
tool.setTool(toolRegFound.getId(), toolRegFound);
tool.setLayoutHints("0,0");
} // Other features
}
// booleans for synoptic views
if (toolId.equals("sakai.announcements"))
{
hasAnnouncement = true;
}
else if (toolId.equals("sakai.chat"))
{
hasChat = true;
}
else if (toolId.equals("sakai.discussion"))
{
hasDiscussion = true;
}
else if (toolId.equals("sakai.siteinfo"))
{
hasSiteInfo = true;
}
} // for
//import
importToolIntoSite(chosenList, importTools, site);
// add home tool
if (hasHome)
{
// Home is a special case, with several tools on the page. "home" is hard coded in chef_site-addRemoveFeatures.vm.
try
{
SitePage page = site.addPage();
page.setTitle(rb.getString("java.home")); // the visible label on the tool menu
if (hasAnnouncement || hasDiscussion || hasChat)
{
page.setLayout(SitePage.LAYOUT_DOUBLE_COL);
}
else
{
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
}
//Add worksite information tool
ToolConfiguration tool = page.addTool();
tool.setTool("sakai.iframe.site", ToolManager.getTool("sakai.iframe.site"));
tool.setTitle(rb.getString("java.workinfo"));
tool.setLayoutHints("0,0");
if (hasAnnouncement)
{
//Add synoptic announcements tool
tool = page.addTool();
tool.setTool("sakai.synoptic.announcement", ToolManager.getTool("sakai.synoptic.announcement"));
tool.setTitle(rb.getString("java.recann"));
tool.setLayoutHints("0,1");
}
if (hasDiscussion)
{
//Add synoptic announcements tool
tool = page.addTool();
tool.setTool("sakai.synoptic.discussion", ToolManager.getTool("sakai.synoptic.discussion"));
tool.setTitle("Recent Discussion Items");
tool.setLayoutHints("1,1");
}
if (hasChat)
{
//Add synoptic chat tool
tool = page.addTool();
tool.setTool("sakai.synoptic.chat", ToolManager.getTool("sakai.synoptic.chat"));
tool.setTitle("Recent Chat Messages");
tool.setLayoutHints("2,1");
}
}
catch (Exception e)
{
M_log.warn("SiteAction.getFeatures Exception " + e.getMessage());
}
state.setAttribute(STATE_TOOL_HOME_SELECTED, Boolean.TRUE);
//Order tools - move Home to the top
pageList = site.getPages();
if(pageList != null && pageList.size() != 0)
{
for (ListIterator i = pageList.listIterator(); i.hasNext(); )
{
SitePage page = (SitePage)i.next();
if((page.getTitle()).equals(rb.getString("java.home")))
{
moves = pageList.indexOf(page);
for (int n = 0; n < moves; n++)
{
page.moveUp();
}
}
}
}
} // Home feature
// move Site Info tool, if selected, to the end of tool list
if (hasSiteInfo)
{
SitePage siteInfoPage = null;
pageList = site.getPages();
String[] toolIds = {"sakai.siteinfo"};
if (pageList != null && pageList.size() != 0)
{
for (ListIterator i = pageList.listIterator(); siteInfoPage==null && i.hasNext(); )
{
SitePage page = (SitePage)i.next();
int s = page.getTools(toolIds).size();
if (s > 0)
{
siteInfoPage = page;
}
}
}
//if found, move it
if (siteInfoPage != null)
{
// move home from it's index to the first position
int siteInfoPosition = pageList.indexOf(siteInfoPage);
for (int n = siteInfoPosition; n<pageList.size(); n++)
{
siteInfoPage.moveDown();
}
}
} // Site Info
}
// commit
commitSite(site);
} // addFeatures
// import tool content into site
private void importToolIntoSite(List toolIds, Hashtable importTools, Site site)
{
if (importTools != null)
{
// import resources first
boolean resourcesImported = false;
for (int i = 0; i < toolIds.size() && !resourcesImported; i++)
{
String toolId = (String) toolIds.get(i);
if (toolId.equalsIgnoreCase("sakai.resources") && importTools.containsKey(toolId))
{
List importSiteIds = (List) importTools.get(toolId);
for (int k = 0; k < importSiteIds.size(); k++)
{
String fromSiteId = (String) importSiteIds.get(k);
String toSiteId = site.getId();
String fromSiteCollectionId = ContentHostingService.getSiteCollection(fromSiteId);
String toSiteCollectionId = ContentHostingService.getSiteCollection(toSiteId);
transferCopyEntities(toolId, fromSiteCollectionId, toSiteCollectionId);
resourcesImported = true;
}
}
}
// ijmport other tools then
for (int i = 0; i < toolIds.size(); i++)
{
String toolId = (String) toolIds.get(i);
if (!toolId.equalsIgnoreCase("sakai.resources") && importTools.containsKey(toolId))
{
List importSiteIds = (List) importTools.get(toolId);
for (int k = 0; k < importSiteIds.size(); k++)
{
String fromSiteId = (String) importSiteIds.get(k);
String toSiteId = site.getId();
transferCopyEntities(toolId, fromSiteId, toSiteId);
}
}
}
}
} // importToolIntoSite
public void saveSiteStatus(SessionState state, boolean published)
{
Site site = getStateSite(state);
site.setPublished(published);
} // saveSiteStatus
public void commitSite(Site site, boolean published)
{
site.setPublished(published);
try
{
SiteService.save(site);
}
catch (IdUnusedException e)
{
// TODO:
}
catch (PermissionException e)
{
// TODO:
}
} // commitSite
public void commitSite(Site site)
{
try
{
SiteService.save(site);
}
catch (IdUnusedException e)
{
// TODO:
}
catch (PermissionException e)
{
// TODO:
}
}// commitSite
private boolean isValidDomain(String email)
{
String invalidEmailInIdAccountString = ServerConfigurationService.getString("invalidEmailInIdAccountString", null);
if(invalidEmailInIdAccountString != null) {
String[] invalidDomains = invalidEmailInIdAccountString.split(",");
for(int i = 0; i < invalidDomains.length; i++) {
String domain = invalidDomains[i].trim();
if(email.toLowerCase().indexOf(domain.toLowerCase()) != -1) {
return false;
}
}
}
return true;
}
private void checkAddParticipant(ParameterParser params, SessionState state)
{
// get the participants to be added
int i;
Vector pList = new Vector();
HashSet existingUsers = new HashSet();
Site site = null;
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
try
{
site = SiteService.getSite(siteId);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("java.specif") + " " + siteId);
}
//accept noEmailInIdAccounts and/or emailInIdAccount account names
String noEmailInIdAccounts = "";
String emailInIdAccounts = "";
//check that there is something with which to work
noEmailInIdAccounts = StringUtil.trimToNull((params.getString("noEmailInIdAccount")));
emailInIdAccounts = StringUtil.trimToNull(params.getString("emailInIdAccount"));
state.setAttribute("noEmailInIdAccountValue", noEmailInIdAccounts);
state.setAttribute("emailInIdAccountValue", emailInIdAccounts);
//if there is no uniquname or emailInIdAccount entered
if (noEmailInIdAccounts == null && emailInIdAccounts == null)
{
addAlert(state, rb.getString("java.guest"));
state.setAttribute(STATE_TEMPLATE_INDEX, "5");
return;
}
String at = "@";
if (noEmailInIdAccounts != null)
{
// adding noEmailInIdAccounts
String[] noEmailInIdAccountArray = noEmailInIdAccounts.split("\r\n");
for (i = 0; i < noEmailInIdAccountArray.length; i++)
{
String noEmailInIdAccount = StringUtil.trimToNull(noEmailInIdAccountArray[i].replaceAll("[\t\r\n]",""));
//if there is some text, try to use it
if(noEmailInIdAccount != null)
{
//automaticially add emailInIdAccount account
Participant participant = new Participant();
try
{
User u = UserDirectoryService.getUserByEid(noEmailInIdAccount);
if (site != null && site.getUserRole(u.getId()) != null)
{
// user already exists in the site, cannot be added again
existingUsers.add(noEmailInIdAccount);
}
else
{
participant.name = u.getDisplayName();
participant.uniqname = noEmailInIdAccount;
pList.add(participant);
}
}
catch (UserNotDefinedException e)
{
addAlert(state, noEmailInIdAccount + " "+rb.getString("java.username")+" ");
}
}
}
} // noEmailInIdAccounts
if (emailInIdAccounts != null)
{
String[] emailInIdAccountArray = emailInIdAccounts.split("\r\n");
for (i = 0; i < emailInIdAccountArray.length; i++)
{
String emailInIdAccount = emailInIdAccountArray[i];
//if there is some text, try to use it
emailInIdAccount.replaceAll("[ \t\r\n]","");
//remove the trailing dots and empty space
while (emailInIdAccount.endsWith(".") || emailInIdAccount.endsWith(" "))
{
emailInIdAccount = emailInIdAccount.substring(0, emailInIdAccount.length() -1);
}
if(emailInIdAccount != null && emailInIdAccount.length() > 0)
{
String[] parts = emailInIdAccount.split(at);
if(emailInIdAccount.indexOf(at) == -1 )
{
// must be a valid email address
addAlert(state, emailInIdAccount + " "+rb.getString("java.emailaddress"));
}
else if((parts.length != 2) || (parts[0].length() == 0))
{
// must have both id and address part
addAlert(state, emailInIdAccount + " "+rb.getString("java.notemailid"));
}
else if (!Validator.checkEmailLocal(parts[0]))
{
addAlert(state, emailInIdAccount + " "+rb.getString("java.emailaddress") + rb.getString("java.theemail"));
}
else if (emailInIdAccount != null && !isValidDomain(emailInIdAccount))
{
// wrong string inside emailInIdAccount id
addAlert(state, emailInIdAccount + " "+rb.getString("java.emailaddress")+" ");
}
else
{
Participant participant = new Participant();
try
{
// if the emailInIdAccount user already exists
User u = UserDirectoryService.getUserByEid(emailInIdAccount);
if (site != null && site.getUserRole(u.getId()) != null)
{
// user already exists in the site, cannot be added again
existingUsers.add(emailInIdAccount);
}
else
{
participant.name = u.getDisplayName();
participant.uniqname = emailInIdAccount;
pList.add(participant);
}
}
catch (UserNotDefinedException e)
{
// if the emailInIdAccount user is not in the system yet
participant.name = emailInIdAccount;
participant.uniqname = emailInIdAccount; // TODO: what would the UDS case this name to? -ggolden
pList.add(participant);
}
}
} // if
} //
} // emailInIdAccounts
boolean same_role = true;
if (params.getString("same_role") == null)
{
addAlert(state, rb.getString("java.roletype")+" ");
}
else
{
same_role = params.getString("same_role").equals("true")?true:false;
state.setAttribute("form_same_role", new Boolean(same_role));
}
if (state.getAttribute(STATE_MESSAGE) != null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "5");
}
else
{
if (same_role)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "19");
}
else
{
state.setAttribute(STATE_TEMPLATE_INDEX, "20");
}
}
// remove duplicate or existing user from participant list
pList=removeDuplicateParticipants(pList, state);
state.setAttribute(STATE_ADD_PARTICIPANTS, pList);
// if the add participant list is empty after above removal, stay in the current page
if (pList.size() == 0)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "5");
}
// add alert for attempting to add existing site user(s)
if (!existingUsers.isEmpty())
{
int count = 0;
String accounts = "";
for (Iterator eIterator = existingUsers.iterator();eIterator.hasNext();)
{
if (count == 0)
{
accounts = (String) eIterator.next();
}
else
{
accounts = accounts + ", " + (String) eIterator.next();
}
count++;
}
addAlert(state, rb.getString("add.existingpart.1") + accounts + rb.getString("add.existingpart.2"));
}
return;
} // checkAddParticipant
private Vector removeDuplicateParticipants(List pList, SessionState state)
{
// check the uniqness of list member
Set s = new HashSet();
Set uniqnameSet = new HashSet();
Vector rv = new Vector();
for (int i = 0; i < pList.size(); i++)
{
Participant p = (Participant) pList.get(i);
if (!uniqnameSet.contains(p.getUniqname()))
{
// no entry for the account yet
rv.add(p);
uniqnameSet.add(p.getUniqname());
}
else
{
// found duplicates
s.add(p.getUniqname());
}
}
if (!s.isEmpty())
{
int count = 0;
String accounts = "";
for (Iterator i = s.iterator();i.hasNext();)
{
if (count == 0)
{
accounts = (String) i.next();
}
else
{
accounts = accounts + ", " + (String) i.next();
}
count++;
}
if (count == 1)
{
addAlert(state, rb.getString("add.duplicatedpart.single") + accounts + ".");
}
else
{
addAlert(state, rb.getString("add.duplicatedpart") + accounts + ".");
}
}
return rv;
}
public void doAdd_participant(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
String siteTitle = getStateSite(state).getTitle();
String emailInIdAccountName = ServerConfigurationService.getString("emailInIdAccountName", "");
Hashtable selectedRoles = (Hashtable) state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES);
boolean notify = false;
if (state.getAttribute("form_selectedNotify") != null)
{
notify = ((Boolean) state.getAttribute("form_selectedNotify")).booleanValue();
}
boolean same_role = ((Boolean) state.getAttribute("form_same_role")).booleanValue();
Hashtable eIdRoles = new Hashtable();
List addParticipantList = (List) state.getAttribute(STATE_ADD_PARTICIPANTS);
for (int i = 0; i < addParticipantList.size(); i++)
{
Participant p = (Participant) addParticipantList.get(i);
String eId = p.getEid();
// role defaults to same role
String role = (String) state.getAttribute("form_selectedRole");
if (!same_role)
{
// if all added participants have different role
role = (String) selectedRoles.get(eId);
}
boolean noEmailInIdAccount = eId.indexOf(EMAIL_CHAR) == -1;
if(noEmailInIdAccount)
{
// if this is a noEmailInIdAccount
// update the hashtable
eIdRoles.put(eId, role);
}
else
{
// if this is an emailInIdAccount
try
{
UserDirectoryService.getUserByEid(eId);
}
catch (UserNotDefinedException e)
{
//if there is no such user yet, add the user
try
{
UserEdit uEdit = UserDirectoryService.addUser(null, eId);
//set email address
uEdit.setEmail(eId);
// set the guest user type
uEdit.setType("guest");
// set password to a positive random number
Random generator = new Random(System.currentTimeMillis());
Integer num = new Integer(generator.nextInt(Integer.MAX_VALUE));
if (num.intValue() < 0) num = new Integer(num.intValue() *-1);
String pw = num.toString();
uEdit.setPassword(pw);
// and save
UserDirectoryService.commitEdit(uEdit);
boolean notifyNewUserEmail = (ServerConfigurationService.getString("notifyNewUserEmail", Boolean.TRUE.toString())).equalsIgnoreCase(Boolean.TRUE.toString());
if (notifyNewUserEmail)
{
notifyNewUserEmail(uEdit.getEid(), uEdit.getEmail(), pw, siteTitle);
}
}
catch(UserIdInvalidException ee)
{
addAlert(state, emailInIdAccountName + " id " + eId + " "+rb.getString("java.isinval") );
M_log.warn(this + " UserDirectoryService addUser exception " + e.getMessage());
}
catch(UserAlreadyDefinedException ee)
{
addAlert(state, "The " + emailInIdAccountName + " " + eId + " " + rb.getString("java.beenused"));
M_log.warn(this + " UserDirectoryService addUser exception " + e.getMessage());
}
catch(UserPermissionException ee)
{
addAlert(state, rb.getString("java.haveadd")+ " " + eId);
M_log.warn(this + " UserDirectoryService addUser exception " + e.getMessage());
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
eIdRoles.put(eId, role);
}
}
}
// batch add and updates the successful added list
List addedParticipantEIds = addUsersRealm(state, eIdRoles, notify, false);
// update the not added user list
String notAddedNoEmailInIdAccounts = null;
String notAddedEmailInIdAccounts = null;
for (Iterator iEIds = eIdRoles.keySet().iterator(); iEIds.hasNext();)
{
String iEId = (String) iEIds.next();
if (!addedParticipantEIds.contains(iEId))
{
if (iEId.indexOf(EMAIL_CHAR) == -1)
{
// no email in eid
notAddedNoEmailInIdAccounts = notAddedNoEmailInIdAccounts.concat(iEId + "\n");
}
else
{
// email in eid
notAddedEmailInIdAccounts = notAddedEmailInIdAccounts.concat(iEId + "\n");
}
}
}
if (addedParticipantEIds.size() != 0 && (notAddedNoEmailInIdAccounts != null || notAddedEmailInIdAccounts != null))
{
// at lease one noEmailInIdAccount account or an emailInIdAccount account added, and there are also failures
addAlert(state, rb.getString("java.allusers"));
}
if (notAddedNoEmailInIdAccounts == null && notAddedEmailInIdAccounts == null)
{
// all account has been added successfully
removeAddParticipantContext(state);
}
else
{
state.setAttribute("noEmailInIdAccountValue", notAddedNoEmailInIdAccounts);
state.setAttribute("emailInIdAccountValue", notAddedEmailInIdAccounts);
}
if (state.getAttribute(STATE_MESSAGE) != null)
{
state.setAttribute(STATE_TEMPLATE_INDEX, "22");
}
else
{
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
return;
} // doAdd_participant
/**
* remove related state variable for adding participants
* @param state SessionState object
*/
private void removeAddParticipantContext(SessionState state)
{
// remove related state variables
state.removeAttribute("form_selectedRole");
state.removeAttribute("noEmailInIdAccountValue");
state.removeAttribute("emailInIdAccountValue");
state.removeAttribute("form_same_role");
state.removeAttribute("form_selectedNotify");
state.removeAttribute(STATE_ADD_PARTICIPANTS);
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.removeAttribute(STATE_SELECTED_PARTICIPANT_ROLES);
} // removeAddParticipantContext
/**
* Send an email to newly added user informing password
* @param newEmailInIdAccount
* @param emailId
* @param userName
* @param siteTitle
*/
private void notifyNewUserEmail(String userName, String newUserEmail, String newUserPassword, String siteTitle)
{
String from = ServerConfigurationService.getString("setup.request", null);
if (from == null)
{
M_log.warn(this + " - no 'setup.request' in configuration");
from = "postmaster@".concat(ServerConfigurationService.getServerName());
}
String productionSiteName = ServerConfigurationService.getString("ui.service", "");
String productionSiteUrl = ServerConfigurationService.getPortalUrl();
String to = newUserEmail;
String headerTo = newUserEmail;
String replyTo = newUserEmail;
String message_subject = productionSiteName + " "+rb.getString("java.newusernoti");
String content = "";
if (from != null && newUserEmail !=null)
{
StringBuffer buf = new StringBuffer();
buf.setLength(0);
// email body
buf.append(userName + ":\n\n");
buf.append(rb.getString("java.addedto")+" " + productionSiteName + " ("+ productionSiteUrl + ") ");
buf.append(rb.getString("java.simpleby")+" ");
buf.append(UserDirectoryService.getCurrentUser().getDisplayName() + ". \n\n");
buf.append(rb.getString("java.passwordis1")+"\n" + newUserPassword + "\n\n");
buf.append(rb.getString("java.passwordis2")+ "\n\n");
content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo, replyTo, null);
}
} // notifyNewUserEmail
/**
* send email notification to added participant
*/
private void notifyAddedParticipant(boolean newEmailInIdAccount, String emailId, String userName, String siteTitle)
{
String from = ServerConfigurationService.getString("setup.request", null);
if (from == null)
{
M_log.warn(this + " - no 'setup.request' in configuration");
}
else
{
String productionSiteName = ServerConfigurationService.getString("ui.service", "");
String productionSiteUrl = ServerConfigurationService.getPortalUrl();
String emailInIdAccountUrl = ServerConfigurationService.getString("emailInIdAccount.url", null);
String to = emailId;
String headerTo = emailId;
String replyTo = emailId;
String message_subject = productionSiteName + " "+rb.getString("java.sitenoti");
String content = "";
StringBuffer buf = new StringBuffer();
buf.setLength(0);
// email body differs between newly added emailInIdAccount account and other users
buf.append(userName + ":\n\n");
buf.append(rb.getString("java.following")+" " + productionSiteName + " "+rb.getString("java.simplesite")+ "\n");
buf.append(siteTitle + "\n");
buf.append(rb.getString("java.simpleby")+" ");
buf.append(UserDirectoryService.getCurrentUser().getDisplayName() + ". \n\n");
if (newEmailInIdAccount)
{
buf.append(ServerConfigurationService.getString("emailInIdAccountInstru", "") + "\n");
if (emailInIdAccountUrl != null)
{
buf.append(rb.getString("java.togeta1") +"\n" + emailInIdAccountUrl + "\n");
buf.append(rb.getString("java.togeta2")+"\n\n");
}
buf.append(rb.getString("java.once")+" " + productionSiteName + ": \n");
buf.append(rb.getString("java.loginhow1")+" " + productionSiteName + ": " + productionSiteUrl + "\n");
buf.append(rb.getString("java.loginhow2")+"\n");
buf.append(rb.getString("java.loginhow3")+"\n");
}
else
{
buf.append(rb.getString("java.tolog")+"\n");
buf.append(rb.getString("java.loginhow1")+" " + productionSiteName + ": " + productionSiteUrl + "\n");
buf.append(rb.getString("java.loginhow2")+"\n");
buf.append(rb.getString("java.loginhow3u")+"\n");
}
buf.append(rb.getString("java.tabscreen"));
content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo, replyTo, null);
} // if
} // notifyAddedParticipant
/*
* Given a list of user eids, add users to realm
* If the user account does not exist yet inside the user directory, assign role to it
* @return A list of eids for successfully added users
*/
private List addUsersRealm (SessionState state, Hashtable eIdRoles, boolean notify, boolean emailInIdAccount)
{
// return the list of user eids for successfully added user
List addedUserEIds = new Vector();
StringBuffer message = new StringBuffer();
if (eIdRoles != null && !eIdRoles.isEmpty())
{
// get the current site
Site sEdit = getStateSite(state);
if (sEdit != null)
{
// get realm object
String realmId = sEdit.getReference();
try
{
AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realmId);
for (Iterator eIds = eIdRoles.keySet().iterator(); eIds.hasNext();)
{
String eId = (String) eIds.next();
String role = (String) eIdRoles.get(eId);
try
{
User user = UserDirectoryService.getUserByEid(eId);
if (AuthzGroupService.allowUpdate(realmId) || SiteService.allowUpdateSiteMembership(sEdit.getId()))
{
realmEdit.addMember(user.getId(), role, true, false);
addedUserEIds.add(eId);
// send notification
if (notify)
{
String emailId = user.getEmail();
String userName = user.getDisplayName();
// send notification email
notifyAddedParticipant(emailInIdAccount, emailId, userName, sEdit.getTitle());
}
}
}
catch (UserNotDefinedException e)
{
message.append(eId + " " +rb.getString("java.account")+" \n");
} // try
} // for
try
{
AuthzGroupService.save(realmEdit);
}
catch (GroupNotDefinedException ee)
{
message.append(rb.getString("java.realm") + realmId);
}
catch (AuthzPermissionException ee)
{
message.append(rb.getString("java.permeditsite") + realmId);
}
}
catch (GroupNotDefinedException eee)
{
message.append(rb.getString("java.realm") + realmId);
}
}
}
if (message.length() != 0)
{
addAlert(state, message.toString());
} // if
return addedUserEIds;
} // addUsersRealm
/**
* addNewSite is called when the site has enough information to create a new site
*
*/
private void addNewSite(ParameterParser params, SessionState state)
{
if(getStateSite(state) != null)
{
// There is a Site in state already, so use it rather than creating a new Site
return;
}
//If cleanState() has removed SiteInfo, get a new instance into state
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null)
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
String id = StringUtil.trimToNull(siteInfo.getSiteId());
if (id == null)
{
//get id
id = IdManager.createUuid();
siteInfo.site_id = id;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
if (state.getAttribute(STATE_MESSAGE) == null)
{
try
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
Site site = SiteService.addSite(id, siteInfo.site_type);
String title = StringUtil.trimToNull(siteInfo.title);
String description = siteInfo.description;
setAppearance(state, site, siteInfo.iconUrl);
site.setDescription(description);
if (title != null)
{
site.setTitle(title);
}
site.setType(siteInfo.site_type);
ResourcePropertiesEdit rp = site.getPropertiesEdit();
site.setShortDescription(siteInfo.short_description);
site.setPubView(siteInfo.include);
site.setJoinable(siteInfo.joinable);
site.setJoinerRole(siteInfo.joinerRole);
site.setPublished(siteInfo.published);
// site contact information
rp.addProperty(PROP_SITE_CONTACT_NAME, siteInfo.site_contact_name);
rp.addProperty(PROP_SITE_CONTACT_EMAIL, siteInfo.site_contact_email);
state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId());
//commit newly added site in order to enable related realm
commitSite(site);
}
catch (IdUsedException e)
{
addAlert(state, rb.getString("java.sitewithid")+" " + id + " "+rb.getString("java.exists"));
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("template-index"));
return;
}
catch (IdInvalidException e)
{
addAlert(state, rb.getString("java.thesiteid")+" " + id + " "+rb.getString("java.notvalid"));
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("template-index"));
return;
}
catch (PermissionException e)
{
addAlert(state, rb.getString("java.permission")+" " + id +".");
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("template-index"));
return;
}
}
} // addNewSite
/**
* Use the AuthzGroup Provider Id to build a Site tab
* @throws IdUnusedException
*
*/
private String getCourseTab(SessionState state, String id)
{
StringBuffer tab = new StringBuffer();
try
{
String courseName = CourseManagementService.getCourseName(id);
if (courseName != null && courseName.length() > 0)
{
tab.append(courseName);
return appendTermInSiteTitle(state, tab.toString());
}
}
catch (IdUnusedException ignore)
{
}
return "";
}// getCourseTab
private String appendTermInSiteTitle (SessionState state, String title)
{
//append term information into the tab in order to differenciate same course taught in different terms
if (state.getAttribute(STATE_TERM_SELECTED) != null)
{
Term t = (Term) state.getAttribute(STATE_TERM_SELECTED);
if (StringUtil.trimToNull(t.getListAbbreviation()) != null)
{
// use term abbreviation, if any
title = title.concat(" ").concat(t.getListAbbreviation());
}
else
{
// use term id
title = title.concat(" ").concat(t.getId());
}
}
return title;
} // appendTermInSiteTitle
/**
* %%% legacy properties, to be cleaned up
*
*/
private void sitePropertiesIntoState (SessionState state)
{
try
{
Site site = getStateSite(state);
SiteInfo siteInfo = new SiteInfo();
// set from site attributes
siteInfo.title = site.getTitle();
siteInfo.description = site.getDescription();
siteInfo.iconUrl = site.getIconUrl();
siteInfo.infoUrl = site.getInfoUrl();
siteInfo.joinable = site.isJoinable();
siteInfo.joinerRole = site.getJoinerRole();
siteInfo.published = site.isPublished();
siteInfo.include = site.isPubView();
siteInfo.short_description = site.getShortDescription();
state.setAttribute(STATE_SITE_TYPE, siteInfo.site_type);
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
catch (Exception e)
{
M_log.warn("SiteAction.sitePropertiesIntoState " + e.getMessage());
}
} // sitePropertiesIntoState
/**
* pageMatchesPattern returns true if a SitePage matches a WorkSite Setup pattern
*
*/
private boolean pageMatchesPattern (SessionState state, SitePage page)
{
List pageToolList = page.getTools();
// if no tools on the page, return false
if(pageToolList == null || pageToolList.size() == 0) { return false; }
//for the case where the page has one tool
ToolConfiguration toolConfiguration = (ToolConfiguration)pageToolList.get(0);
//don't compare tool properties, which may be changed using Options
List toolList = new Vector();
int count = pageToolList.size();
boolean match = false;
//check Worksite Setup Home pattern
if(page.getTitle()!=null && page.getTitle().equals(rb.getString("java.home")))
{
return true;
} // Home
else if(page.getTitle() != null && page.getTitle().equals(rb.getString("java.help")))
{
//if the count of tools on the page doesn't match, return false
if(count != 1) { return false;}
//if the page layout doesn't match, return false
if(page.getLayout() != SitePage.LAYOUT_SINGLE_COL) { return false; }
//if tooId isn't sakai.contactSupport, return false
if(!(toolConfiguration.getTool().getId()).equals("sakai.contactSupport")) { return false; }
return true;
} // Help
else if(page.getTitle() != null && page.getTitle().equals("Chat"))
{
//if the count of tools on the page doesn't match, return false
if(count != 1) { return false;}
//if the page layout doesn't match, return false
if(page.getLayout() != SitePage.LAYOUT_SINGLE_COL) { return false; }
//if the tool doesn't match, return false
if(!(toolConfiguration.getTool().getId()).equals("sakai.chat")) { return false; }
//if the channel doesn't match value for main channel, return false
String channel = toolConfiguration.getPlacementConfig().getProperty("channel");
if(channel == null) { return false; }
if(!(channel.equals(NULL_STRING))) { return false; }
return true;
} // Chat
else
{
//if the count of tools on the page doesn't match, return false
if(count != 1) { return false;}
//if the page layout doesn't match, return false
if(page.getLayout() != SitePage.LAYOUT_SINGLE_COL) { return false; }
toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
if(pageToolList != null || pageToolList.size() != 0)
{
//if tool attributes don't match, return false
match = false;
for (ListIterator i = toolList.listIterator(); i.hasNext(); )
{
MyTool tool = (MyTool) i.next();
if(toolConfiguration.getTitle() != null)
{
if(toolConfiguration.getTool() != null && toolConfiguration.getTool().getId().indexOf(tool.getId()) != -1) { match = true; }
}
}
if (!match) { return false; }
}
} // Others
return true;
} // pageMatchesPattern
/**
* siteToolsIntoState is the replacement for siteToolsIntoState_
* Make a list of pages and tools that match WorkSite Setup configurations into state
*/
private void siteToolsIntoState (SessionState state)
{
String wSetupTool = NULL_STRING;
List wSetupPageList = new Vector();
Site site = getStateSite(state);
List pageList = site.getPages();
//Put up tool lists filtered by category
String type = site.getType();
if (type == null)
{
if (SiteService.isUserSite(site.getId()))
{
type = "myworkspace";
}
else if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null)
{
// for those sites without type, use the tool set for default site type
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
}
}
List toolRegList = new Vector();
if (type != null)
{
Set categories = new HashSet();
categories.add(type);
Set toolRegistrations = ToolManager.findTools(categories, null);
SortedIterator i = new SortedIterator(toolRegistrations.iterator(), new ToolComparator());
for (;i.hasNext();)
{
// form a new Tool
Tool tr = (Tool) i.next();
MyTool newTool = new MyTool();
newTool.title = tr.getTitle();
newTool.id = tr.getId();
newTool.description = tr.getDescription();
toolRegList.add(newTool);
}
}
if (toolRegList.size() == 0 && state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null)
{
// use default site type and try getting tools again
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
Set nCategories = new HashSet();
nCategories.add(type);
Set toolRegistrations = ToolManager.findTools(nCategories, null);
SortedIterator i = new SortedIterator(toolRegistrations.iterator(), new ToolComparator());
for (;i.hasNext();)
{
// form a new Tool
Tool tr = (Tool) i.next();
MyTool newTool = new MyTool();
newTool.title = tr.getTitle();
newTool.id = tr.getId();
newTool.description = tr.getDescription();
toolRegList.add(newTool);
}
}
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolRegList);
state.setAttribute(STATE_SITE_TYPE, type);
if (type == null)
{
M_log.warn(this + ": - unknown STATE_SITE_TYPE");
}
else
{
state.setAttribute(STATE_SITE_TYPE, type);
}
boolean check_home = false;
boolean hasNews = false;
boolean hasWebContent = false;
int newsToolNum = 0;
int wcToolNum = 0;
Hashtable newsTitles = new Hashtable();
Hashtable wcTitles = new Hashtable();
Hashtable newsUrls = new Hashtable();
Hashtable wcUrls = new Hashtable();
Vector idSelected = new Vector();
if (!((pageList == null) || (pageList.size() == 0)))
{
for (ListIterator i = pageList.listIterator(); i.hasNext(); )
{
SitePage page = (SitePage) i.next();
//collect the pages consistent with Worksite Setup patterns
if(pageMatchesPattern(state, page))
{
if(page.getTitle().equals(rb.getString("java.home")))
{
wSetupTool = HOME_TOOL_ID;
check_home = true;
}
else
{
List pageToolList = page.getTools();
wSetupTool = ((ToolConfiguration)pageToolList.get(0)).getTool().getId();
if (wSetupTool.indexOf("sakai.news") != -1)
{
String newsToolId = page.getId() + wSetupTool;
idSelected.add(newsToolId);
newsTitles.put(newsToolId, page.getTitle());
String channelUrl = ((ToolConfiguration)pageToolList.get(0)).getPlacementConfig().getProperty("channel-url");
newsUrls.put(newsToolId, channelUrl!=null?channelUrl:"");
newsToolNum++;
// insert the News tool into the list
hasNews = false;
int j = 0;
MyTool newTool = new MyTool();
newTool.title = NEWS_DEFAULT_TITLE;
newTool.id = newsToolId;
newTool.selected = false;
for (;j< toolRegList.size() && !hasNews; j++)
{
MyTool t = (MyTool) toolRegList.get(j);
if (t.getId().equals("sakai.news"))
{
hasNews = true;
newTool.description = t.getDescription();
}
}
if (hasNews)
{
toolRegList.add(j-1, newTool);
}
else
{
toolRegList.add(newTool);
}
}
else if ((wSetupTool).indexOf("sakai.iframe") != -1)
{
String wcToolId = page.getId() + wSetupTool;
idSelected.add(wcToolId);
wcTitles.put(wcToolId, page.getTitle());
String wcUrl = StringUtil.trimToNull(((ToolConfiguration)pageToolList.get(0)).getPlacementConfig().getProperty("source"));
if (wcUrl == null)
{
// if there is no source URL, seed it with the Web Content default URL
wcUrl = WEB_CONTENT_DEFAULT_URL;
}
wcUrls.put(wcToolId, wcUrl);
wcToolNum++;
MyTool newTool = new MyTool();
newTool.title = WEB_CONTENT_DEFAULT_TITLE;
newTool.id = wcToolId;
newTool.selected = false;
hasWebContent = false;
int j = 0;
for (;j< toolRegList.size() && !hasWebContent; j++)
{
MyTool t = (MyTool) toolRegList.get(j);
if (t.getId().equals("sakai.iframe"))
{
hasWebContent = true;
newTool.description = t.getDescription();
}
}
if (hasWebContent)
{
toolRegList.add(j-1, newTool);
}
else
{
toolRegList.add(newTool);
}
}
/*else if(wSetupTool.indexOf("sakai.syllabus") != -1)
{
//add only one instance of tool per site
if (!(idSelected.contains(wSetupTool)))
{
idSelected.add(wSetupTool);
}
}*/
else
{
idSelected.add(wSetupTool);
}
}
WorksiteSetupPage wSetupPage = new WorksiteSetupPage();
wSetupPage.pageId = page.getId();
wSetupPage.pageTitle = page.getTitle();
wSetupPage.toolId = wSetupTool;
wSetupPageList.add(wSetupPage);
}
}
}
newsTitles.put("sakai.news", NEWS_DEFAULT_TITLE);
newsUrls.put("sakai.news", NEWS_DEFAULT_URL);
wcTitles.put("sakai.iframe", WEB_CONTENT_DEFAULT_TITLE);
wcUrls.put("sakai.iframe", WEB_CONTENT_DEFAULT_URL);
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolRegList);
state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(check_home));
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idSelected); // List of ToolRegistration toolId's
state.setAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST, idSelected); // List of ToolRegistration toolId's
state.setAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME, Boolean.valueOf(check_home));
state.setAttribute(STATE_NEWS_TITLES, newsTitles);
state.setAttribute(STATE_WEB_CONTENT_TITLES, wcTitles);
state.setAttribute(STATE_NEWS_URLS, newsUrls);
state.setAttribute(STATE_WEB_CONTENT_URLS, wcUrls);
state.setAttribute(STATE_WORKSITE_SETUP_PAGE_LIST, wSetupPageList);
} //siteToolsIntoState
/**
* reset the state variables used in edit tools mode
* @state The SessionState object
*/
private void removeEditToolState(SessionState state)
{
state.removeAttribute(STATE_TOOL_HOME_SELECTED);
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // List of ToolRegistration toolId's
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); // List of ToolRegistration toolId's
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_NEWS_TITLES);
state.removeAttribute(STATE_NEWS_URLS);
state.removeAttribute(STATE_WEB_CONTENT_TITLES);
state.removeAttribute(STATE_WEB_CONTENT_URLS);
state.removeAttribute(STATE_WORKSITE_SETUP_PAGE_LIST);
}
private List orderToolIds(SessionState state, String type, List toolIdList)
{
List rv = new Vector();
if (state.getAttribute(STATE_TOOL_HOME_SELECTED) != null
&& ((Boolean) state.getAttribute(STATE_TOOL_HOME_SELECTED)).booleanValue())
{
rv.add(HOME_TOOL_ID);
}
// look for null site type
if (type != null && toolIdList != null)
{
Set categories = new HashSet();
categories.add(type);
Set tools = ToolManager.findTools(categories, null);
SortedIterator i = new SortedIterator(tools.iterator(), new ToolComparator());
for (; i.hasNext(); )
{
String tool_id = ((Tool) i.next()).getId();
for (ListIterator j = toolIdList.listIterator(); j.hasNext(); )
{
String toolId = (String) j.next();
if(toolId.indexOf("assignment") != -1 && toolId.equals(tool_id)
|| toolId.indexOf("assignment") == -1 && toolId.indexOf(tool_id) != -1)
{
rv.add(toolId);
}
}
}
}
return rv;
} // orderToolIds
private void setupFormNamesAndConstants(SessionState state)
{
TimeBreakdown timeBreakdown = (TimeService.newTime ()).breakdownLocal ();
String mycopyright = COPYRIGHT_SYMBOL + " " + timeBreakdown.getYear () + ", " + UserDirectoryService.getCurrentUser().getDisplayName () + ". All Rights Reserved. ";
state.setAttribute (STATE_MY_COPYRIGHT, mycopyright);
state.setAttribute (STATE_SITE_INSTANCE_ID, null);
state.setAttribute (STATE_INITIALIZED, Boolean.TRUE.toString());
SiteInfo siteInfo = new SiteInfo();
Participant participant = new Participant();
participant.name = NULL_STRING;
participant.uniqname = NULL_STRING;
state.setAttribute(STATE_SITE_INFO, siteInfo);
state.setAttribute("form_participantToAdd", participant);
state.setAttribute(FORM_ADDITIONAL, NULL_STRING);
//legacy
state.setAttribute(FORM_HONORIFIC,"0");
state.setAttribute(FORM_REUSE, "0");
state.setAttribute(FORM_RELATED_CLASS, "0");
state.setAttribute(FORM_RELATED_PROJECT, "0");
state.setAttribute(FORM_INSTITUTION, "0");
//sundry form variables
state.setAttribute(FORM_PHONE,"");
state.setAttribute(FORM_EMAIL,"");
state.setAttribute(FORM_SUBJECT,"");
state.setAttribute(FORM_DESCRIPTION,"");
state.setAttribute(FORM_TITLE,"");
state.setAttribute(FORM_NAME,"");
state.setAttribute(FORM_SHORT_DESCRIPTION,"");
} // setupFormNamesAndConstants
/**
* Add these Unit affliates to sites in these
* Subject areas with Instructor role
*
*/
private void setupSubjectAffiliates(SessionState state)
{
Vector affiliates = new Vector();
List subjectList = new Vector();
List campusList = new Vector();
List uniqnameList = new Vector();
//get term information
if (ServerConfigurationService.getStrings("affiliatesubjects") != null)
{
subjectList = new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("affiliatesubjects")));
}
if (ServerConfigurationService.getStrings("affiliatecampus") != null)
{
campusList = new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("affiliatecampus")));
}
if (ServerConfigurationService.getStrings("affiliateuniqnames") != null)
{
uniqnameList = new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("affiliateuniqnames")));
}
if (subjectList.size() > 0 && subjectList.size() == campusList.size() && subjectList.size() == uniqnameList.size())
{
for (int i=0; i < subjectList.size();i++)
{
String[] subjectFields = ((String) subjectList.get(i)).split(",");
String[] uniqnameFields = ((String) uniqnameList.get(i)).split(",");
String campus = (String) campusList.get(i);
for (int j=0; j < subjectFields.length; j++)
{
String subject = StringUtil.trimToZero(subjectFields[j]);
SubjectAffiliates affiliate = new SubjectAffiliates();
affiliate.setSubject(subject);
affiliate.setCampus(campus);
for (int k=0; k < uniqnameFields.length;k++)
{
affiliate.getUniqnames().add(StringUtil.trimToZero(uniqnameFields[k]));
}
affiliates.add(affiliate);
}
}
}
state.setAttribute(STATE_SUBJECT_AFFILIATES, affiliates);
} // setupSubjectAffiliates
/**
* setupSkins
*
*/
private void setupIcons(SessionState state)
{
List icons = new Vector();
String[] iconNames = null;
String[] iconUrls = null;
String[] iconSkins = null;
//get icon information
if (ServerConfigurationService.getStrings("iconNames") != null)
{
iconNames = ServerConfigurationService.getStrings("iconNames");
}
if (ServerConfigurationService.getStrings("iconUrls") != null)
{
iconUrls = ServerConfigurationService.getStrings("iconUrls");
}
if (ServerConfigurationService.getStrings("iconSkins") != null)
{
iconSkins = ServerConfigurationService.getStrings("iconSkins");
}
if ((iconNames != null) && (iconUrls != null) && (iconSkins != null) && (iconNames.length == iconUrls.length) && (iconNames.length == iconSkins.length))
{
for (int i = 0; i < iconNames.length; i++)
{
Icon s = new Icon(
StringUtil.trimToNull((String) iconNames[i]),
StringUtil.trimToNull((String) iconUrls[i]),
StringUtil.trimToNull((String) iconSkins[i]));
icons.add(s);
}
}
state.setAttribute(STATE_ICONS, icons);
}
private void setAppearance(SessionState state, Site edit, String iconUrl)
{
// set the icon
edit.setIconUrl(iconUrl);
if (iconUrl == null)
{
// this is the default case - no icon, no (default) skin
edit.setSkin(null);
return;
}
// if this icon is in the config appearance list, find a skin to set
List icons = (List) state.getAttribute(STATE_ICONS);
for (Iterator i = icons.iterator(); i.hasNext();)
{
Icon icon = (Icon) i.next();
if (!StringUtil.different(icon.getUrl(), iconUrl))
{
edit.setSkin(icon.getSkin());
return;
}
}
}
/**
* A dispatch funtion when selecting course features
*/
public void doAdd_features ( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
String option = params.getString("option");
if (option.equalsIgnoreCase("addNews"))
{
updateSelectedToolList(state, params, false);
insertTool(state, "sakai.news", STATE_NEWS_TITLES, NEWS_DEFAULT_TITLE, STATE_NEWS_URLS, NEWS_DEFAULT_URL, Integer.parseInt(params.getString("newsNum")));
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
}
else if (option.equalsIgnoreCase("addWC"))
{
updateSelectedToolList(state, params, false);
insertTool(state, "sakai.iframe", STATE_WEB_CONTENT_TITLES, WEB_CONTENT_DEFAULT_TITLE, STATE_WEB_CONTENT_URLS, WEB_CONTENT_DEFAULT_URL, Integer.parseInt(params.getString("wcNum")));
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
}
else if (option.equalsIgnoreCase("import"))
{
// import or not
updateSelectedToolList(state, params, false);
String importSites = params.getString("import");
if (importSites != null && importSites.equalsIgnoreCase(Boolean.TRUE.toString()))
{
state.setAttribute(STATE_IMPORT, Boolean.TRUE);
if (importSites.equalsIgnoreCase(Boolean.TRUE.toString()))
{
state.removeAttribute(STATE_IMPORT);
state.removeAttribute(STATE_IMPORT_SITES);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
}
}
else
{
state.removeAttribute(STATE_IMPORT);
}
}
else if (option.equalsIgnoreCase("continue"))
{
// continue
doContinue(data);
}
else if (option.equalsIgnoreCase("back"))
{
// back
doBack(data);
}
else if (option.equalsIgnoreCase("cancel"))
{
// cancel
doCancel_create(data);
}
} // doAdd_features
/**
* update the selected tool list
* @param params The ParameterParser object
* @param verifyData Need to verify input data or not
*/
private void updateSelectedToolList (SessionState state, ParameterParser params, boolean verifyData)
{
List selectedTools = new ArrayList(Arrays.asList(params.getStrings ("selectedTools")));
Hashtable titles = (Hashtable) state.getAttribute(STATE_NEWS_TITLES);
Hashtable urls = (Hashtable) state.getAttribute(STATE_NEWS_URLS);
Hashtable wcTitles = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES);
Hashtable wcUrls = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_URLS);
boolean has_home = false;
String emailId = null;
for (int i = 0; i < selectedTools.size(); i++)
{
String id = (String) selectedTools.get(i);
if (id.indexOf("sakai.news") != -1)
{
String title = StringUtil.trimToNull(params.getString("titlefor" + id));
if (title == null)
{
// if there is no input, make the title for news tool default to NEWS_DEFAULT_TITLE
title = NEWS_DEFAULT_TITLE;
}
titles.put(id, title);
String url = StringUtil.trimToNull(params.getString("urlfor" + id));
if (url == null)
{
// if there is no input, make the title for news tool default to NEWS_DEFAULT_URL
url = NEWS_DEFAULT_URL;
}
urls.put(id, url);
try
{
new URL(url);
}
catch (MalformedURLException e)
{
addAlert(state, rb.getString("java.invurl")+" " + url + ". ");
}
}
else if (id.indexOf("sakai.iframe") != -1)
{
String wcTitle = StringUtil.trimToNull(params.getString("titlefor" + id));
if (wcTitle == null)
{
// if there is no input, make the title for Web Content tool default to WEB_CONTENT_DEFAULT_TITLE
wcTitle = WEB_CONTENT_DEFAULT_TITLE;
}
wcTitles.put(id, wcTitle);
String wcUrl = StringUtil.trimToNull(params.getString("urlfor" + id));
if (wcUrl == null)
{
// if there is no input, make the title for Web Content tool default to WEB_CONTENT_DEFAULT_URL
wcUrl = WEB_CONTENT_DEFAULT_URL;
}
else
{
if ((wcUrl.length() > 0) && (!wcUrl.startsWith("/")) && (wcUrl.indexOf("://") == -1))
{
wcUrl = "http://" + wcUrl;
}
}
wcUrls.put(id, wcUrl);
}
else if (id.equalsIgnoreCase(HOME_TOOL_ID))
{
has_home = true;
}
else if (id.equalsIgnoreCase("sakai.mailbox"))
{
// if Email archive tool is selected, check the email alias
emailId = StringUtil.trimToNull(params.getString("emailId"));
if(verifyData)
{
if (emailId == null)
{
addAlert(state, rb.getString("java.emailarchive")+" ");
}
else
{
if (!Validator.checkEmailLocal(emailId))
{
addAlert(state, rb.getString("java.theemail"));
}
else
{
//check to see whether the alias has been used by other sites
try
{
String target = AliasService.getTarget(emailId);
if (target != null)
{
if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null)
{
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
String channelReference = mailArchiveChannelReference(siteId);
if (!target.equals(channelReference))
{
// the email alias is not used by current site
addAlert(state, rb.getString("java.emailinuse")+" ");
}
}
else
{
addAlert(state, rb.getString("java.emailinuse")+" ");
}
}
}
catch (IdUnusedException ee){}
}
}
}
}
}
state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(has_home));
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, emailId);
state.setAttribute(STATE_NEWS_TITLES, titles);
state.setAttribute(STATE_NEWS_URLS, urls);
state.setAttribute(STATE_WEB_CONTENT_TITLES, wcTitles);
state.setAttribute(STATE_WEB_CONTENT_URLS, wcUrls);
} // updateSelectedToolList
/**
* find the tool in the tool list and insert another tool instance to the list
* @param state SessionState object
* @param toolId The id for the inserted tool
* @param stateTitlesVariable The titles
* @param defaultTitle The default title for the inserted tool
* @param stateUrlsVariable The urls
* @param defaultUrl The default url for the inserted tool
* @param insertTimes How many tools need to be inserted
*/
private void insertTool(SessionState state, String toolId, String stateTitlesVariable, String defaultTitle, String stateUrlsVariable, String defaultUrl, int insertTimes)
{
//the list of available tools
List toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
int toolListedTimes = 0;
int index = 0;
int insertIndex = 0;
while ( index < toolList.size())
{
MyTool tListed = (MyTool) toolList.get(index);
if (tListed.getId().indexOf(toolId) != -1 )
{
toolListedTimes++;
}
if (toolListedTimes > 0 && insertIndex == 0)
{
// update the insert index
insertIndex = index;
}
index ++;
}
List toolSelected = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// the titles
Hashtable titles = (Hashtable) state.getAttribute(stateTitlesVariable);
if (titles == null)
{
titles = new Hashtable();
}
// the urls
Hashtable urls = (Hashtable) state.getAttribute(stateUrlsVariable);
if (urls == null)
{
urls = new Hashtable();
}
// insert multiple tools
for (int i = 0; i < insertTimes; i++)
{
toolListedTimes = toolListedTimes + i;
toolSelected.add(toolId + toolListedTimes);
// We need to insert a specific tool entry only if all the specific tool entries have been selected
MyTool newTool = new MyTool();
newTool.title = defaultTitle;
newTool.id = toolId + toolListedTimes;
toolList.add(insertIndex, newTool);
titles.put(newTool.id, defaultTitle);
urls.put(newTool.id, defaultUrl);
}
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolList);
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolSelected);
state.setAttribute(stateTitlesVariable, titles);
state.setAttribute(stateUrlsVariable, urls);
} // insertTool
/**
*
* set selected participant role Hashtable
*/
private void setSelectedParticipantRoles(SessionState state)
{
List selectedUserIds = (List) state.getAttribute(STATE_SELECTED_USER_LIST);
List participantList = (List) state.getAttribute(STATE_PARTICIPANT_LIST);
List selectedParticipantList = new Vector();
Hashtable selectedParticipantRoles = new Hashtable();
if(!selectedUserIds.isEmpty() && participantList != null)
{
for (int i = 0; i < participantList.size(); i++)
{
String id= "";
Object o = (Object) participantList.get(i);
if (o.getClass().equals(Participant.class))
{
// get participant roles
id = ((Participant) o).getUniqname();
selectedParticipantRoles.put(id, ((Participant) o).getRole());
}
else if (o.getClass().equals(Student.class))
{
// get participant from roster role
id = ((Student) o).getUniqname();
selectedParticipantRoles.put(id, ((Student)o).getRole());
}
if (selectedUserIds.contains(id))
{
selectedParticipantList.add(participantList.get(i));
}
}
}
state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, selectedParticipantRoles);
state.setAttribute(STATE_SELECTED_PARTICIPANTS, selectedParticipantList);
} // setSelectedParticipantRoles
/**
* the SiteComparator class
*/
private class SiteComparator
implements Comparator
{
/**
* the criteria
*/
String m_criterion = null;
String m_asc = null;
/**
* constructor
* @param criteria The sort criteria string
* @param asc The sort order string. TRUE_STRING if ascending; "false" otherwise.
*/
public SiteComparator (String criterion, String asc)
{
m_criterion = criterion;
m_asc = asc;
} // constructor
/**
* implementing the Comparator compare function
* @param o1 The first object
* @param o2 The second object
* @return The compare result. 1 is o1 < o2; -1 otherwise
*/
public int compare ( Object o1, Object o2)
{
int result = -1;
if(m_criterion==null) m_criterion = SORTED_BY_TITLE;
/************* for sorting site list *******************/
if (m_criterion.equals (SORTED_BY_TITLE))
{
// sorted by the worksite title
String s1 = ((Site) o1).getTitle();
String s2 = ((Site) o2).getTitle();
result = compareString(s1, s2);
}
else if (m_criterion.equals (SORTED_BY_DESCRIPTION))
{
// sorted by the site short description
String s1 = ((Site) o1).getShortDescription();
String s2 = ((Site) o2).getShortDescription();
result = compareString(s1, s2);
}
else if (m_criterion.equals (SORTED_BY_TYPE))
{
// sorted by the site type
String s1 = ((Site) o1).getType();
String s2 = ((Site) o2).getType();
result = compareString(s1, s2);
}
else if (m_criterion.equals (SortType.CREATED_BY_ASC.toString()))
{
// sorted by the site creator
String s1 = ((Site) o1).getProperties().getProperty("CHEF:creator");
String s2 = ((Site) o2).getProperties().getProperty("CHEF:creator");
result = compareString(s1, s2);
}
else if (m_criterion.equals (SORTED_BY_STATUS))
{
// sort by the status, published or unpublished
int i1 = ((Site)o1).isPublished() ? 1 : 0;
int i2 = ((Site)o2).isPublished() ? 1 : 0;
if (i1 > i2)
{
result = 1;
}
else
{
result = -1;
}
}
else if (m_criterion.equals (SORTED_BY_JOINABLE))
{
// sort by whether the site is joinable or not
boolean b1 = ((Site)o1).isJoinable();
boolean b2 = ((Site)o2).isJoinable();
if (b1 == b2)
{
result = 0;
}
else if (b1 == true)
{
result = 1;
}
else
{
result = -1;
}
}
else if (m_criterion.equals (SORTED_BY_PARTICIPANT_NAME))
{
// sort by whether the site is joinable or not
String s1 = null;
if (o1.getClass().equals(Participant.class))
{
s1 = ((Participant) o1).getName();
}
String s2 = null;
if (o2.getClass().equals(Participant.class))
{
s2 = ((Participant) o2).getName();
}
result = compareString(s1, s2);
}
else if (m_criterion.equals (SORTED_BY_PARTICIPANT_UNIQNAME))
{
// sort by whether the site is joinable or not
String s1 = null;
if (o1.getClass().equals(Participant.class))
{
s1 = ((Participant) o1).getUniqname();
}
String s2 = null;
if (o2.getClass().equals(Participant.class))
{
s2 = ((Participant) o2).getUniqname();
}
result = compareString(s1, s2);
}
else if (m_criterion.equals (SORTED_BY_PARTICIPANT_ROLE))
{
String s1 = "";
if (o1.getClass().equals(Participant.class))
{
s1 = ((Participant) o1).getRole();
}
String s2 = "";
if (o2.getClass().equals(Participant.class))
{
s2 = ((Participant) o2).getRole();
}
result = compareString(s1, s2);
}
else if (m_criterion.equals (SORTED_BY_PARTICIPANT_COURSE))
{
// sort by whether the site is joinable or not
String s1 = null;
if (o1.getClass().equals(Participant.class))
{
s1 = ((Participant) o1).getCourse();
}
String s2 = null;
if (o2.getClass().equals(Participant.class))
{
s2 = ((Participant) o2).getCourse();
}
result = compareString(s1, s2);
}
else if (m_criterion.equals (SORTED_BY_PARTICIPANT_ID))
{
String s1 = null;
if (o1.getClass().equals(Participant.class))
{
s1 = ((Participant) o1).getRegId();
}
String s2 = null;
if (o2.getClass().equals(Participant.class))
{
s2 = ((Participant) o2).getRegId();
}
result = compareString(s1, s2);
}
else if (m_criterion.equals (SORTED_BY_PARTICIPANT_CREDITS))
{
String s1 = null;
if (o1.getClass().equals(Participant.class))
{
s1 = ((Participant) o1).getCredits();
}
String s2 = null;
if (o2.getClass().equals(Participant.class))
{
s2 = ((Participant) o2).getCredits();
}
result = compareString(s1, s2);
}
else if (m_criterion.equals (SORTED_BY_CREATION_DATE))
{
// sort by the site's creation date
Time t1 = null;
Time t2 = null;
// get the times
try
{
t1 = ((Site)o1).getProperties().getTimeProperty(ResourceProperties.PROP_CREATION_DATE);
}
catch (EntityPropertyNotDefinedException e)
{
}
catch (EntityPropertyTypeException e)
{
}
try
{
t2 = ((Site)o2).getProperties().getTimeProperty(ResourceProperties.PROP_CREATION_DATE);
}
catch (EntityPropertyNotDefinedException e)
{
}
catch (EntityPropertyTypeException e)
{
}
if (t1==null)
{
result = -1;
}
else if (t2==null)
{
result = 1;
}
else if (t1.before (t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criterion.equals (rb.getString("group.title")))
{
// sorted by the group title
String s1 = ((Group) o1).getTitle();
String s2 = ((Group) o2).getTitle();
result = compareString(s1, s2);
}
else if (m_criterion.equals (rb.getString("group.number")))
{
// sorted by the group title
int n1 = ((Group) o1).getMembers().size();
int n2 = ((Group) o2).getMembers().size();
result = (n1 > n2)?1:-1;
}
else if (m_criterion.equals (SORTED_BY_MEMBER_NAME))
{
// sorted by the member name
String s1 = null;
String s2 = null;
try
{
s1 = UserDirectoryService.getUser(((Member) o1).getUserId()).getSortName();
}
catch(Exception ignore)
{
}
try
{
s2 = UserDirectoryService.getUser(((Member) o2).getUserId()).getSortName();
}
catch (Exception ignore)
{
}
result = compareString(s1, s2);
}
if(m_asc == null) m_asc = Boolean.TRUE.toString ();
// sort ascending or descending
if (m_asc.equals (Boolean.FALSE.toString ()))
{
result = -result;
}
return result;
} // compare
private int compareString(String s1, String s2) {
int result;
if (s1==null && s2==null)
{
result = 0;
}
else if (s2==null)
{
result = 1;
}
else if (s1==null)
{
result = -1;
}
else
{
result = s1.compareToIgnoreCase (s2);
}
return result;
}
} //SiteComparator
private class ToolComparator
implements Comparator
{
/**
* implementing the Comparator compare function
* @param o1 The first object
* @param o2 The second object
* @return The compare result. 1 is o1 < o2; 0 is o1.equals(o2); -1 otherwise
*/
public int compare ( Object o1, Object o2)
{
try
{
return ((Tool) o1).getTitle().compareTo(((Tool) o2).getTitle());
}
catch (Exception e)
{
}
return -1;
} // compare
} //ToolComparator
public class Icon
{
protected String m_name = null;
protected String m_url = null;
protected String m_skin = null;
public Icon(String name, String url, String skin)
{
m_name = name;
m_url = url;
m_skin = skin;
}
public String getName() { return m_name; }
public String getUrl() { return m_url; }
public String getSkin() { return m_skin; }
}
// a utility class for form select options
public class IdAndText
{
public int id;
public String text;
public int getId() { return id;}
public String getText() { return text;}
} // IdAndText
// a utility class for working with ToolConfigurations and ToolRegistrations
// %%% convert featureList from IdAndText to Tool so getFeatures item.id = chosen-feature.id is a direct mapping of data
public class MyTool
{
public String id = NULL_STRING;
public String title = NULL_STRING;
public String description = NULL_STRING;
public boolean selected = false;
public String getId() { return id; }
public String getTitle() { return title; }
public String getDescription() { return description; }
public boolean getSelected() { return selected; }
}
/*
* WorksiteSetupPage is a utility class for working with site pages configured by Worksite Setup
*
*/
public class WorksiteSetupPage
{
public String pageId = NULL_STRING;
public String pageTitle = NULL_STRING;
public String toolId = NULL_STRING;
public String getPageId() { return pageId; }
public String getPageTitle() { return pageTitle; }
public String getToolId() { return toolId; }
} // WorksiteSetupPage
/**
* Participant in site access roles
*
*/
public class Participant
{
public String name = NULL_STRING;
// Note: uniqname is really a user ID
public String uniqname = NULL_STRING;
public String role = NULL_STRING;
/** role from provider */
public String providerRole = NULL_STRING;
/** The member credits */
protected String credits = NULL_STRING;
/** The course */
public String course = NULL_STRING;
/** The section */
public String section = NULL_STRING;
/** The regestration id */
public String regId = NULL_STRING;
/** removeable if not from provider */
public boolean removeable = true;
public String getName() {return name; }
public String getUniqname() {return uniqname; }
public String getRole() { return role; } // cast to Role
public String getProviderRole() { return providerRole; }
public boolean isRemoveable(){return removeable;}
// extra info from provider
public String getCredits(){return credits;} // getCredits
public String getCourse(){return course;} // getCourse
public String getSection(){return section;} // getSection
public String getRegId(){return regId;} // getRegId
/**
* Access the user eid, if we can find it - fall back to the id if not.
* @return The user eid.
*/
public String getEid()
{
try
{
return UserDirectoryService.getUserEid(uniqname);
}
catch (UserNotDefinedException e)
{
return uniqname;
}
}
/**
* Access the user display id, if we can find it - fall back to the id if not.
* @return The user display id.
*/
public String getDisplayId()
{
try
{
User user = UserDirectoryService.getUser(uniqname);
return user.getDisplayId();
}
catch (UserNotDefinedException e)
{
return uniqname;
}
}
} // Participant
/**
* Student in roster
*
*/
public class Student
{
public String name = NULL_STRING;
public String uniqname = NULL_STRING;
public String id = NULL_STRING;
public String level = NULL_STRING;
public String credits = NULL_STRING;
public String role = NULL_STRING;
public String course = NULL_STRING;
public String section = NULL_STRING;
public String getName() {return name; }
public String getUniqname() {return uniqname; }
public String getId() { return id; }
public String getLevel() { return level; }
public String getCredits() { return credits; }
public String getRole() { return role; }
public String getCourse() { return course; }
public String getSection() { return section; }
} // Student
public class SiteInfo
{
public String site_id = NULL_STRING; // getId of Resource
public String external_id = NULL_STRING; // if matches site_id connects site with U-M course information
public String site_type = "";
public String iconUrl = NULL_STRING;
public String infoUrl = NULL_STRING;
public boolean joinable = false;
public String joinerRole = NULL_STRING;
public String title = NULL_STRING; // the short name of the site
public String short_description = NULL_STRING; // the short (20 char) description of the site
public String description = NULL_STRING; // the longer description of the site
public String additional = NULL_STRING; // additional information on crosslists, etc.
public boolean published = false;
public boolean include = true; // include the site in the Sites index; default is true.
public String site_contact_name = NULL_STRING; // site contact name
public String site_contact_email = NULL_STRING; // site contact email
public String getSiteId() {return site_id;}
public String getSiteType() { return site_type; }
public String getTitle() { return title; }
public String getDescription() { return description; }
public String getIconUrl() { return iconUrl; }
public String getInfoUrll() { return infoUrl; }
public boolean getJoinable() {return joinable; }
public String getJoinerRole() {return joinerRole; }
public String getAdditional() { return additional; }
public boolean getPublished() { return published; }
public boolean getInclude() {return include;}
public String getSiteContactName() {return site_contact_name; }
public String getSiteContactEmail() {return site_contact_email; }
} // SiteInfo
//dissertation tool related
/**
* doFinish_grad_tools is called when creation of a Grad Tools site is confirmed
*/
public void doFinish_grad_tools ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
//set up for the coming template
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString ("continue"));
int index = Integer.valueOf(params.getString ("template-index")).intValue();
actionForTemplate("continue", index, params, state);
//add the pre-configured Grad Tools tools to a new site
addGradToolsFeatures(state);
// TODO: hard coding this frame id is fragile, portal dependent, and needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
resetPaging(state);
}// doFinish_grad_tools
/**
* addGradToolsFeatures adds features to a new Grad Tools student site
*
*/
private void addGradToolsFeatures(SessionState state)
{
Site edit = null;
Site template = null;
//get a unique id
String id = IdManager.createUuid();
//get the Grad Tools student site template
try
{
template = SiteService.getSite(SITE_GTS_TEMPLATE);
}
catch (Exception e)
{
if(Log.isWarnEnabled())
M_log.warn("addGradToolsFeatures template " + e);
}
if(template != null)
{
//create a new site based on the template
try
{
edit = SiteService.addSite(id, template);
}
catch(Exception e)
{
if(Log.isWarnEnabled())
M_log.warn("addGradToolsFeatures add/edit site " + e);
}
//set the tab, etc.
if(edit != null)
{
SiteInfo siteInfo = (SiteInfo)state.getAttribute(STATE_SITE_INFO);
edit.setShortDescription(siteInfo.short_description);
edit.setTitle(siteInfo.title);
edit.setPublished(true);
edit.setPubView(false);
edit.setType(SITE_TYPE_GRADTOOLS_STUDENT);
//ResourcePropertiesEdit rpe = edit.getPropertiesEdit();
try
{
SiteService.save(edit);
}
catch(Exception e)
{
if(Log.isWarnEnabled())
M_log.warn("addGradToolsFeartures commitEdit " + e);
}
//now that the site and realm exist, we can set the email alias
//set the GradToolsStudent site alias as: gradtools-uniqname@servername
String alias = "gradtools-" + SessionManager.getCurrentSessionUserId();
String channelReference = mailArchiveChannelReference(id);
try
{
AliasService.setAlias(alias, channelReference);
}
catch (IdUsedException ee)
{
addAlert(state, rb.getString("java.alias")+" " + alias + " "+rb.getString("java.exists"));
}
catch (IdInvalidException ee)
{
addAlert(state, rb.getString("java.alias")+" " + alias + " "+rb.getString("java.isinval"));
}
catch (PermissionException ee)
{
M_log.warn(SessionManager.getCurrentSessionUserId() + " does not have permission to add alias. ");
}
}
}
} // addGradToolsFeatures
/**
* handle with add site options
*
*/
public void doAdd_site_option ( RunData data )
{
String option = data.getParameters().getString("option");
if (option.equals("finish"))
{
doFinish(data);
}
else if (option.equals("cancel"))
{
doCancel_create(data);
}
else if (option.equals("back"))
{
doBack(data);
}
} // doAdd_site_option
/**
* handle with duplicate site options
*
*/
public void doDuplicate_site_option ( RunData data )
{
String option = data.getParameters().getString("option");
if (option.equals("duplicate"))
{
doContinue(data);
}
else if (option.equals("cancel"))
{
doCancel(data);
}
else if (option.equals("finish"))
{
doContinue(data);
}
} // doDuplicate_site_option
/**
* Special check against the Dissertation service, which might not be here...
* @return
*/
protected boolean isGradToolsCandidate(String userId)
{
// DissertationService.isCandidate(userId) - but the hard way
Object service = ComponentManager.get("org.sakaiproject.api.app.dissertation.DissertationService");
if (service == null) return false;
// the method signature
Class[] signature = new Class[1];
signature[0] = String.class;
// the method name
String methodName = "isCandidate";
// find a method of this class with this name and signature
try
{
Method method = service.getClass().getMethod(methodName, signature);
// the parameters
Object[] args = new Object[1];
args[0] = userId;
// make the call
Boolean rv = (Boolean) method.invoke(service, args);
return rv.booleanValue();
}
catch (Throwable t)
{
}
return false;
}
/**
* User has a Grad Tools student site
* @return
*/
protected boolean hasGradToolsStudentSite(String userId)
{
boolean has = false;
int n = 0;
try
{
n = SiteService.countSites(org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
SITE_TYPE_GRADTOOLS_STUDENT, null, null);
if(n > 0)
has = true;
}
catch(Exception e)
{
if(Log.isWarnEnabled())
M_log.warn("hasGradToolsStudentSite " + e);
}
return has;
}//hasGradToolsStudentSite
/**
* Get the mail archive channel reference for the main container placement for this site.
* @param siteId The site id.
* @return The mail archive channel reference for this site.
*/
protected String mailArchiveChannelReference(String siteId)
{
MailArchiveService m = (org.sakaiproject.mailarchive.api.MailArchiveService) ComponentManager.get("org.sakaiproject.mailarchive.api.MailArchiveService");
if (m != null)
{
return m.channelReference(siteId, SiteService.MAIN_CONTAINER);
}
else
{
return "";
}
}
/**
* Transfer a copy of all entites from another context for any entity producer that claims this tool id.
*
* @param toolId
* The tool id.
* @param fromContext
* The context to import from.
* @param toContext
* The context to import into.
*/
protected void transferCopyEntities(String toolId, String fromContext, String toContext)
{
// TODO: used to offer to resources first - why? still needed? -ggolden
// offer to all EntityProducers
for (Iterator i = EntityManager.getEntityProducers().iterator(); i.hasNext();)
{
EntityProducer ep = (EntityProducer) i.next();
if (ep instanceof EntityTransferrer)
{
try
{
EntityTransferrer et = (EntityTransferrer) ep;
// if this producer claims this tool id
if (ArrayUtil.contains(et.myToolIds(), toolId))
{
et.transferCopyEntities(fromContext, toContext, new Vector());
}
}
catch (Throwable t)
{
M_log.warn("Error encountered while asking EntityTransfer to transferCopyEntities from: " + fromContext
+ " to: " + toContext, t);
}
}
}
}
/**
* @return Get a list of all tools that support the import (transfer copy) option
*/
protected Set importTools()
{
HashSet rv = new HashSet();
// offer to all EntityProducers
for (Iterator i = EntityManager.getEntityProducers().iterator(); i.hasNext();)
{
EntityProducer ep = (EntityProducer) i.next();
if (ep instanceof EntityTransferrer)
{
EntityTransferrer et = (EntityTransferrer) ep;
String[] tools = et.myToolIds();
if (tools != null)
{
for (int t = 0; t < tools.length; t++)
{
rv.add(tools[t]);
}
}
}
}
return rv;
}
/**
* @param state
* @return Get a list of all tools that should be included as options for import
*/
protected List getToolsAvailableForImport(SessionState state)
{
// The Web Content and News tools do not follow the standard rules for import
// Even if the current site does not contain the tool, News and WC will be
// an option if the imported site contains it
boolean displayWebContent = false;
boolean displayNews = false;
Set importSites = ((Hashtable)state.getAttribute(STATE_IMPORT_SITES)).keySet();
Iterator sitesIter = importSites.iterator();
while (sitesIter.hasNext())
{
Site site = (Site)sitesIter.next();
if (site.getToolForCommonId("sakai.iframe") != null)
displayWebContent = true;
if (site.getToolForCommonId("sakai.news") != null)
displayNews = true;
}
List toolsOnImportList = (List)state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
if (displayWebContent && !toolsOnImportList.contains("sakai.iframe"))
toolsOnImportList.add("sakai.iframe");
if (displayNews && !toolsOnImportList.contains("sakai.news"))
toolsOnImportList.add("sakai.news");
return toolsOnImportList;
}
}
| true | true | private String buildContextForTemplate (int index, VelocityPortlet portlet,
Context context,
RunData data,
SessionState state)
{
String realmId = "";
String site_type = "";
String sortedBy = "";
String sortedAsc = "";
ParameterParser params = data.getParameters ();
context.put("tlang",rb);
context.put("alertMessage", state.getAttribute(STATE_MESSAGE));
// If cleanState() has removed SiteInfo, get a new instance into state
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null)
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
else
{
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
// Lists used in more than one template
// Access
List roles = new Vector();
// the hashtables for News and Web Content tools
Hashtable newsTitles = new Hashtable();
Hashtable newsUrls = new Hashtable();
Hashtable wcTitles = new Hashtable();
Hashtable wcUrls = new Hashtable();
List toolRegistrationList = new Vector();
List toolRegistrationSelectedList = new Vector();
ResourceProperties siteProperties = null;
// for showing site creation steps
if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) != null)
{
context.put("totalSteps", state.getAttribute(SITE_CREATE_TOTAL_STEPS));
}
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null)
{
context.put("step", state.getAttribute(SITE_CREATE_CURRENT_STEP));
}
String hasGradSites = ServerConfigurationService.getString("withDissertation", Boolean.FALSE.toString());
Site site = getStateSite(state);
switch (index)
{
case 0:
/* buildContextForTemplate chef_site-list.vm
*
*/
// site types
List sTypes = (List) state.getAttribute(STATE_SITE_TYPES);
//make sure auto-updates are enabled
Hashtable views = new Hashtable();
if (SecurityService.isSuperUser())
{
views.put(rb.getString("java.allmy"), rb.getString("java.allmy"));
views.put(rb.getString("java.my") + " " + rb.getString("java.sites"), rb.getString("java.my"));
for(int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++)
{
String type = (String) sTypes.get(sTypeIndex);
views.put(type + " " + rb.getString("java.sites"), type);
}
if (hasGradSites.equalsIgnoreCase("true"))
{
views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb.getString("java.gradtools"));
}
if(state.getAttribute(STATE_VIEW_SELECTED) == null)
{
state.setAttribute(STATE_VIEW_SELECTED, rb.getString("java.allmy"));
}
context.put("superUser", Boolean.TRUE);
}
else
{
context.put("superUser", Boolean.FALSE);
views.put(rb.getString("java.allmy"), rb.getString("java.allmy"));
// if there is a GradToolsStudent choice inside
boolean remove = false;
if (hasGradSites.equalsIgnoreCase("true"))
{
try
{
//the Grad Tools site option is only presented to GradTools Candidates
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
//am I a grad student?
if (!isGradToolsCandidate(userId))
{
// not a gradstudent
remove = true;
}
}
catch(Exception e)
{
remove = true;
}
}
else
{
// not support for dissertation sites
remove=true;
}
//do not show this site type in views
//sTypes.remove(new String(SITE_TYPE_GRADTOOLS_STUDENT));
for(int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++)
{
String type = (String) sTypes.get(sTypeIndex);
if(!type.equals(SITE_TYPE_GRADTOOLS_STUDENT))
{
views.put(type + " "+rb.getString("java.sites"), type);
}
}
if (!remove)
{
views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb.getString("java.gradtools"));
}
//default view
if(state.getAttribute(STATE_VIEW_SELECTED) == null)
{
state.setAttribute(STATE_VIEW_SELECTED, rb.getString("java.allmy"));
}
}
context.put("views", views);
if(state.getAttribute(STATE_VIEW_SELECTED) != null)
{
context.put("viewSelected", (String) state.getAttribute(STATE_VIEW_SELECTED));
}
String search = (String) state.getAttribute(STATE_SEARCH);
context.put("search_term", search);
sortedBy = (String) state.getAttribute (SORTED_BY);
if (sortedBy == null)
{
state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString());
sortedBy = SortType.TITLE_ASC.toString();
}
sortedAsc = (String) state.getAttribute (SORTED_ASC);
if (sortedAsc == null)
{
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if(sortedBy!=null) context.put ("currentSortedBy", sortedBy);
if(sortedAsc!=null) context.put ("currentSortAsc", sortedAsc);
String portalUrl = ServerConfigurationService.getPortalUrl();
context.put("portalUrl", portalUrl);
List sites = prepPage(state);
state.setAttribute(STATE_SITES, sites);
context.put("sites", sites);
context.put("totalPageNumber", new Integer(totalPageNumber(state)));
context.put("searchString", state.getAttribute(STATE_SEARCH));
context.put("form_search", FORM_SEARCH);
context.put("formPageNumber", FORM_PAGE_NUMBER);
context.put("prev_page_exists", state.getAttribute(STATE_PREV_PAGE_EXISTS));
context.put("next_page_exists", state.getAttribute(STATE_NEXT_PAGE_EXISTS));
context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE));
// put the service in the context (used for allow update calls on each site)
context.put("service", SiteService.getInstance());
context.put("sortby_title", SortType.TITLE_ASC.toString());
context.put("sortby_type", SortType.TYPE_ASC.toString());
context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString());
context.put("sortby_publish", SortType.PUBLISHED_ASC.toString());
context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString());
// top menu bar
Menu bar = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null))
{
bar.add( new MenuEntry(rb.getString("java.new"), "doNew_site"));
}
bar.add( new MenuEntry(rb.getString("java.revise"), null, true, MenuItem.CHECKED_NA, "doGet_site", "sitesForm"));
bar.add( new MenuEntry(rb.getString("java.delete"), null, true, MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm"));
context.put("menu", bar);
// default to be no pageing
context.put("paged", Boolean.FALSE);
Menu bar2 = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
// add the search commands
addSearchMenus(bar2, state);
context.put("menu2", bar2);
pagingInfoToContext(state, context);
return (String)getContext(data).get("template") + TEMPLATE[0];
case 1:
/* buildContextForTemplate chef_site-type.vm
*
*/
if (hasGradSites.equalsIgnoreCase("true"))
{
context.put("withDissertation", Boolean.TRUE);
try
{
//the Grad Tools site option is only presented to UM grad students
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
//am I a UM grad student?
Boolean isGradStudent = new Boolean(isGradToolsCandidate(userId));
context.put("isGradStudent", isGradStudent);
//if I am a UM grad student, do I already have a Grad Tools site?
boolean noGradToolsSite = true;
if(hasGradToolsStudentSite(userId))
noGradToolsSite = false;
context.put("noGradToolsSite", new Boolean(noGradToolsSite));
}
catch(Exception e)
{
if(Log.isWarnEnabled())
{
M_log.warn("buildContextForTemplate chef_site-type.vm " + e);
}
}
}
else
{
context.put("withDissertation", Boolean.FALSE);
}
List types = (List) state.getAttribute(STATE_SITE_TYPES);
context.put("siteTypes", types);
// put selected/default site type into context
if (siteInfo.site_type != null && siteInfo.site_type.length() >0)
{
context.put("typeSelected", siteInfo.site_type);
}
else if (types.size() > 0)
{
context.put("typeSelected", types.get(0));
}
List termsForSiteCreation = getAvailableTerms();
if (termsForSiteCreation.size() > 0)
{
context.put("termList", termsForSiteCreation);
}
if (state.getAttribute(STATE_TERM_SELECTED) != null)
{
context.put("selectedTerm", state.getAttribute(STATE_TERM_SELECTED));
}
return (String)getContext(data).get("template") + TEMPLATE[1];
case 2:
/* buildContextForTemplate chef_site-newSiteInformation.vm
*
*/
context.put("siteTypes", state.getAttribute(STATE_SITE_TYPES));
String siteType = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("titleEditableSiteType", state.getAttribute(TITLE_EDITABLE_SITE_TYPE));
context.put("type", siteType);
if (siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
context.put ("selectedProviderCourse", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
int number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
context.put ("manualAddNumber", new Integer(number - 1));
context.put ("manualAddFields", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("back", "37");
}
else
{
context.put("back", "36");
}
context.put ("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null)
{
context.put("selectedIcon", siteInfo.getIconUrl());
}
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null)
{
context.put(FORM_ICON_URL, siteInfo.iconUrl);
}
context.put ("back", "1");
}
context.put (FORM_TITLE,siteInfo.title);
context.put(FORM_SHORT_DESCRIPTION, siteInfo.short_description);
context.put (FORM_DESCRIPTION,siteInfo.description);
// defalt the site contact person to the site creator
if (siteInfo.site_contact_name.equals(NULL_STRING) && siteInfo.site_contact_email.equals(NULL_STRING))
{
User user = UserDirectoryService.getCurrentUser();
siteInfo.site_contact_name = user.getDisplayName();
siteInfo.site_contact_email = user.getEmail();
}
context.put("form_site_contact_name", siteInfo.site_contact_name);
context.put("form_site_contact_email", siteInfo.site_contact_email);
// those manual inputs
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String)getContext(data).get("template") + TEMPLATE[2];
case 3:
/* buildContextForTemplate chef_site-newSiteFeatures.vm
*
*/
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType!=null && siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
}
context.put("defaultTools", ServerConfigurationService.getToolsRequired(siteType));
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// If this is the first time through, check for tools
// which should be selected by default.
List defaultSelectedTools = ServerConfigurationService.getDefaultTools(siteType);
if (toolRegistrationSelectedList == null) {
toolRegistrationSelectedList = new Vector(defaultSelectedTools);
}
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST) ); // %%% use ToolRegistrations for template list
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService.getServerName());
// The "Home" tool checkbox needs special treatment to be selected by
// default.
Boolean checkHome = (Boolean)state.getAttribute(STATE_TOOL_HOME_SELECTED);
if (checkHome == null) {
if ((defaultSelectedTools != null) && defaultSelectedTools.contains(HOME_TOOL_ID)) {
checkHome = Boolean.TRUE;
}
}
context.put("check_home", checkHome);
//titles for news tools
context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES));
//titles for web content tools
context.put("wcTitles", state.getAttribute(STATE_WEB_CONTENT_TITLES));
//urls for news tools
context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS));
//urls for web content tools
context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS));
context.put("sites", SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null));
context.put("import", state.getAttribute(STATE_IMPORT));
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
return (String)getContext(data).get("template") + TEMPLATE[3];
case 4:
/* buildContextForTemplate chef_site-addRemoveFeatures.vm
*
*/
context.put("SiteTitle", site.getTitle());
String type = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("defaultTools", ServerConfigurationService.getToolsRequired(type));
boolean myworkspace_site = false;
//Put up tool lists filtered by category
List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES);
if (siteTypes.contains(type))
{
myworkspace_site = false;
}
if (SiteService.isUserSite(site.getId()) || (type!=null && type.equalsIgnoreCase("myworkspace")))
{
myworkspace_site = true;
type="myworkspace";
}
context.put ("myworkspace_site", new Boolean(myworkspace_site));
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST));
//titles for news tools
context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES));
//titles for web content tools
context.put("wcTitles", state.getAttribute(STATE_WEB_CONTENT_TITLES));
//urls for news tools
context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS));
//urls for web content tools
context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS));
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
//get the email alias when an Email Archive tool has been selected
String channelReference = mailArchiveChannelReference(site.getId());
List aliases = AliasService.getAliases(channelReference, 1, 1);
if (aliases.size() > 0)
{
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases.get(0)).getId());
}
else
{
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
}
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null)
{
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService.getServerName());
context.put("backIndex", "12");
return (String)getContext(data).get("template") + TEMPLATE[4];
case 5:
/* buildContextForTemplate chef_site-addParticipant.vm
*
*/
context.put("title", site.getTitle());
roles = getRoles(state);
context.put("roles", roles);
// Note that (for now) these strings are in both sakai.properties and sitesetupgeneric.properties
context.put("noEmailInIdAccountName", ServerConfigurationService.getString("noEmailInIdAccountName"));
context.put("noEmailInIdAccountLabel", ServerConfigurationService.getString("noEmailInIdAccountLabel"));
context.put("emailInIdAccountName", ServerConfigurationService.getString("emailInIdAccountName"));
context.put("emailInIdAccountLabel", ServerConfigurationService.getString("emailInIdAccountLabel"));
if(state.getAttribute("noEmailInIdAccountValue")!=null)
{
context.put("noEmailInIdAccountValue", (String)state.getAttribute("noEmailInIdAccountValue"));
}
if(state.getAttribute("emailInIdAccountValue")!=null)
{
context.put("emailInIdAccountValue", (String)state.getAttribute("emailInIdAccountValue"));
}
if(state.getAttribute("form_same_role") != null)
{
context.put("form_same_role", ((Boolean) state.getAttribute("form_same_role")).toString());
}
else
{
context.put("form_same_role", Boolean.TRUE.toString());
}
context.put("backIndex", "12");
return (String)getContext(data).get("template") + TEMPLATE[5];
case 6:
/* buildContextForTemplate chef_site-removeParticipants.vm
*
*/
context.put("title", site.getTitle());
realmId = SiteService.siteReference(site.getId());
try
{
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
try
{
List removeableList = (List) state.getAttribute(STATE_REMOVEABLE_USER_LIST);
List removeableParticipants = new Vector();
for (int k = 0; k < removeableList.size(); k++)
{
User user = UserDirectoryService.getUser((String) removeableList.get(k));
Participant participant = new Participant();
participant.name = user.getSortName();
participant.uniqname = user.getId();
Role r = realm.getUserRole(user.getId());
if (r != null)
{
participant.role = r.getId();
}
removeableParticipants.add(participant);
}
context.put("removeableList", removeableParticipants);
}
catch (UserNotDefinedException ee)
{
}
}
catch (GroupNotDefinedException e)
{
}
context.put("backIndex", "18");
return (String)getContext(data).get("template") + TEMPLATE[6];
case 7:
/* buildContextForTemplate chef_site-changeRoles.vm
*
*/
context.put("same_role", state.getAttribute(STATE_CHANGEROLE_SAMEROLE));
roles = getRoles(state);
context.put("roles", roles);
context.put("currentRole", state.getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE));
context.put("participantSelectedList", state.getAttribute(STATE_SELECTED_PARTICIPANTS));
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("siteTitle", site.getTitle());
return (String)getContext(data).get("template") + TEMPLATE[7];
case 8:
/* buildContextForTemplate chef_site-siteDeleteConfirm.vm
*
*/
String site_title = NULL_STRING;
String[] removals = (String[]) state.getAttribute(STATE_SITE_REMOVALS);
List remove = new Vector();
String user = SessionManager.getCurrentSessionUserId();
String workspace = SiteService.getUserSiteId(user);
if( removals != null && removals.length != 0 )
{
for (int i = 0; i < removals.length; i++ )
{
String id = (String) removals[i];
if(!(id.equals(workspace)))
{
try
{
site_title = SiteService.getSite(id).getTitle();
}
catch (IdUnusedException e)
{
M_log.warn("SiteAction.doSite_delete_confirmed - IdUnusedException " + id);
addAlert(state, rb.getString("java.sitewith")+" " + id + " "+rb.getString("java.couldnt")+" ");
}
if(SiteService.allowRemoveSite(id))
{
try
{
Site removeSite = SiteService.getSite(id);
remove.add(removeSite);
}
catch (IdUnusedException e)
{
M_log.warn("SiteAction.buildContextForTemplate chef_site-siteDeleteConfirm.vm: IdUnusedException");
}
}
else
{
addAlert(state, site_title + " "+rb.getString("java.couldntdel") + " ");
}
}
else
{
addAlert(state, rb.getString("java.yourwork"));
}
}
if(remove.size() == 0)
{
addAlert(state, rb.getString("java.click"));
}
}
context.put("removals", remove);
return (String)getContext(data).get("template") + TEMPLATE[8];
case 9:
/* buildContextForTemplate chef_site-publishUnpublish.vm
*
*/
context.put("publish", Boolean.valueOf(((SiteInfo)state.getAttribute(STATE_SITE_INFO)).getPublished()));
context.put("backIndex", "12");
return (String)getContext(data).get("template") + TEMPLATE[9];
case 10:
/* buildContextForTemplate chef_site-newSiteConfirm.vm
*
*/
siteInfo = (SiteInfo)state.getAttribute(STATE_SITE_INFO);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put ("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
context.put ("selectedProviderCourse", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
int number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
context.put ("manualAddNumber", new Integer(number - 1));
context.put ("manualAddFields", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
context.put ("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null)
{
context.put("selectedIcon", siteInfo.getIconUrl());
}
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType!=null && siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null)
{
context.put("iconUrl", siteInfo.iconUrl);
}
}
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
context.put("siteContactName", siteInfo.site_contact_name);
context.put("siteContactEmail", siteInfo.site_contact_email);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use Tool
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService.getServerName());
context.put("include", new Boolean(siteInfo.include));
context.put("published", new Boolean(siteInfo.published));
context.put("joinable", new Boolean(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
context.put("newsTitles", (Hashtable) state.getAttribute(STATE_NEWS_TITLES));
context.put("wcTitles", (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES));
// back to edit access page
context.put("back", "18");
context.put("importSiteTools", state.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("siteService", SiteService.getInstance());
// those manual inputs
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String)getContext(data).get("template") + TEMPLATE[10];
case 11:
/* buildContextForTemplate chef_site-newSitePublishUnpublish.vm
*
*/
return (String)getContext(data).get("template") + TEMPLATE[11];
case 12:
/* buildContextForTemplate chef_site-siteInfo-list.vm
*
*/
context.put("userDirectoryService", UserDirectoryService.getInstance());
try
{
siteProperties = site.getProperties();
siteType = site.getType();
if (siteType != null)
{
state.setAttribute(STATE_SITE_TYPE, siteType);
}
boolean isMyWorkspace = false;
if (SiteService.isUserSite(site.getId()))
{
if (SiteService.getSiteUserId(site.getId()).equals(SessionManager.getCurrentSessionUserId()))
{
isMyWorkspace = true;
context.put("siteUserId", SiteService.getSiteUserId(site.getId()));
}
}
context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace));
String siteId = site.getId();
if (state.getAttribute(STATE_ICONS)!= null)
{
List skins = (List)state.getAttribute(STATE_ICONS);
for (int i = 0; i < skins.size(); i++)
{
Icon s = (Icon)skins.get(i);
if(!StringUtil.different(s.getUrl(), site.getIconUrl()))
{
context.put("siteUnit", s.getName());
break;
}
}
}
context.put("siteIcon", site.getIconUrl());
context.put("siteTitle", site.getTitle());
context.put("siteDescription", site.getDescription());
context.put("siteJoinable", new Boolean(site.isJoinable()));
if(site.isPublished())
{
context.put("published", Boolean.TRUE);
}
else
{
context.put("published", Boolean.FALSE);
context.put("owner", site.getCreatedBy().getSortName());
}
Time creationTime = site.getCreatedTime();
if (creationTime != null)
{
context.put("siteCreationDate", creationTime.toStringLocalFull());
}
boolean allowUpdateSite = SiteService.allowUpdateSite(siteId);
context.put("allowUpdate", Boolean.valueOf(allowUpdateSite));
boolean allowUpdateGroupMembership = SiteService.allowUpdateGroupMembership(siteId);
context.put("allowUpdateGroupMembership", Boolean.valueOf(allowUpdateGroupMembership));
boolean allowUpdateSiteMembership = SiteService.allowUpdateSiteMembership(siteId);
context.put("allowUpdateSiteMembership", Boolean.valueOf(allowUpdateSiteMembership));
if (allowUpdateSite)
{
// top menu bar
Menu b = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (!isMyWorkspace)
{
b.add( new MenuEntry(rb.getString("java.editsite"), "doMenu_edit_site_info"));
}
b.add( new MenuEntry(rb.getString("java.edittools"), "doMenu_edit_site_tools"));
if (!isMyWorkspace
&& (ServerConfigurationService.getString("wsetup.group.support") == ""
|| ServerConfigurationService.getString("wsetup.group.support").equalsIgnoreCase(Boolean.TRUE.toString())))
{
// show the group toolbar unless configured to not support group
b.add( new MenuEntry(rb.getString("java.group"), "doMenu_group"));
}
if (!isMyWorkspace)
{
List gradToolsSiteTypes = (List) state.getAttribute(GRADTOOLS_SITE_TYPES);
boolean isGradToolSite = false;
if (siteType != null && gradToolsSiteTypes.contains(siteType))
{
isGradToolSite = true;
}
if (siteType == null
|| siteType != null && !isGradToolSite)
{
// hide site access for GRADTOOLS type of sites
b.add( new MenuEntry(rb.getString("java.siteaccess"), "doMenu_edit_site_access"));
}
b.add( new MenuEntry(rb.getString("java.addp"), "doMenu_siteInfo_addParticipant"));
if (siteType != null && siteType.equals("course"))
{
b.add( new MenuEntry(rb.getString("java.editc"), "doMenu_siteInfo_editClass"));
}
if (siteType == null || siteType != null && !isGradToolSite)
{
// hide site duplicate and import for GRADTOOLS type of sites
b.add( new MenuEntry(rb.getString("java.duplicate"), "doMenu_siteInfo_duplicate"));
List updatableSites = SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null);
// import link should be visible even if only one site
if (updatableSites.size() > 0)
{
b.add( new MenuEntry(rb.getString("java.import"), "doMenu_siteInfo_import"));
// a configuration param for showing/hiding import from file choice
String importFromFile = ServerConfigurationService.getString("site.setup.import.file", Boolean.TRUE.toString());
if (importFromFile.equalsIgnoreCase("true"))
{
//htripath: June 4th added as per Kris and changed desc of above
b.add(new MenuEntry(rb.getString("java.importFile"), "doAttachmentsMtrlFrmFile"));
}
}
}
}
// if the page order helper is available, not stealthed and not hidden, show the link
if (ToolManager.getTool("sakai-site-pageorder-helper") != null
&& !ServerConfigurationService
.getString("[email protected]")
.contains("sakai-site-pageorder-helper")
&& !ServerConfigurationService
.getString("[email protected]")
.contains("sakai-site-pageorder-helper"))
{
b.add(new MenuEntry(rb.getString("java.orderpages"), "doPageOrderHelper"));
}
context.put("menu", b);
}
if (allowUpdateGroupMembership)
{
// show Manage Groups menu
Menu b = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (!isMyWorkspace
&& (ServerConfigurationService.getString("wsetup.group.support") == ""
|| ServerConfigurationService.getString("wsetup.group.support").equalsIgnoreCase(Boolean.TRUE.toString())))
{
// show the group toolbar unless configured to not support group
b.add( new MenuEntry(rb.getString("java.group"), "doMenu_group"));
}
context.put("menu", b);
}
if (allowUpdateSiteMembership)
{
// show add participant menu
Menu b = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (!isMyWorkspace)
{
// show the Add Participant menu
b.add( new MenuEntry(rb.getString("java.addp"), "doMenu_siteInfo_addParticipant"));
}
context.put("menu", b);
}
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP))
{
// editing from worksite setup tool
context.put("fromWSetup", Boolean.TRUE);
if (state.getAttribute(STATE_PREV_SITE) != null)
{
context.put("prevSite", state.getAttribute(STATE_PREV_SITE));
}
if (state.getAttribute(STATE_NEXT_SITE) != null)
{
context.put("nextSite", state.getAttribute(STATE_NEXT_SITE));
}
}
else
{
context.put("fromWSetup", Boolean.FALSE);
}
//allow view roster?
boolean allowViewRoster = SiteService.allowViewRoster(siteId);
if (allowViewRoster)
{
context.put("viewRoster", Boolean.TRUE);
}
else
{
context.put("viewRoster", Boolean.FALSE);
}
//set participant list
if (allowUpdateSite || allowViewRoster || allowUpdateSiteMembership)
{
List participants = new Vector();
participants = getParticipantList(state);
sortedBy = (String) state.getAttribute (SORTED_BY);
sortedAsc = (String) state.getAttribute (SORTED_ASC);
if(sortedBy==null)
{
state.setAttribute(SORTED_BY, SORTED_BY_PARTICIPANT_NAME);
sortedBy = SORTED_BY_PARTICIPANT_NAME;
}
if (sortedAsc==null)
{
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if(sortedBy!=null) context.put ("currentSortedBy", sortedBy);
if(sortedAsc!=null) context.put ("currentSortAsc", sortedAsc);
Iterator sortedParticipants = null;
if (sortedBy != null)
{
sortedParticipants = new SortedIterator (participants.iterator (), new SiteComparator (sortedBy, sortedAsc));
participants.clear();
while (sortedParticipants.hasNext())
{
participants.add(sortedParticipants.next());
}
}
context.put("participantListSize", new Integer(participants.size()));
context.put("participantList", prepPage(state));
pagingInfoToContext(state, context);
}
context.put("include", Boolean.valueOf(site.isPubView()));
// site contact information
String contactName = siteProperties.getProperty(PROP_SITE_CONTACT_NAME);
String contactEmail = siteProperties.getProperty(PROP_SITE_CONTACT_EMAIL);
if (contactName == null && contactEmail == null)
{
User u = site.getCreatedBy();
String email = u.getEmail();
if (email != null)
{
contactEmail = u.getEmail();
}
contactName = u.getDisplayName();
}
if (contactName != null)
{
context.put("contactName", contactName);
}
if (contactEmail != null)
{
context.put("contactEmail", contactEmail);
}
if (siteType != null && siteType.equalsIgnoreCase("course"))
{
context.put("isCourseSite", Boolean.TRUE);
List providerCourseList = getProviderCourseList(StringUtil.trimToNull(getExternalRealmId(state)));
if (providerCourseList != null)
{
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
context.put("providerCourseList", providerCourseList);
}
String manualCourseListString = site.getProperties().getProperty(PROP_SITE_REQUEST_COURSE);
if (manualCourseListString != null)
{
List manualCourseList = new Vector();
if (manualCourseListString.indexOf("+") != -1)
{
manualCourseList = new ArrayList(Arrays.asList(manualCourseListString.split("\\+")));
}
else
{
manualCourseList.add(manualCourseListString);
}
state.setAttribute(SITE_MANUAL_COURSE_LIST, manualCourseList);
context.put("manualCourseList", manualCourseList);
}
context.put("term", siteProperties.getProperty(PROP_SITE_TERM));
}
else
{
context.put("isCourseSite", Boolean.FALSE);
}
}
catch (Exception e)
{
M_log.warn(this + " site info list: " + e.toString());
}
roles = getRoles(state);
context.put("roles", roles);
// will have the choice to active/inactive user or not
String activeInactiveUser = ServerConfigurationService.getString("activeInactiveUser", Boolean.FALSE.toString());
if (activeInactiveUser.equalsIgnoreCase("true"))
{
context.put("activeInactiveUser", Boolean.TRUE);
// put realm object into context
realmId = SiteService.siteReference(site.getId());
try
{
context.put("realm", AuthzGroupService.getAuthzGroup(realmId));
}
catch (GroupNotDefinedException e)
{
M_log.warn(this + " IdUnusedException " + realmId);
}
}
else
{
context.put("activeInactiveUser", Boolean.FALSE);
}
context.put("groupsWithMember", site.getGroupsWithMember(UserDirectoryService.getCurrentUser().getId()));
return (String)getContext(data).get("template") + TEMPLATE[12];
case 13:
/* buildContextForTemplate chef_site-siteInfo-editInfo.vm
*
*/
siteProperties = site.getProperties();
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("titleEditableSiteType", state.getAttribute(TITLE_EDITABLE_SITE_TYPE));
context.put("type", site.getType());
List terms = CourseManagementService.getTerms();
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course"))
{
context.put("isCourseSite", Boolean.TRUE);
context.put("skins", state.getAttribute(STATE_ICONS));
if (state.getAttribute(FORM_SITEINFO_SKIN) != null)
{
context.put("selectedIcon",state.getAttribute(FORM_SITEINFO_SKIN));
}
else if (site.getIconUrl() != null)
{
context.put("selectedIcon",site.getIconUrl());
}
if (terms != null && terms.size() >0)
{
context.put("termList", terms);
}
if (state.getAttribute(FORM_SITEINFO_TERM) == null)
{
String currentTerm = site.getProperties().getProperty(PROP_SITE_TERM);
if (currentTerm != null)
{
state.setAttribute(FORM_SITEINFO_TERM, currentTerm);
}
}
if (state.getAttribute(FORM_SITEINFO_TERM) != null)
{
context.put("selectedTerm", state.getAttribute(FORM_SITEINFO_TERM));
}
}
else
{
context.put("isCourseSite", Boolean.FALSE);
if (state.getAttribute(FORM_SITEINFO_ICON_URL) == null && StringUtil.trimToNull(site.getIconUrl()) != null)
{
state.setAttribute(FORM_SITEINFO_ICON_URL, site.getIconUrl());
}
if (state.getAttribute(FORM_SITEINFO_ICON_URL) != null)
{
context.put("iconUrl", state.getAttribute(FORM_SITEINFO_ICON_URL));
}
}
context.put("description", state.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("short_description", state.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("form_site_contact_name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("form_site_contact_email", state.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
//Display of appearance icon/url list with course site based on
// "disable.course.site.skin.selection" value set with sakai.properties file.
if ((ServerConfigurationService.getString("disable.course.site.skin.selection")).equals("true")){
context.put("disableCourseSelection", Boolean.TRUE);
}
return (String)getContext(data).get("template") + TEMPLATE[13];
case 14:
/* buildContextForTemplate chef_site-siteInfo-editInfoConfirm.vm
*
*/
siteProperties = site.getProperties();
siteType = (String)state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course"))
{
context.put("isCourseSite", Boolean.TRUE);
context.put("siteTerm", state.getAttribute(FORM_SITEINFO_TERM));
}
else
{
context.put("isCourseSite", Boolean.FALSE);
}
context.put("oTitle", site.getTitle());
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("description", state.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("oDescription", site.getDescription());
context.put("short_description", state.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("oShort_description", site.getShortDescription());
context.put("skin", state.getAttribute(FORM_SITEINFO_SKIN));
context.put("oSkin", site.getIconUrl());
context.put("skins", state.getAttribute(STATE_ICONS));
context.put("oIcon", site.getIconUrl());
context.put("icon", state.getAttribute(FORM_SITEINFO_ICON_URL));
context.put("include", state.getAttribute(FORM_SITEINFO_INCLUDE));
context.put("oInclude", Boolean.valueOf(site.isPubView()));
context.put("name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("oName", siteProperties.getProperty(PROP_SITE_CONTACT_NAME));
context.put("email", state.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
context.put("oEmail", siteProperties.getProperty(PROP_SITE_CONTACT_EMAIL));
return (String)getContext(data).get("template") + TEMPLATE[14];
case 15:
/* buildContextForTemplate chef_site-addRemoveFeatureConfirm.vm
*
*/
context.put("title", site.getTitle());
site_type = (String)state.getAttribute(STATE_SITE_TYPE);
myworkspace_site = false;
if (SiteService.isUserSite(site.getId()))
{
if (SiteService.getSiteUserId(site.getId()).equals(SessionManager.getCurrentSessionUserId()))
{
myworkspace_site = true;
site_type = "myworkspace";
}
}
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("selectedTools", orderToolIds(state, (String) state.getAttribute(STATE_SITE_TYPE), (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST)));
context.put("oldSelectedTools", state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
context.put("oldSelectedHome", state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME));
context.put("continueIndex", "12");
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null)
{
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService.getServerName());
context.put("newsTitles", (Hashtable) state.getAttribute(STATE_NEWS_TITLES));
context.put("wcTitles", (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES));
if (fromENWModifyView(state))
{
context.put("back", "26");
}
else
{
context.put("back", "4");
}
return (String)getContext(data).get("template") + TEMPLATE[15];
case 16:
/* buildContextForTemplate chef_site-publishUnpublish-sendEmail.vm
*
*/
context.put("title", site.getTitle());
context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY));
return (String)getContext(data).get("template") + TEMPLATE[16];
case 17:
/* buildContextForTemplate chef_site-publishUnpublish-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("continueIndex", "12");
SiteInfo sInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (sInfo.getPublished())
{
context.put("publish", Boolean.TRUE);
context.put("backIndex", "16");
}
else
{
context.put("publish", Boolean.FALSE);
context.put("backIndex", "9");
}
context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY));
return (String)getContext(data).get("template") + TEMPLATE[17];
case 18:
/* buildContextForTemplate chef_siteInfo-editAccess.vm
*
*/
List publicChangeableSiteTypes = (List) state.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES);
List unJoinableSiteTypes = (List) state.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE);
if (site != null)
{
//editing existing site
context.put("site", site);
siteType = state.getAttribute(STATE_SITE_TYPE)!=null?(String)state.getAttribute(STATE_SITE_TYPE):null;
if ( siteType != null
&& publicChangeableSiteTypes.contains(siteType))
{
context.put ("publicChangeable", Boolean.TRUE);
}
else
{
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(site.isPubView()));
if ( siteType != null && !unJoinableSiteTypes.contains(siteType))
{
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
if (state.getAttribute(STATE_JOINABLE) == null)
{
state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site.isJoinable()));
}
if (state.getAttribute(STATE_JOINERROLE) == null
|| state.getAttribute(STATE_JOINABLE) != null && ((Boolean) state.getAttribute(STATE_JOINABLE)).booleanValue())
{
state.setAttribute(STATE_JOINERROLE, site.getJoinerRole());
}
if (state.getAttribute(STATE_JOINABLE) != null)
{
context.put("joinable", state.getAttribute(STATE_JOINABLE));
}
if (state.getAttribute(STATE_JOINERROLE) != null)
{
context.put("joinerRole", state.getAttribute(STATE_JOINERROLE));
}
}
else
{
//site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
context.put("roles", getRoles(state));
context.put("back", "12");
}
else
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if ( siteInfo.site_type != null
&& publicChangeableSiteTypes.contains(siteInfo.site_type))
{
context.put ("publicChangeable", Boolean.TRUE);
}
else
{
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(siteInfo.getInclude()));
context.put("published", Boolean.valueOf(siteInfo.getPublished()));
if ( siteInfo.site_type != null && !unJoinableSiteTypes.contains(siteInfo.site_type))
{
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
context.put("joinable", Boolean.valueOf(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
}
else
{
// site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
// use the type's template, if defined
String realmTemplate = "!site.template";
if (siteInfo.site_type != null)
{
realmTemplate = realmTemplate + "." + siteInfo.site_type;
}
try
{
AuthzGroup r = AuthzGroupService.getAuthzGroup(realmTemplate);
context.put("roles", r.getRoles());
}
catch (GroupNotDefinedException e)
{
try
{
AuthzGroup rr = AuthzGroupService.getAuthzGroup("!site.template");
context.put("roles", rr.getRoles());
}
catch (GroupNotDefinedException ee)
{
}
}
// new site, go to confirmation page
context.put("continue", "10");
if (fromENWModifyView(state))
{
context.put("back", "26");
}
else if (state.getAttribute(STATE_IMPORT) != null)
{
context.put("back", "27");
}
else
{
context.put("back", "3");
}
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType!=null && siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
}
}
return (String)getContext(data).get("template") + TEMPLATE[18];
case 19:
/* buildContextForTemplate chef_site-addParticipant-sameRole.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("participantList", state.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("form_selectedRole", state.getAttribute("form_selectedRole"));
return (String)getContext(data).get("template") + TEMPLATE[19];
case 20:
/* buildContextForTemplate chef_site-addParticipant-differentRole.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("participantList", state.getAttribute(STATE_ADD_PARTICIPANTS));
return (String)getContext(data).get("template") + TEMPLATE[20];
case 21:
/* buildContextForTemplate chef_site-addParticipant-notification.vm
*
*/
context.put("title", site.getTitle());
context.put("sitePublished", Boolean.valueOf(site.isPublished()));
if (state.getAttribute("form_selectedNotify") == null)
{
state.setAttribute("form_selectedNotify", Boolean.FALSE);
}
context.put("notify", state.getAttribute("form_selectedNotify"));
boolean same_role = state.getAttribute("form_same_role")==null?true:((Boolean) state.getAttribute("form_same_role")).booleanValue();
if (same_role)
{
context.put("backIndex", "19");
}
else
{
context.put("backIndex", "20");
}
return (String)getContext(data).get("template") + TEMPLATE[21];
case 22:
/* buildContextForTemplate chef_site-addParticipant-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("participants", state.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("notify", state.getAttribute("form_selectedNotify"));
context.put("roles", getRoles(state));
context.put("same_role", state.getAttribute("form_same_role"));
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("selectedRole", state.getAttribute("form_selectedRole"));
return (String)getContext(data).get("template") + TEMPLATE[22];
case 23:
/* buildContextForTemplate chef_siteInfo-editAccess-globalAccess.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
if (state.getAttribute("form_joinable") == null)
{
state.setAttribute("form_joinable", new Boolean(site.isJoinable()));
}
context.put("form_joinable", state.getAttribute("form_joinable"));
if (state.getAttribute("form_joinerRole") == null)
{
state.setAttribute("form_joinerRole", site.getJoinerRole());
}
context.put("form_joinerRole", state.getAttribute("form_joinerRole"));
return (String)getContext(data).get("template") + TEMPLATE[23];
case 24:
/* buildContextForTemplate chef_siteInfo-editAccess-globalAccess-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("form_joinable", state.getAttribute("form_joinable"));
context.put("form_joinerRole", state.getAttribute("form_joinerRole"));
return (String)getContext(data).get("template") + TEMPLATE[24];
case 25:
/* buildContextForTemplate chef_changeRoles-confirm.vm
*
*/
Boolean sameRole = (Boolean) state.getAttribute(STATE_CHANGEROLE_SAMEROLE);
context.put("sameRole", sameRole);
if (sameRole.booleanValue())
{
// same role
context.put("currentRole", state.getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE));
}
else
{
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
}
roles = getRoles(state);
context.put("roles", roles);
context.put("participantSelectedList", state.getAttribute(STATE_SELECTED_PARTICIPANTS));
if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) != null)
{
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
}
context.put("siteTitle", site.getTitle());
return (String)getContext(data).get("template") + TEMPLATE[25];
case 26:
/* buildContextForTemplate chef_site-modifyENW.vm
*
*/
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
boolean existingSite = site != null? true:false;
if (existingSite)
{
// revising a existing site's tool
context.put("existingSite", Boolean.TRUE);
context.put("back", "4");
context.put("continue", "15");
context.put("function", "eventSubmit_doAdd_remove_features");
}
else
{
// new site
context.put("existingSite", Boolean.FALSE);
context.put("function", "eventSubmit_doAdd_features");
if (state.getAttribute(STATE_IMPORT) != null)
{
context.put("back", "27");
}
else
{
// new site, go to edit access page
context.put("back", "3");
}
context.put("continue", "18");
}
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
String emailId = (String) state.getAttribute(STATE_TOOL_EMAIL_ADDRESS);
if (emailId != null)
{
context.put("emailId", emailId);
}
//titles for news tools
newsTitles = (Hashtable) state.getAttribute(STATE_NEWS_TITLES);
if (newsTitles == null)
{
newsTitles = new Hashtable();
newsTitles.put("sakai.news", NEWS_DEFAULT_TITLE);
state.setAttribute(STATE_NEWS_TITLES, newsTitles);
}
context.put("newsTitles", newsTitles);
//urls for news tools
newsUrls = (Hashtable) state.getAttribute(STATE_NEWS_URLS);
if (newsUrls == null)
{
newsUrls = new Hashtable();
newsUrls.put("sakai.news", NEWS_DEFAULT_URL);
state.setAttribute(STATE_NEWS_URLS, newsUrls);
}
context.put("newsUrls", newsUrls);
// titles for web content tools
wcTitles = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES);
if (wcTitles == null)
{
wcTitles = new Hashtable();
wcTitles.put("sakai.iframe", WEB_CONTENT_DEFAULT_TITLE);
state.setAttribute(STATE_WEB_CONTENT_TITLES, wcTitles);
}
context.put("wcTitles", wcTitles);
//URLs for web content tools
wcUrls = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_URLS);
if (wcUrls == null)
{
wcUrls = new Hashtable();
wcUrls.put("sakai.iframe", WEB_CONTENT_DEFAULT_URL);
state.setAttribute(STATE_WEB_CONTENT_URLS, wcUrls);
}
context.put("wcUrls", wcUrls);
context.put("serverName", ServerConfigurationService.getServerName());
context.put("oldSelectedTools", state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
return (String)getContext(data).get("template") + TEMPLATE[26];
case 27:
/* buildContextForTemplate chef_site-importSites.vm
*
*/
existingSite = site != null? true:false;
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (existingSite)
{
// revising a existing site's tool
context.put("continue", "12");
context.put("back", "28");
context.put("totalSteps", "2");
context.put("step", "2");
context.put("currentSite", site);
}
else
{
// new site, go to edit access page
context.put("back", "3");
if (fromENWModifyView(state))
{
context.put("continue", "26");
}
else
{
context.put("continue", "18");
}
}
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put ("selectedTools", orderToolIds(state, site_type, getToolsAvailableForImport(state))); // String toolId's
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
context.put("importSitesTools", state.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("importSupportedTools", importTools());
return (String)getContext(data).get("template") + TEMPLATE[27];
case 28:
/* buildContextForTemplate chef_siteinfo-import.vm
*
*/
context.put("currentSite", site);
context.put("importSiteList", state.getAttribute(STATE_IMPORT_SITES));
context.put("sites", SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null));
return (String)getContext(data).get("template") + TEMPLATE[28];
case 29:
/* buildContextForTemplate chef_siteinfo-duplicate.vm
*
*/
context.put("siteTitle", site.getTitle());
String sType = site.getType();
if (sType != null && sType.equals("course"))
{
context.put("isCourseSite", Boolean.TRUE);
context.put("currentTermId", site.getProperties().getProperty(PROP_SITE_TERM));
context.put("termList", getAvailableTerms());
}
else
{
context.put("isCourseSite", Boolean.FALSE);
}
if (state.getAttribute(SITE_DUPLICATED) == null)
{
context.put("siteDuplicated", Boolean.FALSE);
}
else
{
context.put("siteDuplicated", Boolean.TRUE);
context.put("duplicatedName", state.getAttribute(SITE_DUPLICATED_NAME));
}
return (String)getContext(data).get("template") + TEMPLATE[29];
case 36:
/*
* buildContextForTemplate chef_site-newSiteCourse.vm
*/
if (site != null)
{
context.put("site", site);
context.put("siteTitle", site.getTitle());
terms = CourseManagementService.getTerms();
if (terms != null && terms.size() >0)
{
context.put("termList", terms);
}
List providerCourseList = (List) state.getAttribute(SITE_PROVIDER_COURSE_LIST);
context.put("providerCourseList", providerCourseList);
context.put("manualCourseList", state.getAttribute(SITE_MANUAL_COURSE_LIST));
Term t = (Term) state.getAttribute(STATE_TERM_SELECTED);
context.put ("term", t);
if (t != null)
{
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
List courses = CourseManagementService.getInstructorCourses(userId, t.getYear(), t.getTerm());
if (courses != null && courses.size() > 0)
{
Vector notIncludedCourse = new Vector();
// remove included sites
for (Iterator i = courses.iterator(); i.hasNext(); )
{
Course c = (Course) i.next();
if (!providerCourseList.contains(c.getId()))
{
notIncludedCourse.add(c);
}
}
state.setAttribute(STATE_TERM_COURSE_LIST, notIncludedCourse);
}
else
{
state.removeAttribute(STATE_TERM_COURSE_LIST);
}
}
// step number used in UI
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer("1"));
}
else
{
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
context.put ("selectedProviderCourse", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if(state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
context.put("selectedManualCourse", Boolean.TRUE);
}
context.put ("term", (Term) state.getAttribute(STATE_TERM_SELECTED));
}
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP))
{
context.put("backIndex", "1");
}
else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO))
{
context.put("backIndex", "");
}
context.put("termCourseList", (List) state.getAttribute(STATE_TERM_COURSE_LIST));
return (String)getContext(data).get("template") + TEMPLATE[36];
case 37:
/*
* buildContextForTemplate chef_site-newSiteCourseManual.vm
*/
if (site != null)
{
context.put("site", site);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
}
buildInstructorSectionsList(state, params, context);
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("form_requiredFieldsSizes", CourseManagementService.getCourseIdRequiredFieldsSizes());
context.put("form_additional", siteInfo.additional);
context.put("form_title", siteInfo.title);
context.put("form_description", siteInfo.description);
context.put("noEmailInIdAccountName", ServerConfigurationService.getString("noEmailInIdAccountName", ""));
context.put("value_uniqname", state.getAttribute(STATE_SITE_QUEST_UNIQNAME));
int number = 1;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
context.put("currentNumber", new Integer(number));
}
context.put("currentNumber", new Integer(number));
context.put("listSize", new Integer(number-1));
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
List l = (List) state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
context.put ("selectedProviderCourse", l);
context.put("size", new Integer(l.size()-1));
}
if (site != null)
{
context.put("back", "36");
}
else
{
if (state.getAttribute(STATE_AUTO_ADD) != null)
{
context.put("autoAdd", Boolean.TRUE);
context.put("back", "36");
}
else
{
context.put("back", "1");
}
}
context.put("isFutureTerm", state.getAttribute(STATE_FUTURE_TERM_SELECTED));
context.put("weeksAhead", ServerConfigurationService.getString("roster.available.weeks.before.term.start", "0"));
return (String)getContext(data).get("template") + TEMPLATE[37];
case 42:
/* buildContextForTemplate chef_site-gradtoolsConfirm.vm
*
*/
siteInfo = (SiteInfo)state.getAttribute(STATE_SITE_INFO);
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
toolRegistrationList = (Vector) state.getAttribute(STATE_PROJECT_TOOL_LIST);
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
context.put (STATE_TOOL_REGISTRATION_LIST, toolRegistrationList ); // %%% use Tool
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService.getServerName());
context.put("include", new Boolean(siteInfo.include));
return (String)getContext(data).get("template") + TEMPLATE[42];
case 43:
/* buildContextForTemplate chef_siteInfo-editClass.vm
*
*/
bar = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null))
{
bar.add( new MenuEntry(rb.getString("java.addclasses"), "doMenu_siteInfo_addClass"));
}
context.put("menu", bar);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
return (String)getContext(data).get("template") + TEMPLATE[43];
case 44:
/* buildContextForTemplate chef_siteInfo-addCourseConfirm.vm
*
*/
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
context.put("providerAddCourses", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
int addNumber = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue() -1;
context.put("manualAddNumber", new Integer(addNumber));
context.put("requestFields", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("backIndex", "37");
}
else
{
context.put("backIndex", "36");
}
//those manual inputs
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String)getContext(data).get("template") + TEMPLATE[44];
//htripath - import materials from classic
case 45:
/* buildContextForTemplate chef_siteInfo-importMtrlMaster.vm
*
*/
return (String)getContext(data).get("template") + TEMPLATE[45];
case 46:
/* buildContextForTemplate chef_siteInfo-importMtrlCopy.vm
*
*/
// this is for list display in listbox
context.put("allZipSites", state.getAttribute(ALL_ZIP_IMPORT_SITES));
context.put("finalZipSites", state.getAttribute(FINAL_ZIP_IMPORT_SITES));
//zip file
//context.put("zipreffile",state.getAttribute(CLASSIC_ZIP_FILE_NAME));
return (String)getContext(data).get("template") + TEMPLATE[46];
case 47:
/* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String)getContext(data).get("template") + TEMPLATE[47];
case 48:
/* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String)getContext(data).get("template") + TEMPLATE[48];
case 49:
/* buildContextForTemplate chef_siteInfo-group.vm
*
*/
context.put("site", site);
bar = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (SiteService.allowUpdateSite(site.getId()) || SiteService.allowUpdateGroupMembership(site.getId()))
{
bar.add( new MenuEntry(rb.getString("java.new"), "doGroup_new"));
}
context.put("menu", bar);
// the group list
sortedBy = (String) state.getAttribute (SORTED_BY);
sortedAsc = (String) state.getAttribute (SORTED_ASC);
if(sortedBy!=null) context.put ("currentSortedBy", sortedBy);
if(sortedAsc!=null) context.put ("currentSortAsc", sortedAsc);
// only show groups created by WSetup tool itself
Collection groups = (Collection) site.getGroups();
List groupsByWSetup = new Vector();
for(Iterator gIterator = groups.iterator(); gIterator.hasNext();)
{
Group gNext = (Group) gIterator.next();
String gProp = gNext.getProperties().getProperty(GROUP_PROP_WSETUP_CREATED);
if (gProp != null && gProp.equals(Boolean.TRUE.toString()))
{
groupsByWSetup.add(gNext);
}
}
if (sortedBy != null && sortedAsc != null)
{
context.put("groups", new SortedIterator (groupsByWSetup.iterator (), new SiteComparator (sortedBy, sortedAsc)));
}
return (String)getContext(data).get("template") + TEMPLATE[49];
case 50:
/* buildContextForTemplate chef_siteInfo-groupedit.vm
*
*/
Group g = getStateGroup(state);
if (g != null)
{
context.put("group", g);
context.put("newgroup", Boolean.FALSE);
}
else
{
context.put("newgroup", Boolean.TRUE);
}
if (state.getAttribute(STATE_GROUP_TITLE) != null)
{
context.put("title", state.getAttribute(STATE_GROUP_TITLE));
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) != null)
{
context.put("description", state.getAttribute(STATE_GROUP_DESCRIPTION));
}
Iterator siteMembers = new SortedIterator (getParticipantList(state).iterator (), new SiteComparator (SORTED_BY_PARTICIPANT_NAME, Boolean.TRUE.toString()));
if (siteMembers != null && siteMembers.hasNext())
{
context.put("generalMembers", siteMembers);
}
Set groupMembersSet = (Set) state.getAttribute(STATE_GROUP_MEMBERS);
if (state.getAttribute(STATE_GROUP_MEMBERS) != null)
{
context.put("groupMembers", new SortedIterator(groupMembersSet.iterator(), new SiteComparator (SORTED_BY_MEMBER_NAME, Boolean.TRUE.toString())));
}
context.put("groupMembersClone", groupMembersSet);
context.put("userDirectoryService", UserDirectoryService.getInstance());
return (String)getContext(data).get("template") + TEMPLATE[50];
case 51:
/* buildContextForTemplate chef_siteInfo-groupDeleteConfirm.vm
*
*/
context.put("site", site);
context.put("removeGroupIds", new ArrayList(Arrays.asList((String[])state.getAttribute(STATE_GROUP_REMOVE))));
return (String)getContext(data).get("template") + TEMPLATE[51];
}
// should never be reached
return (String)getContext(data).get("template") + TEMPLATE[0];
} // buildContextForTemplate
| private String buildContextForTemplate (int index, VelocityPortlet portlet,
Context context,
RunData data,
SessionState state)
{
String realmId = "";
String site_type = "";
String sortedBy = "";
String sortedAsc = "";
ParameterParser params = data.getParameters ();
context.put("tlang",rb);
context.put("alertMessage", state.getAttribute(STATE_MESSAGE));
// If cleanState() has removed SiteInfo, get a new instance into state
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null)
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
else
{
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
// Lists used in more than one template
// Access
List roles = new Vector();
// the hashtables for News and Web Content tools
Hashtable newsTitles = new Hashtable();
Hashtable newsUrls = new Hashtable();
Hashtable wcTitles = new Hashtable();
Hashtable wcUrls = new Hashtable();
List toolRegistrationList = new Vector();
List toolRegistrationSelectedList = new Vector();
ResourceProperties siteProperties = null;
// for showing site creation steps
if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) != null)
{
context.put("totalSteps", state.getAttribute(SITE_CREATE_TOTAL_STEPS));
}
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null)
{
context.put("step", state.getAttribute(SITE_CREATE_CURRENT_STEP));
}
String hasGradSites = ServerConfigurationService.getString("withDissertation", Boolean.FALSE.toString());
Site site = getStateSite(state);
switch (index)
{
case 0:
/* buildContextForTemplate chef_site-list.vm
*
*/
// site types
List sTypes = (List) state.getAttribute(STATE_SITE_TYPES);
//make sure auto-updates are enabled
Hashtable views = new Hashtable();
if (SecurityService.isSuperUser())
{
views.put(rb.getString("java.allmy"), rb.getString("java.allmy"));
views.put(rb.getString("java.my") + " " + rb.getString("java.sites"), rb.getString("java.my"));
for(int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++)
{
String type = (String) sTypes.get(sTypeIndex);
views.put(type + " " + rb.getString("java.sites"), type);
}
if (hasGradSites.equalsIgnoreCase("true"))
{
views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb.getString("java.gradtools"));
}
if(state.getAttribute(STATE_VIEW_SELECTED) == null)
{
state.setAttribute(STATE_VIEW_SELECTED, rb.getString("java.allmy"));
}
context.put("superUser", Boolean.TRUE);
}
else
{
context.put("superUser", Boolean.FALSE);
views.put(rb.getString("java.allmy"), rb.getString("java.allmy"));
// if there is a GradToolsStudent choice inside
boolean remove = false;
if (hasGradSites.equalsIgnoreCase("true"))
{
try
{
//the Grad Tools site option is only presented to GradTools Candidates
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
//am I a grad student?
if (!isGradToolsCandidate(userId))
{
// not a gradstudent
remove = true;
}
}
catch(Exception e)
{
remove = true;
}
}
else
{
// not support for dissertation sites
remove=true;
}
//do not show this site type in views
//sTypes.remove(new String(SITE_TYPE_GRADTOOLS_STUDENT));
for(int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++)
{
String type = (String) sTypes.get(sTypeIndex);
if(!type.equals(SITE_TYPE_GRADTOOLS_STUDENT))
{
views.put(type + " "+rb.getString("java.sites"), type);
}
}
if (!remove)
{
views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb.getString("java.gradtools"));
}
//default view
if(state.getAttribute(STATE_VIEW_SELECTED) == null)
{
state.setAttribute(STATE_VIEW_SELECTED, rb.getString("java.allmy"));
}
}
context.put("views", views);
if(state.getAttribute(STATE_VIEW_SELECTED) != null)
{
context.put("viewSelected", (String) state.getAttribute(STATE_VIEW_SELECTED));
}
String search = (String) state.getAttribute(STATE_SEARCH);
context.put("search_term", search);
sortedBy = (String) state.getAttribute (SORTED_BY);
if (sortedBy == null)
{
state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString());
sortedBy = SortType.TITLE_ASC.toString();
}
sortedAsc = (String) state.getAttribute (SORTED_ASC);
if (sortedAsc == null)
{
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if(sortedBy!=null) context.put ("currentSortedBy", sortedBy);
if(sortedAsc!=null) context.put ("currentSortAsc", sortedAsc);
String portalUrl = ServerConfigurationService.getPortalUrl();
context.put("portalUrl", portalUrl);
List sites = prepPage(state);
state.setAttribute(STATE_SITES, sites);
context.put("sites", sites);
context.put("totalPageNumber", new Integer(totalPageNumber(state)));
context.put("searchString", state.getAttribute(STATE_SEARCH));
context.put("form_search", FORM_SEARCH);
context.put("formPageNumber", FORM_PAGE_NUMBER);
context.put("prev_page_exists", state.getAttribute(STATE_PREV_PAGE_EXISTS));
context.put("next_page_exists", state.getAttribute(STATE_NEXT_PAGE_EXISTS));
context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE));
// put the service in the context (used for allow update calls on each site)
context.put("service", SiteService.getInstance());
context.put("sortby_title", SortType.TITLE_ASC.toString());
context.put("sortby_type", SortType.TYPE_ASC.toString());
context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString());
context.put("sortby_publish", SortType.PUBLISHED_ASC.toString());
context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString());
// top menu bar
Menu bar = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null))
{
bar.add( new MenuEntry(rb.getString("java.new"), "doNew_site"));
}
bar.add( new MenuEntry(rb.getString("java.revise"), null, true, MenuItem.CHECKED_NA, "doGet_site", "sitesForm"));
bar.add( new MenuEntry(rb.getString("java.delete"), null, true, MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm"));
context.put("menu", bar);
// default to be no pageing
context.put("paged", Boolean.FALSE);
Menu bar2 = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
// add the search commands
addSearchMenus(bar2, state);
context.put("menu2", bar2);
pagingInfoToContext(state, context);
return (String)getContext(data).get("template") + TEMPLATE[0];
case 1:
/* buildContextForTemplate chef_site-type.vm
*
*/
if (hasGradSites.equalsIgnoreCase("true"))
{
context.put("withDissertation", Boolean.TRUE);
try
{
//the Grad Tools site option is only presented to UM grad students
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
//am I a UM grad student?
Boolean isGradStudent = new Boolean(isGradToolsCandidate(userId));
context.put("isGradStudent", isGradStudent);
//if I am a UM grad student, do I already have a Grad Tools site?
boolean noGradToolsSite = true;
if(hasGradToolsStudentSite(userId))
noGradToolsSite = false;
context.put("noGradToolsSite", new Boolean(noGradToolsSite));
}
catch(Exception e)
{
if(Log.isWarnEnabled())
{
M_log.warn("buildContextForTemplate chef_site-type.vm " + e);
}
}
}
else
{
context.put("withDissertation", Boolean.FALSE);
}
List types = (List) state.getAttribute(STATE_SITE_TYPES);
context.put("siteTypes", types);
// put selected/default site type into context
if (siteInfo.site_type != null && siteInfo.site_type.length() >0)
{
context.put("typeSelected", siteInfo.site_type);
}
else if (types.size() > 0)
{
context.put("typeSelected", types.get(0));
}
List termsForSiteCreation = getAvailableTerms();
if (termsForSiteCreation.size() > 0)
{
context.put("termList", termsForSiteCreation);
}
if (state.getAttribute(STATE_TERM_SELECTED) != null)
{
context.put("selectedTerm", state.getAttribute(STATE_TERM_SELECTED));
}
return (String)getContext(data).get("template") + TEMPLATE[1];
case 2:
/* buildContextForTemplate chef_site-newSiteInformation.vm
*
*/
context.put("siteTypes", state.getAttribute(STATE_SITE_TYPES));
String siteType = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("titleEditableSiteType", state.getAttribute(TITLE_EDITABLE_SITE_TYPE));
context.put("type", siteType);
if (siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
context.put ("selectedProviderCourse", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
int number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
context.put ("manualAddNumber", new Integer(number - 1));
context.put ("manualAddFields", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("back", "37");
}
else
{
context.put("back", "36");
}
context.put ("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null)
{
context.put("selectedIcon", siteInfo.getIconUrl());
}
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null)
{
context.put(FORM_ICON_URL, siteInfo.iconUrl);
}
context.put ("back", "1");
}
context.put (FORM_TITLE,siteInfo.title);
context.put(FORM_SHORT_DESCRIPTION, siteInfo.short_description);
context.put (FORM_DESCRIPTION,siteInfo.description);
// defalt the site contact person to the site creator
if (siteInfo.site_contact_name.equals(NULL_STRING) && siteInfo.site_contact_email.equals(NULL_STRING))
{
User user = UserDirectoryService.getCurrentUser();
siteInfo.site_contact_name = user.getDisplayName();
siteInfo.site_contact_email = user.getEmail();
}
context.put("form_site_contact_name", siteInfo.site_contact_name);
context.put("form_site_contact_email", siteInfo.site_contact_email);
// those manual inputs
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String)getContext(data).get("template") + TEMPLATE[2];
case 3:
/* buildContextForTemplate chef_site-newSiteFeatures.vm
*
*/
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType!=null && siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
}
context.put("defaultTools", ServerConfigurationService.getToolsRequired(siteType));
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// If this is the first time through, check for tools
// which should be selected by default.
List defaultSelectedTools = ServerConfigurationService.getDefaultTools(siteType);
if (toolRegistrationSelectedList == null) {
toolRegistrationSelectedList = new Vector(defaultSelectedTools);
}
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST) ); // %%% use ToolRegistrations for template list
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService.getServerName());
// The "Home" tool checkbox needs special treatment to be selected by
// default.
Boolean checkHome = (Boolean)state.getAttribute(STATE_TOOL_HOME_SELECTED);
if (checkHome == null) {
if ((defaultSelectedTools != null) && defaultSelectedTools.contains(HOME_TOOL_ID)) {
checkHome = Boolean.TRUE;
}
}
context.put("check_home", checkHome);
//titles for news tools
context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES));
//titles for web content tools
context.put("wcTitles", state.getAttribute(STATE_WEB_CONTENT_TITLES));
//urls for news tools
context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS));
//urls for web content tools
context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS));
context.put("sites", SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null));
context.put("import", state.getAttribute(STATE_IMPORT));
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
return (String)getContext(data).get("template") + TEMPLATE[3];
case 4:
/* buildContextForTemplate chef_site-addRemoveFeatures.vm
*
*/
context.put("SiteTitle", site.getTitle());
String type = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("defaultTools", ServerConfigurationService.getToolsRequired(type));
boolean myworkspace_site = false;
//Put up tool lists filtered by category
List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES);
if (siteTypes.contains(type))
{
myworkspace_site = false;
}
if (SiteService.isUserSite(site.getId()) || (type!=null && type.equalsIgnoreCase("myworkspace")))
{
myworkspace_site = true;
type="myworkspace";
}
context.put ("myworkspace_site", new Boolean(myworkspace_site));
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST));
//titles for news tools
context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES));
//titles for web content tools
context.put("wcTitles", state.getAttribute(STATE_WEB_CONTENT_TITLES));
//urls for news tools
context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS));
//urls for web content tools
context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS));
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
//get the email alias when an Email Archive tool has been selected
String channelReference = mailArchiveChannelReference(site.getId());
List aliases = AliasService.getAliases(channelReference, 1, 1);
if (aliases.size() > 0)
{
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases.get(0)).getId());
}
else
{
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
}
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null)
{
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService.getServerName());
context.put("backIndex", "12");
return (String)getContext(data).get("template") + TEMPLATE[4];
case 5:
/* buildContextForTemplate chef_site-addParticipant.vm
*
*/
context.put("title", site.getTitle());
roles = getRoles(state);
context.put("roles", roles);
// Note that (for now) these strings are in both sakai.properties and sitesetupgeneric.properties
context.put("noEmailInIdAccountName", ServerConfigurationService.getString("noEmailInIdAccountName"));
context.put("noEmailInIdAccountLabel", ServerConfigurationService.getString("noEmailInIdAccountLabel"));
context.put("emailInIdAccountName", ServerConfigurationService.getString("emailInIdAccountName"));
context.put("emailInIdAccountLabel", ServerConfigurationService.getString("emailInIdAccountLabel"));
if(state.getAttribute("noEmailInIdAccountValue")!=null)
{
context.put("noEmailInIdAccountValue", (String)state.getAttribute("noEmailInIdAccountValue"));
}
if(state.getAttribute("emailInIdAccountValue")!=null)
{
context.put("emailInIdAccountValue", (String)state.getAttribute("emailInIdAccountValue"));
}
if(state.getAttribute("form_same_role") != null)
{
context.put("form_same_role", ((Boolean) state.getAttribute("form_same_role")).toString());
}
else
{
context.put("form_same_role", Boolean.TRUE.toString());
}
context.put("backIndex", "12");
return (String)getContext(data).get("template") + TEMPLATE[5];
case 6:
/* buildContextForTemplate chef_site-removeParticipants.vm
*
*/
context.put("title", site.getTitle());
realmId = SiteService.siteReference(site.getId());
try
{
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
try
{
List removeableList = (List) state.getAttribute(STATE_REMOVEABLE_USER_LIST);
List removeableParticipants = new Vector();
for (int k = 0; k < removeableList.size(); k++)
{
User user = UserDirectoryService.getUser((String) removeableList.get(k));
Participant participant = new Participant();
participant.name = user.getSortName();
participant.uniqname = user.getId();
Role r = realm.getUserRole(user.getId());
if (r != null)
{
participant.role = r.getId();
}
removeableParticipants.add(participant);
}
context.put("removeableList", removeableParticipants);
}
catch (UserNotDefinedException ee)
{
}
}
catch (GroupNotDefinedException e)
{
}
context.put("backIndex", "18");
return (String)getContext(data).get("template") + TEMPLATE[6];
case 7:
/* buildContextForTemplate chef_site-changeRoles.vm
*
*/
context.put("same_role", state.getAttribute(STATE_CHANGEROLE_SAMEROLE));
roles = getRoles(state);
context.put("roles", roles);
context.put("currentRole", state.getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE));
context.put("participantSelectedList", state.getAttribute(STATE_SELECTED_PARTICIPANTS));
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("siteTitle", site.getTitle());
return (String)getContext(data).get("template") + TEMPLATE[7];
case 8:
/* buildContextForTemplate chef_site-siteDeleteConfirm.vm
*
*/
String site_title = NULL_STRING;
String[] removals = (String[]) state.getAttribute(STATE_SITE_REMOVALS);
List remove = new Vector();
String user = SessionManager.getCurrentSessionUserId();
String workspace = SiteService.getUserSiteId(user);
if( removals != null && removals.length != 0 )
{
for (int i = 0; i < removals.length; i++ )
{
String id = (String) removals[i];
if(!(id.equals(workspace)))
{
try
{
site_title = SiteService.getSite(id).getTitle();
}
catch (IdUnusedException e)
{
M_log.warn("SiteAction.doSite_delete_confirmed - IdUnusedException " + id);
addAlert(state, rb.getString("java.sitewith")+" " + id + " "+rb.getString("java.couldnt")+" ");
}
if(SiteService.allowRemoveSite(id))
{
try
{
Site removeSite = SiteService.getSite(id);
remove.add(removeSite);
}
catch (IdUnusedException e)
{
M_log.warn("SiteAction.buildContextForTemplate chef_site-siteDeleteConfirm.vm: IdUnusedException");
}
}
else
{
addAlert(state, site_title + " "+rb.getString("java.couldntdel") + " ");
}
}
else
{
addAlert(state, rb.getString("java.yourwork"));
}
}
if(remove.size() == 0)
{
addAlert(state, rb.getString("java.click"));
}
}
context.put("removals", remove);
return (String)getContext(data).get("template") + TEMPLATE[8];
case 9:
/* buildContextForTemplate chef_site-publishUnpublish.vm
*
*/
context.put("publish", Boolean.valueOf(((SiteInfo)state.getAttribute(STATE_SITE_INFO)).getPublished()));
context.put("backIndex", "12");
return (String)getContext(data).get("template") + TEMPLATE[9];
case 10:
/* buildContextForTemplate chef_site-newSiteConfirm.vm
*
*/
siteInfo = (SiteInfo)state.getAttribute(STATE_SITE_INFO);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put ("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
context.put ("selectedProviderCourse", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
int number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
context.put ("manualAddNumber", new Integer(number - 1));
context.put ("manualAddFields", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
context.put ("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null)
{
context.put("selectedIcon", siteInfo.getIconUrl());
}
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType!=null && siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null)
{
context.put("iconUrl", siteInfo.iconUrl);
}
}
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
context.put("siteContactName", siteInfo.site_contact_name);
context.put("siteContactEmail", siteInfo.site_contact_email);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use Tool
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService.getServerName());
context.put("include", new Boolean(siteInfo.include));
context.put("published", new Boolean(siteInfo.published));
context.put("joinable", new Boolean(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
context.put("newsTitles", (Hashtable) state.getAttribute(STATE_NEWS_TITLES));
context.put("wcTitles", (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES));
// back to edit access page
context.put("back", "18");
context.put("importSiteTools", state.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("siteService", SiteService.getInstance());
// those manual inputs
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String)getContext(data).get("template") + TEMPLATE[10];
case 11:
/* buildContextForTemplate chef_site-newSitePublishUnpublish.vm
*
*/
return (String)getContext(data).get("template") + TEMPLATE[11];
case 12:
/* buildContextForTemplate chef_site-siteInfo-list.vm
*
*/
context.put("userDirectoryService", UserDirectoryService.getInstance());
try
{
siteProperties = site.getProperties();
siteType = site.getType();
if (siteType != null)
{
state.setAttribute(STATE_SITE_TYPE, siteType);
}
boolean isMyWorkspace = false;
if (SiteService.isUserSite(site.getId()))
{
if (SiteService.getSiteUserId(site.getId()).equals(SessionManager.getCurrentSessionUserId()))
{
isMyWorkspace = true;
context.put("siteUserId", SiteService.getSiteUserId(site.getId()));
}
}
context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace));
String siteId = site.getId();
if (state.getAttribute(STATE_ICONS)!= null)
{
List skins = (List)state.getAttribute(STATE_ICONS);
for (int i = 0; i < skins.size(); i++)
{
Icon s = (Icon)skins.get(i);
if(!StringUtil.different(s.getUrl(), site.getIconUrl()))
{
context.put("siteUnit", s.getName());
break;
}
}
}
context.put("siteIcon", site.getIconUrl());
context.put("siteTitle", site.getTitle());
context.put("siteDescription", site.getDescription());
context.put("siteJoinable", new Boolean(site.isJoinable()));
if(site.isPublished())
{
context.put("published", Boolean.TRUE);
}
else
{
context.put("published", Boolean.FALSE);
context.put("owner", site.getCreatedBy().getSortName());
}
Time creationTime = site.getCreatedTime();
if (creationTime != null)
{
context.put("siteCreationDate", creationTime.toStringLocalFull());
}
boolean allowUpdateSite = SiteService.allowUpdateSite(siteId);
context.put("allowUpdate", Boolean.valueOf(allowUpdateSite));
boolean allowUpdateGroupMembership = SiteService.allowUpdateGroupMembership(siteId);
context.put("allowUpdateGroupMembership", Boolean.valueOf(allowUpdateGroupMembership));
boolean allowUpdateSiteMembership = SiteService.allowUpdateSiteMembership(siteId);
context.put("allowUpdateSiteMembership", Boolean.valueOf(allowUpdateSiteMembership));
if (allowUpdateSite)
{
// top menu bar
Menu b = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (!isMyWorkspace)
{
b.add( new MenuEntry(rb.getString("java.editsite"), "doMenu_edit_site_info"));
}
b.add( new MenuEntry(rb.getString("java.edittools"), "doMenu_edit_site_tools"));
if (!isMyWorkspace
&& (ServerConfigurationService.getString("wsetup.group.support") == ""
|| ServerConfigurationService.getString("wsetup.group.support").equalsIgnoreCase(Boolean.TRUE.toString())))
{
// show the group toolbar unless configured to not support group
b.add( new MenuEntry(rb.getString("java.group"), "doMenu_group"));
}
if (!isMyWorkspace)
{
List gradToolsSiteTypes = (List) state.getAttribute(GRADTOOLS_SITE_TYPES);
boolean isGradToolSite = false;
if (siteType != null && gradToolsSiteTypes.contains(siteType))
{
isGradToolSite = true;
}
if (siteType == null
|| siteType != null && !isGradToolSite)
{
// hide site access for GRADTOOLS type of sites
b.add( new MenuEntry(rb.getString("java.siteaccess"), "doMenu_edit_site_access"));
}
b.add( new MenuEntry(rb.getString("java.addp"), "doMenu_siteInfo_addParticipant"));
if (siteType != null && siteType.equals("course"))
{
b.add( new MenuEntry(rb.getString("java.editc"), "doMenu_siteInfo_editClass"));
}
if (siteType == null || siteType != null && !isGradToolSite)
{
// hide site duplicate and import for GRADTOOLS type of sites
b.add( new MenuEntry(rb.getString("java.duplicate"), "doMenu_siteInfo_duplicate"));
List updatableSites = SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null);
// import link should be visible even if only one site
if (updatableSites.size() > 0)
{
b.add( new MenuEntry(rb.getString("java.import"), "doMenu_siteInfo_import"));
// a configuration param for showing/hiding import from file choice
String importFromFile = ServerConfigurationService.getString("site.setup.import.file", Boolean.TRUE.toString());
if (importFromFile.equalsIgnoreCase("true"))
{
//htripath: June 4th added as per Kris and changed desc of above
b.add(new MenuEntry(rb.getString("java.importFile"), "doAttachmentsMtrlFrmFile"));
}
}
}
}
// if the page order helper is available, not stealthed and not hidden, show the link
if (ToolManager.getTool("sakai-site-pageorder-helper") != null
&& !ServerConfigurationService
.getString("[email protected]")
.contains("sakai-site-pageorder-helper")
&& !ServerConfigurationService
.getString("[email protected]")
.contains("sakai-site-pageorder-helper"))
{
b.add(new MenuEntry(rb.getString("java.orderpages"), "doPageOrderHelper"));
}
context.put("menu", b);
}
if (allowUpdateGroupMembership)
{
// show Manage Groups menu
Menu b = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (!isMyWorkspace
&& (ServerConfigurationService.getString("wsetup.group.support") == ""
|| ServerConfigurationService.getString("wsetup.group.support").equalsIgnoreCase(Boolean.TRUE.toString())))
{
// show the group toolbar unless configured to not support group
b.add( new MenuEntry(rb.getString("java.group"), "doMenu_group"));
}
context.put("menu", b);
}
if (allowUpdateSiteMembership)
{
// show add participant menu
Menu b = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (!isMyWorkspace)
{
// show the Add Participant menu
b.add( new MenuEntry(rb.getString("java.addp"), "doMenu_siteInfo_addParticipant"));
}
context.put("menu", b);
}
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP))
{
// editing from worksite setup tool
context.put("fromWSetup", Boolean.TRUE);
if (state.getAttribute(STATE_PREV_SITE) != null)
{
context.put("prevSite", state.getAttribute(STATE_PREV_SITE));
}
if (state.getAttribute(STATE_NEXT_SITE) != null)
{
context.put("nextSite", state.getAttribute(STATE_NEXT_SITE));
}
}
else
{
context.put("fromWSetup", Boolean.FALSE);
}
//allow view roster?
boolean allowViewRoster = SiteService.allowViewRoster(siteId);
if (allowViewRoster)
{
context.put("viewRoster", Boolean.TRUE);
}
else
{
context.put("viewRoster", Boolean.FALSE);
}
//set participant list
if (allowUpdateSite || allowViewRoster || allowUpdateSiteMembership)
{
List participants = new Vector();
participants = getParticipantList(state);
sortedBy = (String) state.getAttribute (SORTED_BY);
sortedAsc = (String) state.getAttribute (SORTED_ASC);
if(sortedBy==null)
{
state.setAttribute(SORTED_BY, SORTED_BY_PARTICIPANT_NAME);
sortedBy = SORTED_BY_PARTICIPANT_NAME;
}
if (sortedAsc==null)
{
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if(sortedBy!=null) context.put ("currentSortedBy", sortedBy);
if(sortedAsc!=null) context.put ("currentSortAsc", sortedAsc);
Iterator sortedParticipants = null;
if (sortedBy != null)
{
sortedParticipants = new SortedIterator (participants.iterator (), new SiteComparator (sortedBy, sortedAsc));
participants.clear();
while (sortedParticipants.hasNext())
{
participants.add(sortedParticipants.next());
}
}
context.put("participantListSize", new Integer(participants.size()));
context.put("participantList", prepPage(state));
pagingInfoToContext(state, context);
}
context.put("include", Boolean.valueOf(site.isPubView()));
// site contact information
String contactName = siteProperties.getProperty(PROP_SITE_CONTACT_NAME);
String contactEmail = siteProperties.getProperty(PROP_SITE_CONTACT_EMAIL);
if (contactName == null && contactEmail == null)
{
User u = site.getCreatedBy();
String email = u.getEmail();
if (email != null)
{
contactEmail = u.getEmail();
}
contactName = u.getDisplayName();
}
if (contactName != null)
{
context.put("contactName", contactName);
}
if (contactEmail != null)
{
context.put("contactEmail", contactEmail);
}
if (siteType != null && siteType.equalsIgnoreCase("course"))
{
context.put("isCourseSite", Boolean.TRUE);
List providerCourseList = getProviderCourseList(StringUtil.trimToNull(getExternalRealmId(state)));
if (providerCourseList != null)
{
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
context.put("providerCourseList", providerCourseList);
}
String manualCourseListString = site.getProperties().getProperty(PROP_SITE_REQUEST_COURSE);
if (manualCourseListString != null)
{
List manualCourseList = new Vector();
if (manualCourseListString.indexOf("+") != -1)
{
manualCourseList = new ArrayList(Arrays.asList(manualCourseListString.split("\\+")));
}
else
{
manualCourseList.add(manualCourseListString);
}
state.setAttribute(SITE_MANUAL_COURSE_LIST, manualCourseList);
context.put("manualCourseList", manualCourseList);
}
context.put("term", siteProperties.getProperty(PROP_SITE_TERM));
}
else
{
context.put("isCourseSite", Boolean.FALSE);
}
}
catch (Exception e)
{
M_log.warn(this + " site info list: " + e.toString());
}
roles = getRoles(state);
context.put("roles", roles);
// will have the choice to active/inactive user or not
String activeInactiveUser = ServerConfigurationService.getString("activeInactiveUser", Boolean.FALSE.toString());
if (activeInactiveUser.equalsIgnoreCase("true"))
{
context.put("activeInactiveUser", Boolean.TRUE);
// put realm object into context
realmId = SiteService.siteReference(site.getId());
try
{
context.put("realm", AuthzGroupService.getAuthzGroup(realmId));
}
catch (GroupNotDefinedException e)
{
M_log.warn(this + " IdUnusedException " + realmId);
}
}
else
{
context.put("activeInactiveUser", Boolean.FALSE);
}
context.put("groupsWithMember", site.getGroupsWithMember(UserDirectoryService.getCurrentUser().getId()));
return (String)getContext(data).get("template") + TEMPLATE[12];
case 13:
/* buildContextForTemplate chef_site-siteInfo-editInfo.vm
*
*/
siteProperties = site.getProperties();
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("titleEditableSiteType", state.getAttribute(TITLE_EDITABLE_SITE_TYPE));
context.put("type", site.getType());
List terms = CourseManagementService.getTerms();
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course"))
{
context.put("isCourseSite", Boolean.TRUE);
context.put("skins", state.getAttribute(STATE_ICONS));
if (state.getAttribute(FORM_SITEINFO_SKIN) != null)
{
context.put("selectedIcon",state.getAttribute(FORM_SITEINFO_SKIN));
}
else if (site.getIconUrl() != null)
{
context.put("selectedIcon",site.getIconUrl());
}
if (terms != null && terms.size() >0)
{
context.put("termList", terms);
}
if (state.getAttribute(FORM_SITEINFO_TERM) == null)
{
String currentTerm = site.getProperties().getProperty(PROP_SITE_TERM);
if (currentTerm != null)
{
state.setAttribute(FORM_SITEINFO_TERM, currentTerm);
}
}
if (state.getAttribute(FORM_SITEINFO_TERM) != null)
{
context.put("selectedTerm", state.getAttribute(FORM_SITEINFO_TERM));
}
}
else
{
context.put("isCourseSite", Boolean.FALSE);
if (state.getAttribute(FORM_SITEINFO_ICON_URL) == null && StringUtil.trimToNull(site.getIconUrl()) != null)
{
state.setAttribute(FORM_SITEINFO_ICON_URL, site.getIconUrl());
}
if (state.getAttribute(FORM_SITEINFO_ICON_URL) != null)
{
context.put("iconUrl", state.getAttribute(FORM_SITEINFO_ICON_URL));
}
}
context.put("description", state.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("short_description", state.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("form_site_contact_name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("form_site_contact_email", state.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
//Display of appearance icon/url list with course site based on
// "disable.course.site.skin.selection" value set with sakai.properties file.
if ((ServerConfigurationService.getString("disable.course.site.skin.selection")).equals("true")){
context.put("disableCourseSelection", Boolean.TRUE);
}
return (String)getContext(data).get("template") + TEMPLATE[13];
case 14:
/* buildContextForTemplate chef_site-siteInfo-editInfoConfirm.vm
*
*/
siteProperties = site.getProperties();
siteType = (String)state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course"))
{
context.put("isCourseSite", Boolean.TRUE);
context.put("siteTerm", state.getAttribute(FORM_SITEINFO_TERM));
}
else
{
context.put("isCourseSite", Boolean.FALSE);
}
context.put("oTitle", site.getTitle());
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("description", state.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("oDescription", site.getDescription());
context.put("short_description", state.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("oShort_description", site.getShortDescription());
context.put("skin", state.getAttribute(FORM_SITEINFO_SKIN));
context.put("oSkin", site.getIconUrl());
context.put("skins", state.getAttribute(STATE_ICONS));
context.put("oIcon", site.getIconUrl());
context.put("icon", state.getAttribute(FORM_SITEINFO_ICON_URL));
context.put("include", state.getAttribute(FORM_SITEINFO_INCLUDE));
context.put("oInclude", Boolean.valueOf(site.isPubView()));
context.put("name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("oName", siteProperties.getProperty(PROP_SITE_CONTACT_NAME));
context.put("email", state.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
context.put("oEmail", siteProperties.getProperty(PROP_SITE_CONTACT_EMAIL));
return (String)getContext(data).get("template") + TEMPLATE[14];
case 15:
/* buildContextForTemplate chef_site-addRemoveFeatureConfirm.vm
*
*/
context.put("title", site.getTitle());
site_type = (String)state.getAttribute(STATE_SITE_TYPE);
myworkspace_site = false;
if (SiteService.isUserSite(site.getId()))
{
if (SiteService.getSiteUserId(site.getId()).equals(SessionManager.getCurrentSessionUserId()))
{
myworkspace_site = true;
site_type = "myworkspace";
}
}
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("selectedTools", orderToolIds(state, (String) state.getAttribute(STATE_SITE_TYPE), (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST)));
context.put("oldSelectedTools", state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
context.put("oldSelectedHome", state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME));
context.put("continueIndex", "12");
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null)
{
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService.getServerName());
context.put("newsTitles", (Hashtable) state.getAttribute(STATE_NEWS_TITLES));
context.put("wcTitles", (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES));
if (fromENWModifyView(state))
{
context.put("back", "26");
}
else
{
context.put("back", "4");
}
return (String)getContext(data).get("template") + TEMPLATE[15];
case 16:
/* buildContextForTemplate chef_site-publishUnpublish-sendEmail.vm
*
*/
context.put("title", site.getTitle());
context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY));
return (String)getContext(data).get("template") + TEMPLATE[16];
case 17:
/* buildContextForTemplate chef_site-publishUnpublish-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("continueIndex", "12");
SiteInfo sInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (sInfo.getPublished())
{
context.put("publish", Boolean.TRUE);
context.put("backIndex", "16");
}
else
{
context.put("publish", Boolean.FALSE);
context.put("backIndex", "9");
}
context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY));
return (String)getContext(data).get("template") + TEMPLATE[17];
case 18:
/* buildContextForTemplate chef_siteInfo-editAccess.vm
*
*/
List publicChangeableSiteTypes = (List) state.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES);
List unJoinableSiteTypes = (List) state.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE);
if (site != null)
{
//editing existing site
context.put("site", site);
siteType = state.getAttribute(STATE_SITE_TYPE)!=null?(String)state.getAttribute(STATE_SITE_TYPE):null;
if ( siteType != null
&& publicChangeableSiteTypes.contains(siteType))
{
context.put ("publicChangeable", Boolean.TRUE);
}
else
{
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(site.isPubView()));
if ( siteType != null && !unJoinableSiteTypes.contains(siteType))
{
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
if (state.getAttribute(STATE_JOINABLE) == null)
{
state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site.isJoinable()));
}
if (state.getAttribute(STATE_JOINERROLE) == null
|| state.getAttribute(STATE_JOINABLE) != null && ((Boolean) state.getAttribute(STATE_JOINABLE)).booleanValue())
{
state.setAttribute(STATE_JOINERROLE, site.getJoinerRole());
}
if (state.getAttribute(STATE_JOINABLE) != null)
{
context.put("joinable", state.getAttribute(STATE_JOINABLE));
}
if (state.getAttribute(STATE_JOINERROLE) != null)
{
context.put("joinerRole", state.getAttribute(STATE_JOINERROLE));
}
}
else
{
//site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
context.put("roles", getRoles(state));
context.put("back", "12");
}
else
{
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if ( siteInfo.site_type != null
&& publicChangeableSiteTypes.contains(siteInfo.site_type))
{
context.put ("publicChangeable", Boolean.TRUE);
}
else
{
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(siteInfo.getInclude()));
context.put("published", Boolean.valueOf(siteInfo.getPublished()));
if ( siteInfo.site_type != null && !unJoinableSiteTypes.contains(siteInfo.site_type))
{
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
context.put("joinable", Boolean.valueOf(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
}
else
{
// site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
// use the type's template, if defined
String realmTemplate = "!site.template";
if (siteInfo.site_type != null)
{
realmTemplate = realmTemplate + "." + siteInfo.site_type;
}
try
{
AuthzGroup r = AuthzGroupService.getAuthzGroup(realmTemplate);
context.put("roles", r.getRoles());
}
catch (GroupNotDefinedException e)
{
try
{
AuthzGroup rr = AuthzGroupService.getAuthzGroup("!site.template");
context.put("roles", rr.getRoles());
}
catch (GroupNotDefinedException ee)
{
}
}
// new site, go to confirmation page
context.put("continue", "10");
if (fromENWModifyView(state))
{
context.put("back", "26");
}
else if (state.getAttribute(STATE_IMPORT) != null)
{
context.put("back", "27");
}
else
{
context.put("back", "3");
}
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType!=null && siteType.equalsIgnoreCase("course"))
{
context.put ("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
}
else
{
context.put ("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project"))
{
context.put("isProjectSite", Boolean.TRUE);
}
}
}
return (String)getContext(data).get("template") + TEMPLATE[18];
case 19:
/* buildContextForTemplate chef_site-addParticipant-sameRole.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("participantList", state.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("form_selectedRole", state.getAttribute("form_selectedRole"));
return (String)getContext(data).get("template") + TEMPLATE[19];
case 20:
/* buildContextForTemplate chef_site-addParticipant-differentRole.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("participantList", state.getAttribute(STATE_ADD_PARTICIPANTS));
return (String)getContext(data).get("template") + TEMPLATE[20];
case 21:
/* buildContextForTemplate chef_site-addParticipant-notification.vm
*
*/
context.put("title", site.getTitle());
context.put("sitePublished", Boolean.valueOf(site.isPublished()));
if (state.getAttribute("form_selectedNotify") == null)
{
state.setAttribute("form_selectedNotify", Boolean.FALSE);
}
context.put("notify", state.getAttribute("form_selectedNotify"));
boolean same_role = state.getAttribute("form_same_role")==null?true:((Boolean) state.getAttribute("form_same_role")).booleanValue();
if (same_role)
{
context.put("backIndex", "19");
}
else
{
context.put("backIndex", "20");
}
return (String)getContext(data).get("template") + TEMPLATE[21];
case 22:
/* buildContextForTemplate chef_site-addParticipant-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("participants", state.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("notify", state.getAttribute("form_selectedNotify"));
context.put("roles", getRoles(state));
context.put("same_role", state.getAttribute("form_same_role"));
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("selectedRole", state.getAttribute("form_selectedRole"));
return (String)getContext(data).get("template") + TEMPLATE[22];
case 23:
/* buildContextForTemplate chef_siteInfo-editAccess-globalAccess.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
if (state.getAttribute("form_joinable") == null)
{
state.setAttribute("form_joinable", new Boolean(site.isJoinable()));
}
context.put("form_joinable", state.getAttribute("form_joinable"));
if (state.getAttribute("form_joinerRole") == null)
{
state.setAttribute("form_joinerRole", site.getJoinerRole());
}
context.put("form_joinerRole", state.getAttribute("form_joinerRole"));
return (String)getContext(data).get("template") + TEMPLATE[23];
case 24:
/* buildContextForTemplate chef_siteInfo-editAccess-globalAccess-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("form_joinable", state.getAttribute("form_joinable"));
context.put("form_joinerRole", state.getAttribute("form_joinerRole"));
return (String)getContext(data).get("template") + TEMPLATE[24];
case 25:
/* buildContextForTemplate chef_changeRoles-confirm.vm
*
*/
Boolean sameRole = (Boolean) state.getAttribute(STATE_CHANGEROLE_SAMEROLE);
context.put("sameRole", sameRole);
if (sameRole.booleanValue())
{
// same role
context.put("currentRole", state.getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE));
}
else
{
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
}
roles = getRoles(state);
context.put("roles", roles);
context.put("participantSelectedList", state.getAttribute(STATE_SELECTED_PARTICIPANTS));
if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) != null)
{
context.put("selectedRoles", state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
}
context.put("siteTitle", site.getTitle());
return (String)getContext(data).get("template") + TEMPLATE[25];
case 26:
/* buildContextForTemplate chef_site-modifyENW.vm
*
*/
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
boolean existingSite = site != null? true:false;
if (existingSite)
{
// revising a existing site's tool
context.put("existingSite", Boolean.TRUE);
context.put("back", "4");
context.put("continue", "15");
context.put("function", "eventSubmit_doAdd_remove_features");
}
else
{
// new site
context.put("existingSite", Boolean.FALSE);
context.put("function", "eventSubmit_doAdd_features");
if (state.getAttribute(STATE_IMPORT) != null)
{
context.put("back", "27");
}
else
{
// new site, go to edit access page
context.put("back", "3");
}
context.put("continue", "18");
}
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
String emailId = (String) state.getAttribute(STATE_TOOL_EMAIL_ADDRESS);
if (emailId != null)
{
context.put("emailId", emailId);
}
//titles for news tools
newsTitles = (Hashtable) state.getAttribute(STATE_NEWS_TITLES);
if (newsTitles == null)
{
newsTitles = new Hashtable();
newsTitles.put("sakai.news", NEWS_DEFAULT_TITLE);
state.setAttribute(STATE_NEWS_TITLES, newsTitles);
}
context.put("newsTitles", newsTitles);
//urls for news tools
newsUrls = (Hashtable) state.getAttribute(STATE_NEWS_URLS);
if (newsUrls == null)
{
newsUrls = new Hashtable();
newsUrls.put("sakai.news", NEWS_DEFAULT_URL);
state.setAttribute(STATE_NEWS_URLS, newsUrls);
}
context.put("newsUrls", newsUrls);
// titles for web content tools
wcTitles = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES);
if (wcTitles == null)
{
wcTitles = new Hashtable();
wcTitles.put("sakai.iframe", WEB_CONTENT_DEFAULT_TITLE);
state.setAttribute(STATE_WEB_CONTENT_TITLES, wcTitles);
}
context.put("wcTitles", wcTitles);
//URLs for web content tools
wcUrls = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_URLS);
if (wcUrls == null)
{
wcUrls = new Hashtable();
wcUrls.put("sakai.iframe", WEB_CONTENT_DEFAULT_URL);
state.setAttribute(STATE_WEB_CONTENT_URLS, wcUrls);
}
context.put("wcUrls", wcUrls);
context.put("serverName", ServerConfigurationService.getServerName());
context.put("oldSelectedTools", state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
return (String)getContext(data).get("template") + TEMPLATE[26];
case 27:
/* buildContextForTemplate chef_site-importSites.vm
*
*/
existingSite = site != null? true:false;
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (existingSite)
{
// revising a existing site's tool
context.put("continue", "12");
context.put("back", "28");
context.put("totalSteps", "2");
context.put("step", "2");
context.put("currentSite", site);
}
else
{
// new site, go to edit access page
context.put("back", "3");
if (fromENWModifyView(state))
{
context.put("continue", "26");
}
else
{
context.put("continue", "18");
}
}
context.put (STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put ("selectedTools", orderToolIds(state, site_type, getToolsAvailableForImport(state))); // String toolId's
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
context.put("importSitesTools", state.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("importSupportedTools", importTools());
return (String)getContext(data).get("template") + TEMPLATE[27];
case 28:
/* buildContextForTemplate chef_siteinfo-import.vm
*
*/
context.put("currentSite", site);
context.put("importSiteList", state.getAttribute(STATE_IMPORT_SITES));
context.put("sites", SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null));
return (String)getContext(data).get("template") + TEMPLATE[28];
case 29:
/* buildContextForTemplate chef_siteinfo-duplicate.vm
*
*/
context.put("siteTitle", site.getTitle());
String sType = site.getType();
if (sType != null && sType.equals("course"))
{
context.put("isCourseSite", Boolean.TRUE);
context.put("currentTermId", site.getProperties().getProperty(PROP_SITE_TERM));
context.put("termList", getAvailableTerms());
}
else
{
context.put("isCourseSite", Boolean.FALSE);
}
if (state.getAttribute(SITE_DUPLICATED) == null)
{
context.put("siteDuplicated", Boolean.FALSE);
}
else
{
context.put("siteDuplicated", Boolean.TRUE);
context.put("duplicatedName", state.getAttribute(SITE_DUPLICATED_NAME));
}
return (String)getContext(data).get("template") + TEMPLATE[29];
case 36:
/*
* buildContextForTemplate chef_site-newSiteCourse.vm
*/
if (site != null)
{
context.put("site", site);
context.put("siteTitle", site.getTitle());
terms = CourseManagementService.getTerms();
if (terms != null && terms.size() >0)
{
context.put("termList", terms);
}
List providerCourseList = (List) state.getAttribute(SITE_PROVIDER_COURSE_LIST);
context.put("providerCourseList", providerCourseList);
context.put("manualCourseList", state.getAttribute(SITE_MANUAL_COURSE_LIST));
Term t = (Term) state.getAttribute(STATE_TERM_SELECTED);
context.put ("term", t);
if (t != null)
{
String userId = StringUtil.trimToZero(SessionManager.getCurrentSessionUserId());
List courses = CourseManagementService.getInstructorCourses(userId, t.getYear(), t.getTerm());
if (courses != null && courses.size() > 0)
{
Vector notIncludedCourse = new Vector();
// remove included sites
for (Iterator i = courses.iterator(); i.hasNext(); )
{
Course c = (Course) i.next();
if (!providerCourseList.contains(c.getId()))
{
notIncludedCourse.add(c);
}
}
state.setAttribute(STATE_TERM_COURSE_LIST, notIncludedCourse);
}
else
{
state.removeAttribute(STATE_TERM_COURSE_LIST);
}
}
// step number used in UI
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer("1"));
}
else
{
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
context.put ("selectedProviderCourse", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if(state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
context.put("selectedManualCourse", Boolean.TRUE);
}
context.put ("term", (Term) state.getAttribute(STATE_TERM_SELECTED));
}
if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP))
{
context.put("backIndex", "1");
}
else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO))
{
context.put("backIndex", "");
}
context.put("termCourseList", (List) state.getAttribute(STATE_TERM_COURSE_LIST));
return (String)getContext(data).get("template") + TEMPLATE[36];
case 37:
/*
* buildContextForTemplate chef_site-newSiteCourseManual.vm
*/
if (site != null)
{
context.put("site", site);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
}
buildInstructorSectionsList(state, params, context);
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("form_requiredFieldsSizes", CourseManagementService.getCourseIdRequiredFieldsSizes());
context.put("form_additional", siteInfo.additional);
context.put("form_title", siteInfo.title);
context.put("form_description", siteInfo.description);
context.put("noEmailInIdAccountName", ServerConfigurationService.getString("noEmailInIdAccountName", ""));
context.put("value_uniqname", state.getAttribute(STATE_SITE_QUEST_UNIQNAME));
int number = 1;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
context.put("currentNumber", new Integer(number));
}
context.put("currentNumber", new Integer(number));
context.put("listSize", new Integer(number-1));
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null)
{
List l = (List) state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
context.put ("selectedProviderCourse", l);
context.put("size", new Integer(l.size()-1));
}
if (site != null)
{
context.put("back", "36");
}
else
{
if (state.getAttribute(STATE_AUTO_ADD) != null)
{
context.put("autoAdd", Boolean.TRUE);
context.put("back", "36");
}
else
{
context.put("back", "1");
}
}
context.put("isFutureTerm", state.getAttribute(STATE_FUTURE_TERM_SELECTED));
context.put("weeksAhead", ServerConfigurationService.getString("roster.available.weeks.before.term.start", "0"));
return (String)getContext(data).get("template") + TEMPLATE[37];
case 42:
/* buildContextForTemplate chef_site-gradtoolsConfirm.vm
*
*/
siteInfo = (SiteInfo)state.getAttribute(STATE_SITE_INFO);
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
toolRegistrationList = (Vector) state.getAttribute(STATE_PROJECT_TOOL_LIST);
toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put (STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
context.put (STATE_TOOL_REGISTRATION_LIST, toolRegistrationList ); // %%% use Tool
context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService.getServerName());
context.put("include", new Boolean(siteInfo.include));
return (String)getContext(data).get("template") + TEMPLATE[42];
case 43:
/* buildContextForTemplate chef_siteInfo-editClass.vm
*
*/
bar = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null))
{
bar.add( new MenuEntry(rb.getString("java.addclasses"), "doMenu_siteInfo_addClass"));
}
context.put("menu", bar);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
return (String)getContext(data).get("template") + TEMPLATE[43];
case 44:
/* buildContextForTemplate chef_siteInfo-addCourseConfirm.vm
*
*/
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
context.put("providerAddCourses", state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null)
{
int addNumber = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue() -1;
context.put("manualAddNumber", new Integer(addNumber));
context.put("requestFields", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("backIndex", "37");
}
else
{
context.put("backIndex", "36");
}
//those manual inputs
context.put("form_requiredFields", CourseManagementService.getCourseIdRequiredFields());
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String)getContext(data).get("template") + TEMPLATE[44];
//htripath - import materials from classic
case 45:
/* buildContextForTemplate chef_siteInfo-importMtrlMaster.vm
*
*/
return (String)getContext(data).get("template") + TEMPLATE[45];
case 46:
/* buildContextForTemplate chef_siteInfo-importMtrlCopy.vm
*
*/
// this is for list display in listbox
context.put("allZipSites", state.getAttribute(ALL_ZIP_IMPORT_SITES));
context.put("finalZipSites", state.getAttribute(FINAL_ZIP_IMPORT_SITES));
//zip file
//context.put("zipreffile",state.getAttribute(CLASSIC_ZIP_FILE_NAME));
return (String)getContext(data).get("template") + TEMPLATE[46];
case 47:
/* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String)getContext(data).get("template") + TEMPLATE[47];
case 48:
/* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String)getContext(data).get("template") + TEMPLATE[48];
case 49:
/* buildContextForTemplate chef_siteInfo-group.vm
*
*/
context.put("site", site);
bar = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
if (SiteService.allowUpdateSite(site.getId()) || SiteService.allowUpdateGroupMembership(site.getId()))
{
bar.add( new MenuEntry(rb.getString("editgroup.new"), "doGroup_new"));
}
context.put("menu", bar);
// the group list
sortedBy = (String) state.getAttribute (SORTED_BY);
sortedAsc = (String) state.getAttribute (SORTED_ASC);
if(sortedBy!=null) context.put ("currentSortedBy", sortedBy);
if(sortedAsc!=null) context.put ("currentSortAsc", sortedAsc);
// only show groups created by WSetup tool itself
Collection groups = (Collection) site.getGroups();
List groupsByWSetup = new Vector();
for(Iterator gIterator = groups.iterator(); gIterator.hasNext();)
{
Group gNext = (Group) gIterator.next();
String gProp = gNext.getProperties().getProperty(GROUP_PROP_WSETUP_CREATED);
if (gProp != null && gProp.equals(Boolean.TRUE.toString()))
{
groupsByWSetup.add(gNext);
}
}
if (sortedBy != null && sortedAsc != null)
{
context.put("groups", new SortedIterator (groupsByWSetup.iterator (), new SiteComparator (sortedBy, sortedAsc)));
}
return (String)getContext(data).get("template") + TEMPLATE[49];
case 50:
/* buildContextForTemplate chef_siteInfo-groupedit.vm
*
*/
Group g = getStateGroup(state);
if (g != null)
{
context.put("group", g);
context.put("newgroup", Boolean.FALSE);
}
else
{
context.put("newgroup", Boolean.TRUE);
}
if (state.getAttribute(STATE_GROUP_TITLE) != null)
{
context.put("title", state.getAttribute(STATE_GROUP_TITLE));
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) != null)
{
context.put("description", state.getAttribute(STATE_GROUP_DESCRIPTION));
}
Iterator siteMembers = new SortedIterator (getParticipantList(state).iterator (), new SiteComparator (SORTED_BY_PARTICIPANT_NAME, Boolean.TRUE.toString()));
if (siteMembers != null && siteMembers.hasNext())
{
context.put("generalMembers", siteMembers);
}
Set groupMembersSet = (Set) state.getAttribute(STATE_GROUP_MEMBERS);
if (state.getAttribute(STATE_GROUP_MEMBERS) != null)
{
context.put("groupMembers", new SortedIterator(groupMembersSet.iterator(), new SiteComparator (SORTED_BY_MEMBER_NAME, Boolean.TRUE.toString())));
}
context.put("groupMembersClone", groupMembersSet);
context.put("userDirectoryService", UserDirectoryService.getInstance());
return (String)getContext(data).get("template") + TEMPLATE[50];
case 51:
/* buildContextForTemplate chef_siteInfo-groupDeleteConfirm.vm
*
*/
context.put("site", site);
context.put("removeGroupIds", new ArrayList(Arrays.asList((String[])state.getAttribute(STATE_GROUP_REMOVE))));
return (String)getContext(data).get("template") + TEMPLATE[51];
}
// should never be reached
return (String)getContext(data).get("template") + TEMPLATE[0];
} // buildContextForTemplate
|
diff --git a/src/frontend/org/voltdb/SnapshotDaemon.java b/src/frontend/org/voltdb/SnapshotDaemon.java
index ca79949f6..f345ed808 100644
--- a/src/frontend/org/voltdb/SnapshotDaemon.java
+++ b/src/frontend/org/voltdb/SnapshotDaemon.java
@@ -1,1515 +1,1515 @@
/* This file is part of VoltDB.
* Copyright (C) 2008-2011 VoltDB Inc.
*
* VoltDB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* VoltDB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb;
import java.io.File;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.apache.zookeeper_voltpatches.CreateMode;
import org.apache.zookeeper_voltpatches.KeeperException;
import org.apache.zookeeper_voltpatches.KeeperException.NodeExistsException;
import org.apache.zookeeper_voltpatches.WatchedEvent;
import org.apache.zookeeper_voltpatches.Watcher;
import org.apache.zookeeper_voltpatches.Watcher.Event.EventType;
import org.apache.zookeeper_voltpatches.Watcher.Event.KeeperState;
import org.apache.zookeeper_voltpatches.ZooDefs.Ids;
import org.apache.zookeeper_voltpatches.ZooKeeper;
import org.apache.zookeeper_voltpatches.data.Stat;
import org.json_voltpatches.JSONObject;
import org.voltdb.catalog.SnapshotSchedule;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.ProcedureCallback;
import org.voltdb.logging.VoltLogger;
import org.voltdb.messaging.FastDeserializer;
import org.voltdb.messaging.FastSerializer;
import org.voltdb.network.Connection;
import org.voltdb.sysprocs.SnapshotSave;
/**
* A scheduler of automated snapshots and manager of archived and retained snapshots.
* The new functionality for handling truncation snapshots operates separately from
* the old automated snapshots. They just share the same event processing threads. Future work
* should merge them.
*
*/
public class SnapshotDaemon implements SnapshotCompletionInterest {
private class TruncationSnapshotAttempt {
private String path;
private String nonce;
private boolean finished;
}
static int m_periodicWorkInterval = 2000;
public static volatile int m_userSnapshotRetryInterval = 30;
/*
* Something that initiates procedures for the snapshot daemon.
*/
public interface DaemonInitiator {
public void initiateSnapshotDaemonWork(final String procedureName, long clientData, Object params[]);
};
private static final VoltLogger hostLog = new VoltLogger("HOST");
private static final VoltLogger loggingLog = new VoltLogger("LOGGING");
private final ScheduledExecutorService m_es = new ScheduledThreadPoolExecutor( 1, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "SnapshotDaemon");
}
},
new java.util.concurrent.ThreadPoolExecutor.DiscardPolicy());
private ZooKeeper m_zk;
private DaemonInitiator m_initiator;
private long m_nextCallbackHandle;
private String m_truncationSnapshotPath;
private boolean m_isLeader = false;
/*
* Before doing truncation snapshot operations, wait a few seconds
* to give a few nodes a chance to get into the same state WRT to truncation
* so that a truncation snapshot will can service multiple truncation requests
* that arrive at the same time.
*/
int m_truncationGatheringPeriod = 10;
private final TreeMap<Long, TruncationSnapshotAttempt> m_truncationSnapshotAttempts =
new TreeMap<Long, TruncationSnapshotAttempt>();
private Future<?> m_truncationSnapshotScanTask;
private TimeUnit m_frequencyUnit;
private long m_frequencyInMillis;
private int m_frequency;
private int m_retain;
private String m_path;
private String m_prefix;
private String m_prefixAndSeparator;
private Future<?> m_snapshotTask;
private final HashMap<Long, ProcedureCallback> m_procedureCallbacks = new HashMap<Long, ProcedureCallback>();
private final SimpleDateFormat m_dateFormat = new SimpleDateFormat("'_'yyyy.MM.dd.HH.mm.ss");
// true if this SnapshotDaemon is the one responsible for generating
// snapshots
private boolean m_isActive = false;
private long m_nextSnapshotTime;
/**
* Don't invoke sysprocs too close together.
* Keep track of the last call and only do it after
* enough time has passed.
*/
private long m_lastSysprocInvocation = System.currentTimeMillis();
static long m_minTimeBetweenSysprocs = 3000;
/**
* List of snapshots on disk sorted by creation time
*/
final LinkedList<Snapshot> m_snapshots = new LinkedList<Snapshot>();
/**
* States the daemon can be in
*
*/
enum State {
/*
* Initial state
*/
STARTUP,
/*
* Invoked @SnapshotScan, waiting for results.
* Done once on startup to find number of snapshots on disk
* at path with prefix
*/
SCANNING,
/*
* Waiting in between snapshots
*/
WAITING,
/*
* Deleting snapshots that are no longer going to be retained.
*/
DELETING,
/*
* Initiated a snapshot. Will call snapshot scan occasionally to find out
* when it completes.
*/
SNAPSHOTTING,
/*
* Failure state. This state is entered when a sysproc
* fails and the snapshot Daemon can't recover. An error is logged
* and the Daemon stops working
*/
FAILURE;
}
private State m_state = State.STARTUP;
SnapshotDaemon() {
m_frequencyUnit = null;
m_retain = 0;
m_frequency = 0;
m_frequencyInMillis = 0;
m_prefix = null;
m_path = null;
m_prefixAndSeparator = null;
// Register the snapshot status to the StatsAgent
SnapshotStatus snapshotStatus = new SnapshotStatus("Snapshot Status");
VoltDB.instance().getStatsAgent().registerStatsSource(SysProcSelector.SNAPSHOTSTATUS,
0,
snapshotStatus);
VoltDB.instance().getSnapshotCompletionMonitor().addInterest(this);
}
public void init(DaemonInitiator initiator, ZooKeeper zk) {
m_initiator = initiator;
m_zk = zk;
try {
zk.create("/nodes_currently_snapshotting", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (Exception e) {}
try {
zk.create("/completed_snapshots", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (Exception e) {}
// Really shouldn't leak this from a constructor, and twice to boot
m_es.execute(new Runnable() {
@Override
public void run() {
leaderElection();
}
});
}
/*
* Search for truncation snapshots, after a failure there may be
* ones we don't know about, there may be ones from a previous instance etc.
* Do this every five minutes as an easy hack to make sure we don't leak them.
* Next time groom is called it will delete the old ones after a success.
*/
private void scanTruncationSnapshots() {
if (m_truncationSnapshotPath == null) {
try {
m_truncationSnapshotPath = new String(m_zk.getData("/test_scan_path", false, null), "UTF-8");
} catch (Exception e) {
return;
}
}
Object params[] = new Object[1];
params[0] = m_truncationSnapshotPath;
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(final ClientResponse clientResponse)
throws Exception {
if (clientResponse.getStatus() != ClientResponse.SUCCESS){
hostLog.error(clientResponse.getStatusString());
return;
}
final VoltTable results[] = clientResponse.getResults();
if (results.length == 1) {
setState(State.FAILURE);
final VoltTable result = results[0];
boolean advanced = result.advanceRow();
assert(advanced);
assert(result.getColumnCount() == 1);
assert(result.getColumnType(0) == VoltType.STRING);
loggingLog.error("Snapshot scan failed with failure response: " + result.getString("ERR_MSG"));
return;
}
assert(results.length == 3);
final VoltTable snapshots = results[0];
assert(snapshots.getColumnCount() == 9);
TreeMap<Long, TruncationSnapshotAttempt> foundSnapshots =
new TreeMap<Long, TruncationSnapshotAttempt>();
while (snapshots.advanceRow()) {
final String path = snapshots.getString("PATH");
final String nonce = snapshots.getString("NONCE");
final Long txnId = snapshots.getLong("TXNID");
TruncationSnapshotAttempt snapshotAttempt = new TruncationSnapshotAttempt();
snapshotAttempt.path = path;
snapshotAttempt.nonce = nonce;
foundSnapshots.put(txnId, snapshotAttempt);
}
for (Map.Entry<Long, TruncationSnapshotAttempt> entry : foundSnapshots.entrySet()) {
if (!m_truncationSnapshotAttempts.containsKey(entry.getKey())) {
loggingLog.info("Truncation snapshot scan discovered new snapshot txnid " + entry.getKey() +
" path " + entry.getValue().path + " nonce " + entry.getValue().nonce);
m_truncationSnapshotAttempts.put(entry.getKey(), entry.getValue());
}
}
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotScan", handle, params);
}
/*
* Delete all snapshots older then the last successful snapshot.
* This only effects snapshots used for log truncation
*/
private void groomTruncationSnapshots() {
ArrayList<TruncationSnapshotAttempt> toDelete = new ArrayList<TruncationSnapshotAttempt>();
boolean foundMostRecentSuccess = false;
Iterator<Map.Entry<Long, TruncationSnapshotAttempt>> iter =
m_truncationSnapshotAttempts.descendingMap().entrySet().iterator();
loggingLog.info("Snapshot daemon grooming truncation snapshots");
while (iter.hasNext()) {
Map.Entry<Long, TruncationSnapshotAttempt> entry = iter.next();
TruncationSnapshotAttempt snapshotAttempt = entry.getValue();
if (!foundMostRecentSuccess) {
if (snapshotAttempt.finished) {
loggingLog.info("Found most recent successful snapshot txnid " + entry.getKey()
+ " path " + entry.getValue().path + " nonce " + entry.getValue().nonce);
foundMostRecentSuccess = true;
} else {
loggingLog.info("Retaining possible partial snapshot txnid " + entry.getKey()
+ " path " + entry.getValue().path + " nonce " + entry.getValue().nonce);
}
} else {
loggingLog.info("Deleting old unecessary snapshot txnid " + entry.getKey()
+ " path " + entry.getValue().path + " nonce " + entry.getValue().nonce);
toDelete.add(entry.getValue());
iter.remove();
}
}
String paths[] = new String[toDelete.size()];
String nonces[] = new String[toDelete.size()];
int ii = 0;
for (TruncationSnapshotAttempt attempt : toDelete) {
paths[ii] = attempt.path;
nonces[ii++] = attempt.nonce;
}
Object params[] =
new Object[] {
paths,
nonces,
};
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(ClientResponse clientResponse)
throws Exception {
if (clientResponse.getStatus() != ClientResponse.SUCCESS) {
hostLog.error(clientResponse.getStatusString());
}
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotDelete", handle, params);
}
/**
* Leader election for snapshots.
* Leader will watch for truncation and user snapshot requests
*/
private void leaderElection() {
loggingLog.info("Starting leader election for snapshot truncation daemon");
try {
while (true) {
Stat stat = m_zk.exists("/snapshot_truncation_master", new Watcher() {
@Override
public void process(WatchedEvent event) {
switch(event.getType()) {
case NodeDeleted:
loggingLog.info("Detected the snapshot truncation leader's ephemeral node deletion");
m_es.execute(new Runnable() {
@Override
public void run() {
leaderElection();
}
});
break;
default:
break;
}
}
});
if (stat == null) {
try {
m_zk.create("/snapshot_truncation_master", null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
m_isLeader = true;
loggingLog.info("This node was selected as the leader for snapshot truncation");
m_truncationSnapshotScanTask = m_es.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
try {
scanTruncationSnapshots();
} catch (Exception e) {
loggingLog.error("Error during scan and group of truncation snapshots");
}
}
}, 0, 1, TimeUnit.HOURS);
truncationRequestExistenceCheck();
userSnapshotRequestExistenceCheck();
return;
} catch (NodeExistsException e) {
}
} else {
loggingLog.info("Leader election concluded, a leader already exists");
break;
}
}
} catch (Exception e) {
loggingLog.fatal("Exception in snapshot daemon electing master via ZK", e);
VoltDB.crashVoltDB();
}
}
/*
* Process the event generated when the node for a truncation request
* is created, reschedules it for a few seconds later
*/
private void processTruncationRequestEvent(final WatchedEvent event) {
if (event.getType() == EventType.NodeCreated) {
/*
* Do it five seconds later because these requests tend to come in bunches
* and we want one truncation snapshot to do truncation for all nodes
* so we don't get them back to back
*/
m_es.schedule(new Runnable() {
@Override
public void run() {
processSnapshotTruncationRequestCreated(event);
}
}, m_truncationGatheringPeriod, TimeUnit.SECONDS);
return;
}
}
/*
* A ZK event occured requestion a truncation snapshot be taken
*/
private void processSnapshotTruncationRequestCreated(
final WatchedEvent event) {
loggingLog.info("Snapshot truncation leader received snapshot truncation request");
String snapshotPathTemp;
try {
snapshotPathTemp = new String(m_zk.getData("/truncation_snapshot_path", false, null), "UTF-8");
} catch (Exception e) {
loggingLog.error("Unable to retrieve truncation snapshot path from ZK, log can't be truncated");
return;
}
m_truncationSnapshotPath = snapshotPathTemp;
final String snapshotPath = snapshotPathTemp;
final long now = System.currentTimeMillis();
final String nonce = Long.toString(now);
//Allow nodes to check and see if the nonce incoming for a snapshot is
//for a truncation snapshot. In that case they will mark the completion node
//to be for a truncation snapshot. SnapshotCompletionMonitor notices the mark.
try {
ByteBuffer payload = ByteBuffer.allocate(8);
payload.putLong(0, now);
m_zk.setData("/request_truncation_snapshot", payload.array(), -1);
} catch (Exception e) {
loggingLog.error("Setting data on the truncation snapshot request in ZK should never fail", e);
//Cause a cascading failure?
VoltDB.crashVoltDB();
}
final Object params[] = new Object[3];
params[0] = snapshotPath;
params[1] = nonce;
params[2] = 0;//don't block
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(ClientResponse clientResponse)
throws Exception {
if (clientResponse.getStatus() != ClientResponse.SUCCESS){
loggingLog.warn(
"Attempt to initiate a truncation snapshot was not successful: " +
clientResponse.getStatusString());
loggingLog.warn("Retrying log truncation snapshot in 5 minutes");
/*
* Try again in a few minute
*/
m_es.schedule(new Runnable() {
@Override
public void run() {
processTruncationRequestEvent(event);
}
}, 5, TimeUnit.MINUTES);
return;
}
final VoltTable results[] = clientResponse.getResults();
final VoltTable result = results[0];
boolean success = true;
if (result.getColumnCount() == 1) {
boolean advanced = result.advanceRow();
assert(advanced);
assert(result.getColumnCount() == 1);
assert(result.getColumnType(0) == VoltType.STRING);
loggingLog.error("Snapshot failed with failure response: " + result.getString(0));
success = false;
}
//assert(result.getColumnName(1).equals("TABLE"));
if (success) {
while (result.advanceRow()) {
if (!result.getString("RESULT").equals("SUCCESS")) {
success = false;
loggingLog.warn("Snapshot save feasibility test failed for host "
+ result.getLong("HOST_ID") + " table " + result.getString("TABLE") +
" with error message " + result.getString("ERR_MSG"));
}
}
}
if (success) {
/*
* Race to create the completion node before deleting
* the request node so that we can guarantee that the
* completion node will have the correct information
*/
JSONObject obj = new JSONObject(clientResponse.getAppStatusString());
final long snapshotTxnId = Long.valueOf(obj.getLong("txnId"));
int hosts = VoltDB.instance().getCatalogContext().siteTracker
.getAllLiveHosts().size();
SnapshotSaveAPI.createSnapshotCompletionNode(snapshotTxnId,
true, hosts);
/*
* Truncation requests tend to come in clusters, wait 5 seconds before
* deleting the request so that they don't always happen back to back
*/
m_es.schedule(new Runnable() {
@Override
public void run() {
try {
try {
m_zk.delete("/request_truncation_snapshot", -1);
} catch (Exception e) {
VoltDB.crashLocalVoltDB(
"Unexpected error deleting truncation snapshot request", true, e);
}
TruncationSnapshotAttempt snapshotAttempt =
m_truncationSnapshotAttempts.get(snapshotTxnId);
if (snapshotAttempt == null) {
snapshotAttempt = new TruncationSnapshotAttempt();
m_truncationSnapshotAttempts.put(snapshotTxnId, snapshotAttempt);
}
snapshotAttempt.nonce = nonce;
snapshotAttempt.path = snapshotPath;
} finally {
try {
truncationRequestExistenceCheck();
} catch (Exception e) {
VoltDB.crashLocalVoltDB(
"Unexpected error checking for existence of truncation snapshot request"
, true, e);
}
}
}
}, m_truncationGatheringPeriod, TimeUnit.SECONDS);
} else {
loggingLog.info("Retrying log truncation snapshot in 60 seconds");
/*
* Try again in a few minutes
*/
m_es.schedule(new Runnable() {
@Override
public void run() {
processTruncationRequestEvent(event);
}
}, 1, TimeUnit.MINUTES);
}
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotSave", handle, params);
return;
}
/*
* Watcher that handles changes to the ZK node for
* internal truncation snapshot requests
*/
private final Watcher m_truncationRequestExistenceWatcher = new Watcher() {
@Override
public void process(final WatchedEvent event) {
if (event.getState() == KeeperState.Disconnected) return;
m_es.execute(new Runnable() {
@Override
public void run() {
processTruncationRequestEvent(event);
}
});
}
};
/*
* Watcher that handles events to the user snapshot request node
* in ZK
*/
private final Watcher m_userSnapshotRequestExistenceWatcher = new Watcher() {
@Override
public void process(final WatchedEvent event) {
if (event.getState() == KeeperState.Disconnected) return;
m_es.execute(new Runnable() {
@Override
public void run() {
try {
processUserSnapshotRequestEvent(event);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Error processing user snapshot request event", false, e);
}
}
});
}
};
/*
* Process the event generated when the node for a user snapshot request
* is created.
*/
private void processUserSnapshotRequestEvent(final WatchedEvent event) throws Exception {
if (event.getType() == EventType.NodeCreated) {
byte data[] = m_zk.getData(event.getPath(), false, null);
String jsonString = new String(data, "UTF-8");
JSONObject jsObj = new JSONObject(jsonString);
final String path = jsObj.getString("path");
final String nonce = jsObj.getString("nonce");
final long blocking = jsObj.getLong("blocking");
final String requestId = jsObj.getString("requestId");
final long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(ClientResponse clientResponse)
throws Exception {
/*
* If there is an error then we are done.
*/
if (clientResponse.getStatus() != ClientResponse.SUCCESS) {
hostLog.error(clientResponse.getStatusString());
FastSerializer fs = new FastSerializer();
fs.writeObject((ClientResponseImpl)clientResponse);
m_zk.create(
"/user_snapshot_response_" + requestId, fs.getBytes(),
Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
//Reset the watch
userSnapshotRequestExistenceCheck();
}
/*
* Now analyze the response. If a snapshot was in progress
* we have to reattempt it later, and send a response to the client
* saying it was queued. Otherwise, forward the response
* failure/success to the client.
*/
if (isSnapshotInProgressResponse(clientResponse)) {
scheduleSnapshotForLater( path, nonce, blocking, requestId, true);
} else {
FastSerializer fs = new FastSerializer();
fs.writeObject((ClientResponseImpl)clientResponse);
m_zk.create(
"/user_snapshot_response_" + requestId, fs.getBytes(),
Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
//Reset the watch
userSnapshotRequestExistenceCheck();
}
}
});
m_initiator.initiateSnapshotDaemonWork(
"@SnapshotSave",
handle,
new Object[] { path, nonce, blocking });
return;
}
}
/*
* Schedule a user snapshot request for later since the database was busy.
* Continue doing this as long as the error response returned by the DB is snapshot in progress.
* Since the snapshot is being scheduled for later we will send an immediate response to the client
* via ZK relay.
*/
private void scheduleSnapshotForLater(
final String path,
final String nonce,
final long blocking,
final String requestId,
final boolean isFirstAttempt
) throws Exception {
/*
* Only need to send the queue response the first time we attempt to schedule the snapshot
* for later. It may be necessary to reschedule via this function multiple times.
*/
if (isFirstAttempt) {
hostLog.info("A user snapshot request could not be immediately fulfilled and will be reattempted later");
/*
* Construct a result to send to the client right now via ZK
* saying we queued it to run later
*/
VoltTable result = SnapshotSave.constructNodeResultsTable();
result.addRow(-1,
org.voltdb.client.ConnectionUtil.getHostnameOrAddress(),
"",
"SUCCESS",
"SNAPSHOT REQUEST QUEUED");
final ClientResponseImpl queuedResponse =
new ClientResponseImpl(ClientResponseImpl.SUCCESS,
new VoltTable[] { result },
"Snapshot request could not be fulfilled because a snapshot " +
"is in progress. It was queued for execution",
0);
FastSerializer fs = new FastSerializer();
fs.writeObject(queuedResponse);
m_zk.create("/user_snapshot_response_" + requestId, fs.getBytes(),
Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
}
/*
* Now queue the request for later
*/
final Runnable r = new Runnable() {
@Override
public void run() {
/*
* Construct a callback to handle the response to the
* @SnapshotSave invocation that will reattempt the user snapshot
*/
final long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(ClientResponse clientResponse)
throws Exception {
/*
* If there is an error then we are done
* attempting this user snapshot. The params must be bad
* or things are broken.
*/
if (clientResponse.getStatus() != ClientResponse.SUCCESS) {
hostLog.error(clientResponse.getStatusString());
//Reset the watch, in case this is recoverable
userSnapshotRequestExistenceCheck();
}
VoltTable results[] = clientResponse.getResults();
//Do this check to avoid an NPE
if (results == null || results.length == 0 || results[0].getRowCount() < 1) {
hostLog.error("Queued user snapshot request reattempt received an unexpected response" +
" and will not be reattempted");
/*
* Don't think this should happen, reset the watch to allow later requests
*/
userSnapshotRequestExistenceCheck();
}
VoltTable result = results[0];
boolean snapshotInProgress = false;
boolean haveFailure = false;
while (result.advanceRow()) {
if (result.getString("RESULT").equals("FAILURE")) {
if (result.getString("ERR_MSG").equals("SNAPSHOT IN PROGRESS")) {
snapshotInProgress = true;
} else {
haveFailure = true;
}
}
}
/*
* If a snapshot was in progress, reattempt later, otherwise,
* if there was a failure, abort the attempt and log.
*/
if (snapshotInProgress) {
hostLog.info("Queued user snapshot was reattempted, but a snapshot was " +
" still in progress. It will be reattempted.");
//Turtles all the way down
scheduleSnapshotForLater(
path,
nonce,
blocking,
null,//null because it shouldn't be used, request already responded to
false);
} else if (haveFailure) {
hostLog.info("Queued user snapshot was attempted, but there was a failure.");
//Reset the watch, in case this is recoverable
userSnapshotRequestExistenceCheck();
//Log the details of the failure, after resetting the watch in case of some odd NPE
result.resetRowPosition();
hostLog.info(result);
} else {
/*
* Snapshot was started no problem, reset the watch for new requests
*/
userSnapshotRequestExistenceCheck();
}
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotSave", handle,
new Object[] { path, nonce, blocking });
}
};
m_es.schedule(r, m_userSnapshotRetryInterval, TimeUnit.SECONDS);
}
/*
* Check a client response to and determine if it is a snapshot in progress response
* to a snapshot request
*/
private boolean isSnapshotInProgressResponse(
ClientResponse response) {
if (response.getStatus() != ClientResponse.SUCCESS) {
return false;
}
if (response.getResults() == null) {
return false;
}
if (response.getResults().length < 1) {
return false;
}
VoltTable results = response.getResults()[0];
if (results.getRowCount() < 1) {
return false;
}
boolean snapshotInProgress = false;
while (results.advanceRow()) {
if (results.getString("RESULT").equals("FAILURE")) {
if (results.getString("ERR_MSG").equals("SNAPSHOT IN PROGRESS")) {
snapshotInProgress = true;
}
}
}
return snapshotInProgress;
}
/*
* Set the watch in ZK on the node that represents an internal request
* for a truncation snapshot
*/
void truncationRequestExistenceCheck() throws KeeperException, InterruptedException {
if (m_zk.exists("/request_truncation_snapshot", m_truncationRequestExistenceWatcher) != null) {
processTruncationRequestEvent(new WatchedEvent(
EventType.NodeCreated,
KeeperState.SyncConnected,
"/snapshot_truncation_master"));
}
}
/*
* Set the watch in ZK on the node that represents a user
* request for a snapshot
*/
void userSnapshotRequestExistenceCheck() throws Exception {
m_zk.delete("/user_snapshot_request", -1, null, null);
if (m_zk.exists("/user_snapshot_request", m_userSnapshotRequestExistenceWatcher) != null) {
processUserSnapshotRequestEvent(new WatchedEvent(
EventType.NodeCreated,
KeeperState.SyncConnected,
"/user_snapshot_request"));
}
}
/**
* Make this SnapshotDaemon responsible for generating snapshots
*/
public Future<Void> makeActive(final SnapshotSchedule schedule)
{
return m_es.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
makeActivePrivate(schedule);
return null;
}
});
}
private void makeActivePrivate(final SnapshotSchedule schedule) {
m_isActive = true;
m_frequency = schedule.getFrequencyvalue();
m_retain = schedule.getRetain();
m_path = schedule.getPath();
m_prefix = schedule.getPrefix();
m_prefixAndSeparator = m_prefix + "_";
final String frequencyUnitString = schedule.getFrequencyunit().toLowerCase();
assert(frequencyUnitString.length() == 1);
final char frequencyUnit = frequencyUnitString.charAt(0);
switch (frequencyUnit) {
case 's':
m_frequencyUnit = TimeUnit.SECONDS;
break;
case 'm':
m_frequencyUnit = TimeUnit.MINUTES;
break;
case 'h':
m_frequencyUnit = TimeUnit.HOURS;
break;
default:
throw new RuntimeException("Frequency unit " + frequencyUnitString + "" +
" in snapshot schedule is not one of d,m,h");
}
m_frequencyInMillis = TimeUnit.MILLISECONDS.convert( m_frequency, m_frequencyUnit);
m_nextSnapshotTime = System.currentTimeMillis() + m_frequencyInMillis;
m_es.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
doPeriodicWork(System.currentTimeMillis());
} catch (Exception e) {
}
}
}, 0, m_periodicWorkInterval, TimeUnit.MILLISECONDS);
}
public void makeInactive() {
m_es.execute(new Runnable() {
@Override
public void run() {
m_isActive = false;
m_snapshots.clear();
}
});
}
private class Snapshot implements Comparable<Snapshot> {
private final String path;
private final String nonce;
private final Long txnId;
private Snapshot (String path, String nonce, Long txnId) {
this.path = path;
this.nonce = nonce;
this.txnId = txnId;
}
@Override
public int compareTo(Snapshot o) {
return txnId.compareTo(o.txnId);
}
@Override
public String toString() {
return path + "/" + nonce;
}
}
/**
* Invoked by the client interface occasionally. Returns null
* if nothing needs to be done or the name of a sysproc along with procedure parameters
* if there is work to be done. Responses come back later via invocations
* of processClientResponse
* @param now Current time
* @return null if there is no work to do or a sysproc with parameters if there is work
*/
private void doPeriodicWork(final long now) {
if (!m_isActive)
{
setState(State.STARTUP);
return;
}
if (m_frequencyUnit == null) {
return;
}
if (m_state == State.STARTUP) {
initiateSnapshotScan();
} else if (m_state == State.SCANNING) {
return;
} else if (m_state == State.FAILURE) {
return;
} else if (m_state == State.WAITING){
processWaitingPeriodicWork(now);
} else if (m_state == State.SNAPSHOTTING) {
return;
} else if (m_state == State.DELETING){
return;
}
}
/**
* Do periodic work when the daemon is in the waiting state. The
* daemon paces out sysproc invocations over time
* to avoid disrupting regular work. If the time for the next
* snapshot has passed it attempts to initiate a new snapshot.
* If there are too many snapshots being retains it attempts to delete
* the extras. Then it attempts to initiate a new snapshot if
* one is due
*/
private void processWaitingPeriodicWork(long now) {
if (now - m_lastSysprocInvocation < m_minTimeBetweenSysprocs) {
return;
}
if (m_snapshots.size() > m_retain) {
//Quick hack to make sure we don't delete while the snapshot is running.
//Deletes work really badly during a snapshot because the FS is occupied
if (SnapshotSiteProcessor.ExecutionSitesCurrentlySnapshotting.get() > 0) {
m_lastSysprocInvocation = System.currentTimeMillis() + 3000;
return;
}
deleteExtraSnapshots();
return;
}
if (m_nextSnapshotTime < now) {
initiateNextSnapshot(now);
return;
}
}
private void initiateNextSnapshot(long now) {
setState(State.SNAPSHOTTING);
m_lastSysprocInvocation = now;
final Date nowDate = new Date(now);
final String dateString = m_dateFormat.format(nowDate);
final String nonce = m_prefix + dateString;
Object params[] = new Object[3];
params[0] = m_path;
params[1] = nonce;
params[2] = 0;//don't block
m_snapshots.offer(new Snapshot(m_path, nonce, now));
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(final ClientResponse clientResponse)
throws Exception {
processClientResponsePrivate(clientResponse);
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotSave", handle, params);
}
/**
* Invoke the @SnapshotScan system procedure to discover
* snapshots on disk that are managed by this daemon
* @return
*/
private void initiateSnapshotScan() {
m_lastSysprocInvocation = System.currentTimeMillis();
Object params[] = new Object[1];
params[0] = m_path;
setState(State.SCANNING);
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(final ClientResponse clientResponse)
throws Exception {
processClientResponsePrivate(clientResponse);
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotScan", handle, params);
}
/**
* Process responses to sysproc invocations generated by this daemon
* via processPeriodicWork
* @param response
* @return
*/
public Future<Void> processClientResponse(final ClientResponse response, final long handle) {
return m_es.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
try {
m_procedureCallbacks.remove(handle).clientCallback(response);
} catch (Exception e) {
- hostLog.warn(e);
+ hostLog.warn("Error when SnapshotDaemon invoked callback for a procedure invocation", e);
throw e;
}
return null;
}
});
}
private void processClientResponsePrivate(ClientResponse response) {
if (m_frequencyUnit == null) {
throw new RuntimeException("SnapshotDaemon received a response when it has not been configured to run");
}
if (m_state == State.STARTUP) {
throw new RuntimeException("SnapshotDaemon received a response in the startup state");
} else if (m_state == State.SCANNING) {
processScanResponse(response);
} else if (m_state == State.FAILURE) {
return;
} else if (m_state == State.DELETING){
processDeleteResponse(response);
return;
} else if (m_state == State.SNAPSHOTTING){
processSnapshotResponse(response);
return;
}
}
/**
* Confirm and log that the snapshot was a success
* @param response
*/
private void processSnapshotResponse(ClientResponse response) {
setState(State.WAITING);
final long now = System.currentTimeMillis();
m_nextSnapshotTime += m_frequencyInMillis;
if (m_nextSnapshotTime < now) {
m_nextSnapshotTime = now - 1;
}
if (response.getStatus() != ClientResponse.SUCCESS){
setState(State.FAILURE);
logFailureResponse("Snapshot failed", response);
return;
}
final VoltTable results[] = response.getResults();
final VoltTable result = results[0];
if (result.getColumnCount() == 1) {
boolean advanced = result.advanceRow();
assert(advanced);
assert(result.getColumnCount() == 1);
assert(result.getColumnType(0) == VoltType.STRING);
hostLog.error("Snapshot failed with failure response: " + result.getString(0));
m_snapshots.removeLast();
return;
}
//assert(result.getColumnName(1).equals("TABLE"));
boolean success = true;
while (result.advanceRow()) {
if (!result.getString("RESULT").equals("SUCCESS")) {
success = false;
hostLog.warn("Snapshot save feasibility test failed for host "
+ result.getLong("HOST_ID") + " table " + result.getString("TABLE") +
" with error message " + result.getString("ERR_MSG"));
}
}
if (!success) {
m_snapshots.removeLast();
}
}
/**
* Process a response to a request to delete snapshots.
* Always transitions to the waiting state even if the delete
* fails. This ensures the system will continue to snapshot
* until the disk is full in the event that there is an administration
* error or a bug.
* @param response
*/
private void processDeleteResponse(ClientResponse response) {
//Continue snapshotting even if a delete fails.
setState(State.WAITING);
if (response.getStatus() != ClientResponse.SUCCESS){
/*
* The delete may fail but the procedure should at least return success...
*/
setState(State.FAILURE);
logFailureResponse("Delete of snapshots failed", response);
return;
}
final VoltTable results[] = response.getResults();
assert(results.length > 0);
if (results[0].getColumnCount() == 1) {
final VoltTable result = results[0];
boolean advanced = result.advanceRow();
assert(advanced);
assert(result.getColumnCount() == 1);
assert(result.getColumnType(0) == VoltType.STRING);
hostLog.error("Snapshot delete failed with failure response: " + result.getString("ERR_MSG"));
return;
}
}
/**
* Process the response to a snapshot scan. Find the snapshots
* that are managed by this daemon by path and nonce
* and add it the list. Initiate a delete of any that should
* not be retained
* @param response
* @return
*/
private void processScanResponse(ClientResponse response) {
if (response.getStatus() != ClientResponse.SUCCESS){
setState(State.FAILURE);
logFailureResponse("Initial snapshot scan failed", response);
return;
}
final VoltTable results[] = response.getResults();
if (results.length == 1) {
setState(State.FAILURE);
final VoltTable result = results[0];
boolean advanced = result.advanceRow();
assert(advanced);
assert(result.getColumnCount() == 1);
assert(result.getColumnType(0) == VoltType.STRING);
hostLog.error("Initial snapshot scan failed with failure response: " + result.getString("ERR_MSG"));
return;
}
assert(results.length == 3);
final VoltTable snapshots = results[0];
assert(snapshots.getColumnCount() == 9);
final File myPath = new File(m_path);
while (snapshots.advanceRow()) {
final String path = snapshots.getString("PATH");
final File pathFile = new File(path);
if (pathFile.equals(myPath)) {
final String nonce = snapshots.getString("NONCE");
if (nonce.startsWith(m_prefixAndSeparator)) {
final Long txnId = snapshots.getLong("TXNID");
m_snapshots.add(new Snapshot(path, nonce, txnId));
}
}
}
java.util.Collections.sort(m_snapshots);
deleteExtraSnapshots();
}
/**
* Check if there are extra snapshots and initiate deletion
* @return
*/
private void deleteExtraSnapshots() {
if (m_snapshots.size() <= m_retain) {
setState(State.WAITING);
} else {
m_lastSysprocInvocation = System.currentTimeMillis();
setState(State.DELETING);
final int numberToDelete = m_snapshots.size() - m_retain;
String pathsToDelete[] = new String[numberToDelete];
String noncesToDelete[] = new String[numberToDelete];
for (int ii = 0; ii < numberToDelete; ii++) {
final Snapshot s = m_snapshots.poll();
pathsToDelete[ii] = s.path;
noncesToDelete[ii] = s.nonce;
hostLog.info("Snapshot daemon deleting " + s.nonce);
}
Object params[] =
new Object[] {
pathsToDelete,
noncesToDelete,
};
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(final ClientResponse clientResponse)
throws Exception {
processClientResponsePrivate(clientResponse);
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotDelete", handle, params);
}
}
private void logFailureResponse(String message, ClientResponse response) {
hostLog.error(message, response.getException());
if (response.getStatusString() != null) {
hostLog.error(response.getStatusString());
}
}
State getState() {
return m_state;
}
void setState(State state) {
m_state = state;
}
public void shutdown() throws InterruptedException {
if (m_snapshotTask != null) {
m_snapshotTask.cancel(false);
}
if (m_truncationSnapshotScanTask != null) {
m_truncationSnapshotScanTask.cancel(false);
}
m_es.shutdown();
m_es.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
}
/*
* If we are the leader, go ahead an create the procedure invocation to do the work.
* We aren't going to journal this in ZK. if the leader dies there will be no
* one to try and complete the work. C'est la vie.
*/
public void requestUserSnapshot(final StoredProcedureInvocation invocation, final Connection c) {
m_es.submit(new Runnable() {
@Override
public void run() {
submitUserSnapshotRequest(invocation, c);
}
});
}
private void submitUserSnapshotRequest(final StoredProcedureInvocation invocation, final Connection c) {
Object params[] = invocation.getParams().toArray();
/*
* Dang it, have to parse the params here
*/
if (params.length != 3) {
final ClientResponseImpl errorResponse =
new ClientResponseImpl(ClientResponseImpl.GRACEFUL_FAILURE,
new VoltTable[0],
"@SnapshotSave requires 3 parameters. Path, nonce, and blocking",
invocation.clientHandle);
c.writeStream().enqueue(errorResponse);
return;
}
if (params[0] == null) {
final ClientResponseImpl errorResponse =
new ClientResponseImpl(ClientResponseImpl.GRACEFUL_FAILURE,
new VoltTable[0],
"@SnapshotSave path is null",
invocation.clientHandle);
c.writeStream().enqueue(errorResponse);
return;
}
if (params[1] == null) {
final ClientResponseImpl errorResponse =
new ClientResponseImpl(ClientResponseImpl.GRACEFUL_FAILURE,
new VoltTable[0],
"@SnapshotSave nonce is null",
invocation.clientHandle);
c.writeStream().enqueue(errorResponse);
return;
}
if (params[2] == null) {
final ClientResponseImpl errorResponse =
new ClientResponseImpl(ClientResponseImpl.GRACEFUL_FAILURE,
new VoltTable[0],
"@SnapshotSave blocking is null",
invocation.clientHandle);
c.writeStream().enqueue(errorResponse);
return;
}
if (!(params[0] instanceof String)) {
final ClientResponseImpl errorResponse =
new ClientResponseImpl(ClientResponseImpl.GRACEFUL_FAILURE,
new VoltTable[0],
"@SnapshotSave path param is a " + params[0].getClass().getSimpleName() +
" and should be a java.lang.String",
invocation.clientHandle);
c.writeStream().enqueue(errorResponse);
return;
}
if (!(params[1] instanceof String)) {
final ClientResponseImpl errorResponse =
new ClientResponseImpl(ClientResponseImpl.GRACEFUL_FAILURE,
new VoltTable[0],
"@SnapshotSave nonce param is a " + params[0].getClass().getSimpleName() +
" and should be a java.lang.String",
invocation.clientHandle);
c.writeStream().enqueue(errorResponse);
return;
}
if (!(params[2] instanceof Byte ||
params[2] instanceof Short ||
params[2] instanceof Integer ||
params[2] instanceof Long)) {
final ClientResponseImpl errorResponse =
new ClientResponseImpl(ClientResponseImpl.GRACEFUL_FAILURE,
new VoltTable[0],
"@SnapshotSave blocking param is a " + params[0].getClass().getSimpleName() +
" and should be a java.lang.[Byte|Short|Integer|Long]",
invocation.clientHandle);
c.writeStream().enqueue(errorResponse);
return;
}
boolean requestExists = false;
try {
final JSONObject jsObj = new JSONObject();
jsObj.put("path", (params[0]));
jsObj.put("nonce", (params[1]));
final long blocking = ((Number)params[2]).longValue();
jsObj.put("blocking", blocking);
final String requestId = java.util.UUID.randomUUID().toString();
jsObj.put("requestId", requestId);
String zkString = jsObj.toString(4);
byte zkBytes[] = zkString.getBytes("UTF-8");
m_zk.create("/user_snapshot_request", zkBytes, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
registerUserSnapshotResponseWatch(requestId, invocation, c);
} catch (KeeperException.NodeExistsException e) {
requestExists = true;
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Exception while attempting to create user snapshot request in ZK", true, e);
}
if (requestExists) {
VoltTable result = org.voltdb.sysprocs.SnapshotSave.constructNodeResultsTable();
result.addRow(-1,
org.voltdb.client.ConnectionUtil.getHostnameOrAddress(),
"",
"FAILURE",
"SNAPSHOT IN PROGRESS");
final ClientResponseImpl errorResponse =
new ClientResponseImpl(ClientResponseImpl.SUCCESS,
new VoltTable[] { result },
"A request to perform a user snapshot already exists",
invocation.clientHandle);
c.writeStream().enqueue(errorResponse);
return;
}
}
private void registerUserSnapshotResponseWatch(
final String requestId,
final StoredProcedureInvocation invocation,
final Connection c
) throws Exception {
final String responseNode = "/user_snapshot_response_" + requestId;
Stat exists = m_zk.exists(responseNode, new Watcher() {
@Override
public void process(final WatchedEvent event) {
if (event.getState() == KeeperState.Disconnected) return;
switch (event.getType()) {
case NodeCreated:
m_es.submit(new Runnable() {
@Override
public void run() {
try {
processUserSnapshotRequestResponse(
event,
invocation,
c);
} catch (Exception e) {
VoltDB.crashLocalVoltDB(
"Error retrieving user snapshot request response from ZK",
true,
e);
}
}
});
break;
default:
}
}
});
if (exists != null) {
processUserSnapshotRequestResponse(
new WatchedEvent(
EventType.NodeCreated,
KeeperState.SyncConnected,
responseNode),
invocation,
c);
}
}
void processUserSnapshotRequestResponse(
final WatchedEvent event,
final StoredProcedureInvocation invocation,
final Connection c) throws Exception {
byte responseBytes[] = m_zk.getData(event.getPath(), false, null);
try {
m_zk.delete(event.getPath(), -1, null, null);
} catch (Exception e) {
hostLog.error("Error cleaning up user snapshot request response in ZK", e);
}
FastDeserializer fds = new FastDeserializer(responseBytes);
ClientResponseImpl response = fds.readObject(org.voltdb.ClientResponseImpl.class);
response.setClientHandle(invocation.clientHandle);
c.writeStream().enqueue(response);
}
@Override
public CountDownLatch snapshotCompleted(final long txnId, final boolean truncation) {
if (!truncation) {
return new CountDownLatch(0);
}
final CountDownLatch latch = new CountDownLatch(1);
m_es.execute(new Runnable() {
@Override
public void run() {
try {
TruncationSnapshotAttempt snapshotAttempt = m_truncationSnapshotAttempts.get(txnId);
if (snapshotAttempt == null) {
snapshotAttempt = new TruncationSnapshotAttempt();
m_truncationSnapshotAttempts.put(txnId, snapshotAttempt);
}
snapshotAttempt.finished = true;
groomTruncationSnapshots();
} finally {
latch.countDown();
}
}
});
return latch;
}
}
diff --git a/src/frontend/org/voltdb/SnapshotSaveAPI.java b/src/frontend/org/voltdb/SnapshotSaveAPI.java
index f6ece92b8..584a9e435 100644
--- a/src/frontend/org/voltdb/SnapshotSaveAPI.java
+++ b/src/frontend/org/voltdb/SnapshotSaveAPI.java
@@ -1,501 +1,508 @@
/* This file is part of VoltDB.
* Copyright (C) 2008-2011 VoltDB Inc.
*
* VoltDB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* VoltDB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.zookeeper_voltpatches.CreateMode;
import org.apache.zookeeper_voltpatches.KeeperException;
import org.apache.zookeeper_voltpatches.KeeperException.NodeExistsException;
import org.apache.zookeeper_voltpatches.ZooDefs.Ids;
import org.voltdb.ExecutionSite.SystemProcedureExecutionContext;
import org.voltdb.SnapshotSiteProcessor.SnapshotTableTask;
import org.voltdb.agreement.ZKUtil;
import org.voltdb.catalog.Host;
import org.voltdb.catalog.Table;
import org.voltdb.logging.VoltLogger;
import org.voltdb.sysprocs.SnapshotRegistry;
import org.voltdb.sysprocs.SnapshotSave;
import org.voltdb.sysprocs.saverestore.SnapshotUtil;
import org.voltdb.utils.CatalogUtil;
/**
* SnapshotSaveAPI extracts reusuable snapshot production code
* that can be called from the SnapshotSave stored procedure or
* directly from an ExecutionSite thread, perhaps has a message
* or failure action.
*/
public class SnapshotSaveAPI
{
private static final VoltLogger TRACE_LOG = new VoltLogger(SnapshotSaveAPI.class.getName());
private static final VoltLogger HOST_LOG = new VoltLogger("HOST");
/**
* The only public method: do all the work to start a snapshot.
* Assumes that a snapshot is feasible, that the caller has validated it can
* be accomplished, that the caller knows this is a consistent or useful
* transaction point at which to snapshot.
*
* @param file_path
* @param file_nonce
* @param block
* @param startTime
* @param context
* @param hostname
* @return VoltTable describing the results of the snapshot attempt
*/
public VoltTable startSnapshotting(String file_path, String file_nonce, byte block,
long txnId, SystemProcedureExecutionContext context, String hostname)
{
TRACE_LOG.trace("Creating snapshot target and handing to EEs");
final VoltTable result = SnapshotSave.constructNodeResultsTable();
final int numLocalSites = VoltDB.instance().getLocalSites().values().size();
// One site wins the race to create the snapshot targets, populating
// m_taskListsForSites for the other sites and creating an appropriate
// number of snapshot permits.
synchronized (SnapshotSiteProcessor.m_snapshotCreateLock) {
// First time use lazy initialization (need to calculate numLocalSites.
if (SnapshotSiteProcessor.m_snapshotCreateSetupPermit == null) {
SnapshotSiteProcessor.m_snapshotCreateSetupPermit = new Semaphore(numLocalSites);
}
try {
//From within this EE, record the sequence numbers as of the start of the snapshot (now)
//so that the info can be put in the digest.
SnapshotSiteProcessor.populateExportSequenceNumbersForExecutionSite(context);
SnapshotSiteProcessor.m_snapshotCreateSetupPermit.acquire();
} catch (InterruptedException e) {
result.addRow(Integer.parseInt(context.getSite().getHost().getTypeName()),
hostname,
"",
"FAILURE",
e.toString());
return result;
}
if (SnapshotSiteProcessor.m_snapshotCreateSetupPermit.availablePermits() == 0) {
createSetup(file_path, file_nonce, txnId, context, hostname, result);
// release permits for the next setup, now that is one is complete
SnapshotSiteProcessor.m_snapshotCreateSetupPermit.release(numLocalSites);
}
}
// All sites wait for a permit to start their individual snapshot tasks
VoltTable error = acquireSnapshotPermit(context, hostname, result);
if (error != null) {
return error;
}
synchronized (SnapshotSiteProcessor.m_taskListsForSites) {
final Deque<SnapshotTableTask> m_taskList = SnapshotSiteProcessor.m_taskListsForSites.poll();
if (m_taskList == null) {
return result;
} else {
assert(SnapshotSiteProcessor.ExecutionSitesCurrentlySnapshotting.get() > 0);
context.getExecutionSite().initiateSnapshots(
m_taskList,
txnId,
context.getExecutionSite().m_context.siteTracker.getAllLiveHosts().size());
}
}
if (block != 0) {
HashSet<Exception> failures = null;
String status = "SUCCESS";
String err = "";
try {
failures = context.getExecutionSite().completeSnapshotWork();
} catch (InterruptedException e) {
status = "FAILURE";
err = e.toString();
}
final VoltTable blockingResult = SnapshotSave.constructPartitionResultsTable();
if (failures.isEmpty()) {
blockingResult.addRow(
Integer.parseInt(context.getSite().getHost().getTypeName()),
hostname,
Integer.parseInt(context.getSite().getTypeName()),
status,
err);
} else {
status = "FAILURE";
for (Exception e : failures) {
err = e.toString();
}
blockingResult.addRow(
Integer.parseInt(context.getSite().getHost().getTypeName()),
hostname,
Integer.parseInt(context.getSite().getTypeName()),
status,
err);
}
return blockingResult;
}
return result;
}
private void logSnapshotStartToZK(long txnId,
SystemProcedureExecutionContext context, String nonce) {
/*
* Going to send out the requests async to make snapshot init move faster
*/
ZKUtil.StringCallback cb1 = new ZKUtil.StringCallback();
/*
* Log that we are currently snapshotting this snapshot
*/
try {
//This node shouldn't already exist... should have been erased when the last snapshot finished
assert(VoltDB.instance().getZK().exists(
"/nodes_currently_snapshotting/" + VoltDB.instance().getHostMessenger().getHostId(), false)
== null);
ByteBuffer snapshotTxnId = ByteBuffer.allocate(8);
snapshotTxnId.putLong(txnId);
VoltDB.instance().getZK().create(
"/nodes_currently_snapshotting/" + VoltDB.instance().getHostMessenger().getHostId(),
snapshotTxnId.array(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, cb1, null);
} catch (NodeExistsException e) {
HOST_LOG.warn("Didn't expect the snapshot node to already exist", e);
} catch (Exception e) {
VoltDB.crashVoltDB();
}
String nextTruncationNonce = null;
boolean isTruncation = false;
try {
final byte payloadBytes[] =
VoltDB.instance().getZK().getData("/request_truncation_snapshot", false, null);
//request_truncation_snapshot data may be null when initially created. If that is the case
//then this snapshot is definitely not a truncation snapshot because
//the snapshot daemon hasn't gotten around to asking for a truncation snapshot
if (payloadBytes != null) {
ByteBuffer payload = ByteBuffer.wrap(payloadBytes);
nextTruncationNonce = Long.toString(payload.getLong());
}
} catch (KeeperException.NoNodeException e) {}
catch (Exception e) {
HOST_LOG.error("Getting the nonce should never fail with anything other than no node", e);
VoltDB.crashVoltDB();
}
if (nextTruncationNonce == null) {
isTruncation = false;
} else {
if (nextTruncationNonce.equals(nonce)) {
isTruncation = true;
} else {
isTruncation = false;
}
}
/*
* Race with the others to create the place where will count down to completing the snapshot
*/
int hosts = context.getExecutionSite().m_context.siteTracker.getAllLiveHosts().size();
createSnapshotCompletionNode(txnId, isTruncation, hosts);
try {
cb1.get();
} catch (NodeExistsException e) {
HOST_LOG.warn("Didn't expect the snapshot node to already exist", e);
} catch (Exception e) {
VoltDB.crashVoltDB();
}
}
/**
* Create the completion node for the snapshot identified by the txnId. It
* assumes that all hosts will race to call this, so it doesn't fail if the
* node already exists.
*
* @param txnId
* @param isTruncation Whether or not this is a truncation snapshot
* @param hosts The total number of live hosts
*/
public static void createSnapshotCompletionNode(long txnId,
boolean isTruncation,
int hosts) {
+ if (hosts == 0) {
+ VoltDB.crashGlobalVoltDB("Hosts must be greater than 0", true, null);
+ }
+ if (!(txnId > 0)) {
+ VoltDB.crashGlobalVoltDB("Txnid must be greather than 0", true, null);
+ }
+
ByteBuffer buf = ByteBuffer.allocate(17);
buf.putLong(txnId);
buf.putInt(hosts);
buf.putInt(0);
buf.put(isTruncation ? 1 : (byte) 0);
ZKUtil.StringCallback cb = new ZKUtil.StringCallback();
final String snapshotPath = "/completed_snapshots/" + txnId;
VoltDB.instance().getZK().create(
snapshotPath, buf.array(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT,
cb, null);
try {
cb.get();
} catch (KeeperException.NodeExistsException e) {
} catch (Exception e) {
HOST_LOG.fatal("Unexpected exception logging snapshot completion to ZK", e);
VoltDB.crashVoltDB();
}
}
@SuppressWarnings("unused")
private void createSetup(String file_path, String file_nonce,
long txnId, SystemProcedureExecutionContext context,
String hostname, final VoltTable result) {
{
final int numLocalSites = VoltDB.instance().getLocalSites().values().size();
/*
* Used to close targets on failure
*/
final ArrayList<SnapshotDataTarget> targets = new ArrayList<SnapshotDataTarget>();
try {
final ArrayDeque<SnapshotTableTask> partitionedSnapshotTasks =
new ArrayDeque<SnapshotTableTask>();
final ArrayList<SnapshotTableTask> replicatedSnapshotTasks =
new ArrayList<SnapshotTableTask>();
assert(SnapshotSiteProcessor.ExecutionSitesCurrentlySnapshotting.get() == -1);
final List<Table> tables = SnapshotUtil.getTablesToSave(context.getDatabase());
Runnable completionTask = SnapshotUtil.writeSnapshotDigest(
txnId,
file_path,
file_nonce,
tables,
context.getExecutionSite().getCorrespondingHostId(),
SnapshotSiteProcessor.getExportSequenceNumbers());
if (completionTask != null) {
SnapshotSiteProcessor.m_tasksOnSnapshotCompletion.offer(completionTask);
}
completionTask = SnapshotUtil.writeSnapshotCatalog(file_path, file_nonce);
if (completionTask != null) {
SnapshotSiteProcessor.m_tasksOnSnapshotCompletion.offer(completionTask);
}
final AtomicInteger numTables = new AtomicInteger(tables.size());
final SnapshotRegistry.Snapshot snapshotRecord =
SnapshotRegistry.startSnapshot(
txnId,
context.getExecutionSite().getCorrespondingHostId(),
file_path,
file_nonce,
tables.toArray(new Table[0]));
for (final Table table : SnapshotUtil.getTablesToSave(context.getDatabase()))
{
String canSnapshot = "SUCCESS";
String err_msg = "";
final File saveFilePath =
SnapshotUtil.constructFileForTable(table, file_path, file_nonce,
context.getSite().getHost().getTypeName());
SnapshotDataTarget sdt = null;
try {
sdt =
constructSnapshotDataTargetForTable(
context,
saveFilePath,
table,
context.getSite().getHost(),
context.getCluster().getPartitions().size(),
txnId);
targets.add(sdt);
final SnapshotDataTarget sdtFinal = sdt;
final Runnable onClose = new Runnable() {
@Override
public void run() {
snapshotRecord.updateTable(table.getTypeName(),
new SnapshotRegistry.Snapshot.TableUpdater() {
@Override
public SnapshotRegistry.Snapshot.Table update(
SnapshotRegistry.Snapshot.Table registryTable) {
return snapshotRecord.new Table(
registryTable,
sdtFinal.getBytesWritten(),
sdtFinal.getLastWriteException());
}
});
int tablesLeft = numTables.decrementAndGet();
if (tablesLeft == 0) {
final SnapshotRegistry.Snapshot completed =
SnapshotRegistry.finishSnapshot(snapshotRecord);
final double duration =
(completed.timeFinished - org.voltdb.TransactionIdManager.getTimestampFromTransactionId(completed.txnId)) / 1000.0;
HOST_LOG.info(
"Snapshot " + snapshotRecord.nonce + " finished at " +
completed.timeFinished + " and took " + duration
+ " seconds ");
}
}
};
sdt.setOnCloseHandler(onClose);
final SnapshotTableTask task =
new SnapshotTableTask(
table.getRelativeIndex(),
sdt,
table.getIsreplicated(),
table.getTypeName());
if (table.getIsreplicated()) {
replicatedSnapshotTasks.add(task);
} else {
partitionedSnapshotTasks.offer(task);
}
} catch (IOException ex) {
/*
* Creation of this specific target failed. Close it if it was created.
* Continue attempting the snapshot anyways so that at least some of the data
* can be retrieved.
*/
try {
if (sdt != null) {
targets.remove(sdt);
sdt.close();
}
} catch (Exception e) {
HOST_LOG.error(e);
}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
pw.flush();
canSnapshot = "FAILURE";
err_msg = "SNAPSHOT INITIATION OF " + saveFilePath +
"RESULTED IN IOException: \n" + sw.toString();
}
result.addRow(Integer.parseInt(context.getSite().getHost().getTypeName()),
hostname,
table.getTypeName(),
canSnapshot,
err_msg);
}
synchronized (SnapshotSiteProcessor.m_taskListsForSites) {
boolean aborted = false;
if (!partitionedSnapshotTasks.isEmpty() || !replicatedSnapshotTasks.isEmpty()) {
SnapshotSiteProcessor.ExecutionSitesCurrentlySnapshotting.set(
VoltDB.instance().getLocalSites().values().size());
for (int ii = 0; ii < numLocalSites; ii++) {
SnapshotSiteProcessor.m_taskListsForSites.add(new ArrayDeque<SnapshotTableTask>());
}
} else {
SnapshotRegistry.discardSnapshot(snapshotRecord);
aborted = true;
}
/**
* Distribute the writing of replicated tables to exactly one partition.
*/
for (int ii = 0; ii < numLocalSites && !partitionedSnapshotTasks.isEmpty(); ii++) {
SnapshotSiteProcessor.m_taskListsForSites.get(ii).addAll(partitionedSnapshotTasks);
}
int siteIndex = 0;
for (SnapshotTableTask t : replicatedSnapshotTasks) {
SnapshotSiteProcessor.m_taskListsForSites.get(siteIndex++ % numLocalSites).offer(t);
}
if (!aborted) {
logSnapshotStartToZK( txnId, context, file_nonce);
}
}
} catch (Exception ex) {
/*
* Close all the targets to release the threads. Don't let sites get any tasks.
*/
SnapshotSiteProcessor.m_taskListsForSites.clear();
for (SnapshotDataTarget sdt : targets) {
try {
sdt.close();
} catch (Exception e) {
HOST_LOG.error(ex);
}
}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
pw.flush();
result.addRow(
Integer.parseInt(context.getSite().getHost().getTypeName()),
hostname,
"",
"FAILURE",
"SNAPSHOT INITIATION OF " + file_path + file_nonce +
"RESULTED IN Exception: \n" + sw.toString());
HOST_LOG.error(ex);
} finally {
SnapshotSiteProcessor.m_snapshotPermits.release(numLocalSites);
}
}
}
private VoltTable acquireSnapshotPermit(SystemProcedureExecutionContext context,
String hostname, final VoltTable result) {
try {
SnapshotSiteProcessor.m_snapshotPermits.acquire();
} catch (Exception e) {
result.addRow(Integer.parseInt(context.getSite().getHost().getTypeName()),
hostname,
"",
"FAILURE",
e.toString());
return result;
}
return null;
}
private final SnapshotDataTarget constructSnapshotDataTargetForTable(
SystemProcedureExecutionContext context,
File f,
Table table,
Host h,
int numPartitions,
long txnId)
throws IOException
{
return new DefaultSnapshotDataTarget(f,
Integer.parseInt(h.getTypeName()),
context.getCluster().getTypeName(),
context.getDatabase().getTypeName(),
table.getTypeName(),
numPartitions,
table.getIsreplicated(),
SnapshotUtil.getPartitionsOnHost(context, h),
CatalogUtil.getVoltTable(table),
txnId);
}
}
diff --git a/tests/frontend/org/voltdb/TestSnapshotDaemon.java b/tests/frontend/org/voltdb/TestSnapshotDaemon.java
index 06985844d..c54a5a062 100644
--- a/tests/frontend/org/voltdb/TestSnapshotDaemon.java
+++ b/tests/frontend/org/voltdb/TestSnapshotDaemon.java
@@ -1,722 +1,722 @@
/* This file is part of VoltDB.
* Copyright (C) 2008-2011 VoltDB Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.voltdb;
import static org.junit.Assert.*;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.concurrent.Future;
import org.apache.zookeeper_voltpatches.CreateMode;
import org.apache.zookeeper_voltpatches.ZooDefs.Ids;
import org.apache.zookeeper_voltpatches.ZooKeeper;
import org.apache.zookeeper_voltpatches.data.Stat;
import org.json_voltpatches.JSONException;
import org.json_voltpatches.JSONStringer;
import org.junit.*;
import org.voltdb.SnapshotDaemon;
import org.voltdb.catalog.SnapshotSchedule;
import org.voltdb.client.ClientResponse;
import org.voltdb.sysprocs.SnapshotScan;
import org.voltdb.sysprocs.SnapshotSave;
import org.voltdb.VoltTable;
import org.voltdb.VoltTable.ColumnInfo;
public class TestSnapshotDaemon {
static class Initiator implements SnapshotDaemon.DaemonInitiator {
private final SnapshotDaemon daemon;
String procedureName;
long clientData;
Object[] params;
public Initiator() {
this(null);
}
public Initiator(SnapshotDaemon daemon) {
this.daemon = daemon;
}
@Override
public void initiateSnapshotDaemonWork(String procedureName,
long clientData, Object[] params) {
this.procedureName = procedureName;
this.clientData = clientData;
this.params = params;
/*
* Fake a snapshot response if the daemon is set
*/
if (this.daemon != null) {
/*
* We need at least two columns so that the snapshot daemon won't
* think that this is an error.
*/
ColumnInfo column1 = new ColumnInfo("RESULT", VoltType.STRING);
- ColumnInfo column2 = new ColumnInfo("BLAH", VoltType.STRING);
+ ColumnInfo column2 = new ColumnInfo("ERR_MSG", VoltType.STRING);
VoltTable result = new VoltTable(new ColumnInfo[] {column1, column2});
result.addRow("SUCCESS", "BLAH");
JSONStringer stringer = new JSONStringer();
try {
stringer.object();
stringer.key("txnId").value(1);
stringer.endObject();
} catch (JSONException e) {
e.printStackTrace();
}
ClientResponse response =
new ClientResponseImpl(ClientResponse.SUCCESS,
(byte) 0, stringer.toString(),
new VoltTable[] {result}, null);
this.daemon.processClientResponse(response, clientData);
}
}
public void clear() {
procedureName = null;
clientData = Long.MIN_VALUE;
params = null;
}
}
protected Initiator m_initiator;
protected SnapshotDaemon m_daemon;
protected MockVoltDB m_mockVoltDB;
@Before
public void setUp() throws Exception {
SnapshotDaemon.m_periodicWorkInterval = 100;
SnapshotDaemon.m_minTimeBetweenSysprocs = 1000;
}
@After
public void tearDown() throws Exception {
m_daemon.shutdown();
m_mockVoltDB.shutdown(null);
m_mockVoltDB = null;
m_daemon = null;
m_initiator = null;
}
public SnapshotDaemon getSnapshotDaemon() throws Exception {
if (m_daemon != null) {
m_daemon.shutdown();
m_mockVoltDB.shutdown(null);
}
m_mockVoltDB = new MockVoltDB();
VoltDB.replaceVoltDBInstanceForTest(m_mockVoltDB);
m_initiator = new Initiator();
m_daemon = new SnapshotDaemon();
m_daemon.init(m_initiator, m_mockVoltDB.getZK());
return m_daemon;
}
@Test
public void testBadFrequencyAndBasicInit() throws Exception {
SnapshotDaemon noSnapshots = getSnapshotDaemon();
Thread.sleep(60);
assertNull(m_initiator.procedureName);
boolean threwException = false;
try {
Future<Void> future = noSnapshots.processClientResponse(null, 0);
future.get();
} catch (Throwable t) {
threwException = true;
}
assertTrue(threwException);
final SnapshotSchedule schedule = new SnapshotSchedule();
schedule.setFrequencyunit("q");
threwException = false;
SnapshotDaemon d = getSnapshotDaemon();
try {
Future<Void> future = d.makeActive(schedule);
future.get();
} catch (Throwable t) {
threwException = true;
}
assertTrue(threwException);
schedule.setFrequencyunit("s");
d.makeActive(schedule);
schedule.setFrequencyunit("m");
d.makeActive(schedule);
schedule.setFrequencyunit("h");
d.makeActive(schedule);
threwException = false;
try {
Future<Void> future = d.processClientResponse(null, 0);
future.get();
} catch (Throwable t) {
threwException = true;
}
assertTrue(threwException);
}
public SnapshotDaemon getBasicDaemon() throws Exception {
final SnapshotSchedule schedule = new SnapshotSchedule();
schedule.setFrequencyunit("s");
schedule.setFrequencyvalue(1);
schedule.setPath("/tmp");
schedule.setPrefix("woobie");
schedule.setRetain(2);
SnapshotDaemon d = getSnapshotDaemon();
d.makeActive(schedule);
return d;
}
public ClientResponse getFailureResponse() {
return new ClientResponse() {
@Override
public Exception getException() {
return null;
}
@Override
public String getStatusString() {
return "Super fail";
}
@Override
public VoltTable[] getResults() {
return null;
}
@Override
public byte getStatus() {
return ClientResponse.UNEXPECTED_FAILURE;
}
@Override
public int getClusterRoundtrip() {
return 0;
}
@Override
public int getClientRoundtrip() {
return 0;
}
@Override
public byte getAppStatus() {
return 0;
}
@Override
public String getAppStatusString() {
return null;
}
};
}
public ClientResponse getSuccessResponse(final long txnId) {
return new ClientResponse() {
@Override
public byte getStatus() {
return ClientResponse.SUCCESS;
}
@Override
public byte getAppStatus() {
// TODO Auto-generated method stub
return 0;
}
@Override
public VoltTable[] getResults() {
VoltTable result =
new VoltTable(
new ColumnInfo("ERR_MSG", VoltType.STRING),
new ColumnInfo("RESULT", VoltType.STRING));
return new VoltTable[] { result };
}
@Override
public String getStatusString() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getAppStatusString() {
try {
JSONStringer stringer = new JSONStringer();
stringer.object();
stringer.key("txnId").value(Long.toString(txnId));
stringer.endObject();
return stringer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public Exception getException() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getClusterRoundtrip() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getClientRoundtrip() {
// TODO Auto-generated method stub
return 0;
}
};
}
public ClientResponse getErrMsgResponse() {
return new ClientResponse() {
@Override
public Exception getException() {
return null;
}
@Override
public VoltTable[] getResults() {
VoltTable resultTable = new VoltTable(new ColumnInfo("ERR_MSG", VoltType.STRING));
resultTable.addRow("It's a fail!");
return new VoltTable[] { resultTable };
}
@Override
public byte getStatus() {
return ClientResponse.SUCCESS;
}
@Override
public int getClusterRoundtrip() {
return 0;
}
@Override
public int getClientRoundtrip() {
return 0;
}
@Override
public byte getAppStatus() {
return 0;
}
@Override
public String getAppStatusString() {
return null;
}
@Override
public String getStatusString() {
return null;
}
};
}
@Test
public void testFailedScan() throws Exception {
SnapshotDaemon daemon = getBasicDaemon();
Thread.sleep(60);
long handle = m_initiator.clientData;
assertTrue("@SnapshotScan".equals(m_initiator.procedureName));
assertEquals(1, m_initiator.params.length);
assertTrue("/tmp".equals(m_initiator.params[0]));
m_initiator.clear();
Thread.sleep(60);
assertNull(m_initiator.params);
daemon.processClientResponse(getFailureResponse(), handle);
Thread.sleep(60);
assertNull(m_initiator.params);
daemon.processClientResponse(null, 0);
Thread.sleep(60);
assertNull(m_initiator.params);
daemon = getBasicDaemon();
Thread.sleep(60);
assertNotNull(m_initiator.params);
daemon.processClientResponse(getErrMsgResponse(), m_initiator.clientData).get();
assertEquals(SnapshotDaemon.State.FAILURE, daemon.getState());
}
public ClientResponse getSuccessfulScanOneResult() {
return new ClientResponse() {
@Override
public Exception getException() {
return null;
}
@Override
public String getStatusString() {
return null;
}
@Override
public VoltTable[] getResults() {
VoltTable resultTable = new VoltTable(SnapshotScan.clientColumnInfo);
resultTable.addRow(
"/tmp",
"woobie_",
0,
1,
0,
"",
"",
"",
"");
return new VoltTable[] { resultTable, null, null };
}
@Override
public byte getStatus() {
return ClientResponse.SUCCESS;
}
@Override
public int getClusterRoundtrip() {
return 0;
}
@Override
public int getClientRoundtrip() {
return 0;
}
@Override
public byte getAppStatus() {
return 0;
}
@Override
public String getAppStatusString() {
return null;
}
};
}
public ClientResponse getSuccessfulScanThreeResults() {
return new ClientResponse() {
@Override
public Exception getException() {
return null;
}
@Override
public String getStatusString() {
return null;
}
@Override
public VoltTable[] getResults() {
VoltTable resultTable = new VoltTable(SnapshotScan.clientColumnInfo);
resultTable.addRow(
"/tmp",
"woobie_2",
- 0,
+ 2,
2,
0,
"",
"",
"",
"");
resultTable.addRow(
"/tmp",
"woobie_5",
- 0,
+ 5,
5,
0,
"",
"",
"",
"");
resultTable.addRow(
"/tmp",
"woobie_3",
- 0,
+ 3,
3,
0,
"",
"",
"",
"");
return new VoltTable[] { resultTable, null, null };
}
@Override
public byte getStatus() {
return ClientResponse.SUCCESS;
}
@Override
public int getClusterRoundtrip() {
return 0;
}
@Override
public int getClientRoundtrip() {
return 0;
}
@Override
public byte getAppStatus() {
return 0;
}
@Override
public String getAppStatusString() {
return null;
}
};
}
@Test
public void testSuccessfulScan() throws Exception {
SnapshotDaemon daemon = getBasicDaemon();
Thread.sleep(60);
long handle = m_initiator.clientData;
m_initiator.clear();
daemon.processClientResponse(getSuccessfulScanOneResult(), handle).get();
Thread.sleep(60);
assertNull(m_initiator.procedureName);
daemon = getBasicDaemon();
Thread.sleep(60);
handle = m_initiator.clientData;
daemon.processClientResponse(getSuccessfulScanThreeResults(), handle).get();
assertNotNull(m_initiator.procedureName);
assertTrue("@SnapshotDelete".equals(m_initiator.procedureName));
String path = ((String[])m_initiator.params[0])[0];
String nonce = ((String[])m_initiator.params[1])[0];
assertTrue("/tmp".equals(path));
assertTrue("woobie_2".equals(nonce));
handle = m_initiator.clientData;
m_initiator.clear();
Thread.sleep(60);
assertNull(m_initiator.procedureName);
daemon.processClientResponse(getFailureResponse(), handle).get();
assertNull(m_initiator.procedureName);
assertEquals(daemon.getState(), SnapshotDaemon.State.FAILURE);
daemon = getBasicDaemon();
Thread.sleep(60);
handle = m_initiator.clientData;
daemon.processClientResponse(getSuccessfulScanThreeResults(), handle).get();
daemon.processClientResponse(getErrMsgResponse(), 1);
Thread.sleep(60);
assertEquals(daemon.getState(), SnapshotDaemon.State.WAITING);
}
@Test
public void testDoSnapshot() throws Exception {
SnapshotDaemon daemon = getBasicDaemon();
Thread.sleep(60);
long handle = m_initiator.clientData;
m_initiator.clear();
daemon.processClientResponse(getSuccessfulScanOneResult(), handle).get();
assertNull(m_initiator.procedureName);
Thread.sleep(500);
assertNull(m_initiator.procedureName);
Thread.sleep(800);
assertNotNull(m_initiator.procedureName);
assertTrue("@SnapshotSave".equals(m_initiator.procedureName));
assertTrue("/tmp".equals(m_initiator.params[0]));
assertTrue(((String)m_initiator.params[1]).startsWith("woobie_"));
assertEquals(0, m_initiator.params[2]);
handle = m_initiator.clientData;
m_initiator.clear();
daemon.processClientResponse(getFailureResponse(), handle).get();
assertNull(m_initiator.procedureName);
assertEquals(SnapshotDaemon.State.FAILURE, daemon.getState());
daemon = getBasicDaemon();
Thread.sleep(60);
assertNotNull(m_initiator.procedureName);
handle = m_initiator.clientData;
m_initiator.clear();
daemon.processClientResponse(getSuccessfulScanOneResult(), handle);
Thread.sleep(1200);
assertNotNull(m_initiator.procedureName);
handle = m_initiator.clientData;
m_initiator.clear();
daemon.processClientResponse(getErrMsgResponse(), handle).get();
assertEquals(daemon.getState(), SnapshotDaemon.State.WAITING);
daemon = getBasicDaemon();
Thread.sleep(60);
assertNotNull(m_initiator.procedureName);
handle = m_initiator.clientData;
m_initiator.clear();
daemon.processClientResponse(getSuccessfulScanThreeResults(), handle).get();
assertNotNull(m_initiator.procedureName);
handle = m_initiator.clientData;
m_initiator.clear();
daemon.processClientResponse(getErrMsgResponse(), handle).get();
assertNull(m_initiator.procedureName);
Thread.sleep(1200);
assertNotNull(m_initiator.procedureName);
handle = m_initiator.clientData;
m_initiator.clear();
Thread.sleep(1200);
assertNull(m_initiator.procedureName);
daemon.processClientResponse(new ClientResponse() {
@Override
public Exception getException() {
return null;
}
@Override
public String getStatusString() {
return null;
}
@Override
public VoltTable[] getResults() {
VoltTable result = new VoltTable(SnapshotSave.nodeResultsColumns);
result.addRow(0, "desktop", "0", "FAILURE", "epic fail");
return new VoltTable[] { result };
}
@Override
public byte getStatus() {
return ClientResponse.SUCCESS;
}
@Override
public int getClusterRoundtrip() {
return 0;
}
@Override
public int getClientRoundtrip() {
return 0;
}
@Override
public byte getAppStatus() {
return 0;
}
@Override
public String getAppStatusString() {
return null;
}
}, handle).get();
assertEquals(SnapshotDaemon.State.WAITING, daemon.getState());
assertNull(m_initiator.procedureName);
Thread.sleep(1200);
assertNotNull(m_initiator.procedureName);
assertTrue("@SnapshotSave".equals(m_initiator.procedureName));
handle = m_initiator.clientData;
m_initiator.clear();
daemon.processClientResponse(new ClientResponse() {
@Override
public Exception getException() {
return null;
}
@Override
public String getStatusString() {
return null;
}
@Override
public VoltTable[] getResults() {
VoltTable result = new VoltTable(SnapshotSave.nodeResultsColumns);
result.addRow(0, "desktop", "0", "SUCCESS", "epic success");
return new VoltTable[] { result };
}
@Override
public byte getStatus() {
return ClientResponse.SUCCESS;
}
@Override
public int getClusterRoundtrip() {
return 0;
}
@Override
public int getClientRoundtrip() {
return 0;
}
@Override
public byte getAppStatus() {
return 0;
}
@Override
public String getAppStatusString() {
return null;
}
}, handle);
Thread.sleep(1200);
assertNotNull(m_initiator.procedureName);
assertTrue("@SnapshotDelete".equals(m_initiator.procedureName));
}
}
| false | false | null | null |
diff --git a/com.wwm.db.server/src/main/java/com/wwm/db/internal/server/ServerCreateStoreTransaction.java b/com.wwm.db.server/src/main/java/com/wwm/db/internal/server/ServerCreateStoreTransaction.java
index 9f07cceb..a89a3adb 100644
--- a/com.wwm.db.server/src/main/java/com/wwm/db/internal/server/ServerCreateStoreTransaction.java
+++ b/com.wwm.db.server/src/main/java/com/wwm/db/internal/server/ServerCreateStoreTransaction.java
@@ -1,71 +1,70 @@
/******************************************************************************
* Copyright (c) 2005-2008 Whirlwind Match Limited. All rights reserved.
*
* This is open source software; you can use, redistribute and/or modify
* it under the terms of the Open Software Licence v 3.0 as published by the
* Open Source Initiative.
*
* You should have received a copy of the Open Software Licence along with this
* application. if not, contact the Open Source Initiative (www.opensource.org)
*****************************************************************************/
package com.wwm.db.internal.server;
import java.io.IOException;
import java.nio.ByteBuffer;
-import com.wwm.db.core.exceptions.ArchException;
import com.wwm.db.exceptions.StoreExistsException;
import com.wwm.db.exceptions.UnknownStoreException;
import com.wwm.db.internal.comms.messages.CreateStoreCmd;
import com.wwm.db.internal.comms.messages.CreateStoreRsp;
import com.wwm.io.core.MessageSink;
import com.wwm.io.core.messages.Command;
public class ServerCreateStoreTransaction extends ServerTransaction {
private int storeId;
public ServerCreateStoreTransaction(ServerTransactionCoordinator stc, MessageSink source) {
super(stc, source);
}
@Override
public void setWriteCommand(Command command, ByteBuffer packet) {
assert(command instanceof CreateStoreCmd);
super.setWriteCommand(command, packet);
}
@Override
protected void doCommitChecks() {
String storeName = getStoreName();
// Pre checks
try {
stc.getRepository().getStore(storeName);
} catch (UnknownStoreException e) {
return;
}
- throw new StoreExistsException(storeName);
+ throw new StoreExistsException("Store already exists: " + storeName);
}
@Override
protected void doCommit() {
storeId = stc.getRepository().createStore(getStoreName());
}
@Override
protected void sendCommitOk() {
String storeName = getStoreName();
CreateStoreRsp ok = new CreateStoreRsp(command.getCommandId(), storeName, storeId);
try {
source.send(ok);
} catch (IOException e) {
source.close();
}
}
private String getStoreName() {
CreateStoreCmd cmd = (CreateStoreCmd)command;
return cmd.getStoreName();
}
}
diff --git a/com.wwm.db/src/main/java/com/wwm/db/exceptions/StoreExistsException.java b/com.wwm.db/src/main/java/com/wwm/db/exceptions/StoreExistsException.java
index e24f3147..3d375bb8 100644
--- a/com.wwm.db/src/main/java/com/wwm/db/exceptions/StoreExistsException.java
+++ b/com.wwm.db/src/main/java/com/wwm/db/exceptions/StoreExistsException.java
@@ -1,35 +1,25 @@
/******************************************************************************
* Copyright (c) 2005-2008 Whirlwind Match Limited. All rights reserved.
*
* This is open source software; you can use, redistribute and/or modify
* it under the terms of the Open Software Licence v 3.0 as published by the
* Open Source Initiative.
*
* You should have received a copy of the Open Software Licence along with this
* application. if not, contact the Open Source Initiative (www.opensource.org)
*****************************************************************************/
package com.wwm.db.exceptions;
import com.wwm.db.core.exceptions.ArchException;
@SuppressWarnings("serial")
public class StoreExistsException extends ArchException {
- private final String storeName;
public StoreExistsException() {
- storeName = null;
+ super();
}
- public StoreExistsException(String storeName) {
- this.storeName = storeName;
- }
-
- public String getStoreName() {
- return storeName;
- }
-
- @Override
- public String toString() {
- return "Store already exists: " + storeName;
+ public StoreExistsException(String message) {
+ super(message);
}
}
| false | false | null | null |
diff --git a/ggvis4j/src/ch/akuhn/mds/MultidimensionalScaling.java b/ggvis4j/src/ch/akuhn/mds/MultidimensionalScaling.java
index ea04217c..18304183 100644
--- a/ggvis4j/src/ch/akuhn/mds/MultidimensionalScaling.java
+++ b/ggvis4j/src/ch/akuhn/mds/MultidimensionalScaling.java
@@ -1,75 +1,76 @@
package ch.akuhn.mds;
import java.io.PrintStream;
import java.util.EventListener;
import ch.akuhn.org.ggobi.plugins.ggvis.Mds;
/** Multidimensional scaling, based on GGobi/GGvis.
*
* @author Adrian Kuhn, 2009
*
*/
public class MultidimensionalScaling {
double[][] fdistances;
int fiterations = 100;
private PointsListener flistener;
private PrintStream fout;
public MultidimensionalScaling dissimilarities(double[][] matrix) {
for (double[] each: matrix) assert each.length == matrix.length;
fdistances = matrix;
return this;
}
public MultidimensionalScaling listener(PointsListener listener) {
this.flistener = listener;
return this;
}
public MultidimensionalScaling maxIterations(int iterations) {
this.fiterations = iterations;
return this;
}
public double[][] run() {
+ if (fdistances.length == 0) return new double[0][2];
Mds mds = new Mds();
mds.ggvis_init();
mds.init(fdistances);
int len = fdistances.length;
fdistances = null;
while (fiterations > 0) {
if (flistener != null) flistener.update(mds.points());
long t = System.nanoTime();
for (int n = 0; n < 10; n++) mds.mds_once(true);
if (fout != null) fout.printf("%d\n", (int) (1e12 / (System.nanoTime() - t)) * 10);
fiterations -= 10;
}
double[][] points = mds.points();
- mds = null;
assert points.length == len;
for (double[] each: points) assert each.length == 2;
+ mds = null;
return points;
}
public MultidimensionalScaling similarities(double[][] matrix) {
for (double[] each: matrix) assert each.length == matrix.length;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
matrix[i][j] = Math.sqrt(Math.max(0, 1 -matrix[i][j]));
}
}
return this.dissimilarities(matrix);
}
public MultidimensionalScaling verbose() {
fout = System.out;
return this;
}
public interface PointsListener extends EventListener {
public void update(double[][] points);
}
}
diff --git a/ggvis4j/src/ch/akuhn/org/ggobi/plugins/ggvis/Main.java b/ggvis4j/src/ch/akuhn/org/ggobi/plugins/ggvis/Main.java
index 0ce879b6..d9fcbb6a 100644
--- a/ggvis4j/src/ch/akuhn/org/ggobi/plugins/ggvis/Main.java
+++ b/ggvis4j/src/ch/akuhn/org/ggobi/plugins/ggvis/Main.java
@@ -1,34 +1,34 @@
package ch.akuhn.org.ggobi.plugins.ggvis;
import java.io.IOException;
import ch.akuhn.hapax.Hapax;
import ch.akuhn.mds.MultidimensionalScaling;
public class Main {
private transient static boolean VIZ = true;
public static void main(String[] args) throws IOException {
Hapax hapax = Hapax.newCorpus()
.useTFIDF()
.useCamelCaseScanner()
.addFiles("..", ".java")
.build();
System.out.println("done");
Viz viz = VIZ ? new Viz().open() : null;
new MultidimensionalScaling()
.similarities(hapax.getIndex().documentCorrelation().asArray())
.verbose()
.listener(viz)
- .maxIterations(Integer.MAX_VALUE)
+ .maxIterations(10+0*Integer.MAX_VALUE)
.run();
}
}
diff --git a/ggvis4j/src/ch/akuhn/org/ggobi/plugins/ggvis/Mds.java b/ggvis4j/src/ch/akuhn/org/ggobi/plugins/ggvis/Mds.java
index ea2e439f..184d4956 100644
--- a/ggvis4j/src/ch/akuhn/org/ggobi/plugins/ggvis/Mds.java
+++ b/ggvis4j/src/ch/akuhn/org/ggobi/plugins/ggvis/Mds.java
@@ -1,603 +1,603 @@
package ch.akuhn.org.ggobi.plugins.ggvis;
import static java.lang.Math.sqrt;
import static java.lang.Math.pow;
import static java.lang.Math.abs;
/** Multidimensional scaling.
* Initially ported from ggvis and greatly rewritten in Java by Adrian Kuhn.
* Original copyright notice:
*<PRE>/<span/>*
* * mds.c: multidimensional scaling
* * code originally written for xgvis by Michael Littman, greatly extended
* * and tuned by Andreas Buja. Now being ported to ggvis.
* *<span/>/</PRE>
* @author Adrian Kuhn (this in Java)
* @author Andreas Buja (ggvis in C++)
* @author Michael Littman (xgvis in C++)
*
*/
public class Mds extends Ggvisd {
/* these belong in ggv */
double stress, stress_dx, stress_dd, stress_xx;
static final double delta = 1E-10;
static final int ANCHOR = 2;
static final int DRAGGED = 4;
private static final boolean ANCHOR_FIXED = false;
private static final boolean ANCHOR_SCALE = false;
private static final boolean TODO_SYMMETRY = false;
private boolean SAMEGLYPH(int i, int j) {
return (i / 100) == (j / 100);
}
private boolean IS_ANCHOR(int i) {
return i % 100 == 0;
}
private boolean dragged_by_mouse() {
return false;
}
public void init(double[][] dissimilarities) {
this.Dtarget = new array_d();
this.Dtarget.arrayd_alloc(dissimilarities.length, dissimilarities.length);
this.trans_dist.arrayd_alloc(dissimilarities.length, dissimilarities.length);
this.config_dist.arrayd_alloc(dissimilarities.length, dissimilarities.length);
this.ggv_init_Dtarget(dissimilarities); /* populate with INF */
this.ggv_compute_Dtarget(dissimilarities);
this.pos = new array_d();
- this.pos.arrayd_alloc(dissimilarities.length, dissimilarities.length);
- this.gradient.arrayd_alloc(dissimilarities.length, dissimilarities.length);
- for (int a = 0; a < dissimilarities.length; a++) {
- for (int b = 0; b < dissimilarities.length; b++) {
+ this.pos.arrayd_alloc(dissimilarities.length, dim);
+ this.gradient.arrayd_alloc(dissimilarities.length, dim);
+ for (int a = 0; a < pos.vals.length; a++) {
+ for (int b = 0; b < pos.vals[a].length; b++) {
this.pos.vals[a][b] = (Math.random() - 0.5) * 2;
}
}
this.trans_dist.fill(Double.NaN);
this.config_dist.fill(Double.NaN);
}
static final double sig_pow(double x, double p) {
return (x >= 0.0 ? pow(x, p) : -pow(-x, p));
}
double Lp_distance_pow (int i, int j) {
double dsum = 0.0;
int k;
if (this.lnorm == 2. && this.dist_power == 1.) {
for (k = 0; k < this.dim; k++) {
dsum += (this.pos.vals[i][k] - this.pos.vals[j][k]) * (this.pos.vals[i][k] - this.pos.vals[j][k]);
}
return (sqrt(dsum));
} else { /* non-Euclidean or Dtarget power != 1. */
for (k = 0; k < this.dim; k++) {
dsum += pow (abs (this.pos.vals[i][k] - this.pos.vals[j][k]), this.lnorm);
}
return (pow(dsum, this.dist_power_over_lnorm));
}
}
/* begin centering and sizing routines */
void get_center () {
int i, k, n;
this.pos_mean = new double[this.dim];
n = 0;
for (i=0; i<this.pos.nrows; i++) {
if (IS_DRAGGED(i)) continue;
for(k=0; k<this.dim; k++) {
this.pos_mean[k] += this.pos.vals[i][k];
}
n++;
}
for(k=0; k<this.dim; k++) {
this.pos_mean[k] /= n;
}
}
private boolean IS_DRAGGED(int i) {
return false;
}
void get_center_scale () {
int n, i, k;
get_center ();
n = 0;
this.pos_scl = 0.;
for(i=0; i<this.pos.nrows; i++) {
if (IS_DRAGGED(i)) continue;
for (k=0; k<this.dim; k++) {
this.pos_scl += ((this.pos.vals[i][k] - this.pos_mean[k]) *
(this.pos.vals[i][k] - this.pos_mean[k]));
}
n++;
}
this.pos_scl = sqrt(this.pos_scl/(double)n/(double)this.dim);
}
void ggv_center_scale_pos() {
int i, k;
get_center_scale();
for (i=0; i<this.pos.nrows; i++) {
if (IS_DRAGGED(i)) continue;
for (k=0; k<this.dim; k++)
this.pos.vals[i][k] = (this.pos.vals[i][k] - this.pos_mean[k])/this.pos_scl;
}
}
/* end centering and sizing routines */
double dot_prod (int i, int j ) {
double dsum = 0.0;
int k;
for (k=0; k<this.dim; k++) {
dsum += (this.pos.vals[i][k] - this.pos_mean[k]) *
(this.pos.vals[j][k] - this.pos_mean[k]);
}
return(dsum);
}
double L2_norm (double p1[] ) {
double dsum = 0.0;
int k;
for (k = 0; k < this.dim; k++) {
dsum += (p1[k] - this.pos_mean[k])*(p1[k] - this.pos_mean[k]);
}
return(dsum);
}
/*
* weights are only set if weightpow != 0; for 0 there's simpler
*code throughout, and we save space
*/
void set_weights () {
int i, j;
double this_weight;
double local_weight_power = 0.;
double local_within_between = 1.;
/* the weights will be used in metric and nonmetric scaling
* as soon as weightpow != 0. or within_between != 1.
* weights vector only if needed */
if ((this.weight_power != local_weight_power &&
this.weight_power != 0.) ||
(this.within_between != local_within_between &&
this.within_between != 1.))
{
if (this.weights.nels < this.ndistances) /* power weights */ {
this.weights.arrayd_alloc (this.Dtarget.nrows,this.Dtarget.ncols);
}
for (i=0; i<this.Dtarget.nrows; i++) {
for (j=0; j<this.Dtarget.ncols; j++) {
if (Double.isNaN(this.Dtarget.vals[i][j])) {
this.weights.vals[i][j] = Double.NaN;
continue;
}
if (this.weight_power != 0.) {
if(this.Dtarget.vals[i][j] == 0.) { /* cap them */
if (this.weight_power < 0.) {
this.weights.vals[i][j] = 1E5;
continue;
}
else {
this.weights.vals[i][j] = 1E-5;
}
}
this_weight = pow(this.Dtarget.vals[i][j], this.weight_power);
/* cap them */
if (this_weight > 1E5) this_weight = 1E5;
else if (this_weight < 1E-5) this_weight = 1E-5;
/* within-between weighting */
if (SAMEGLYPH(i,j))
this_weight *= (2. - this.within_between);
else
this_weight *= this.within_between;
this.weights.vals[i][j] = this_weight;
} else { /* weightpow == 0. */
if (SAMEGLYPH(i,j))
this_weight = (2. - this.within_between);
else
this_weight = this.within_between;
this.weights.vals[i][j] = this_weight;
}
}
}
}
} /* end set_weights() */
void set_random_selection () {
if (this.rand_select_val != 1.0) {
throw null;
// if (this.rand_sel.length < this.ndistances) {
// this.rand_sel.vectord_realloc(this.ndistances);
// for (i=0; i<this.ndistances; i++) {
// this.rand_sel.els[i] = (double) Math.random(); /* uniform on [0,1] */
// }
// }
// if (!Double.isNaN(this.rand_select_new)) {
// for (i=0; i<this.ndistances; i++)
// this.rand_sel.els[i] = (double) Math.random();
// this.rand_select_new = Double.NaN;
// }
}
} /* end set_random_selection() */
void update_stress () {
int i, j;
double this_weight, dist_config, dist_trans;
stress_dx = stress_xx = stress_dd = 0.0;
for (i=0; i < this.Dtarget.nrows; i++)
for (j=0; j < this.Dtarget.nrows; j++) {
dist_trans = this.trans_dist.vals[i][j];
if (Double.isNaN(dist_trans)) continue;
dist_config = this.config_dist.vals[i][j];
if (this.weight_power == 0. && this.within_between == 1.) {
stress_dx += dist_trans * dist_config;
stress_xx += dist_config * dist_config;
stress_dd += dist_trans * dist_trans;
} else {
this_weight = this.weights.vals[i][j];
stress_dx += dist_trans * dist_config * this_weight;
stress_xx += dist_config * dist_config * this_weight;
stress_dd += dist_trans * dist_trans * this_weight;
}
}
/* calculate stress and draw it */
if (stress_dd * stress_xx > delta*delta) {
stress = pow( 1.0 - stress_dx * stress_dx / stress_xx / stress_dd, 0.5);
// FIXME add_stress_value (stress, ggv);
// draw_stress (ggv, gg);
} else {
throw new Error("didn't draw stress: stress_dx = %5.5g stress_dd = %5.5g stress_xx = %5.5g\n");
}
} /* end update_stress() */
/* we assume in this routine that trans_dist contains
dist.data for KruskalShepard and
-dist.data*dist.data for CLASSIC MDS */
void power_transform () {
if (this.Dtarget_power == 1.) {
return;
} else if (this.Dtarget_power == 2.) {
throw null;
// if (this.KruskalShepard_classic == MDSKSInd.KruskalShepard) {
// for (i=0; i<this.ndistances; i++) {
// tmp = this.trans_dist.els[i];
// if (tmp != Double.MAX_VALUE)
// this.trans_dist.els[i] = tmp*tmp/this.Dtarget_max;
// }
// } else {
// for (i=0; i<this.ndistances; i++) {
// tmp = this.trans_dist.els[i];
// if (tmp != Double.MAX_VALUE)
// this.trans_dist.els[i] = -tmp*tmp/this.Dtarget_max;
// }
// }
} else {
throw null;
// fac = pow (this.Dtarget_max, this.Dtarget_power-1);
// if (this.KruskalShepard_classic == MDSKSInd.KruskalShepard) {
// for(i=0; i<this.ndistances; i++) {
// tmp = this.trans_dist.els[i];
// if (tmp != Double.MAX_VALUE)
// this.trans_dist.els[i] = pow(tmp, this.Dtarget_power)/fac;
// }
// } else {
// for(i=0; i<this.ndistances; i++) {
// tmp = this.trans_dist.els[i];
// if(tmp != Double.MAX_VALUE)
// this.trans_dist.els[i] = -pow(-tmp, this.Dtarget_power)/fac;
// }
// }
}
} /* end power_transform() */
/* ---------------------------------------------------------------- */
/*
* Perform one loop of the iterative mds function.
*
* If doit is False, then we really want to determine the
* stress function without doing anything to the gradient
*/
public void mds_once (boolean doit) {
int num_active_dist_prev = this.num_active_dist;
mds_once_part1();
this.printSymtriacMatrices();
mds_once_part2();
this.printSymtriacMatrices();
mds_once_part3(doit); /* close: if (doit && num_active_dist > 0) */
this.printSymtriacMatrices();
/* experiment: normalize point cloud after using simplified gradient */
// FIXME can we avoid this?
// ggv_center_scale_pos ();
/* update Shepard labels */
if (this.num_active_dist != num_active_dist_prev) {
/*update_shepard_labels (this.num_active_dist);*/
}
} /* end mds_once() */
private void mds_once_part1() {
// /* preparation for transformation */
// if (this.trans_dist.nels < this.ndistances) {
// /* transformation of raw_dist */
// this.trans_dist.arrayd_alloc (this.Dtarget.nrows,this.Dtarget.ncols);
// }
// /* distances of configuration points */
// if (this.config_dist.nels < this.ndistances) {
// this.config_dist.arrayd_alloc (this.Dtarget.nrows,this.Dtarget.ncols);
// }
// /* initialize everytime we come thru because missings may change
// due to user interaction */
// for (int i = 0 ; i < this.Dtarget.nrows; i++) {
// for (int j = 0; j < this.Dtarget.ncols; j++) {
// this.config_dist.els[i][j] = Double.MAX_VALUE;
// this.trans_dist.els[i][j] = Double.MAX_VALUE;
// }
// }
// this.trans_dist.fill(Double.NaN);
// this.config_dist.fill(Double.NaN);
/* weight vector */
set_weights ();
/* random selection vector */
set_random_selection ();
/* anchors of either kind */
// FIXME if (this.anchor_group.length > 0 && this.n_anchors > 0 &&
// (this.anchor_ind == MDSAnchorInd.fixed || this.anchor_ind == MDSAnchorInd.scaled))
// {
// for (i=0; i<this.pos.nrows; i++) {
// if (!IS_EXCLUDED(i) &&
// this.anchor_group.els[this.dsrc.clusterid.els[i]]) /* which d? */
// {
// this.point_status.els[i] = ANCHOR;
// }
// }
// }
/* dragged by mouse */
if (/* TODO imode_get (gg) == MOVEPTS && gg->buttondown && dpos->nearest_point != -1 */
dragged_by_mouse()) {
// TODO if (gg.movepts.cluster_p) {
// TODO for (i=0; i<this.pos.nrows; i++) {
// TODO if (!IS_EXCLUDED(i) && SAMEGLYPH(dpos,i,dpos->nearest_point)) {
// TODO this.point_status.els[i] = DRAGGED;
// TODO }
// TODO }
// TODO } else {
// TODO this.point_status.els[dpos->nearest_point] = DRAGGED;
// TODO }
}
}
private boolean mds_once_part2_continue(int i, int j) {
/* these points do not contribute to the gradient */
if ((ANCHOR_SCALE || ANCHOR_FIXED) && !IS_ANCHOR(j) && !IS_DRAGGED(j)) return true;
if ((ANCHOR_SCALE || ANCHOR_FIXED) && !IS_ANCHOR(i) && !IS_DRAGGED(i)) return true;
/* if the target distance is missing, skip */
if (Double.isNaN(this.Dtarget.vals[i][j])) return true;
/* if weight is zero, skip */
if (this.weights.nels != 0 && this.weights.vals[i][j] == 0.) return true;
/* using groups */
if (this.group_ind == MDSGroupInd.within && !SAMEGLYPH(i,j)) return true;
if (this.group_ind == MDSGroupInd.between && SAMEGLYPH(i,j)) return true;
/*
* if the target distance is within the thresholds
* set using the barplot of distances, keep going.
*/
if (this.Dtarget.vals[i][j] < this.threshold_low ||
this.Dtarget.vals[i][j] > this.threshold_high) return true;
/*
* random selection: needs to be done symmetrically
*/
if (this.rand_select_val < 1.0) {
//if (i < j && this.rand_sel.vals[i][j] > this.rand_select_val) continue;
//if (i > j && this.rand_sel.vals[j][i] > this.rand_select_val) continue;
}
/*
* zero weights:
* assume weights exist if test is positive, and
* can now assume that weights are >0 for non-NA
*/
if (this.weight_power != 0. || this.within_between != 1.) {
if (this.weights.vals[i][j] == 0.) return true;
}
return false;
}
private void mds_once_part2() {
// allocate position and compute means
get_center ();
// collect and count active dissimilarities (j's move i's)
this.num_active_dist = 0;
// i's are moved by j's
for (int i = 0; i < this.Dtarget.nrows; i++) {
// do not exclude moving i's: in non-metric MDS it matters what the set of distances is!
// these points are not moved by the gradient
// if (IS_DRAGGED(i) || (ANCHOR_FIXED && IS_ANCHOR(i))) continue;
/* j's are moving i's */
for (int j = 0; j < this.Dtarget.nrows; j++) {
if (i == j) continue;
if (mds_once_part2_continue(i, j)) continue;
this.num_active_dist++;
/* configuration distance */
this.config_dist.vals[i][j] = Lp_distance_pow(i, j);
this.trans_dist.vals[i][j] = this.Dtarget.vals[i][j];
/* store untransformed dissimilarity in transform vector for now:
* METRIC will transform it; NONMETRIC will used it for sorting first.
*/
} /* j */
} /* i */
/* ------------ end collecting active dissimilarities ------------------ */
}
private void mds_once_part3(boolean doit) {
/* ---------- for active dissimilarities, do some work ------------------ */
if (this.num_active_dist > 0) {
/*-- power transform for metric MDS --*/
power_transform ();
/*-- stress (always lags behind gradient by one step) --*/
update_stress ();
}
/* --- for active dissimilarities, do the gradient push if asked for ----*/
if (doit && this.num_active_dist > 0) {
/* Zero out the gradient matrix. */
this.gradient.arrayd_zero();
/* ------------- gradient accumulation: j's push i's ----------- */
for (int i = 0; i < this.Dtarget.nrows; i++) {
for (int j = 0; j < this.Dtarget.ncols; j++) {
double weight;
double dist_trans = this.trans_dist.vals[i][j];
if (Double.isNaN(dist_trans))
continue;
double dist_config = this.config_dist.vals[i][j];
if (this.weight_power == 0. && this.within_between == 1.) {
weight = 1.0;
} else {
weight = this.weights.vals[i][j];
}
/* gradient */
mds_once_part3_gradient(dist_trans,
dist_config, weight, i, j);
} /* for (j = 0; j < dist.nrows; j++) */
} /* for (i = 0; i < dist.nrows; i++) */
/* ------------- end gradient accumulation ----------- */
/* center the classical gradient */
double gfactor = mds_once_part3_normalizeGradient();
/* add the gradient matrix to the position matrix and drag points */
for (int i=0; i<this.pos.nrows; i++) {
if (!IS_DRAGGED(i)) {
for (int k = 0; k<this.dim; k++) {
this.pos.vals[i][k] += (gfactor * this.gradient.vals[i][k]);
}
} else {
throw null;
// for (int k=0; k < this.dim; k++)
// this.pos.vals[i][k] = dpos.tform.vals[i][k] ;
}
}
}
}
private double mds_once_part3_normalizeGradient() {
double gsum;
double psum;
double gfactor;
/* gradient normalizing factor to scale gradient to a fraction of
the size of the configuration */
gsum = psum = 0.0 ;
for (int i=0; i<this.pos.nrows; i++) {
// if (true || (ANCHOR_SCALE && IS_ANCHOR(i)))
gsum += L2_norm (this.gradient.vals[i]);
psum += L2_norm (this.pos.vals[i]);
}
if (gsum < delta) gfactor = 0.0;
else gfactor = this.stepsize * sqrt(psum/gsum);
return gfactor;
}
private void mds_once_part3_gradient(double dist_trans,
double dist_config, double weight, int i, int j) {
double resid;
double step_mag;
if (abs(dist_config) < delta) dist_config = delta;
/* scale independent version: */
resid = (dist_trans - stress_dx / stress_xx * dist_config);
/* scale dependent version: resid = (dist_trans - dist_config); */
if (this.lnorm != 2) {
assert TODO_SYMMETRY;
/* non-Euclidean Minkowski/Lebesgue metric */
step_mag = weight * resid *
pow (dist_config, 1 - this.lnorm_over_dist_power);
for (int k = 0; k < this.dim; k++) {
this.gradient.vals[i][k] += step_mag *
sig_pow(this.pos.vals[i][k]-this.pos.vals[j][k],
this.lnorm-1.0);
}
} else { /* Euclidean Minkowski/Lebesgue metric */
/* Note the simplification of the code for the special
* cases when dist_power takes on an integer value. */
if (this.dist_power == 1)
step_mag = weight * resid / dist_config;
else if(this.dist_power == 2)
step_mag = weight * resid;
else if (this.dist_power == 3)
step_mag = weight * resid * dist_config;
else if (this.dist_power == 4)
step_mag = weight * resid * dist_config * dist_config;
else
step_mag = weight * resid *
pow(dist_config, this.dist_power-2.);
for (int k = 0; k < this.dim; k++) {
this.gradient.vals[i][k] += step_mag *
(this.pos.vals[i][k]-this.pos.vals[j][k]); /* Euclidean! */
}
}
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/plugins/adufour/roi/ROIMeasures.java b/src/plugins/adufour/roi/ROIMeasures.java
index 33d41b9..a39764a 100644
--- a/src/plugins/adufour/roi/ROIMeasures.java
+++ b/src/plugins/adufour/roi/ROIMeasures.java
@@ -1,474 +1,474 @@
package plugins.adufour.roi;
import icy.gui.main.MainEvent;
import icy.gui.main.MainListener;
import icy.main.Icy;
import icy.roi.ROI2D;
import icy.sequence.Sequence;
import icy.sequence.SequenceEvent;
import icy.sequence.SequenceEvent.SequenceEventSourceType;
import icy.sequence.SequenceListener;
import icy.type.collection.array.Array1DUtil;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import javax.vecmath.Point3d;
import jxl.Workbook;
import jxl.format.Colour;
import jxl.format.RGB;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import plugins.adufour.ezplug.EzButton;
import plugins.adufour.ezplug.EzException;
import plugins.adufour.ezplug.EzPlug;
import plugins.adufour.ezplug.EzVar;
import plugins.adufour.ezplug.EzVarBoolean;
import plugins.adufour.ezplug.EzVarListener;
import plugins.adufour.ezplug.EzVarSequence;
public class ROIMeasures extends EzPlug implements MainListener, SequenceListener
{
private static File xlsFile;
private static WritableWorkbook workbook;
// Create a static workbook instance to make sure a single file is opened
static
{
try
{
xlsFile = File.createTempFile("icy_ROI_Measures_" + UUID.randomUUID().toString(), "xls");
workbook = Workbook.createWorkbook(xlsFile);
}
catch (IOException e)
{
e.printStackTrace();
throw new EzException("ROI Meaasures: unable to initialize\n(see output console for details)", true);
}
}
private final EzVarSequence currentSeq = new EzVarSequence("Current sequence");
private final EzVarBoolean liveUpdate = new EzVarBoolean("Auto-update", true);
private final ExcelTable table = new ExcelTable();
private final HashMap<ROI2D, Color> ROIColors = new HashMap<ROI2D, Color>();
@Override
protected void initialize()
{
getUI().setParametersIOVisible(false);
getUI().setRunButtonText("Update");
getUI().setActionPanelVisible(!liveUpdate.getValue());
addEzComponent(currentSeq);
addEzComponent(liveUpdate);
table.setPreferredSize(new Dimension(500, 100));
addComponent(table);
try
{
xlsFile = File.createTempFile("icy_ROI_Measures_" + UUID.randomUUID().toString(), "xls");
workbook = Workbook.createWorkbook(xlsFile);
}
catch (IOException e)
{
e.printStackTrace();
throw new EzException("ROI Meaasures: unable to initialize\n(see output console for details)", true);
}
EzButton buttonExport = new EzButton("Export to .CSV file...", new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
JFileChooser jfc = new JFileChooser();
jfc.setFileFilter(new FileFilter()
{
@Override
public boolean accept(File f)
{
return f.isDirectory() || f.getAbsolutePath().toLowerCase().endsWith(".csv");
}
@Override
public String getDescription()
{
return ".CSV (Comma Separated Values)";
}
});
if (jfc.showSaveDialog(getUI()) == JFileChooser.APPROVE_OPTION)
{
try
{
ExportCSV.export(workbook, jfc.getSelectedFile(), false);
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
});
addEzComponent(buttonExport);
// Listeners
// add a listener to currently opened sequences
for (final Sequence sequence : Icy.getMainInterface().getSequences())
sequence.addListener(this);
// add a listener to detect newly opened sequences
Icy.getMainInterface().addListener(this);
currentSeq.addVarChangeListener(new EzVarListener<Sequence>()
{
@Override
public void variableChanged(EzVar<Sequence> source, Sequence sequence)
{
table.updateSheet(sequence == null ? null : getOrCreateSheet(sequence));
- if (sequence != null) update(sequence);
+ if (sequence != null && sequence.getFirstViewer() != null) update(sequence);
getUI().repack(false);
}
});
liveUpdate.addVarChangeListener(new EzVarListener<Boolean>()
{
@Override
public void variableChanged(EzVar<Boolean> source, Boolean newValue)
{
getUI().setActionPanelVisible(!newValue);
}
});
try
{
currentSeq.setValue(getFocusedSequence());
update(currentSeq.getValue());
table.repaint();
}
catch (EzException e)
{
}
}
/**
* Creates a new sheet for the given sequence, or returns the current existing sheet (if any)
*
* @param sequence
* @return
*/
private static synchronized WritableSheet getOrCreateSheet(Sequence sequence)
{
String sheetName = getSheetName(sequence);
WritableSheet sheet = workbook.getSheet(sheetName);
if (sheet == null)
{
sheet = workbook.createSheet(sheetName, workbook.getNumberOfSheets() + 1);
try
{
sheet.addCell(new Label(0, 0, "Name"));
sheet.addCell(new Label(1, 0, "Color"));
sheet.addCell(new Label(2, 0, "min. X"));
sheet.addCell(new Label(3, 0, "min. Y"));
sheet.addCell(new Label(4, 0, "width"));
sheet.addCell(new Label(5, 0, "height"));
for (int c = 0; c < sequence.getSizeC(); c++)
{
sheet.addCell(new Label(5 + 4 * c + 1, 0, "min. (ch " + c + ")"));
sheet.addCell(new Label(5 + 4 * c + 2, 0, "max. (ch " + c + ")"));
sheet.addCell(new Label(5 + 4 * c + 3, 0, "avg. (ch " + c + ")"));
sheet.addCell(new Label(5 + 4 * c + 4, 0, "sum. (ch " + c + ")"));
}
}
catch (RowsExceededException e)
{
e.printStackTrace();
}
catch (WriteException e)
{
e.printStackTrace();
}
}
return sheet;
}
private static String getSheetName(Sequence s)
{
return "Sequence " + s.hashCode();
}
@Override
protected void execute()
{
update(currentSeq.getValue());
}
private void update(Sequence sequence)
{
for (ROI2D roi : sequence.getROI2Ds())
update(sequence, roi);
}
private void update(Sequence sequence, ROI2D roi)
{
try
{
int row = sequence.getROI2Ds().indexOf(roi) + 1;
WritableSheet sheet = getOrCreateSheet(sequence);
// set the name
sheet.addCell(new Label(0, row, roi.getName()));
// set the color (if it has changed)
if (roi.getColor() != ROIColors.get(roi))
{
ROIColors.put(roi, roi.getColor());
// JXL is VERY nasty, won't allow custom (AWT) colors !!!
// walk-around: look for the closest color match
Color col = roi.getColor();
Point3d cval = new Point3d(col.getRed(), col.getGreen(), col.getBlue());
Colour colour = Colour.AUTOMATIC;
double minDistance = Double.MAX_VALUE;
for (Colour c : Colour.getAllColours())
{
RGB rgb = c.getDefaultRGB();
Point3d cval_jxl = new Point3d(rgb.getRed(), rgb.getGreen(), rgb.getBlue());
// compute (squared) distance (to go faster)
// I mean, this is lame anyway, isn't it !!
double dist = cval.distanceSquared(cval_jxl);
if (dist < minDistance)
{
minDistance = dist;
colour = c;
}
}
// do you realize what we did JUST to get the color ?!!
final Colour finalColour = colour;
sheet.addCell(new Label(1, row, colour.getDescription(), new WritableCellFormat()
{
@Override
public Colour getBackgroundColour()
{
return finalColour;
}
}));
}
// set x,y,w,h
Rectangle bounds = roi.getBounds();
sheet.addCell(new Number(2, row, bounds.x));
sheet.addCell(new Number(3, row, bounds.y));
sheet.addCell(new Number(4, row, bounds.width));
sheet.addCell(new Number(5, row, bounds.height));
boolean[] mask = roi.getAsBooleanMask().mask;
Object[][] z_c_xy = (Object[][]) sequence.getDataXYCZ(sequence.getFirstViewer().getT());
boolean signed = sequence.getDataType_().isSigned();
int width = sequence.getSizeX();
int height = sequence.getSizeY();
double[] min = new double[sequence.getSizeC()];
double[] max = new double[sequence.getSizeC()];
double[] sum = new double[sequence.getSizeC()];
double[] cpt = new double[sequence.getSizeC()];
int ioff = bounds.x + bounds.y * width;
int moff = 0;
for (int iy = bounds.y, my = 0; my < bounds.height; my++, iy++, ioff += sequence.getSizeX() - bounds.width)
for (int ix = bounds.x, mx = 0; mx < bounds.width; mx++, ix++, ioff++, moff++)
{
if (iy >= 0 && ix >= 0 && iy < height && ix < width && mask[moff])
for (int z = 0; z < sequence.getSizeZ(); z++)
for (int c = 0; c < sum.length; c++)
{
cpt[c]++;
double val = Array1DUtil.getValue(z_c_xy[z][c], ioff, signed);
sum[c] += val;
if (val > max[c]) max[c] = val;
if (val < min[c]) min[c] = val;
}
}
for (int c = 0; c < sum.length; c++)
{
sheet.addCell(new Number(5 + 4 * c + 1, row, min[c]));
sheet.addCell(new Number(5 + 4 * c + 2, row, max[c]));
sheet.addCell(new Number(5 + 4 * c + 3, row, sum[c] / cpt[c]));
sheet.addCell(new Number(5 + 4 * c + 4, row, sum[c]));
}
}
catch (RowsExceededException e)
{
e.printStackTrace();
}
catch (WriteException e)
{
e.printStackTrace();
}
}
@Override
public void clean()
{
ROIColors.clear();
// remove listeners
for (final Sequence sequence : Icy.getMainInterface().getSequences())
sequence.removeListener(this);
Icy.getMainInterface().removeListener(this);
// clean static stuff (if this is the last instance)
if (getNbInstances() == 1)
{
try
{
workbook.close();
xlsFile.deleteOnExit();
}
catch (WriteException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
// MAIN LISTENER //
public void viewerOpened(MainEvent event)
{
}
public void viewerFocused(MainEvent event)
{
}
public void viewerClosed(MainEvent event)
{
}
public void sequenceOpened(MainEvent event)
{
((Sequence) event.getSource()).addListener(this);
}
public void sequenceFocused(MainEvent event)
{
}
public void sequenceClosed(MainEvent event)
{
((Sequence) event.getSource()).removeListener(this);
}
public void roiRemoved(MainEvent event)
{
}
public void roiAdded(MainEvent event)
{
}
public void pluginOpened(MainEvent event)
{
}
public void pluginClosed(MainEvent event)
{
}
public void painterRemoved(MainEvent event)
{
}
public void painterAdded(MainEvent event)
{
}
// SEQUENCE LISTENER //
@Override
public void sequenceClosed(Sequence sequence)
{
sequence.removeListener(this);
}
@Override
public void sequenceChanged(SequenceEvent sequenceEvent)
{
if (!liveUpdate.getValue()) return;
if (sequenceEvent.getSourceType() != SequenceEventSourceType.SEQUENCE_ROI) return;
Sequence sequence = sequenceEvent.getSequence();
Sequence selected = currentSeq.getValue(false);
if (selected != sequence) return;
Object roi = sequenceEvent.getSource();
WritableSheet sheet = getOrCreateSheet(sequence);
switch (sequenceEvent.getType())
{
case ADDED:
case CHANGED:
if (roi == null)
update(sequence);
else update(sequence, (ROI2D) roi);
break;
case REMOVED:
int nbDeleted = (roi == null) ? sheet.getRows() - 1 : 1;
for (int i = nbDeleted; i > 0; i--)
sheet.removeRow(i);
update(sequence);
break;
}
// in any case, update the table
// table.repaint();
table.updateSheet(sheet);
}
}
| true | false | null | null |
diff --git a/common/java/com/android/common/widget/CompositeCursorAdapter.java b/common/java/com/android/common/widget/CompositeCursorAdapter.java
index d6064e1..605eb82 100644
--- a/common/java/com/android/common/widget/CompositeCursorAdapter.java
+++ b/common/java/com/android/common/widget/CompositeCursorAdapter.java
@@ -1,531 +1,535 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.common.widget;
import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
/**
* A general purpose adapter that is composed of multiple cursors. It just
* appends them in the order they are added.
*/
public abstract class CompositeCursorAdapter extends BaseAdapter {
private static final int INITIAL_CAPACITY = 2;
public static class Partition {
boolean showIfEmpty;
boolean hasHeader;
Cursor cursor;
int idColumnIndex;
int count;
public Partition(boolean showIfEmpty, boolean hasHeader) {
this.showIfEmpty = showIfEmpty;
this.hasHeader = hasHeader;
}
/**
* True if the directory should be shown even if no contacts are found.
*/
public boolean getShowIfEmpty() {
return showIfEmpty;
}
public boolean getHasHeader() {
return hasHeader;
}
}
private final Context mContext;
private Partition[] mPartitions;
private int mSize = 0;
private int mCount = 0;
private boolean mCacheValid = true;
private boolean mNotificationsEnabled = true;
private boolean mNotificationNeeded;
public CompositeCursorAdapter(Context context) {
this(context, INITIAL_CAPACITY);
}
public CompositeCursorAdapter(Context context, int initialCapacity) {
mContext = context;
mPartitions = new Partition[INITIAL_CAPACITY];
}
public Context getContext() {
return mContext;
}
/**
* Registers a partition. The cursor for that partition can be set later.
* Partitions should be added in the order they are supposed to appear in the
* list.
*/
public void addPartition(boolean showIfEmpty, boolean hasHeader) {
addPartition(new Partition(showIfEmpty, hasHeader));
}
public void addPartition(Partition partition) {
if (mSize >= mPartitions.length) {
int newCapacity = mSize + 2;
Partition[] newAdapters = new Partition[newCapacity];
System.arraycopy(mPartitions, 0, newAdapters, 0, mSize);
mPartitions = newAdapters;
}
mPartitions[mSize++] = partition;
invalidate();
notifyDataSetChanged();
}
public void removePartition(int partitionIndex) {
Cursor cursor = mPartitions[partitionIndex].cursor;
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
System.arraycopy(mPartitions, partitionIndex + 1, mPartitions, partitionIndex,
mSize - partitionIndex - 1);
mSize--;
invalidate();
notifyDataSetChanged();
}
/**
* Removes cursors for all partitions.
*/
public void clearPartitions() {
for (int i = 0; i < mSize; i++) {
mPartitions[i].cursor = null;
}
invalidate();
notifyDataSetChanged();
}
/**
* Closes all cursors and removes all partitions.
*/
public void close() {
for (int i = 0; i < mSize; i++) {
Cursor cursor = mPartitions[i].cursor;
if (cursor != null && !cursor.isClosed()) {
cursor.close();
mPartitions[i].cursor = null;
}
}
mSize = 0;
invalidate();
notifyDataSetChanged();
}
public void setHasHeader(int partitionIndex, boolean flag) {
mPartitions[partitionIndex].hasHeader = flag;
invalidate();
}
public void setShowIfEmpty(int partitionIndex, boolean flag) {
mPartitions[partitionIndex].showIfEmpty = flag;
invalidate();
}
public Partition getPartition(int partitionIndex) {
if (partitionIndex >= mSize) {
throw new ArrayIndexOutOfBoundsException(partitionIndex);
}
return mPartitions[partitionIndex];
}
protected void invalidate() {
mCacheValid = false;
}
public int getPartitionCount() {
return mSize;
}
protected void ensureCacheValid() {
if (mCacheValid) {
return;
}
mCount = 0;
for (int i = 0; i < mSize; i++) {
Cursor cursor = mPartitions[i].cursor;
int count = cursor != null ? cursor.getCount() : 0;
if (mPartitions[i].hasHeader) {
if (count != 0 || mPartitions[i].showIfEmpty) {
count++;
}
}
mPartitions[i].count = count;
mCount += count;
}
mCacheValid = true;
}
/**
* Returns true if the specified partition was configured to have a header.
*/
public boolean hasHeader(int partition) {
return mPartitions[partition].hasHeader;
}
/**
* Returns the total number of list items in all partitions.
*/
public int getCount() {
ensureCacheValid();
return mCount;
}
/**
* Returns the cursor for the given partition
*/
public Cursor getCursor(int partition) {
return mPartitions[partition].cursor;
}
/**
* Changes the cursor for an individual partition.
*/
public void changeCursor(int partition, Cursor cursor) {
Cursor prevCursor = mPartitions[partition].cursor;
if (prevCursor != cursor) {
if (prevCursor != null && !prevCursor.isClosed()) {
prevCursor.close();
}
mPartitions[partition].cursor = cursor;
if (cursor != null) {
mPartitions[partition].idColumnIndex = cursor.getColumnIndex("_id");
}
invalidate();
notifyDataSetChanged();
}
}
/**
* Returns true if the specified partition has no cursor or an empty cursor.
*/
public boolean isPartitionEmpty(int partition) {
Cursor cursor = mPartitions[partition].cursor;
return cursor == null || cursor.getCount() == 0;
}
/**
* Given a list position, returns the index of the corresponding partition.
*/
public int getPartitionForPosition(int position) {
ensureCacheValid();
int start = 0;
for (int i = 0; i < mSize; i++) {
int end = start + mPartitions[i].count;
if (position >= start && position < end) {
return i;
}
start = end;
}
return -1;
}
/**
* Given a list position, return the offset of the corresponding item in its
* partition. The header, if any, will have offset -1.
*/
public int getOffsetInPartition(int position) {
ensureCacheValid();
int start = 0;
for (int i = 0; i < mSize; i++) {
int end = start + mPartitions[i].count;
if (position >= start && position < end) {
int offset = position - start;
if (mPartitions[i].hasHeader) {
offset--;
}
return offset;
}
start = end;
}
return -1;
}
/**
* Returns the first list position for the specified partition.
*/
public int getPositionForPartition(int partition) {
ensureCacheValid();
int position = 0;
for (int i = 0; i < partition; i++) {
position += mPartitions[i].count;
}
return position;
}
@Override
public int getViewTypeCount() {
return getItemViewTypeCount() + 1;
}
/**
* Returns the overall number of item view types across all partitions. An
* implementation of this method needs to ensure that the returned count is
* consistent with the values returned by {@link #getItemViewType(int,int)}.
*/
public int getItemViewTypeCount() {
return 1;
}
/**
* Returns the view type for the list item at the specified position in the
* specified partition.
*/
protected int getItemViewType(int partition, int position) {
return 1;
}
@Override
public int getItemViewType(int position) {
ensureCacheValid();
int start = 0;
for (int i = 0; i < mSize; i++) {
int end = start + mPartitions[i].count;
if (position >= start && position < end) {
int offset = position - start;
- if (mPartitions[i].hasHeader && offset == 0) {
+ if (mPartitions[i].hasHeader) {
+ offset--;
+ }
+ if (offset == -1) {
return IGNORE_ITEM_VIEW_TYPE;
+ } else {
+ return getItemViewType(i, offset);
}
- return getItemViewType(i, position);
}
start = end;
}
throw new ArrayIndexOutOfBoundsException(position);
}
public View getView(int position, View convertView, ViewGroup parent) {
ensureCacheValid();
int start = 0;
for (int i = 0; i < mSize; i++) {
int end = start + mPartitions[i].count;
if (position >= start && position < end) {
int offset = position - start;
if (mPartitions[i].hasHeader) {
offset--;
}
View view;
if (offset == -1) {
view = getHeaderView(i, mPartitions[i].cursor, convertView, parent);
} else {
if (!mPartitions[i].cursor.moveToPosition(offset)) {
throw new IllegalStateException("Couldn't move cursor to position "
+ offset);
}
view = getView(i, mPartitions[i].cursor, offset, convertView, parent);
}
if (view == null) {
throw new NullPointerException("View should not be null, partition: " + i
+ " position: " + offset);
}
return view;
}
start = end;
}
throw new ArrayIndexOutOfBoundsException(position);
}
/**
* Returns the header view for the specified partition, creating one if needed.
*/
protected View getHeaderView(int partition, Cursor cursor, View convertView,
ViewGroup parent) {
View view = convertView != null
? convertView
: newHeaderView(mContext, partition, cursor, parent);
bindHeaderView(view, partition, cursor);
return view;
}
/**
* Creates the header view for the specified partition.
*/
protected View newHeaderView(Context context, int partition, Cursor cursor,
ViewGroup parent) {
return null;
}
/**
* Binds the header view for the specified partition.
*/
protected void bindHeaderView(View view, int partition, Cursor cursor) {
}
/**
* Returns an item view for the specified partition, creating one if needed.
*/
protected View getView(int partition, Cursor cursor, int position, View convertView,
ViewGroup parent) {
View view;
if (convertView != null) {
view = convertView;
} else {
view = newView(mContext, partition, cursor, position, parent);
}
bindView(view, partition, cursor, position);
return view;
}
/**
* Creates an item view for the specified partition and position. Position
* corresponds directly to the current cursor position.
*/
protected abstract View newView(Context context, int partition, Cursor cursor, int position,
ViewGroup parent);
/**
* Binds an item view for the specified partition and position. Position
* corresponds directly to the current cursor position.
*/
protected abstract void bindView(View v, int partition, Cursor cursor, int position);
/**
* Returns a pre-positioned cursor for the specified list position.
*/
public Object getItem(int position) {
ensureCacheValid();
int start = 0;
for (int i = 0; i < mSize; i++) {
int end = start + mPartitions[i].count;
if (position >= start && position < end) {
int offset = position - start;
if (mPartitions[i].hasHeader) {
offset--;
}
if (offset == -1) {
return null;
}
Cursor cursor = mPartitions[i].cursor;
cursor.moveToPosition(offset);
return cursor;
}
start = end;
}
return null;
}
/**
* Returns the item ID for the specified list position.
*/
public long getItemId(int position) {
ensureCacheValid();
int start = 0;
for (int i = 0; i < mSize; i++) {
int end = start + mPartitions[i].count;
if (position >= start && position < end) {
int offset = position - start;
if (mPartitions[i].hasHeader) {
offset--;
}
if (offset == -1) {
return 0;
}
if (mPartitions[i].idColumnIndex == -1) {
return 0;
}
Cursor cursor = mPartitions[i].cursor;
if (cursor == null || cursor.isClosed() || !cursor.moveToPosition(offset)) {
return 0;
}
return cursor.getLong(mPartitions[i].idColumnIndex);
}
start = end;
}
return 0;
}
/**
* Returns false if any partition has a header.
*/
@Override
public boolean areAllItemsEnabled() {
for (int i = 0; i < mSize; i++) {
if (mPartitions[i].hasHeader) {
return false;
}
}
return true;
}
/**
* Returns true for all items except headers.
*/
@Override
public boolean isEnabled(int position) {
ensureCacheValid();
int start = 0;
for (int i = 0; i < mSize; i++) {
int end = start + mPartitions[i].count;
if (position >= start && position < end) {
int offset = position - start;
if (mPartitions[i].hasHeader && offset == 0) {
return false;
} else {
return isEnabled(i, offset);
}
}
start = end;
}
return false;
}
/**
* Returns true if the item at the specified offset of the specified
* partition is selectable and clickable.
*/
protected boolean isEnabled(int partition, int position) {
return true;
}
/**
* Enable or disable data change notifications. It may be a good idea to
* disable notifications before making changes to several partitions at once.
*/
public void setNotificationsEnabled(boolean flag) {
mNotificationsEnabled = flag;
if (flag && mNotificationNeeded) {
notifyDataSetChanged();
}
}
@Override
public void notifyDataSetChanged() {
if (mNotificationsEnabled) {
mNotificationNeeded = false;
super.notifyDataSetChanged();
} else {
mNotificationNeeded = true;
}
}
}
| false | false | null | null |
diff --git a/org.eclipse.riena.ui.ridgets.swt/src/org/eclipse/riena/ui/ridgets/swt/AbstractComboRidget.java b/org.eclipse.riena.ui.ridgets.swt/src/org/eclipse/riena/ui/ridgets/swt/AbstractComboRidget.java
index 242adc41d..e2a4a71cf 100644
--- a/org.eclipse.riena.ui.ridgets.swt/src/org/eclipse/riena/ui/ridgets/swt/AbstractComboRidget.java
+++ b/org.eclipse.riena.ui.ridgets.swt/src/org/eclipse/riena/ui/ridgets/swt/AbstractComboRidget.java
@@ -1,592 +1,594 @@
/*******************************************************************************
* Copyright (c) 2007, 2009 compeople AG and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* compeople AG - initial API and implementation
*******************************************************************************/
package org.eclipse.riena.ui.ridgets.swt;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.databinding.Binding;
import org.eclipse.core.databinding.BindingException;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.UpdateListStrategy;
import org.eclipse.core.databinding.UpdateValueStrategy;
import org.eclipse.core.databinding.beans.BeansObservables;
import org.eclipse.core.databinding.beans.PojoObservables;
import org.eclipse.core.databinding.conversion.Converter;
import org.eclipse.core.databinding.conversion.IConverter;
import org.eclipse.core.databinding.observable.list.IObservableList;
import org.eclipse.core.databinding.observable.list.WritableList;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.databinding.observable.value.IValueChangeListener;
import org.eclipse.core.databinding.observable.value.ValueChangeEvent;
import org.eclipse.core.databinding.observable.value.WritableValue;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.databinding.swt.ISWTObservableValue;
import org.eclipse.riena.core.util.ListenerList;
import org.eclipse.riena.core.util.ReflectionUtils;
import org.eclipse.riena.ui.core.marker.ErrorMarker;
import org.eclipse.riena.ui.core.marker.ErrorMessageMarker;
import org.eclipse.riena.ui.ridgets.IComboRidget;
import org.eclipse.riena.ui.ridgets.IRidget;
import org.eclipse.riena.ui.ridgets.listener.ISelectionListener;
import org.eclipse.riena.ui.ridgets.listener.SelectionEvent;
+import org.eclipse.riena.ui.ridgets.swt.nls.Messages;
/**
* Superclass of ComboRidget that does not depend on the Combo SWT control. May
* be reused for custom Combo controls.
*/
public abstract class AbstractComboRidget extends AbstractSWTRidget implements IComboRidget {
/** List of available options (ridget). */
private final IObservableList rowObservables;
/** The selected option (ridget). */
private final IObservableValue selectionObservable;
/** Selection validator that allows or cancels a selection request. */
private final SelectionBindingValidator selectionValidator;
/** IValueChangeListener that fires a selection event on change. */
private final IValueChangeListener valueChangeNotifier;
/** A list of selection listeners. */
private ListenerList<ISelectionListener> selectionListeners;
/** If this item is selected, treat it as if nothing is selected */
private Object emptySelection;
/** List of available options (model). */
private IObservableList optionValues;
/** Class of the optional values. */
private Class<? extends Object> rowClass;
/** The selected option (model). */
private IObservableValue selectionValue;
/** A string used for converting from Object to String */
private String renderingMethod;
/**
* Converts from objects (rowObsservables) to strings (Combo) using the
* renderingMethod.
*/
private IConverter objToStrConverter;
/** Convers from strings (Combo) to objects (rowObservables). */
private IConverter strToObjConverter;
/**
* The list of items to show in the combo. These entries are created from
* the optionValues by applying the current conversion stategy to them.
*/
private List<String> items;
/**
* Binding between the rowObservables and the list of choices from the
* model. May be null, when there is no model.
*/
private Binding listBindingExternal;
/**
* Binding between the selection in the combo and the selectionObservable.
* May be null, when there is no control or model.
*/
private Binding selectionBindingInternal;
/**
* Binding between the selectionObservable and the selection in the model.
* May be null, when there is no model.
*/
private Binding selectionBindingExternal;
/**
* If true, it will cause an error marker to be shown, once the selected
* value in the combo is no longer available in the list of selectable
* values. This can occur if the selection was removed from the bound model
* and {@link #updateFromModel()} is called.
* <p>
* The default setting is false.
*
* @see Bug 304733
*/
private boolean markSelectionMismatch;
/**
* The {@link ErrorMarker} used when a 'selection mismatch' occurs
*/
private ErrorMarker selectionMismatchMarker;
public AbstractComboRidget() {
super();
rowClass = null;
rowObservables = new WritableList();
selectionObservable = new WritableValue();
objToStrConverter = new ObjectToStringConverter();
strToObjConverter = new StringToObjectConverter();
selectionValidator = new SelectionBindingValidator();
valueChangeNotifier = new ValueChangeNotifier();
addPropertyChangeListener(IRidget.PROPERTY_ENABLED, new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
applyEnabled();
}
});
}
@Override
protected void bindUIControl() {
if (optionValues != null) {
// These bindings are only necessary when we have a model
DataBindingContext dbc = new DataBindingContext();
if (getUIControl() != null) {
applyEnabled();
}
listBindingExternal = dbc
.bindList(rowObservables, optionValues,
new UpdateListStrategy(UpdateListStrategy.POLICY_ON_REQUEST), new UpdateListStrategy(
UpdateListStrategy.POLICY_ON_REQUEST));
selectionBindingExternal = dbc.bindValue(selectionObservable, selectionValue, new UpdateValueStrategy(
UpdateValueStrategy.POLICY_UPDATE).setAfterGetValidator(selectionValidator),
new UpdateValueStrategy(UpdateValueStrategy.POLICY_ON_REQUEST));
// Ensure valueChangeNotifier is not added more that once.
selectionObservable.removeValueChangeListener(valueChangeNotifier);
// We have to add the notifier after installing selectionBindingExternal,
// to guarantee that the binding updates the selection value before
// the valueChangeNotifier sends the selection changed event (bug 287740)
selectionObservable.addValueChangeListener(valueChangeNotifier);
}
}
@Override
protected void unbindUIControl() {
super.unbindUIControl();
disposeBinding(listBindingExternal);
listBindingExternal = null;
disposeBinding(selectionBindingInternal);
selectionBindingInternal = null;
disposeBinding(selectionBindingExternal);
selectionBindingExternal = null;
}
/**
* {@inheritDoc}
* <p>
* Implementation note: the {@link ISelectionListener} will receive a list
* with the selected values. Since the combo only supports a single
* selection, the value will be the one element in the list. If there is no
* selection or the 'empty' selection entry is selected, the list will be
* empty.
*/
public void addSelectionListener(ISelectionListener selectionListener) {
Assert.isNotNull(selectionListener, "selectionListener is null"); //$NON-NLS-1$
if (selectionListeners == null) {
selectionListeners = new ListenerList<ISelectionListener>(ISelectionListener.class);
addPropertyChangeListener(IComboRidget.PROPERTY_SELECTION, new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
notifySelectionListeners(evt.getOldValue(), evt.getNewValue());
}
});
}
selectionListeners.add(selectionListener);
}
public void removeSelectionListener(ISelectionListener selectionListener) {
if (selectionListeners != null) {
selectionListeners.remove(selectionListener);
}
}
public void bindToModel(IObservableList optionValues, Class<? extends Object> rowClass, String renderingMethod,
IObservableValue selectionValue) {
unbindUIControl();
this.optionValues = optionValues;
this.rowClass = rowClass;
this.renderingMethod = renderingMethod;
this.selectionValue = selectionValue;
bindUIControl();
}
public void bindToModel(Object listHolder, String listPropertyName, Class<? extends Object> rowClass,
String renderingMethod, Object selectionHolder, String selectionPropertyName) {
IObservableList listObservableValue;
if (AbstractSWTWidgetRidget.isBean(rowClass)) {
listObservableValue = BeansObservables.observeList(listHolder, listPropertyName);
} else {
listObservableValue = PojoObservables.observeList(listHolder, listPropertyName);
}
IObservableValue selectionObservableValue = PojoObservables
.observeValue(selectionHolder, selectionPropertyName);
bindToModel(listObservableValue, rowClass, renderingMethod, selectionObservableValue);
}
public Object getEmptySelectionItem() {
return emptySelection;
}
// TODO [ev] should method return null when not bound? See ListRidget#getObservableList()
public IObservableList getObservableList() {
return rowObservables;
}
public Object getSelection() {
Object selection = selectionObservable.getValue();
return selection == emptySelection ? null : selection;
}
public int getSelectionIndex() {
int result = -1;
Object selection = selectionObservable.getValue();
if (emptySelection != selection) {
result = rowObservables.indexOf(selection);
}
return result;
}
public boolean isDisableMandatoryMarker() {
return hasInput();
}
@Override
public boolean isEnabled() {
return super.isEnabled() && !isOutputOnly();
}
public boolean isMarkSelectionMismatch() {
return markSelectionMismatch;
}
public void setEmptySelectionItem(Object emptySelection) {
this.emptySelection = emptySelection;
}
public void setMarkSelectionMismatch(boolean mark) {
if (mark != markSelectionMismatch) {
if (mark == true && selectionMismatchMarker == null) {
- selectionMismatchMarker = new ErrorMessageMarker("The selected value is no longer available"); // TODO [ev] i18n
+ selectionMismatchMarker = new ErrorMessageMarker(
+ Messages.AbstractComboRidget_markerMessage_selectionMismatch);
}
markSelectionMismatch = mark;
applyMarkSelectionMismatch();
}
}
public void setSelection(Object newSelection) {
assertIsBoundToModel();
Object oldSelection = selectionObservable.getValue();
if (oldSelection != newSelection) {
if (newSelection == null || !rowObservables.contains(newSelection)) {
if (getUIControl() != null) {
clearUIControlListSelection();
}
selectionObservable.setValue(null);
} else {
selectionObservable.setValue(newSelection);
}
}
}
public void setSelection(int index) {
if (index == -1) {
setSelection(null);
} else {
Object newSelection = rowObservables.get(index);
setSelection(newSelection);
}
}
public void setModelToUIControlConverter(IConverter converter) {
objToStrConverter = (converter != null) ? converter : new ObjectToStringConverter();
}
public void setUIControlToModelConverter(IConverter converter) {
strToObjConverter = (converter != null) ? converter : new StringToObjectConverter();
}
// abstract methods
///////////////////
@Override
public void updateFromModel() {
assertIsBoundToModel();
super.updateFromModel();
// disable the selection binding, because updating the combo items
// causes the selection to change temporarily
selectionValidator.enableBinding(false);
try {
listBindingExternal.updateModelToTarget();
items = new ArrayList<String>();
updateValueToItem();
} finally {
selectionValidator.enableBinding(true);
}
selectionBindingExternal.updateModelToTarget();
if (selectionBindingInternal != null) {
selectionBindingInternal.updateModelToTarget();
}
// Bug 304733: clear selection if not in rowObservables
applyMarkSelectionMismatch();
}
/**
* Deselects all selected items in the controls list.
*/
protected abstract void clearUIControlListSelection();
/**
* @return The items of the controls list. May be an empty array.
*/
protected abstract String[] getUIControlItems();
/**
* @return an observable observing the items attribute of the control.
*/
protected abstract IObservableList getUIControlItemsObservable();
/**
* @return an observable observing the selection attribute of the control.
*/
protected abstract ISWTObservableValue getUIControlSelectionObservable();
/**
* Selects the item in the controls list.
*/
protected abstract void selectInUIControl(int index);
/**
* @return The index of the item in the controls list or -1 if no such item
* is found.
*/
protected abstract int indexOfInUIControl(String item);
/**
* Removes all of the items from the controls list and clears the controls
* text field.
*/
protected abstract void removeAllFromUIControl();
/**
* Make the given array the list of selectable items in the combo.
*
* @param arrItems
* an array; never null.
* @since 1.2
*/
protected abstract void setItemsToControl(String[] arrItems);
// helping methods
//////////////////
private void applyEnabled() {
if (super.isEnabled()) {
bindControlToSelectionAndUpdate();
} else {
unbindControlFromSelectionAndClear();
}
}
private void applyMarkSelectionMismatch() {
Object selection = selectionObservable.getValue();
if (markSelectionMismatch && selection != null && !rowObservables.contains(selection)) {
Assert.isNotNull(markSelectionMismatch);
addMarker(selectionMismatchMarker);
} else {
if (selectionMismatchMarker != null) {
removeMarker(selectionMismatchMarker);
}
}
}
private void assertIsBoundToModel() {
if (optionValues == null) {
throw new BindingException("ridget not bound to model"); //$NON-NLS-1$
}
}
/**
* Restores the list of items / selection in the combo, when the ridget is
* enabled.
*/
private void bindControlToSelectionAndUpdate() {
if (getUIControl() != null) {
/* update list of items in combo */
updateValueToItem();
/* re-create selectionBinding */
ISWTObservableValue controlSelection = getUIControlSelectionObservable();
DataBindingContext dbc = new DataBindingContext();
selectionBindingInternal = dbc.bindValue(controlSelection, selectionObservable, new UpdateValueStrategy(
UpdateValueStrategy.POLICY_UPDATE).setConverter(strToObjConverter).setAfterGetValidator(
selectionValidator), new UpdateValueStrategy(UpdateValueStrategy.POLICY_UPDATE)
.setConverter(objToStrConverter));
/* update selection in combo */
selectionBindingInternal.updateModelToTarget();
}
}
private void disposeBinding(Binding binding) {
if (binding != null && !binding.isDisposed()) {
binding.dispose();
}
}
private String getItemFromValue(Object value) {
Object valueObject = value;
if (value != null && renderingMethod != null) {
valueObject = ReflectionUtils.invoke(value, renderingMethod, (Object[]) null);
}
if (valueObject == null || valueObject.toString() == null) {
throw new NullPointerException("The item value for a model element is null"); //$NON-NLS-1$
}
return valueObject.toString();
}
/**
* Returns the value of the given item.
*
* @param item
* item of combo box
* @return value relevant object; {@code null} or empty string if no
* relevant object exists
*/
private Object getValueFromItem(String item) {
String[] uiItems = getUIControlItems();
for (int i = 0; i < uiItems.length; i++) {
if (uiItems[i].equals(item)) {
return rowObservables.get(i);
}
}
if (rowClass == String.class) {
return ""; //$NON-NLS-1$
} else {
return null;
}
}
private boolean hasInput() {
Object selection = selectionObservable.getValue();
return selection != null && selection != emptySelection;
}
private void notifySelectionListeners(Object oldValue, Object newValue) {
if (selectionListeners != null) {
List<Object> oldSelectionList = new ArrayList<Object>();
if (oldValue != null) {
oldSelectionList.add(oldValue);
}
List<Object> newSelectionList = new ArrayList<Object>();
if (newValue != null) {
newSelectionList.add(newValue);
}
SelectionEvent event = new SelectionEvent(this, oldSelectionList, newSelectionList);
for (ISelectionListener listener : selectionListeners.getListeners()) {
listener.ridgetSelected(event);
}
}
}
/**
* Clears the list of items in the combo, when the ridget is disabled.
*/
private void unbindControlFromSelectionAndClear() {
if (getUIControl() != null && !super.isEnabled()) {
/* dispose selectionBinding to avoid sync */
disposeBinding(selectionBindingInternal);
selectionBindingInternal = null;
/* clear combo */
if (MarkerSupport.isHideDisabledRidgetContent()) {
removeAllFromUIControl();
}
}
}
private void updateValueToItem() {
if (items != null) {
items.clear();
try {
for (Object value : optionValues) {
String item = (String) objToStrConverter.convert(value);
items.add(item);
}
} finally {
if (getUIControl() != null) {
String[] arrItems = items.toArray(new String[items.size()]);
setItemsToControl(arrItems);
}
}
}
}
// helping classes
//////////////////
/**
* Convert from model object to combo box items (strings).
*/
private final class ObjectToStringConverter extends Converter {
public ObjectToStringConverter() {
super(Object.class, String.class);
}
public Object convert(Object fromObject) {
return getItemFromValue(fromObject);
}
}
/**
* Convert from combo box items (strings) to model objects.
*/
private final class StringToObjectConverter extends Converter {
public StringToObjectConverter() {
super(String.class, Object.class);
}
public Object convert(Object fromObject) {
return getValueFromItem((String) fromObject);
}
}
/**
* This validator can be used to interrupt an update request
*/
private final class SelectionBindingValidator implements IValidator {
private boolean isEnabled = true;
public IStatus validate(Object value) {
IStatus result = Status.OK_STATUS;
// disallow control to ridget update, isEnabled == false || output
if (!isEnabled) {
result = Status.CANCEL_STATUS;
}
return result;
}
void enableBinding(final boolean isEnabled) {
this.isEnabled = isEnabled;
}
}
/**
* Upon a selection change:
* <ul>
* <li>fire a PROPERTY_SELECTION event and</li>
* <li>update the mandatory marker state</li>
* </ul>
*/
private final class ValueChangeNotifier implements IValueChangeListener {
public void handleValueChange(ValueChangeEvent event) {
Object oldValue = event.diff.getOldValue();
Object newValue = event.diff.getNewValue();
try {
firePropertyChange(IComboRidget.PROPERTY_SELECTION, oldValue, newValue);
} finally {
disableMandatoryMarkers(hasInput());
applyMarkSelectionMismatch();
}
}
}
}
diff --git a/org.eclipse.riena.ui.ridgets.swt/src/org/eclipse/riena/ui/ridgets/swt/nls/Messages.java b/org.eclipse.riena.ui.ridgets.swt/src/org/eclipse/riena/ui/ridgets/swt/nls/Messages.java
index cc28b6988..cf3d2953b 100644
--- a/org.eclipse.riena.ui.ridgets.swt/src/org/eclipse/riena/ui/ridgets/swt/nls/Messages.java
+++ b/org.eclipse.riena.ui.ridgets.swt/src/org/eclipse/riena/ui/ridgets/swt/nls/Messages.java
@@ -1,31 +1,30 @@
/*******************************************************************************
* Copyright (c) 2007, 2009 compeople AG and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* compeople AG - initial API and implementation
*******************************************************************************/
package org.eclipse.riena.ui.ridgets.swt.nls;
import org.eclipse.osgi.util.NLS;
/**
* Provides internationalized UI strings.
*/
public class Messages extends NLS {
private static final String BUNDLE_NAME = "org.eclipse.riena.ui.ridgets.swt.nls.messages"; //$NON-NLS-1$
- // example:
- // public static String MasterDetailsRidget_dialogTitle_applyFailed;
+ public static String AbstractComboRidget_markerMessage_selectionMismatch;
static {
// initialize resource bundle
NLS.initializeMessages(BUNDLE_NAME, Messages.class);
}
private Messages() {
}
}
| false | false | null | null |
diff --git a/src/com/android/contacts/GroupMemberLoader.java b/src/com/android/contacts/GroupMemberLoader.java
index e2945f6d1..452c5d0d1 100644
--- a/src/com/android/contacts/GroupMemberLoader.java
+++ b/src/com/android/contacts/GroupMemberLoader.java
@@ -1,104 +1,104 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.android.contacts;
import com.android.contacts.list.ContactListAdapter;
import android.content.Context;
import android.content.CursorLoader;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.Directory;
import java.util.ArrayList;
import java.util.List;
/**
* Group Member loader. Loads all group members from the given groupId
*/
public final class GroupMemberLoader extends CursorLoader {
/**
* Projection map is taken from {@link ContactListAdapter}
*/
private final String[] PROJECTION_DATA = new String[] {
// TODO: Pull Projection_data out into util class
Data.CONTACT_ID, // 0
Data.RAW_CONTACT_ID, // 1
Data.DISPLAY_NAME_PRIMARY, // 2
Data.DISPLAY_NAME_ALTERNATIVE, // 3
Data.SORT_KEY_PRIMARY, // 4
Data.STARRED, // 5
Data.CONTACT_PRESENCE, // 6
Data.CONTACT_CHAT_CAPABILITY, // 7
Data.PHOTO_ID, // 8
Data.PHOTO_URI, // 9
Data.PHOTO_THUMBNAIL_URI, // 10
Data.LOOKUP_KEY, // 11
Data.PHONETIC_NAME, // 12
Data.HAS_PHONE_NUMBER, // 13
};
private final long mGroupId;
public static final int CONTACT_ID_COLUMN_INDEX = 0;
public static final int RAW_CONTACT_ID_COLUMN_INDEX = 1;
public static final int CONTACT_DISPLAY_NAME_PRIMARY_COLUMN_INDEX = 2;
public static final int CONTACT_DISPLAY_NAME_ALTERNATIVE_COLUMN_INDEX = 3;
public static final int CONTACT_SORT_KEY_PRIMARY_COLUMN_INDEX = 4;
public static final int CONTACT_STARRED_COLUMN_INDEX = 5;
public static final int CONTACT_PRESENCE_STATUS_COLUMN_INDEX = 6;
public static final int CONTACT_CHAT_CAPABILITY_COLUMN_INDEX = 7;
public static final int CONTACT_PHOTO_ID_COLUMN_INDEX = 8;
public static final int CONTACT_PHOTO_URI_COLUMN_INDEX = 9;
public static final int CONTACT_PHOTO_THUMBNAIL_URI_COLUMN_INDEX = 10;
- public static final int CONTACT_LOOKUP_KEY_COLUMN_INDEX = 10;
- public static final int CONTACT_PHONETIC_NAME_COLUMN_INDEX = 11;
- public static final int CONTACT_HAS_PHONE_COLUMN_INDEX = 12;
+ public static final int CONTACT_LOOKUP_KEY_COLUMN_INDEX = 11;
+ public static final int CONTACT_PHONETIC_NAME_COLUMN_INDEX = 12;
+ public static final int CONTACT_HAS_PHONE_COLUMN_INDEX = 13;
public GroupMemberLoader(Context context, long groupId) {
super(context);
mGroupId = groupId;
setUri(createUri());
setProjection(PROJECTION_DATA);
setSelection(createSelection());
setSelectionArgs(createSelectionArgs());
setSortOrder(Contacts.SORT_KEY_ALTERNATIVE);
}
private Uri createUri() {
Uri uri = Data.CONTENT_URI;
uri = uri.buildUpon().appendQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY,
String.valueOf(Directory.DEFAULT)).build();
return uri;
}
private String createSelection() {
StringBuilder selection = new StringBuilder();
selection.append(Data.MIMETYPE + "=?" + " AND " + GroupMembership.GROUP_ROW_ID + "=?");
return selection.toString();
}
private String[] createSelectionArgs() {
List<String> selectionArgs = new ArrayList<String>();
selectionArgs.add(GroupMembership.CONTENT_ITEM_TYPE);
selectionArgs.add(String.valueOf(mGroupId));
return selectionArgs.toArray(new String[0]);
}
}
| true | false | null | null |
diff --git a/openregistry-webapp/src/test/java/org/openregistry/core/web/resources/AddNewPersonMockitoBasedPersonServiceFactoryBean.java b/openregistry-webapp/src/test/java/org/openregistry/core/web/resources/AddNewPersonMockitoBasedPersonServiceFactoryBean.java
index 011a0ca9..6984851d 100644
--- a/openregistry-webapp/src/test/java/org/openregistry/core/web/resources/AddNewPersonMockitoBasedPersonServiceFactoryBean.java
+++ b/openregistry-webapp/src/test/java/org/openregistry/core/web/resources/AddNewPersonMockitoBasedPersonServiceFactoryBean.java
@@ -1,94 +1,92 @@
package org.openregistry.core.web.resources;
import org.springframework.beans.factory.FactoryBean;
import static org.mockito.Mockito.*;
import org.mockito.ArgumentMatcher;
import org.openregistry.core.domain.sor.ReconciliationCriteria;
import org.openregistry.core.domain.Identifier;
import org.openregistry.core.domain.IdentifierType;
import org.openregistry.core.domain.Person;
import org.openregistry.core.service.reconciliation.ReconciliationResult;
import org.openregistry.core.service.PersonService;
import org.openregistry.core.service.ServiceExecutionResult;
-import org.openregistry.core.web.resources.representations.PersonRequestRepresentation;
import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;
-import java.util.Collections;
/**
* FactoryBean to create Mockito-based mocks of <code>PersonService</code> and related collaborators needed to test
* 'POST /people' scenarios of <code>PeopleResource</code>
*
* @author Dmitriy Kopylenko
* @since 1.0
*/
public class AddNewPersonMockitoBasedPersonServiceFactoryBean implements FactoryBean<PersonService> {
PersonService mockPersonService;
public void init() {
//Stubbing Person
Person mockPerson = mock(Person.class);
Set<Identifier> ids = buildMockIdentifiers();
when(mockPerson.getIdentifiers()).thenReturn(ids);
//Stubbing no people found result
final ReconciliationResult mockNoPeopleFoundReconciliationResult = mock(ReconciliationResult.class);
when(mockNoPeopleFoundReconciliationResult.noPeopleFound()).thenReturn(true);
//Stubbing no people found service execution result
final ServiceExecutionResult mockNoPeopleFoundServiceExecutionResult = mock(ServiceExecutionResult.class);
when(mockNoPeopleFoundServiceExecutionResult.succeeded()).thenReturn(true);
when(mockNoPeopleFoundServiceExecutionResult.getReconciliationResult()).thenReturn(mockNoPeopleFoundReconciliationResult);
when(mockNoPeopleFoundServiceExecutionResult.getTargetObject()).thenReturn(mockPerson);
//Stubbing PersonService
final PersonService ps = mock(PersonService.class);
when(ps.addPerson(argThat(new IsNewPerson()), (ReconciliationResult) isNull())).thenReturn(mockNoPeopleFoundServiceExecutionResult);
this.mockPersonService = ps;
}
public PersonService getObject() throws Exception {
return this.mockPersonService;
}
public Class<? extends PersonService> getObjectType() {
return PersonService.class;
}
public boolean isSingleton() {
return true;
}
private Set<Identifier> buildMockIdentifiers() {
//Mock it all up:
//NetID
Identifier mockNetId = mock(Identifier.class);
IdentifierType mockNetIdType = mock(IdentifierType.class);
when(mockNetIdType.getName()).thenReturn("NETID");
when(mockNetId.getType()).thenReturn(mockNetIdType);
when(mockNetId.getValue()).thenReturn("test-netid");
//RcpId
Identifier mockRcpId = mock(Identifier.class);
IdentifierType mockRcpIdType = mock(IdentifierType.class);
when(mockNetIdType.getName()).thenReturn("RCPID");
- when(mockNetId.getType()).thenReturn(mockNetIdType);
+ when(mockNetId.getType()).thenReturn(mockRcpIdType);
when(mockNetId.getValue()).thenReturn("test-rcpid");
return new HashSet<Identifier>(Arrays.asList(mockNetId, mockRcpId));
}
private static class IsNewPerson extends ArgumentMatcher<ReconciliationCriteria> {
@Override
public boolean matches(Object criteria) {
return "new".equals(((ReconciliationCriteria) criteria).getPerson().getSsn());
}
}
}
| false | false | null | null |
diff --git a/src/main/java/com/pance/springIntSpike/BarMessageService.java b/src/main/java/com/pance/springIntSpike/BarMessageService.java
index e314b8e..4dd6082 100644
--- a/src/main/java/com/pance/springIntSpike/BarMessageService.java
+++ b/src/main/java/com/pance/springIntSpike/BarMessageService.java
@@ -1,14 +1,14 @@
package com.pance.springIntSpike;
import org.springframework.integration.annotation.MessageEndpoint;
import org.springframework.integration.annotation.ServiceActivator;
@MessageEndpoint
public class BarMessageService {
- @ServiceActivator(inputChannel="bar", outputChanne="out")
+ @ServiceActivator(inputChannel="bar", outputChannel="out")
public String getMessage(String message) {
System.out.println("Bar: " + message);
return message;
}
}
\ No newline at end of file
diff --git a/src/main/java/com/pance/springIntSpike/FooMessageService.java b/src/main/java/com/pance/springIntSpike/FooMessageService.java
index b1536ee..c4e346b 100644
--- a/src/main/java/com/pance/springIntSpike/FooMessageService.java
+++ b/src/main/java/com/pance/springIntSpike/FooMessageService.java
@@ -1,17 +1,15 @@
package com.pance.springIntSpike;
import org.springframework.integration.annotation.MessageEndpoint;
import org.springframework.integration.annotation.ServiceActivator;
@MessageEndpoint
public class FooMessageService {
@ServiceActivator(inputChannel="foo", outputChannel="bar")
-
- @Polled(period=300)
public String getMessage(String message) {
System.out.println("Foo: " + message);
return message;
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/org.eclipse.stem.ui.diseasemodels/src/org/eclipse/stem/diseasemodels/standard/presentation/DiseasemodelsEditorAdvisor.java b/org.eclipse.stem.ui.diseasemodels/src/org/eclipse/stem/diseasemodels/standard/presentation/DiseasemodelsEditorAdvisor.java
index c6ef5e22..8e1744e8 100644
--- a/org.eclipse.stem.ui.diseasemodels/src/org/eclipse/stem/diseasemodels/standard/presentation/DiseasemodelsEditorAdvisor.java
+++ b/org.eclipse.stem.ui.diseasemodels/src/org/eclipse/stem/diseasemodels/standard/presentation/DiseasemodelsEditorAdvisor.java
@@ -1,592 +1,595 @@
package org.eclipse.stem.diseasemodels.standard.presentation;
/*******************************************************************************
* Copyright (c) 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import java.io.File;
import java.util.Arrays;
import java.util.List;
import org.eclipse.emf.common.ui.URIEditorInput;
import org.eclipse.emf.common.ui.action.WorkbenchWindowActionDelegate;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.common.util.UniqueEList;
import org.eclipse.emf.edit.ui.action.LoadResourceAction;
import org.eclipse.emf.edit.ui.util.EditUIUtil;
import org.eclipse.stem.diseasemodels.standard.presentation.DiseasemodelsEditorPlugin;
import org.eclipse.stem.core.common.presentation.CommonEditor;
import org.eclipse.stem.core.graph.presentation.GraphEditor;
import org.eclipse.stem.core.model.presentation.ModelEditor;
import org.eclipse.stem.core.scenario.presentation.ScenarioEditor;
import org.eclipse.stem.definitions.labels.presentation.LabelsEditor;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
//import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IFolderLayout;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.ContributionItemFactory;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
import org.eclipse.ui.application.IWorkbenchConfigurer;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchAdvisor;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;
/**
* Customized {@link WorkbenchAdvisor} for the RCP application.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public final class DiseasemodelsEditorAdvisor extends WorkbenchAdvisor {
/**
* The default file extension filters for use in dialogs.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final String[] FILE_EXTENSION_FILTERS = getFileExtensionFilters();
/**
* Returns the default file extension filters. This method should only be used to initialize {@link #FILE_EXTENSION_FILTERS}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
private static String[] getFileExtensionFilters() {
List<String> result = new UniqueEList<String>();
result.addAll(StandardEditor.FILE_EXTENSION_FILTERS);
return result.toArray(new String[0]);
}
/**
* This looks up a string in the plugin's plugin.properties file.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static String getString(String key) {
return DiseasemodelsEditorPlugin.INSTANCE.getString(key);
}
/**
* This looks up a string in plugin.properties, making a substitution.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static String getString(String key, Object s1) {
return org.eclipse.stem.diseasemodels.standard.presentation.DiseasemodelsEditorPlugin.INSTANCE.getString(key, new Object [] { s1 });
}
/**
* RCP's application
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static class Application implements IApplication {
/**
* @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Object start(IApplicationContext context) throws Exception {
WorkbenchAdvisor workbenchAdvisor = new DiseasemodelsEditorAdvisor();
Display display = PlatformUI.createDisplay();
try {
int returnCode = PlatformUI.createAndRunWorkbench(display, workbenchAdvisor);
if (returnCode == PlatformUI.RETURN_RESTART) {
return IApplication.EXIT_RESTART;
}
else {
return IApplication.EXIT_OK;
}
}
finally {
display.dispose();
}
}
/**
* @see org.eclipse.equinox.app.IApplication#stop()
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void stop() {
// Do nothing.
}
}
/**
* RCP's perspective
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static class Perspective implements IPerspectiveFactory {
/**
* Perspective ID
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final String ID_PERSPECTIVE = "org.eclipse.stem.diseasemodels.standard.presentation.DiseasemodelsEditorAdvisorPerspective"; //$NON-NLS-1$
/**
* @see org.eclipse.ui.IPerspectiveFactory#createInitialLayout(org.eclipse.ui.IPageLayout)
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void createInitialLayout(IPageLayout layout) {
layout.setEditorAreaVisible(true);
layout.addPerspectiveShortcut(ID_PERSPECTIVE);
IFolderLayout right = layout.createFolder("right", IPageLayout.RIGHT, (float)0.66, layout.getEditorArea()); //$NON-NLS-1$
right.addView(IPageLayout.ID_OUTLINE);
IFolderLayout bottonRight = layout.createFolder("bottonRight", IPageLayout.BOTTOM, (float)0.60, "right"); //$NON-NLS-1$ //$NON-NLS-2$
bottonRight.addView(IPageLayout.ID_PROP_SHEET);
}
}
/**
* RCP's window advisor
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static class WindowAdvisor extends WorkbenchWindowAdvisor {
/**
* @see WorkbenchWindowAdvisor#WorkbenchWindowAdvisor(org.eclipse.ui.application.IWorkbenchWindowConfigurer)
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public WindowAdvisor(IWorkbenchWindowConfigurer configurer) {
super(configurer);
}
/**
* @see org.eclipse.ui.application.WorkbenchWindowAdvisor#preWindowOpen()
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void preWindowOpen() {
IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
configurer.setInitialSize(new Point(600, 450));
configurer.setShowCoolBar(false);
configurer.setShowStatusLine(true);
configurer.setTitle(getString("_UI_Application_title")); //$NON-NLS-1$
}
/**
* @see org.eclipse.ui.application.WorkbenchWindowAdvisor#createActionBarAdvisor(org.eclipse.ui.application.IActionBarConfigurer)
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public ActionBarAdvisor createActionBarAdvisor(IActionBarConfigurer configurer) {
return new WindowActionBarAdvisor(configurer);
}
}
/**
* RCP's action bar advisor
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static class WindowActionBarAdvisor extends ActionBarAdvisor {
/**
* @see ActionBarAdvisor#ActionBarAdvisor(org.eclipse.ui.application.IActionBarConfigurer)
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public WindowActionBarAdvisor(IActionBarConfigurer configurer) {
super(configurer);
}
/**
* @see org.eclipse.ui.application.ActionBarAdvisor#fillMenuBar(org.eclipse.jface.action.IMenuManager)
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void fillMenuBar(IMenuManager menuBar) {
IWorkbenchWindow window = getActionBarConfigurer().getWindowConfigurer().getWindow();
menuBar.add(createFileMenu(window));
menuBar.add(createEditMenu(window));
menuBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
menuBar.add(createWindowMenu(window));
menuBar.add(createHelpMenu(window));
}
/**
* Creates the 'File' menu.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IMenuManager createFileMenu(IWorkbenchWindow window) {
IMenuManager menu = new MenuManager(getString("_UI_Menu_File_label"), //$NON-NLS-1$
IWorkbenchActionConstants.M_FILE);
menu.add(new GroupMarker(IWorkbenchActionConstants.FILE_START));
IMenuManager newMenu = new MenuManager(getString("_UI_Menu_New_label"), "new"); //$NON-NLS-1$ //$NON-NLS-2$
newMenu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
menu.add(newMenu);
menu.add(new Separator());
menu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
menu.add(new Separator());
addToMenuAndRegister(menu, ActionFactory.CLOSE.create(window));
addToMenuAndRegister(menu, ActionFactory.CLOSE_ALL.create(window));
menu.add(new Separator());
addToMenuAndRegister(menu, ActionFactory.SAVE.create(window));
addToMenuAndRegister(menu, ActionFactory.SAVE_AS.create(window));
addToMenuAndRegister(menu, ActionFactory.SAVE_ALL.create(window));
menu.add(new Separator());
addToMenuAndRegister(menu, ActionFactory.QUIT.create(window));
menu.add(new GroupMarker(IWorkbenchActionConstants.FILE_END));
return menu;
}
/**
* Creates the 'Edit' menu.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IMenuManager createEditMenu(IWorkbenchWindow window) {
IMenuManager menu = new MenuManager(getString("_UI_Menu_Edit_label"), //$NON-NLS-1$
IWorkbenchActionConstants.M_EDIT);
menu.add(new GroupMarker(IWorkbenchActionConstants.EDIT_START));
addToMenuAndRegister(menu, ActionFactory.UNDO.create(window));
addToMenuAndRegister(menu, ActionFactory.REDO.create(window));
menu.add(new GroupMarker(IWorkbenchActionConstants.UNDO_EXT));
menu.add(new Separator());
addToMenuAndRegister(menu, ActionFactory.CUT.create(window));
addToMenuAndRegister(menu, ActionFactory.COPY.create(window));
addToMenuAndRegister(menu, ActionFactory.PASTE.create(window));
menu.add(new GroupMarker(IWorkbenchActionConstants.CUT_EXT));
menu.add(new Separator());
addToMenuAndRegister(menu, ActionFactory.DELETE.create(window));
addToMenuAndRegister(menu, ActionFactory.SELECT_ALL.create(window));
menu.add(new Separator());
menu.add(new GroupMarker(IWorkbenchActionConstants.ADD_EXT));
menu.add(new GroupMarker(IWorkbenchActionConstants.EDIT_END));
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
return menu;
}
/**
* Creates the 'Window' menu.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IMenuManager createWindowMenu(IWorkbenchWindow window) {
IMenuManager menu = new MenuManager(getString("_UI_Menu_Window_label"), //$NON-NLS-1$
IWorkbenchActionConstants.M_WINDOW);
addToMenuAndRegister(menu, ActionFactory.OPEN_NEW_WINDOW.create(window));
menu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
menu.add(ContributionItemFactory.OPEN_WINDOWS.create(window));
return menu;
}
/**
* Creates the 'Help' menu.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IMenuManager createHelpMenu(IWorkbenchWindow window) {
IMenuManager menu = new MenuManager(getString("_UI_Menu_Help_label"), IWorkbenchActionConstants.M_HELP); //$NON-NLS-1$
// Welcome or intro page would go here
// Help contents would go here
// Tips and tricks page would go here
menu.add(new GroupMarker(IWorkbenchActionConstants.HELP_START));
menu.add(new GroupMarker(IWorkbenchActionConstants.HELP_END));
menu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
return menu;
}
/**
* Adds the specified action to the given menu and also registers the action with the
* action bar configurer, in order to activate its key binding.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addToMenuAndRegister(IMenuManager menuManager, IAction action) {
menuManager.add(action);
getActionBarConfigurer().registerGlobalAction(action);
}
}
/**
* About action for the RCP application.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static class AboutAction extends WorkbenchWindowActionDelegate {
/**
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void run(IAction action) {
MessageDialog.openInformation(getWindow().getShell(), getString("_UI_About_title"), //$NON-NLS-1$
getString("_UI_About_text")); //$NON-NLS-1$
}
}
/**
* Open action for the objects from the Diseasemodels model.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static class OpenAction extends WorkbenchWindowActionDelegate {
/**
* Opens the editors for the files selected using the file dialog.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void run(IAction action) {
String[] filePaths = openFilePathDialog(getWindow().getShell(), SWT.OPEN, null);
if (filePaths.length > 0) {
openEditor(getWindow().getWorkbench(), URI.createFileURI(filePaths[0]));
}
}
}
/**
* Open URI action for the objects from the Diseasemodels model.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static class OpenURIAction extends WorkbenchWindowActionDelegate {
/**
* Opens the editors for the files selected using the LoadResourceDialog.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void run(IAction action) {
LoadResourceAction.LoadResourceDialog loadResourceDialog = new LoadResourceAction.LoadResourceDialog(getWindow().getShell());
if (Window.OK == loadResourceDialog.open()) {
for (URI uri : loadResourceDialog.getURIs()) {
openEditor(getWindow().getWorkbench(), uri);
}
}
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static String[] openFilePathDialog(Shell shell, int style, String[] fileExtensionFilters) {
return openFilePathDialog(shell, style, fileExtensionFilters, (style & SWT.OPEN) != 0, (style & SWT.OPEN) != 0, (style & SWT.SAVE) != 0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static String[] openFilePathDialog(Shell shell, int style, String[] fileExtensionFilters, boolean includeGroupFilter, boolean includeAllFilter, boolean addExtension) {
FileDialog fileDialog = new FileDialog(shell, style);
if (fileExtensionFilters == null) {
fileExtensionFilters = FILE_EXTENSION_FILTERS;
}
// If requested, augment the file extension filters by adding a group of all the other filters (*.ext1;*.ext2;...)
// at the beginning and/or an all files wildcard (*.*) at the end.
//
includeGroupFilter &= fileExtensionFilters.length > 1;
int offset = includeGroupFilter ? 1 : 0;
if (includeGroupFilter || includeAllFilter) {
int size = fileExtensionFilters.length + offset + (includeAllFilter ? 1 : 0);
String[] allFilters = new String[size];
StringBuilder group = includeGroupFilter ? new StringBuilder() : null;
for (int i = 0; i < fileExtensionFilters.length; i++) {
if (includeGroupFilter) {
if (i != 0) {
group.append(';');
}
group.append(fileExtensionFilters[i]);
}
allFilters[i + offset] = fileExtensionFilters[i];
}
if (includeGroupFilter) {
allFilters[0] = group.toString();
}
if (includeAllFilter) {
allFilters[allFilters.length - 1] = "*.*"; //$NON-NLS-1$
}
fileDialog.setFilterExtensions(allFilters);
}
else {
fileDialog.setFilterExtensions(fileExtensionFilters);
}
fileDialog.open();
String[] filenames = fileDialog.getFileNames();
String[] result = new String[filenames.length];
String path = fileDialog.getFilterPath() + File.separator;
String extension = null;
// If extension adding requested, get the dotted extension corresponding to the selected filter.
//
if (addExtension) {
int i = fileDialog.getFilterIndex();
if (i != -1 && (!includeAllFilter || i != fileExtensionFilters.length)) {
i = includeGroupFilter && i == 0 ? 0 : i - offset;
String filter = fileExtensionFilters[i];
int dot = filter.lastIndexOf('.');
if (dot == 1 && filter.charAt(0) == '*') {
extension = filter.substring(dot);
}
}
}
// Build the result by adding the selected path and, if needed, auto-appending the extension.
//
for (int i = 0; i < filenames.length; i++) {
String filename = path + filenames[i];
if (extension != null) {
int dot = filename.lastIndexOf('.');
+ StringBuilder str = new StringBuilder(filename);
if (dot == -1 || !Arrays.asList(fileExtensionFilters).contains("*" + filename.substring(dot))) //$NON-NLS-1$
{
- filename += extension;
+ str.append(extension);
+ //filename += extension;
}
+ filename = str.toString();
}
result[i] = filename;
}
return result;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static boolean openEditor(IWorkbench workbench, URI uri) {
IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
IWorkbenchPage page = workbenchWindow.getActivePage();
IEditorDescriptor editorDescriptor = EditUIUtil.getDefaultEditor(uri, null);
if (editorDescriptor == null) {
MessageDialog.openError(
workbenchWindow.getShell(),
getString("_UI_Error_title"), //$NON-NLS-1$
getString("_WARN_No_Editor", uri.lastSegment())); //$NON-NLS-1$
return false;
}
else {
try {
page.openEditor(new URIEditorInput(uri), editorDescriptor.getId());
}
catch (PartInitException exception) {
MessageDialog.openError(
workbenchWindow.getShell(),
getString("_UI_OpenEditorError_label"), //$NON-NLS-1$
exception.getMessage());
return false;
}
}
return true;
}
/**
* @see org.eclipse.ui.application.WorkbenchAdvisor#getInitialWindowPerspectiveId()
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getInitialWindowPerspectiveId() {
return Perspective.ID_PERSPECTIVE;
}
/**
* @see org.eclipse.ui.application.WorkbenchAdvisor#initialize(org.eclipse.ui.application.IWorkbenchConfigurer)
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void initialize(IWorkbenchConfigurer configurer) {
super.initialize(configurer);
configurer.setSaveAndRestore(true);
}
/**
* @see org.eclipse.ui.application.WorkbenchAdvisor#createWorkbenchWindowAdvisor(org.eclipse.ui.application.IWorkbenchWindowConfigurer)
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
return new WindowAdvisor(configurer);
}
}
| false | true | public static String[] openFilePathDialog(Shell shell, int style, String[] fileExtensionFilters, boolean includeGroupFilter, boolean includeAllFilter, boolean addExtension) {
FileDialog fileDialog = new FileDialog(shell, style);
if (fileExtensionFilters == null) {
fileExtensionFilters = FILE_EXTENSION_FILTERS;
}
// If requested, augment the file extension filters by adding a group of all the other filters (*.ext1;*.ext2;...)
// at the beginning and/or an all files wildcard (*.*) at the end.
//
includeGroupFilter &= fileExtensionFilters.length > 1;
int offset = includeGroupFilter ? 1 : 0;
if (includeGroupFilter || includeAllFilter) {
int size = fileExtensionFilters.length + offset + (includeAllFilter ? 1 : 0);
String[] allFilters = new String[size];
StringBuilder group = includeGroupFilter ? new StringBuilder() : null;
for (int i = 0; i < fileExtensionFilters.length; i++) {
if (includeGroupFilter) {
if (i != 0) {
group.append(';');
}
group.append(fileExtensionFilters[i]);
}
allFilters[i + offset] = fileExtensionFilters[i];
}
if (includeGroupFilter) {
allFilters[0] = group.toString();
}
if (includeAllFilter) {
allFilters[allFilters.length - 1] = "*.*"; //$NON-NLS-1$
}
fileDialog.setFilterExtensions(allFilters);
}
else {
fileDialog.setFilterExtensions(fileExtensionFilters);
}
fileDialog.open();
String[] filenames = fileDialog.getFileNames();
String[] result = new String[filenames.length];
String path = fileDialog.getFilterPath() + File.separator;
String extension = null;
// If extension adding requested, get the dotted extension corresponding to the selected filter.
//
if (addExtension) {
int i = fileDialog.getFilterIndex();
if (i != -1 && (!includeAllFilter || i != fileExtensionFilters.length)) {
i = includeGroupFilter && i == 0 ? 0 : i - offset;
String filter = fileExtensionFilters[i];
int dot = filter.lastIndexOf('.');
if (dot == 1 && filter.charAt(0) == '*') {
extension = filter.substring(dot);
}
}
}
// Build the result by adding the selected path and, if needed, auto-appending the extension.
//
for (int i = 0; i < filenames.length; i++) {
String filename = path + filenames[i];
if (extension != null) {
int dot = filename.lastIndexOf('.');
if (dot == -1 || !Arrays.asList(fileExtensionFilters).contains("*" + filename.substring(dot))) //$NON-NLS-1$
{
filename += extension;
}
}
result[i] = filename;
}
return result;
}
| public static String[] openFilePathDialog(Shell shell, int style, String[] fileExtensionFilters, boolean includeGroupFilter, boolean includeAllFilter, boolean addExtension) {
FileDialog fileDialog = new FileDialog(shell, style);
if (fileExtensionFilters == null) {
fileExtensionFilters = FILE_EXTENSION_FILTERS;
}
// If requested, augment the file extension filters by adding a group of all the other filters (*.ext1;*.ext2;...)
// at the beginning and/or an all files wildcard (*.*) at the end.
//
includeGroupFilter &= fileExtensionFilters.length > 1;
int offset = includeGroupFilter ? 1 : 0;
if (includeGroupFilter || includeAllFilter) {
int size = fileExtensionFilters.length + offset + (includeAllFilter ? 1 : 0);
String[] allFilters = new String[size];
StringBuilder group = includeGroupFilter ? new StringBuilder() : null;
for (int i = 0; i < fileExtensionFilters.length; i++) {
if (includeGroupFilter) {
if (i != 0) {
group.append(';');
}
group.append(fileExtensionFilters[i]);
}
allFilters[i + offset] = fileExtensionFilters[i];
}
if (includeGroupFilter) {
allFilters[0] = group.toString();
}
if (includeAllFilter) {
allFilters[allFilters.length - 1] = "*.*"; //$NON-NLS-1$
}
fileDialog.setFilterExtensions(allFilters);
}
else {
fileDialog.setFilterExtensions(fileExtensionFilters);
}
fileDialog.open();
String[] filenames = fileDialog.getFileNames();
String[] result = new String[filenames.length];
String path = fileDialog.getFilterPath() + File.separator;
String extension = null;
// If extension adding requested, get the dotted extension corresponding to the selected filter.
//
if (addExtension) {
int i = fileDialog.getFilterIndex();
if (i != -1 && (!includeAllFilter || i != fileExtensionFilters.length)) {
i = includeGroupFilter && i == 0 ? 0 : i - offset;
String filter = fileExtensionFilters[i];
int dot = filter.lastIndexOf('.');
if (dot == 1 && filter.charAt(0) == '*') {
extension = filter.substring(dot);
}
}
}
// Build the result by adding the selected path and, if needed, auto-appending the extension.
//
for (int i = 0; i < filenames.length; i++) {
String filename = path + filenames[i];
if (extension != null) {
int dot = filename.lastIndexOf('.');
StringBuilder str = new StringBuilder(filename);
if (dot == -1 || !Arrays.asList(fileExtensionFilters).contains("*" + filename.substring(dot))) //$NON-NLS-1$
{
str.append(extension);
//filename += extension;
}
filename = str.toString();
}
result[i] = filename;
}
return result;
}
|
diff --git a/QuizWebsite/src/servlets/AddCategory.java b/QuizWebsite/src/servlets/AddCategory.java
index 44ee8f6..160f22a 100644
--- a/QuizWebsite/src/servlets/AddCategory.java
+++ b/QuizWebsite/src/servlets/AddCategory.java
@@ -1,44 +1,63 @@
package servlets;
import java.io.IOException;
import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import database.MyDB;
/**
* Servlet implementation class AddCategory
*/
@WebServlet("/AddCategory")
public class AddCategory extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AddCategory() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn = MyDB.getConnection();
+ String text = request.getParameter("text");
+ try {
+ Statement stmt = conn.createStatement();
+ String query = "SELECT MAX(id) from Category;";
+ ResultSet rs = stmt.executeQuery(query);
+ rs.next();
+ int id = rs.getInt(1) + 1;
+ query = "INSERT into Category VALUES (" + id + ", '" + text + "');";
+ stmt.executeUpdate(query);
+
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ RequestDispatcher dispatch = request.getRequestDispatcher("AdminServlet");
+ dispatch.forward(request, response);
}
}
diff --git a/QuizWebsite/src/servlets/UserProfileServlet.java b/QuizWebsite/src/servlets/UserProfileServlet.java
index 2077ef7..f905f19 100644
--- a/QuizWebsite/src/servlets/UserProfileServlet.java
+++ b/QuizWebsite/src/servlets/UserProfileServlet.java
@@ -1,163 +1,163 @@
package servlets;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import quiz.*;
import user.*;
import database.*;
/**
* Servlet implementation class UserServlet
*/
@WebServlet("/UserProfileServlet")
public class UserProfileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UserProfileServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn = MyDB.getConnection();
String user = request.getParameter("username");
boolean sameUser = false;
User curUser = (User) request.getSession().getAttribute("user");
if (curUser.getName().equals(user)) {
sameUser = true;
request.setAttribute("friend_status", 0); //this is for your own page
}
try {
Statement stmt = conn.createStatement();
String query = "SELECT * FROM User WHERE username='" + user + "';";
ResultSet rs = stmt.executeQuery(query);
RequestDispatcher dispatch;
if (rs.next()) {
String[] attrs = DataBaseObject.getRow(rs, QuizConstants.USER_N_COLUMNS);
User usr = new User(attrs, conn);
request.setAttribute("user", usr);
if (!sameUser)
setFriendStatus(usr, curUser, request);
HomePageQueries.getUserRecentQuizzes(request, conn, usr, QuizConstants.N_TOP_RATED);
HomePageQueries.getAuthoring(request, conn, usr);
HomePageQueries.getAchievements(request, conn, usr);
getActivity(usr, request);
dispatch = request.getRequestDispatcher("profile.jsp");
dispatch.forward(request, response);
}
} catch (SQLException e) {
e.printStackTrace();
}
//list of recent activities
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
private void setFriendStatus(User profile, User curUser, HttpServletRequest request) {
Connection conn = MyDB.getConnection();
try {
Statement stmt = conn.createStatement();
String query = "SELECT * FROM Message inner join Friend_Request on Message.id=Friend_Request.id" +
" WHERE recipient='" + profile.getName() + "' AND sender='" + curUser.getName() + "';";
ResultSet rs = stmt.executeQuery(query);
if (rs.next()) {
if (rs.getBoolean("isAccepted")) {
request.setAttribute("friend_status", 4);
String[] attrs = DataBaseObject.getRow(rs, QuizConstants.MSG_FRIEND_N_COLS);
FriendRequest req = new FriendRequest(attrs, conn);
request.getSession().setAttribute("friend", req);
} else {
request.setAttribute("friend_status", 1); //you sent a friend request to this person
}
return;
}
query = "SELECT * FROM Message inner join Friend_Request on Message.id=Friend_Request.id" +
" WHERE recipient='" + curUser.getName() + "' AND sender='" + profile.getName() + "';";
rs = stmt.executeQuery(query);
if (rs.next()) {
+ String[] attrs = DataBaseObject.getRow(rs, QuizConstants.MSG_FRIEND_N_COLS);
+ FriendRequest req = new FriendRequest(attrs, conn);
if (rs.getBoolean("isAccepted")) {
request.setAttribute("friend_status", 4);
- String[] attrs = DataBaseObject.getRow(rs, QuizConstants.MSG_FRIEND_N_COLS);
- FriendRequest req = new FriendRequest(attrs, conn);
- request.getSession().setAttribute("friend", req);
+
} else {
request.setAttribute("friend_status", 2); //this person sent a friend request to you }
}
-
+ request.getSession().setAttribute("friend", req);
return;
}
request.setAttribute("friend_status", 3); //no friend relationship with this person
} catch (SQLException e) {
e.printStackTrace();
}
}
private void getActivity(User profile, HttpServletRequest request) {
Connection conn = MyDB.getConnection();
List<Activity> activities = new ArrayList<Activity>();
try {
Statement stmt = conn.createStatement();
String query = "SELECT * FROM Quiz WHERE author='" + profile.getName() + "';";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String[] attrs = DataBaseObject.getRow(rs, QuizConstants.QUIZ_N_COLS); //
Quiz quiz = new Quiz(attrs, conn);
activities.add(new Activity(profile, rs.getInt("id"), true, quiz.getName()));
}
query = "SELECT * FROM Quiz_Result WHERE username='" + profile.getName() + "';";
rs = stmt.executeQuery(query);
while (rs.next()) {
activities.add(new Activity(profile, rs.getInt("id"), false , ""));
}
request.setAttribute("activities", activities);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| false | false | null | null |
diff --git a/gsf-facades/src/main/java/com/fatwire/gst/foundation/facade/uri/BlobUriBuilder.java b/gsf-facades/src/main/java/com/fatwire/gst/foundation/facade/uri/BlobUriBuilder.java
index 7b170a8d..747dd853 100644
--- a/gsf-facades/src/main/java/com/fatwire/gst/foundation/facade/uri/BlobUriBuilder.java
+++ b/gsf-facades/src/main/java/com/fatwire/gst/foundation/facade/uri/BlobUriBuilder.java
@@ -1,197 +1,203 @@
/*
* Copyright 2008 FatWire Corporation. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fatwire.gst.foundation.facade.uri;
import COM.FutureTense.Interfaces.ICS;
import com.fatwire.assetapi.data.AssetData;
import com.fatwire.assetapi.data.AssetId;
import com.fatwire.assetapi.data.AttributeData;
import com.fatwire.assetapi.data.BlobObject;
import com.fatwire.assetapi.data.BlobObject.BlobAddress;
import com.fatwire.gst.foundation.DebugHelper;
import com.fatwire.gst.foundation.facade.assetapi.AttributeDataUtils;
import com.fatwire.gst.foundation.facade.runtag.render.GetBlobUrl;
/**
* Builder support for blob urls.
*
* <pre>
* new BlobUriBuilder(blob).mimeType("image/jpeg").parent("12345").toURI(ics);
* </pre>
*
* @author Dolf Dijkstra
* @since Feb 15, 2011
*
*/
public class BlobUriBuilder {
private GetBlobUrl tag = new GetBlobUrl();
private int n = 1;
/**
* Constructor that accepts AssetData and an attribute name.
*
* @param data the asset.
* @param attributeName the name of the attribute containing the blob.
*/
public BlobUriBuilder(final AssetData data, String attributeName) {
AttributeData attr = data.getAttributeData(attributeName);
if (attr == null)
throw new IllegalStateException("Can't find attribute " + attributeName + " on asset "
+ DebugHelper.toString(data.getAssetId()));
BlobObject blob = AttributeDataUtils.asBlob(attr);
if (blob == null)
throw new IllegalStateException("Attribute " + attributeName + " on asset "
+ DebugHelper.toString(data.getAssetId()) + " is not found.");
populateTag(blob.getBlobAddress());
parent(data.getAssetId());
}
-
/**
* Constructor accepting a BlobObject.
+ *
* @param blob
*/
public BlobUriBuilder(final BlobObject blob) {
this(blob.getBlobAddress());
}
/**
* Constructor accepting a BlobAddress.
+ *
* @param address
*/
public BlobUriBuilder(final BlobAddress address) {
populateTag(address);
}
/**
* @param address
*/
private void populateTag(final BlobAddress address) {
tag.setBlobCol(address.getColumnName());
- tag.setBlobKey(address.getIdentifier().toString());
+ tag.setBlobKey(address.getIdentifierColumnName());
tag.setBlobTable(address.getTableName());
- tag.setBlobWhere(address.getIdentifierColumnName());
+ tag.setBlobWhere(address.getIdentifier().toString());
}
/**
* @param ics
* @return the URI
*/
public String toURI(ICS ics) {
tag.setOutstr("foo_");
- tag.execute(ics);
- String ret = ics.GetVar("foo_");
- ics.RemoveVar("foo_");
+ String ret;
+ try {
+ tag.execute(ics);
+ ret = ics.GetVar("foo_");
+ } finally {
+ ics.RemoveVar("foo_");
+ }
return ret;
}
/**
* @param s
* @return this
* @see com.fatwire.gst.foundation.facade.runtag.render.GetBlobUrl#setAssembler(java.lang.String)
*/
public BlobUriBuilder assembler(String s) {
tag.setAssembler(s);
return this;
}
/**
* @param s
* @return this
* @see com.fatwire.gst.foundation.facade.runtag.render.GetBlobUrl#setFragment(java.lang.String)
*/
public BlobUriBuilder fragment(String s) {
tag.setFragment(s);
return this;
}
/**
* @param s
* @return this
* @see com.fatwire.gst.foundation.facade.runtag.render.GetBlobUrl#setBobHeader(java.lang.String)
*/
public BlobUriBuilder mimeType(String s) {
tag.setBobHeader(s);
return this;
}
/**
* @param s
* @return this
* @see com.fatwire.gst.foundation.facade.runtag.render.GetBlobUrl#setBlobNoCache(java.lang.String)
*/
public BlobUriBuilder blobNoCache(String s) {
tag.setBlobNoCache(s);
return this;
}
/**
* @param name
* @param value
* @return this
* @see com.fatwire.gst.foundation.facade.runtag.render.GetBlobUrl#setBlobHeaderName(int,
* java.lang.String)
*/
public BlobUriBuilder header(String name, String value) {
tag.setBlobHeaderName(n, name);
tag.setBlobHeaderValue(n, value);
n++;
return this;
}
/**
* Sets the Cache-Control: max-age http response header for this blob.
*
* @param value the max-age value as per http specification.
* @return this
* @see com.fatwire.gst.foundation.facade.runtag.render.GetBlobUrl#setBlobHeaderName(int,
* java.lang.String)
*/
public BlobUriBuilder maxAge(int value) {
if (value < 0)
throw new IllegalArgumentException("Cache-Control: max-age can not be negative");
tag.setBlobHeaderName(n, "Cache-Control");
tag.setBlobHeaderValue(n, "max-age=" + value);
n++;
return this;
}
/**
* @param s
* @return this
* @see com.fatwire.gst.foundation.facade.runtag.render.GetBlobUrl#setParentId(java.lang.String)
*/
public BlobUriBuilder parent(String s) {
tag.setParentId(s);
return this;
}
+
/**
* @param assetId
* @see com.fatwire.gst.foundation.facade.runtag.render.GetBlobUrl#setParentId(java.lang.String)
* @return this
*/
public BlobUriBuilder parent(AssetId assetId) {
return parent(Long.toString(assetId.getId()));
}
}
| false | false | null | null |
diff --git a/src/dispatcher/Dispatcher.java b/src/dispatcher/Dispatcher.java
index 6ba9134..6b079dc 100644
--- a/src/dispatcher/Dispatcher.java
+++ b/src/dispatcher/Dispatcher.java
@@ -1,317 +1,318 @@
package dispatcher;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.imageio.ImageIO;
import playable.Player;
import playable.TypeOfPlayer;
import renderer.Renderer;
import renderer.sprite.BaseSprite;
import renderer.sprite.SelectedSprite;
import renderer.sprite.TowerSprite;
import engine.Base;
import engine.Engine;
import engine.tower.Tower;
/**
* This class represents the link between the engine, the renderer, and the IHM of the player.
* @author Yuki
*
*/
public class Dispatcher {
private static final int FRAME_RATE = 60;
private static final int MILLISECOND_PER_FRAME = 1000 / FRAME_RATE;
private static long nbFrame = 0;
private static final int MAP_SCALE = 5;
private static int currentLevel = 0;
private static final Engine Engine = new Engine();
private static final Renderer Renderer = new Renderer("Nano WAAAARS!!!");
private static final HashMap<String, Player> Players = new HashMap<String, Player>();
/**
* This method loads the map from a datamap image.
* To make the map (from Photoshop for example) :
* - blue[50, 150], red[0], green[0] => a base for the player
* - red[50, 150], blue[0], green[0] => a base for the IA_1
* - green[50, 150], blue[0], red[0] => a base for the IA_2
* - white[50, 150], blue[50, 150], red[50, 150] => a neutral base
*
* - blue [200], red [200], green [200] => a tower
*
* - blue [255], red [255], green [255] => the gold base
*
* @param filepath path of the datamap grey-scale image
* @throws IOException
*/
public static void loadMap(String filepath) throws IOException{
BufferedImage map = ImageIO.read(new File(filepath));
Raster mapData = map.getData();
//For each pixels, create the bases
for(int y=0;y<map.getHeight();++y){
for(int x=0;x<map.getWidth();++x){
Color color = new Color(map.getRGB(x, y));
//if the pixel is not black
if(color.getRed() > 0 || color.getBlue() > 0 || color.getGreen() > 0){
//blue [20, 150] => a base for the player
if(color.getBlue() >= 20 && color.getBlue() <= 150 && color.getRed() == 0 && color.getGreen() == 0){
if(!Players.containsKey("Player"))
Players.put("Player", new Player("You", TypeOfPlayer.PLAYER));
float pixelBlue = mapData.getSampleFloat(x, y, 2);
Base newBase = new Base(MAP_SCALE*x, MAP_SCALE*y, (int)(Base.MAX_CAPACITY*(pixelBlue/150.)), Players.get("Player"));
newBase.setId(Renderer.addBaseSprite(newBase));
Engine.addBase(newBase);
}
//red [20, 150] => a base for the IA_1
else if(color.getRed() >= 20 && color.getRed() <= 150 && color.getBlue() == 0 && color.getGreen() == 0){
if(!Players.containsKey("IA_1"))
Players.put("IA_1", new Player("Jean Vilain", TypeOfPlayer.IA_1));
float pixelRed = mapData.getSampleFloat(x, y, 0);
Base newBase = new Base(MAP_SCALE*x, MAP_SCALE*y, (int)(Base.MAX_CAPACITY*(pixelRed/150.)), Players.get("IA_1"));
newBase.setId(Renderer.addBaseSprite(newBase));
Engine.addBase(newBase);
}
//green [20, 150] => a base for the IA_2
else if(color.getGreen() >= 20 && color.getGreen() <= 150 && color.getBlue() == 0 && color.getRed() == 0){
if(!Players.containsKey("IA_2"))
Players.put("IA_2", new Player("Mr Smith", TypeOfPlayer.IA_2));
float pixelGreen = mapData.getSampleFloat(x, y, 1);
Base newBase = new Base(MAP_SCALE*x, MAP_SCALE*y, (int)(Base.MAX_CAPACITY*(pixelGreen/150.)), Players.get("IA_2"));
newBase.setId(Renderer.addBaseSprite(newBase));
Engine.addBase(newBase);
}
//white [20, 150] => a neutral base
else if(color.getRed() >= 20 && color.getRed() <= 150 && color.getBlue() >= 20 && color.getBlue() <= 150 && color.getGreen() >= 20 && color.getGreen() <= 150){
float pixelRed = mapData.getSampleFloat(x, y, 0);
Base newBase = new Base(MAP_SCALE*x, MAP_SCALE*y, (int)(Base.MAX_CAPACITY*(pixelRed/150.)), null);
newBase.setId(Renderer.addBaseSprite(newBase));
Engine.addBase(newBase);
}
}
}
}
//For each pixel, create the towers
for(int y=0;y<map.getHeight();++y){
for(int x=0;x<map.getWidth();++x){
Color color = new Color(map.getRGB(x, y));
//if the pixel is not black
if(color.getRed() > 0 || color.getBlue() > 0 || color.getGreen() > 0){
//blue [200], red [200], green [200] => a tower
if(color.getBlue() == 200 && color.getRed() == 200 && color.getGreen() == 200){
Tower newTower = new Tower(MAP_SCALE*x, MAP_SCALE*y);
newTower.setId(Renderer.addTowerSprite(newTower));
Engine.addTower(newTower);
}
}
}
}
}
/**
* @param args input arguments
* @throws IOException
*/
public static void main(String[] args){
//init the renderer
try {
Renderer.init();
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
//display the renderer
Renderer.render();
//start the thread
boolean endOfTheWholeGame = false;
while(!endOfTheWholeGame){
/////////////////////////////
//the menu : choose a level//
/////////////////////////////
if(Renderer.getLvlSelected() == null){
try {
Renderer.addLvlsToTheMenu();
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
Renderer.displayMenu();
while(Renderer.getLvlSelected() == null){}
Dispatcher.currentLevel = Renderer.getLvlSelected().getNumLvl();
Renderer.hideMenu();
Renderer.setBackgroundImage();
}
/////////////////////////////
////////load the map/////////
/////////////////////////////
try {
Dispatcher.loadMap(Renderer.getLvlSelected().getPathOfTheLevel());
Renderer.addPlayerSprites(Players);
Renderer.resetLvlSelected();
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
////////////////////////////////////
//start the thread of the players///
////////////////////////////////////
Dispatcher.startThreadOfPlayers();
/////////////////////////////
///////start a game//////////
/////////////////////////////
ArrayList<Integer> idOfElementsDeleted = new ArrayList<Integer>();
boolean endOfAGame = false;
//=>what we have to do in each frame
while(!endOfAGame) {
long begin = System.currentTimeMillis();
Dispatcher.nbFrame = Dispatcher.nbFrame + 1;
//work of the engine
idOfElementsDeleted = Engine.doATurnGame();
//work of the renderer
Renderer.refreshView(idOfElementsDeleted);
//work of the dispatcher : manage interactions between players and the engine
//create units
if(SelectedSprite.isThereAtLeastOneStartingElement() && SelectedSprite.isThereAnEndingElement()) {
if(!Renderer.isChoosingUnit()){
for(Base b:BaseSprite.getStartingBases()){
double nbAgentsOfUnitSent = b.getNbAgents() * Renderer.getUnitPercentChosen();
if(nbAgentsOfUnitSent == b.getNbAgents()){
nbAgentsOfUnitSent -= 1;
}
b.sendUnit(nbAgentsOfUnitSent, SelectedSprite.getEndingElement());
}
SelectedSprite.resetEndingElement();
}
}
//build specialized tower
if(TowerSprite.isThereOneTowerToBuild()){
if(Renderer.isTowerTypeChosen()){
Tower specTower = Engine.specializeTower(TowerSprite.getChosenTowerType(), TowerSprite.getTowerToBuild().getEngineTower());
Renderer.updateTowerSprite(specTower, TowerSprite.getTowerToBuild().getEngineTower().getId());
TowerSprite.resetTowerToBuild();
}
}
//check if there is a winner
if(Dispatcher.theWinner() != null){
if(Dispatcher.theWinner().isPlayer()){
Renderer.displayWinner(Dispatcher.currentLevel);
}
else{
Renderer.displayLoser(Dispatcher.currentLevel);
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(0);
}
Player.flagThread = false;
endOfAGame = true;
}
//if the loop is too fast, we need to wait
long end = System.currentTimeMillis();
if ((end - begin) < Dispatcher.MILLISECOND_PER_FRAME) {
try {
Thread.sleep(Dispatcher.MILLISECOND_PER_FRAME - (end - begin));
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(0);
}
}
}
/////////////////////////////
///////reset the game////////
/////////////////////////////
Dispatcher.resetTheGame();
+ Renderer.setBackgroundImage();
}
}
/**
* This function starts the thread of each player concerned.
*/
private static void startThreadOfPlayers() {
if(Players.get("Player").getState() == Thread.State.NEW)
Players.get("Player").start();
if(Players.get("IA_1").getState() == Thread.State.NEW)
Players.get("IA_1").start();
if(Players.size() == 3){
if(Players.get("IA_2").getState() == Thread.State.NEW)
Players.get("IA_2").start();
}
}
/**
* Return the winner of the game (or null if there is no winner yet).
* Note : we don't care who is the winner if it's not the player : we return "IA_1" in that case.
* @return Player : the winner if there is one, or null if not
*/
public static Player theWinner(){
if(Players.size() == 2){
if(Players.get("Player").isAlive() && !Players.get("IA_1").isAlive())
return Players.get("Player");
else if(!Players.get("Player").isAlive() && Players.get("IA_1").isAlive())
return Players.get("IA_1");
else
return null;
}
else if(Players.size() == 3){
if(Players.get("Player").isAlive() && !Players.get("IA_1").isAlive() && !Players.get("IA_2").isAlive())
return Players.get("Player");
else if(!Players.get("Player").isAlive() && (Players.get("IA_1").isAlive() || Players.get("IA_2").isAlive()))
return Players.get("IA_1");
else
return null;
}
else
return null;
}
/**
* Reset all the data of the game, in order to restart a new game (from a different map for example) properly.
*/
private static void resetTheGame() {
Renderer.resetTheGame(Dispatcher.theWinner());
Engine.resetTheGame();
Player.resetFlagThread();
Players.clear();
}
// GETTERS & SETTERS
public static Engine getEngine() {
return Dispatcher.Engine;
}
public static Renderer getRenderer() {
return Dispatcher.Renderer;
}
public static HashMap<String, Player> getPlayers() {
return Dispatcher.Players;
}
public static int getCurrentLevel(){
return Dispatcher.currentLevel;
}
}
diff --git a/src/renderer/Level.java b/src/renderer/Level.java
index bc65197..2cffc41 100644
--- a/src/renderer/Level.java
+++ b/src/renderer/Level.java
@@ -1,46 +1,46 @@
package renderer;
public enum Level {
LVL_1("./tex/datamap/datamap_1.png", "./tex/background/background_lvl1.jpg", 1),
LVL_2("./tex/datamap/datamap_2.png", "./tex/background/background_lvl2.jpg", 2),
LVL_3("./tex/datamap/datamap_3.png", "./tex/background/background_lvl3.jpg", 3),
LVL_4("./tex/datamap/datamap_4.png", "./tex/background/background.jpg", 4),
LVL_5("./tex/datamap/datamap_5.png", "./tex/background/background.jpg", 5),
LVL_6("./tex/datamap/datamap_6.png", "./tex/background/background.jpg", 6),
LVL_7("./tex/datamap/datamap_7.png", "./tex/background/background.jpg", 7),
LVL_8("./tex/datamap/datamap_8.png", "./tex/background/background.jpg", 8),
LVL_9("./tex/datamap/datamap_9.png", "./tex/background/background.jpg", 9),
LVL_10("./tex/datamap/datamap_10.png", "./tex/background/background.jpg", 10);
private String path;
private String bgPath;
private int id;
- public static final int idOfLastLevel = 3;
+ public static final int idOfLastLevel = 10;
Level(String path, String bgPath, int id){
this.path = path;
this.bgPath = bgPath;
this.id = id;
}
public int getId(){
return this.id;
}
public String getPath(){
return this.path;
}
public String getBackgroundPath(){
return this.bgPath;
}
public static Level getLevel(int id){
for(Level l:Level.values()){
if(l.id == id)
return l;
}
return null;
}
}
diff --git a/src/renderer/Menu.java b/src/renderer/Menu.java
index 9456974..83407bb 100644
--- a/src/renderer/Menu.java
+++ b/src/renderer/Menu.java
@@ -1,113 +1,113 @@
package renderer;
import java.awt.Container;
import java.awt.MediaTracker;
import java.io.IOException;
import java.util.LinkedList;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import playable.TypeOfPlayer;
import renderer.sprite.LvlSprite;
@SuppressWarnings("serial")
public class Menu extends JLabel {
private Container container;
private int width;
private int height;
private LinkedList<LvlSprite> lvlSprites;
public Menu(Container c, int width, int height){
super();
this.container = c;
this.height = height;
this.width = width;
this.lvlSprites = new LinkedList<LvlSprite>();
}
public void init() throws IOException{
//Load the menu background image
ImageIcon bgMenuImage = new ImageIcon("./tex/MENU.png");
if(bgMenuImage.getImageLoadStatus() != MediaTracker.COMPLETE){
}
this.setBounds(0, 0, this.width, this.height);
this.setIcon(bgMenuImage);
}
/**
* Add a level to the menu.
* @param pathOfTheLevel : path of the corresponding image of the level.
* @param numOfTheLevel : the number of the level, display in the menu.
* @param x : x position
* @param y : y position
* @throws IOException
*/
public int addLvlSprite(String pathOfTheLevel, String pathOfTheBackground, int numOfTheLevel, int x, int y) throws IOException{
LvlSprite newSprite = new LvlSprite(pathOfTheLevel, pathOfTheBackground, numOfTheLevel);
newSprite.setSize(50);
newSprite.setImage(TypeOfPlayer.NEUTRAL.getImageOfBase());
newSprite.setBounds(x, y, 50, 50);
container.add(newSprite, Layer.UI.id());
lvlSprites.add(newSprite);
return newSprite.getId();
}
public void resetLvlSelected(){
this.getLvlSelected().resetIsSelected();
}
public void addLvlsToTheMenu() throws IOException{
//currently 3 levels
this.addLvlSprite(Level.LVL_1.getPath(), Level.LVL_1.getBackgroundPath(), Level.LVL_1.getId(), 170, this.height - 200);
this.addLvlSprite(Level.LVL_2.getPath(), Level.LVL_2.getBackgroundPath(), Level.LVL_2.getId(), 270, this.height - 200);
this.addLvlSprite(Level.LVL_3.getPath(), Level.LVL_3.getBackgroundPath(), Level.LVL_3.getId(), 370, this.height - 200);
this.addLvlSprite(Level.LVL_4.getPath(), Level.LVL_4.getBackgroundPath(), Level.LVL_4.getId(), 470, this.height - 200);
this.addLvlSprite(Level.LVL_5.getPath(), Level.LVL_5.getBackgroundPath(), Level.LVL_5.getId(), 570, this.height - 200);
this.addLvlSprite(Level.LVL_6.getPath(), Level.LVL_6.getBackgroundPath(), Level.LVL_6.getId(), 170, this.height - 100);
this.addLvlSprite(Level.LVL_7.getPath(), Level.LVL_7.getBackgroundPath(), Level.LVL_7.getId(), 270, this.height - 100);
this.addLvlSprite(Level.LVL_8.getPath(), Level.LVL_8.getBackgroundPath(), Level.LVL_8.getId(), 370, this.height - 100);
this.addLvlSprite(Level.LVL_9.getPath(), Level.LVL_9.getBackgroundPath(), Level.LVL_9.getId(), 470, this.height - 100);
this.addLvlSprite(Level.LVL_10.getPath(), Level.LVL_10.getBackgroundPath(), Level.LVL_10.getId(), 570, this.height - 100);
}
// GETTERS
public LinkedList<LvlSprite> getLvlSprites(){
return lvlSprites;
}
public LvlSprite getLvlSprite(int id){
for(LvlSprite lvl:this.lvlSprites){
if(lvl.getId() == id)
return lvl;
}
return null;
}
/**
* This function returns the level selected in the menu, or null if the user doesn't make a choice yet.
* @return
*/
public LvlSprite getLvlSelected() {
for(LvlSprite lvl:this.lvlSprites){
if(lvl.isSelected())
return lvl;
}
return null;
}
public ImageIcon getBackgroundImage(){
for(LvlSprite lvl:this.lvlSprites){
if(lvl.isSelected()){
return lvl.getBackgroundImage();
}
}
- return null;
+ return this.lvlSprites.getLast().getBackgroundImage();
}
}
| false | false | null | null |
diff --git a/PanChat/src/simulation/order_dinamic/SimulationOrderModel.java b/PanChat/src/simulation/order_dinamic/SimulationOrderModel.java
index 76b994b..73d9dc3 100644
--- a/PanChat/src/simulation/order_dinamic/SimulationOrderModel.java
+++ b/PanChat/src/simulation/order_dinamic/SimulationOrderModel.java
@@ -1,302 +1,291 @@
package simulation.order_dinamic;
import java.awt.Graphics2D;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Observable;
import order.Message;
import panchat.data.User;
import simulation.arrows.MultipleArrow;
import simulation.arrows.SingleArrow;
import simulation.model.SimulationArrowModel;
import simulation.order_dinamic.arrows.DeliveryArrow;
import simulation.view.CellPosition;
import simulation.view.ISimulator;
import simulation.view.SimulationView;
/**
* SimulationOrderLayer almacena los mensajes llegados desde capas superiores en
* una tabla hash, además del estado de los relojes en el instante de la
* recepcion.
*
*/
public class SimulationOrderModel extends Observable implements ISimulator {
/*
* Atributos
*/
/*
* Conjunto de las capas de ordenación. Para cada usuario disponemos de una
* capa de ordenación. Esta capa está diseñada para la simulación y por
* tanto permite simular el funcionamiento de la red, obteniendo el mensaje
* que deberíamos haber enviado por la red, e inyectando más tarde el
* mensaje como si lo hubieramos recibido.
*/
private HashMap<User, SimulationTopLayer> topLayers = new HashMap<User, SimulationTopLayer>();
/*
* Los mensajes recibidos para cada posición. Las flechas semánticamente
* representan entregar un mensaje
*/
private HashMap<CellPosition, Message> receive = new HashMap<CellPosition, Message>();
/*
* Guardamos los clocks para cada posición.
*/
private HashMap<CellPosition, SavedClocks> receiveClocks = new HashMap<CellPosition, SavedClocks>();
/*
* Guardamos los logs para cada posición.
*/
private HashMap<CellPosition, String> receiveLogs = new HashMap<CellPosition, String>();
/*
* Lista de flechas de entrega
*/
private List<SingleArrow> simulationArrows = new LinkedList<SingleArrow>();
/*
* Referencia al modelo de flechas.
*/
private SimulationArrowModel simulationArrowModel;
/*
* Referencia a la vista.
*/
private SimulationView simulationView;
/*
* Usamos esta variable para indicar si dibujamos la simulación real o no.
*/
private boolean drawSimulation = true;
public SimulationOrderModel(SimulationView view) {
simulationView = view;
simulationArrowModel = view.getSimulationModel();
}
/**
- * Cargamos un nuevo SimulationModel
- *
- * @param simulationModel
- */
- public void setSimulationModel(SimulationArrowModel simulationModel) {
-
- // Observamos la nueva simulacion;
- this.simulationArrowModel = simulationModel;
- }
-
- /**
* @return Obtenemos el número de procesos
*/
public int getNumProcesses() {
return this.simulationArrowModel.getNumProcesses();
}
/**
* @param process
*
* @return Devuelve el usuario correspondiente a un proceso determinado.
*/
public User getUser(int process) {
return this.simulationArrowModel.getUser(process);
}
/**
* @param position
*
* @return Devuelve la información del reloj correspondiente a la posición
* position.
*/
public SavedClocks getClocks(CellPosition position) {
if (position != null)
return receiveClocks.get(position);
else
return null;
}
/**
*
* @param position
*
* @return Devuelve la información de las capas de ordenación.
*/
public String getLog(CellPosition position) {
if (position != null)
return receiveLogs.get(position);
else
return null;
}
/**
* Realizar nueva simulacion
*/
@Override
public void simulate(SimulationView simulationView) {
simulationArrowModel = simulationView.getSimulationModel();
// Reiniciamos la simulacion.
topLayers.clear();
simulationArrows.clear();
receive.clear();
receiveClocks.clear();
receiveLogs.clear();
// Creamos los top layers
for (User user : simulationArrowModel.getUserList()) {
topLayers.put(user, new SimulationTopLayer(user));
}
// Registramos los usuarios en los top layers
for (User user : simulationArrowModel.getUserList()) {
for (User user2 : simulationArrowModel.getUserList()) {
if (!user.equals(user2))
topLayers.get(user).addUser(user2);
}
}
CellPosition iterator = new CellPosition(0, 0);
// Vamos recorriendo las casillas
for (iterator.tick = 0; iterator.tick < simulationArrowModel
.getTimeTicks(); iterator.tick++) {
for (iterator.process = 0; iterator.process < simulationArrowModel
.getNumProcesses(); iterator.process++) {
// Los topLayers está diseñados para usarse con usuarios, por lo
// tanto para la simulación realizamos un mapeo entre el
// identificador proceso, y un usuario creado para
// representarlo.
User user = simulationArrowModel.getUser(iterator.process);
SimulationTopLayer topLayer = topLayers.get(user);
/*
* Recepción de mensajes
*/
// Obtenemos el mensaje que previamente habíamos guardado en el
// paso anterior, y que debemos entregar según la posición.
Message msg = receive.get(iterator);
// Si existe un nensaje por recibir
if (msg != null) {
// Hacemos que al capa simule la recepción del mensaje a
// nivel de red.
topLayer.receive(msg);
// Ahora obtenemos el listado de mensajes que recibe el
// usuario en ese instante. Como pueden existir mensajes
// encolados, en un mismo tick podríamos recibir varios
// mensajes.
Iterator<Message> receivedMessages;
receivedMessages = topLayer.getReceivedMsgs().iterator();
while (receivedMessages.hasNext()) {
Message rMsg = receivedMessages.next();
if (rMsg.getContent() instanceof CellPosition) {
// En el interior del mensaje habíamos guardado la
// posición de destino
CellPosition pos = (CellPosition) rMsg.getContent();
// Creamos la flecha que representa la entrega
SingleArrow arrow = new DeliveryArrow(pos, iterator
.clone());
// La añadimos al listado de flechas de entrega.
simulationArrows.add(arrow);
}
}
}
// Comprobamos si la recepción de mensajes ha generado envio de
// mensajes.
Collection<Message> messages = topLayer.getSendedMsg().values();
/*
* Envio de mensajes
*/
// Las MultipleArrow son el conjunto de flechas que conforman
// una operación.
MultipleArrow multipleArrow;
// Listado de flechas que salen del punto que estamos evaluando.
List<SingleArrow> sendArrows;
// Obtenemos la flecha correspondiente a este paso en el
// simulador, comprobando si esta existe.
multipleArrow = simulationArrowModel.getArrow(iterator);
if (multipleArrow != null) {
// Obtenemos las flechas que salen de este punto
sendArrows = multipleArrow.getInitialArrow(iterator);
LinkedList<User> listDest = new LinkedList<User>();
for (SingleArrow destArrow : sendArrows) {
// Necesitamos hacer el mapeo proceso - usuario
int process = destArrow.getFinalPos().process;
User user2 = simulationArrowModel.getUser(process);
listDest.add(user2);
}
if (messages.size() == 0 && listDest.size() > 0) {
// Creamos el mensaje, y guardamos en el la posición
// donde estamos (el tick y el proceso), de modo que
// cuando lo recibamos creamos una flecha desde que se
// envio, a ese momento en el que se reciba.
msg = new Message(iterator.clone(), user, multipleArrow
.getProperties().clone());
topLayer.sendMsg(listDest, msg);
// Al ser simulado, no se envia realmente el paquete, y
// lo que hacemos es recogerlo de la capa más baja de
// las capas de ordenación. Tras su paso por las capas
// de ordenación ellas habrán introducido en el mensaje
// los relojes necesarios.
messages = topLayer.getSendedMsg().values();
}
Iterator<Message> iter = messages.iterator();
for (SingleArrow destArrow : sendArrows) {
// Guardamos el mensaje (simulando el retardo de la
// red), y lo añadiremos al destinatario en el momento
// que representa el final de la flecha.
if (iter.hasNext())
receive.put(destArrow.getFinalPos(), iter.next());
}
}
/*
* Registramos los relojes de cada paso.
*/
CellPosition pos = iterator.clone();
receiveClocks.put(pos, topLayer.getClocks());
receiveLogs.put(pos, topLayer.getDebugLog());
}
}
}
@Override
public void drawSimulation(Graphics2D g) {
if (drawSimulation)
SimulationView.paintArrows(g, this.simulationArrows);
}
public void setDrawSimulation(boolean selected) {
drawSimulation = selected;
simulationView.repaint();
}
}
diff --git a/PanChat/src/simulation/view/SimulationView.java b/PanChat/src/simulation/view/SimulationView.java
index a1261ee..3493f9e 100644
--- a/PanChat/src/simulation/view/SimulationView.java
+++ b/PanChat/src/simulation/view/SimulationView.java
@@ -1,509 +1,511 @@
package simulation.view;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.util.EnumMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JPanel;
import order.Message.Type;
import simulation.arrows.MessageArrow;
import simulation.arrows.MultipleArrow;
import simulation.model.SimulationArrowModel;
import simulation.view.listener.CreateListener;
import simulation.view.listener.DeleteListener;
import simulation.view.listener.MoveListener;
import simulation.view.listener.ViewListener;
@SuppressWarnings("serial")
public class SimulationView extends JPanel implements Observer {
public static enum State {
OVER, CREATE, MOVE, DELETE
}
/*
* Constantes
*/
// Constantes del tamaño de las celdas
public static final int cellWidth = 40;
public static final int cellHeight = 25;
public static final int paddingX = 40;
public static final int paddingY = 30;
// Constantes de color
private static final Color tickLineCol = Color.getHSBColor(.7f, .08f, .9f);
private static final Color evenTickCol = Color.getHSBColor(.7f, .05f, 1f);
private static final Color oddTickCol = Color.getHSBColor(.4f, .02f, 1f);
private static final Color overCellColor = new Color(1f, 1f, 1f, .8f);
private static final Color overColColor = new Color(0f, 0f, 0f, .04f);
private static final Color invalidOverColor = new Color(1f, .6f, .6f);
/*
* Atributos
*/
// El modelo de datos
private SimulationArrowModel simulationModel;
// Numero de procesos y de ticks
private int processes;
private int ticks;
// Dimensiones del tablero (en pixels)
private int width = ticks * cellWidth + paddingX + 1;
private int height = processes * (cellHeight + paddingY) + 1;
// Atributo que usamos para guardar sobre que estamos (celda, corte o fuera
// de la pantalla)
private IPosition overPosition;
private Boolean validOverPosition = true;
// Flecha que estamos modificando sobre la vista. Como no es una flecha
// definitiva, trabajamos directamente sobre la vista en vez del modelo.
private MessageArrow drawingArrow;
// Implementamos un doble buffer, realizando las operaciones de dibujo sobre
// el buffer, y después volcando la imagen sobre el contexto del panel.
BufferedImage backBuffer;
// Cuando redimensionamos nuestra vista necesitamos ejecutar super.paint()
// para limpiar la ventana.
private boolean screenResized;
// Guardamos en una lista, los listeners que controlan el comportamiento de
// la vista.
private ViewListener[] listViewListeners = new ViewListener[State.values().length];
// Guardamos una referencia al listener actual para poder cambiarlo por otro
private ViewListener actualViewListener;
// Lista de observadores de posición. Como por ejemplo el panel de
// información de relojes lógicos.
private List<IPositionObserver> positionObservers = new LinkedList<IPositionObserver>();
// Lista de simuladores de información
private List<ISimulator> simulatorList = new LinkedList<ISimulator>();
/**
* Crea un nuevo tablero con el simulation model.
*/
public SimulationView(SimulationArrowModel simulationModel) {
this.simulationModel = simulationModel;
this.simulationModel.addObserver(this);
createViewListeners();
// Por defecto el comportamiento es moverse con el ratón.
this.setState(State.CREATE);
updateData();
}
/**
* Creamos los listeners que controlan el comportamiento de la vista.
*
*/
private void createViewListeners() {
listViewListeners[State.OVER.ordinal()] = new ViewListener(this);
listViewListeners[State.CREATE.ordinal()] = new CreateListener(this);
listViewListeners[State.MOVE.ordinal()] = new MoveListener(this);
listViewListeners[State.DELETE.ordinal()] = new DeleteListener(this);
}
/*
* Funciones de dibujo
*/
/**
* Dibujar el tablero.
*
* @param g
* el contexto grafico en el cual se pinta.
*/
@Override
public void paint(Graphics g) {
// Obtenemos el doble buffer
Graphics2D g2 = (Graphics2D) backBuffer.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// Dibujamos las columnas y los procesos
paintColumns(g2);
paintProcesses(g2);
// Dibujamos las flechas
paintArrows(g2, simulationModel.getArrowList());
// Si estamos editando una flecha dibujamos la fecha en dibujo
if (this.drawingArrow != null)
drawingArrow.draw(g2);
// Si no mostramos la simulación realizada por los simuladores
else
for (ISimulator simul : this.simulatorList)
simul.drawSimulation(g2);
if (screenResized)
super.paint(g);
// Dibujamos sobre el doble buffer
g.drawImage(backBuffer, 0, 0, this);
}
/**
* Dibujar las lineas verticales del tablero.
*
* @param g
* el contexto grafico en el cual se pinta.
*/
private void paintColumns(Graphics2D g) {
int x0, x1;
int y0 = 0;
int y1 = height;
x1 = cellWidth;
boolean even = true;
for (int i = 0; i < ticks; i++) {
x0 = i * cellWidth + paddingX;
g.setColor(even ? evenTickCol : oddTickCol);
even = !even;
g.fillRect(x0, y0, x1, y1);
g.setPaint(tickLineCol);
g.drawRect(x0, y0, x1, y1);
}
// Dibujamos el efecto over de iluminación. Osea iluminamos toda la
// columna.
if (overPosition instanceof CutPosition) {
CutPosition pos = (CutPosition) overPosition;
x0 = pos.tick * cellWidth + paddingX;
g.setColor(overColColor);
g.fillRect(x0, y0, x1, y1);
}
}
/**
* Dibujar las lineas horizontales del tablero.
*
* @param g
* el contexto grafico en el cual se pinta.
*/
private void paintProcesses(Graphics g) {
int x1 = cellWidth;
int y1 = cellHeight;
for (int i = 0; i <= processes; i++) {
int y0 = i * (cellHeight + paddingY) + paddingY;
for (int j = 0; j < ticks; j++) {
int x0 = paddingX + cellWidth * j;
g.setColor(Color.getHSBColor(i * .10f % 1, .20f, 1f));
g.fillRect(x0, y0, x1, y1);
g.setColor(Color.getHSBColor(i * .10f % 1, .50f, .6f));
g.drawRect(x0, y0, x1, y1);
}
}
// Dibujamos el efecto over de iluminación. Iluminamos la celda cuando
// pasamos por encima.
if (overPosition instanceof CellPosition) {
CellPosition pos = (CellPosition) overPosition;
int x0 = pos.tick * cellWidth + paddingX;
int y0 = pos.process * (cellHeight + paddingY) + paddingY;
// Si la posicion over es invalida, la pintamos de rojo
if (!validOverPosition)
g.setColor(invalidOverColor);
else
g.setColor(overCellColor);
g.fillRect(x0 + 1, y0 + 1, x1 - 1, y1 - 1);
}
}
/**
* Dibuja las flechas
*
* @param g
* el contexto grafico en el cual se pinta.
*/
public static void paintArrows(Graphics2D g,
List<? extends MessageArrow> arrowList) {
for (MessageArrow arrow : arrowList) {
arrow.draw(g);
}
}
/*
* Getters y setters
*/
/**
* Cambiamos el modo de comportamiento de la vista :
* <ul>
* <li>Type.Over = Moverse sin hacer nada</li>
* <li>Type.Create = Crear flechas, y mover los puntos del final</li>
* <li>Type.Move = Mover flechas</li>
* <li>Type.Delete = Eliminar flechas</li>
* </ul>
*
* @param state
*/
public void setState(State state) {
if (actualViewListener != null) {
this.removeMouseListener(actualViewListener);
this.removeMouseMotionListener(actualViewListener);
}
actualViewListener = listViewListeners[state.ordinal()];
this.addMouseListener(actualViewListener);
this.addMouseMotionListener(actualViewListener);
}
/**
*
* @return Devuelve las propiedades de creación de flechas del
* CreateListener.
*/
public EnumMap<Type, Boolean> getCreationProperties() {
CreateListener listener = (CreateListener) listViewListeners[State.CREATE
.ordinal()];
return listener.getProperties();
}
/*
* Métodos para obtener y cambiar el modelo de flechas (patrón MVC).
*
* Podemos cambiar el modelo de flechas ya que soportamos la carga de
* escenacios de flechas desde ficheros de datos.
*/
/**
* Cambia el modelo (patron MVC)
*
* @param simulationModel
*/
public void setSimulationModel(SimulationArrowModel simulationModel) {
+ this.simulationModel.deleteObserver(this);
this.simulationModel = simulationModel;
+ this.simulationModel.addObserver(this);
for (MultipleArrow arrow : this.simulationModel.getArrowList())
arrow.initialize();
for (ViewListener view : listViewListeners) {
view.updateModel();
}
updateData();
}
/**
* Devuelve la clase modelo
*/
public SimulationArrowModel getSimulationModel() {
return this.simulationModel;
}
/*
* Funciones para establecer la flecha que estamos editando sobre el canvas.
*/
/**
* @param drawingArrow
* the drawingArrow to set
*/
public void setDrawingArrow(MessageArrow drawingArrow) {
this.drawingArrow = drawingArrow;
}
/**
* @return the drawingArrow
*/
public MessageArrow getDrawingArrow() {
return drawingArrow;
}
/**
* Calcula la posicion centrada en una celda según la posicion de una celda.
*
* @param position
*
* @return Punto centrado en la celda position
*/
public static Point2D.Float PositionCoords(CellPosition position) {
// Espacio de la izquierda + celda * tick + mitad celda
int x = paddingX + position.tick * cellWidth + cellWidth / 2;
// Espacio de arriba + celda * proceso + mitad celda
int y = paddingY + position.process * (cellHeight + paddingY)
+ cellHeight / 2;
return new Point2D.Float(x, y);
}
/**
* Establecemos la posición sobre la que esta el cursor. Sólo si cambiamos
* el estado actualizamos y repintamos la pantalla.
*
* @param newPosition
*/
public void setPosition(IPosition newPosition, IPositionObserver.Mode mode) {
/*
* - Si la posicion antigua era distinta de null y ahora es null, ya no
* estamos encima de la pantalla. (evitamos el null pointer)
*
* - Si la posicion antigua es distinta de null, comprobamos que la
* posicion nueva sea distinta de la antigua.
*/
if (mode.equals(IPositionObserver.Mode.Over)
&& ((this.overPosition != null && newPosition == null) || (newPosition != null && !newPosition
.equals(this.overPosition)))) {
this.overPosition = newPosition;
for (IPositionObserver observer : this.positionObservers)
observer.setPosition(overPosition, mode);
this.repaint();
} else {
for (IPositionObserver observer : this.positionObservers)
observer.setPosition(overPosition, mode);
}
}
/**
* Establecemos la posición sobre la que esta el cursor. Sólo si cambiamos
* el estado actualizamos y repintamos la pantalla.
*
* @param newPosition
*/
public void setPosition(IPosition newPosition, IPositionObserver.Mode mode,
Boolean valid) {
setPosition(newPosition, mode);
this.validOverPosition = valid;
}
/**
*
* @return Devuelve la posición actual
*/
public IPosition getOverPosition() {
return this.overPosition;
}
/**
* Calcular el indice de la celda en funcion de la posicion del cursor
*/
public IPosition getPosition(MouseEvent e) {
int x = e.getX();
int y = e.getY();
// Calculamos donde cae dentro de una fila (donde una fila es el espacio
// de un proceso y el espacio que tiene justo antes de el)
int fila = y % (paddingY + cellHeight);
// columna, que es la columna una vez hemos restado el espacio de la
// izquierda
int columna = (x - paddingX) / cellWidth;
// // Si está en el margen izquierdo null
if (x < paddingX || columna >= ticks || y > height - 1)
return null;
// Sino, puede ser o bien una celda o una columna.
if (fila >= paddingY) {
// Calculamos la fila
fila = y / (paddingY + cellHeight);
return new CellPosition(fila, columna);
} // Estamos en una columna
else
return new CutPosition(columna);
}
/**
* @param obj
* Añade el objeto a la lista de observadores de posición.
*/
public void addPositionObserver(IPositionObserver obj) {
this.positionObservers.add(obj);
}
/**
* @param obj
* Añade el simulador a la lista de simuladores.
*/
public void addSimulator(ISimulator obj) {
this.simulatorList.add(obj);
}
/*
* Patron MVC
*/
/**
* Actualizar la vista cuando se actualiza el modelo
*/
@Override
public void update(Observable o, Object arg) {
updateData();
}
public void updateData() {
int ticks = simulationModel.getTimeTicks();
int processes = simulationModel.getNumProcesses();
// Solo cambiar el tamaño de la ventana si han cambiado el número de
// ticks y el número de procesos.
if (this.ticks != ticks || this.processes != processes) {
this.ticks = ticks;
this.processes = processes;
width = ticks * cellWidth + 2 * paddingX;
height = processes * (cellHeight + paddingY) + paddingY;
this.backBuffer = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
this.screenResized = true;
this.setPreferredSize(new Dimension(width, height));
} else {
this.screenResized = false;
}
// Llamamos a los simuladores
for (ISimulator simul : this.simulatorList)
simul.simulate(this);
// Redibujamos la pantalla
this.repaint();
}
}
\ No newline at end of file
diff --git a/PanChat/src/simulation/view/listener/ViewListener.java b/PanChat/src/simulation/view/listener/ViewListener.java
index 462027f..b32ba46 100644
--- a/PanChat/src/simulation/view/listener/ViewListener.java
+++ b/PanChat/src/simulation/view/listener/ViewListener.java
@@ -1,86 +1,79 @@
package simulation.view.listener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
-import java.util.EnumMap;
-
-import order.Message.Type;
import simulation.model.SimulationArrowModel;
import simulation.view.IPositionObserver;
import simulation.view.SimulationView;
public class ViewListener implements MouseListener, MouseMotionListener {
protected SimulationView simulationView;
protected SimulationArrowModel simulationModel;
public ViewListener(SimulationView simulationView) {
this.simulationView = simulationView;
updateModel();
}
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2)
simulationView.setPosition(simulationView.getPosition(e),
IPositionObserver.Mode.DoubleClick);
else
simulationView.setPosition(simulationView.getPosition(e),
IPositionObserver.Mode.Click);
}
@Override
public void mouseEntered(MouseEvent e) {
// Sirve para indicarle a la vista en que posicion está el cursor para
// que ilumine la celda correspondiente.
simulationView.setPosition(simulationView.getPosition(e),
IPositionObserver.Mode.Over);
}
@Override
public void mouseExited(MouseEvent e) {
// Hemos salido de la ventana, la posición es null.
simulationView.setPosition(null, IPositionObserver.Mode.Over);
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
// Sirve para indicarle a la vista en que posicion está el cursor para
// que ilumine la celda correspondiente.
simulationView.setPosition(simulationView.getPosition(e),
IPositionObserver.Mode.Over);
}
@Override
public void mouseDragged(MouseEvent e) {
// Sirve para indicarle a la vista en que posicion está el cursor para
// que ilumine la celda correspondiente.
simulationView.setPosition(simulationView.getPosition(e),
IPositionObserver.Mode.Over);
}
@Override
public void mouseMoved(MouseEvent e) {
// Sirve para indicarle a la vista en que posicion está el cursor para
// que ilumine la celda correspondiente.
simulationView.setPosition(simulationView.getPosition(e),
IPositionObserver.Mode.Over);
}
/**
* Permite cambiar el model.
*/
public void updateModel() {
this.simulationModel = simulationView.getSimulationModel();
}
-
- public void setProperties(EnumMap<Type, Boolean> properties) {
- // TODO Auto-generated method stub
- }
}
| false | false | null | null |