answer
stringlengths 17
10.2M
|
|---|
package org.csstudio.archive.sdds.server;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import org.csstudio.archive.sdds.server.internal.ServerPreferenceKey;
import org.csstudio.archive.sdds.server.io.Server;
import org.csstudio.archive.sdds.server.io.ServerException;
import org.csstudio.archive.sdds.server.management.Restart;
import org.csstudio.archive.sdds.server.management.Stop;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.preferences.IPreferencesService;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.remotercp.common.tracker.IGenericServiceListener;
import org.remotercp.service.connection.session.ISessionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Markus Moeller
*
*/
public class SddsServerApplication implements IApplication, RemotelyStoppable, SddsServerApplicationMBean, IGenericServiceListener<ISessionService> {
/** The instance of the server */
private Server server;
/** The logger of this class */
private static final Logger LOG = LoggerFactory.getLogger(SddsServerApplication.class);
/** Session service for the XMPP login */
private ISessionService xmppService;
/** Help object for synchronization purposes */
private final Object lock;
/** Flag that indicates if the server is running */
private boolean running;
/** Flag that indicates if the server has to be restarted */
private boolean restart;
/**
* The standard constructor
*/
public SddsServerApplication() {
lock = new Object();
xmppService = null;
running = true;
restart = false;
}
/* (non-Javadoc)
* @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
*/
@Override
public Object start(IApplicationContext context) throws Exception {
int serverPort;
boolean useJmx = false;
LOG.info("Starting {}", SddsServerActivator.PLUGIN_ID);
IPreferencesService pref = Platform.getPreferencesService();
serverPort = pref.getInt(SddsServerActivator.PLUGIN_ID, ServerPreferenceKey.P_SERVER_PORT, 4056, null);
LOG.info("The server uses port {}", serverPort);
useJmx = pref.getBoolean(SddsServerActivator.PLUGIN_ID, ServerPreferenceKey.P_USE_JMX,
false, null);
try {
if (useJmx == false) {
Stop.injectStaticObject(this);
Restart.injectStaticObject(this);
SddsServerActivator.getDefault().addSessionServiceListener(this);
} else {
connectMBeanServer();
}
server = new Server(serverPort);
server.start();
} catch(ServerException se) {
LOG.error("Cannot create an instance of the Server class. ", se);
LOG.error("Stopping application!");
running = false;
restart = false;
}
context.applicationRunning();
while(running) {
synchronized(lock) {
try {
lock.wait();
} catch(InterruptedException ie) {
LOG.debug("Interrupted");
}
}
}
if(server != null) {
server.stopServer();
}
if (xmppService != null) {
xmppService.disconnect();
LOG.info("XMPP connection disconnected.");
}
Integer exitType = null;
if(restart) {
LOG.info("Restarting {}", SddsServerActivator.PLUGIN_ID);
exitType = IApplication.EXIT_RESTART;
} else {
LOG.info("Stopping {}", SddsServerActivator.PLUGIN_ID);
exitType = IApplication.EXIT_OK;
}
return exitType;
}
/* (non-Javadoc)
* @see org.eclipse.equinox.app.IApplication#stop()
*/
@Override
public void stop() {
// Nothing to do here
}
public void connectMBeanServer() {
MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
ObjectName myname = null;
String jmxPort = System.getProperty("com.sun.management.jmxremote.port");
LOG.info("The server uses JMX for remote access. Port: " + jmxPort);
try {
myname = new ObjectName("org.csstudio.archive.sdds.server:name=SddsServer");
mbeanServer.registerMBean(this, myname);
} catch (MalformedObjectNameException mone) {
LOG.error("[*** MalformedObjectNameException ***]: ", mone);
} catch (NullPointerException npe) {
LOG.error("[*** NullPointerException ***]: ", npe);
} catch (InstanceAlreadyExistsException iaee) {
LOG.error("[*** InstanceAlreadyExistsException ***]: ", iaee);
} catch (MBeanRegistrationException mbre) {
LOG.error("[*** MBeanRegistrationException ***]: ", mbre);
} catch (NotCompliantMBeanException ncmbe) {
LOG.error("[*** NotCompliantMBeanException ***]: ", ncmbe);
}
}
/**
*
* @param setRestart
*/
@Override
public void stopApplication(boolean setRestart) {
this.running = false;
this.restart = setRestart;
synchronized(lock) {
lock.notify();
}
}
/**
* Stops the application. Used by JMX.
*/
@Override
public void stopApplication() {
stopApplication(false);
}
@Override
public String readVersion() {
String workspaceDirectory = Platform.getInstallLocation()
.getURL().getPath() + ".eclipseproduct";
BufferedReader reader = null;
String version = null;
try {
reader = new BufferedReader(new FileReader(workspaceDirectory));
while (reader.ready()) {
version = reader.readLine().trim();
if (version.startsWith("version=")) {
int indexOfEqual = version.indexOf("=") + 1;
version = version.substring(indexOfEqual);
break;
}
}
} catch (FileNotFoundException fnfe) {
LOG.warn("Workspace directory cannot be found: {}", workspaceDirectory);
version = null;
} catch (IOException ioe) {
LOG.warn("Cannot read version file.");
version = null;
} finally {
if (reader!=null) {
try{reader.close();}catch(Exception e){/* Can be ignored */}
reader=null;
}
}
if (version == null) {
version = "N/A";
}
return version;
}
@Override
public void bindService(ISessionService sessionService) {
IPreferencesService pref = Platform.getPreferencesService();
String xmppServer = pref.getString(SddsServerActivator.PLUGIN_ID, ServerPreferenceKey.P_XMPP_SERVER,
"krynfs.desy.de", null);
String xmppUser = pref.getString(SddsServerActivator.PLUGIN_ID, ServerPreferenceKey.P_XMPP_USER,
"sdds-server", null);
String xmppPassword = pref.getString(SddsServerActivator.PLUGIN_ID, ServerPreferenceKey.P_XMPP_PASSWORD,
"sdds-server", null);
try {
sessionService.connect(xmppUser, xmppPassword, xmppServer);
xmppService = sessionService;
} catch (Exception e) {
LOG.warn("XMPP connection is not available, ", e);
xmppService = null;
}
}
@Override
public void unbindService(ISessionService service) {
// Nothing to do here
}
public void nirvana()
{
//sddsReader.readDataPortionSimple("HQCO7L~B", null, -1, startTime, endTime, (short)1, -1, null);
// running = true;
// while(running)
// synchronized(this)
// EpicsRecordData[] data = sddsReader.readData("CMTBVA3V112_ai", 1249120800L, 1249120860L);
// if(data != null)
// logger.info("Anzahl: " + data.length);
// for(EpicsRecordData p : data)
// System.out.println(p);
// this.wait(1000);
// running = false;
// URL url = new URL(null, "sdds://krynfs.desy.de:4000", new SddsStreamHandler());
// System.out.println(url.getProtocol());
// startTime = TimeConverter.convertToLong("2009-01-10 12:00:00.000", "yyyy-MM-dd HH:mm:ss.SSS");
// endTime = TimeConverter.convertToLong("2009-01-10 12:10:00.000", "yyyy-MM-dd HH:mm:ss.SSS");
// EpicsRecordData[] data = sddsReader.readData("krykWeather_Temp_ai", startTime, endTime);
// System.out.println("Anzahl der Datenwerte: " + data.length);
// EpicsRecordData erd = data[0];
// System.out.println(erd.getTime());
// TimeInterval ti = new TimeInterval(startTime, endTime);
// System.out.println("Start month: " + ti.getStartMonthAsString());
// System.out.println("End month: " + ti.getEndMonthAsString());
// int[] years = ti.getYears();
// for(int i : years)
// System.out.println(i);
}
}
|
package org.csstudio.sds.components.epics;
import java.util.HashMap;
import java.util.Map;
import org.csstudio.platform.simpledal.ConnectionState;
import org.csstudio.sds.components.model.BargraphModel;
import org.csstudio.sds.components.model.RectangleModel;
import org.csstudio.sds.model.initializers.AbstractControlSystemSchema;
import org.csstudio.sds.model.initializers.AbstractWidgetModelInitializer;
import org.eclipse.swt.graphics.RGB;
/**
* Initializes a bargraph with EPICS specific property values.
*
* @author Kai Meyer
*
*/
public final class BargraphInitializer extends AbstractWidgetModelInitializer {
/**
* {@inheritDoc}
*/
@Override
protected void initialize(final AbstractControlSystemSchema schema) {
initializeDynamicProperty(BargraphModel.PROP_MIN, "$channel$.[graphMin], double");
initializeDynamicProperty(BargraphModel.PROP_MAX, "$channel$.[graphMax], double");
initializeDynamicProperty(BargraphModel.PROP_HIHI_LEVEL,
"$channel$.[alarmMax], double");
initializeDynamicProperty(BargraphModel.PROP_HI_LEVEL, "$channel$.[warningMax], double");
initializeDynamicProperty(BargraphModel.PROP_LOLO_LEVEL,
"$channel$.[alarmMin], double");
initializeDynamicProperty(BargraphModel.PROP_LO_LEVEL, "$channel$.[warningMin], double");
initializeDynamicProperty(BargraphModel.PROP_FILL, "$channel$");
Map<ConnectionState, Object> colorsByConnectionState = new HashMap<ConnectionState, Object>();
colorsByConnectionState.put(ConnectionState.CONNECTION_LOST, new RGB(255,255,255));
colorsByConnectionState.put(ConnectionState.INITIAL, new RGB(245,181,237));
initializeDynamicPropertyForConnectionState(RectangleModel.PROP_COLOR_BACKGROUND, "$channel$", colorsByConnectionState);
// initializeDynamicProperty(BargraphModel.PROP_FILL, "$channel$.VAL");
}
}
|
package org.jvnet.jaxb2_commons.plugin.simplehashcode.generator;
import java.util.Collection;
import com.sun.codemodel.JBlock;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JExpr;
import com.sun.codemodel.JExpression;
import com.sun.codemodel.JOp;
import com.sun.codemodel.JType;
import com.sun.codemodel.JVar;
public abstract class ValueBasedBlockHashCodeCodeGenerator extends
AbstractHashCodeCodeGenerator {
public ValueBasedBlockHashCodeCodeGenerator(
TypedHashCodeCodeGeneratorFactory factory, JCodeModel codeModel) {
super(factory, codeModel);
}
@Override
public void generate(JBlock block, JVar currentHashCode, JType exposedType,
Collection<JType> possibleTypes, JVar value, JExpression hasSetValue, boolean isAlwaysSet) {
final JExpression valueHashCode = valueHashCode(block, exposedType, value);
final JExpression newHashCodeValue;
if (isAlwaysSet || !isCheckForNullRequired()) {
newHashCodeValue = valueHashCode;
} else {
newHashCodeValue = JOp.cond(hasSetValue, valueHashCode,
JExpr.lit((int) 0));
}
block.assign(currentHashCode,
currentHashCode.mul(JExpr.lit(getFactory().getMultiplier()))
.plus(newHashCodeValue));
}
protected boolean isCheckForNullRequired()
{
return true;
}
protected abstract JExpression valueHashCode(JBlock block, JType type,
JVar value);
}
|
package org.opencb.commons.datastore.mongodb;
import com.mongodb.client.model.Accumulators;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Projections;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.opencb.commons.datastore.core.Query;
import org.opencb.commons.datastore.core.QueryParam;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MongoDBQueryUtils {
private static final String REGEX_SEPARATOR = "(\\w+|\\^)";
private static final Pattern OPERATION_STRING_PATTERN = Pattern.compile("(!=|!?=?~|==?)([^=<>~!]+.*)$");
private static final Pattern OPERATION_NUMERIC_PATTERN = Pattern.compile("(<=?|>=?|!=|!?=?~|==?)([^=<>~!]+.*)$");
private static final Pattern OPERATION_BOOLEAN_PATTERN = Pattern.compile("(!=|!?=?~|==?)([^=<>~!]+.*)$");
public enum LogicalOperator {
AND,
OR;
}
public enum ComparisonOperator {
EQUAL,
NOT_EQUAL,
IN,
NOT_IN,
ALL,
// String comparators
EQUAL_IGNORE_CASE,
START_WITH,
END_WITH,
REGEX,
TEXT,
// Numeric comparators
GREATER_THAN,
GREATER_THAN_EQUAL,
LESS_THAN,
LESS_THAN_EQUAL;
}
public static Bson createFilter(String mongoDbField, String queryParam, Query query) {
return createFilter(mongoDbField, queryParam, query, QueryParam.Type.TEXT, ComparisonOperator.EQUAL, LogicalOperator.OR);
}
public static Bson createFilter(String mongoDbField, String queryParam, Query query, QueryParam.Type type) {
return createFilter(mongoDbField, queryParam, query, type, ComparisonOperator.EQUAL, LogicalOperator.OR);
}
public static Bson createFilter(String mongoDbField, String queryParam, Query query, QueryParam.Type type, ComparisonOperator
comparator) {
return createFilter(mongoDbField, queryParam, query, type, comparator, LogicalOperator.OR);
}
public static Bson createFilter(String mongoDbField, String queryParam, Query query, QueryParam.Type type, ComparisonOperator
comparator, LogicalOperator operator) {
Bson filter = null;
if (query != null && query.containsKey(queryParam)) {
switch (type) {
case TEXT:
case TEXT_ARRAY:
filter = createFilter(mongoDbField, query.getAsStringList(queryParam), comparator, operator);
break;
case INTEGER:
case INTEGER_ARRAY:
filter = createFilter(mongoDbField, query.getAsIntegerList(queryParam), comparator, operator);
break;
case DECIMAL:
case DECIMAL_ARRAY:
filter = createFilter(mongoDbField, query.getAsDoubleList(queryParam), comparator, operator);
break;
case BOOLEAN:
filter = createFilter(mongoDbField, query.getBoolean(queryParam), comparator);
break;
default:
break;
}
}
return filter;
}
public static Bson createAutoFilter(String mongoDbField, String queryParam, Query query, QueryParam.Type type) throws
NumberFormatException {
return createAutoFilter(mongoDbField, queryParam, query, type, LogicalOperator.OR);
}
public static Bson createAutoFilter(String mongoDbField, String queryParam, Query query, QueryParam.Type type, LogicalOperator operator)
throws NumberFormatException {
Bson filter = null;
if (query != null && query.containsKey(queryParam)) {
List<String> queryParamList = query.getAsStringList(queryParam);
List<Bson> bsonList = new ArrayList<>(queryParamList.size());
for (String queryItem : queryParamList) {
Matcher matcher = getPattern(type).matcher(queryItem);
String op;
String queryValueString;
if (!matcher.find()) {
op = "";
queryValueString = queryItem;
} else {
op = matcher.group(1);
queryValueString = matcher.group(2);
}
ComparisonOperator comparator = getComparisonOperator(op, type);
switch (type) {
case TEXT:
case TEXT_ARRAY:
bsonList.add(createFilter(mongoDbField, queryValueString, comparator));
break;
case INTEGER:
case INTEGER_ARRAY:
bsonList.add(createFilter(mongoDbField, Integer.parseInt(queryValueString), comparator));
break;
case DECIMAL:
case DECIMAL_ARRAY:
bsonList.add(createFilter(mongoDbField, Double.parseDouble(queryValueString), comparator));
break;
case BOOLEAN:
bsonList.add(createFilter(mongoDbField, Boolean.parseBoolean(queryValueString), comparator));
break;
default:
break;
}
}
if (bsonList.size() == 1) {
filter = bsonList.get(0);
} else {
if (operator.equals(LogicalOperator.OR)) {
filter = Filters.or(bsonList);
} else {
filter = Filters.and(bsonList);
}
}
}
return filter;
}
public static <T> Bson createFilter(String mongoDbField, T queryValue) {
return createFilter(mongoDbField, queryValue, ComparisonOperator.EQUAL);
}
public static <T> Bson createFilter(String mongoDbField, T queryValue, ComparisonOperator comparator) {
Bson filter = null;
if (queryValue != null) {
if (queryValue instanceof String) {
switch (comparator) {
case EQUAL:
filter = Filters.eq(mongoDbField, queryValue);
break;
case NOT_EQUAL:
filter = Filters.ne(mongoDbField, queryValue);
break;
case EQUAL_IGNORE_CASE:
filter = Filters.regex(mongoDbField, queryValue.toString(), "i");
break;
case START_WITH:
filter = Filters.regex(mongoDbField, "^" + queryValue + "*");
break;
case END_WITH:
filter = Filters.regex(mongoDbField, "*" + queryValue + "$");
break;
case REGEX:
filter = Filters.regex(mongoDbField, queryValue.toString());
break;
case TEXT:
filter = Filters.text(String.valueOf(queryValue));
break;
default:
break;
}
} else {
switch (comparator) {
case EQUAL:
filter = Filters.eq(mongoDbField, queryValue);
break;
case NOT_EQUAL:
filter = Filters.ne(mongoDbField, queryValue);
break;
case GREATER_THAN:
filter = Filters.gt(mongoDbField, queryValue);
break;
case GREATER_THAN_EQUAL:
filter = Filters.gte(mongoDbField, queryValue);
break;
case LESS_THAN:
filter = Filters.lt(mongoDbField, queryValue);
break;
case LESS_THAN_EQUAL:
filter = Filters.lte(mongoDbField, queryValue);
break;
default:
break;
}
}
}
return filter;
}
public static <T> Bson createFilter(String mongoDbField, List<T> queryValues) {
return createFilter(mongoDbField, queryValues, ComparisonOperator.EQUAL, LogicalOperator.OR);
}
public static <T> Bson createFilter(String mongoDbField, List<T> queryValues, LogicalOperator operator) {
return createFilter(mongoDbField, queryValues, ComparisonOperator.EQUAL, operator);
}
public static <T> Bson createFilter(String mongoDbField, List<T> queryValues, ComparisonOperator comparator) {
return createFilter(mongoDbField, queryValues, comparator, LogicalOperator.OR);
}
public static <T> Bson createFilter(String mongoDbField, List<T> queryValues, ComparisonOperator comparator, LogicalOperator operator) {
Bson filter = null;
if (queryValues != null && queryValues.size() > 0) {
if (comparator.equals(ComparisonOperator.IN) || comparator.equals(ComparisonOperator.NOT_IN)
|| comparator.equals(ComparisonOperator.ALL)) {
switch (comparator) {
case IN:
filter = Filters.in(mongoDbField, queryValues);
break;
case NOT_IN:
filter = Filters.nin(mongoDbField, queryValues);
break;
case ALL:
filter = Filters.all(mongoDbField, queryValues);
break;
default:
break;
}
} else {
// If there is only on element in the array then it does not make sense to create an OR or AND filter
if (queryValues.size() == 1) {
filter = createFilter(mongoDbField, queryValues.get(0), comparator);
} else {
List<Bson> bsonList = new ArrayList<>(queryValues.size());
for (T queryItem : queryValues) {
Bson filter1 = createFilter(mongoDbField, queryItem, comparator);
if (filter1 != null) {
bsonList.add(filter1);
}
}
if (operator.equals(LogicalOperator.OR)) {
filter = Filters.or(bsonList);
} else {
filter = Filters.and(bsonList);
}
}
}
}
return filter;
}
public static List<Bson> createGroupBy(Bson query, String groupByField, String idField, boolean count) {
if (groupByField == null || groupByField.isEmpty()) {
return new ArrayList<>();
}
if (groupByField.contains(",")) {
// call to multiple createGroupBy if commas are present
return createGroupBy(query, Arrays.asList(groupByField.split(",")), idField, count);
} else {
Bson match = Aggregates.match(query);
Bson project = Aggregates.project(Projections.include(groupByField, idField));
Bson group;
if (count) {
group = Aggregates.group("$" + groupByField, Accumulators.sum("count", 1));
} else {
group = Aggregates.group("$" + groupByField, Accumulators.addToSet("features", "$" + idField));
}
return Arrays.asList(match, project, group);
}
}
public static List<Bson> createGroupBy(Bson query, List<String> groupByField, String idField, boolean count) {
if (groupByField == null || groupByField.isEmpty()) {
return new ArrayList<>();
}
if (groupByField.size() == 1) {
// if only one field then we call to simple createGroupBy
return createGroupBy(query, groupByField.get(0), idField, count);
} else {
Bson match = Aggregates.match(query);
// add all group-by fields to the projection together with the aggregation field name
List<String> groupByFields = new ArrayList<>(groupByField);
groupByFields.add(idField);
Bson project = Aggregates.project(Projections.include(groupByFields));
// _id document creation to have the multiple id
Document id = new Document();
for (String s : groupByField) {
id.append(s, "$" + s);
}
Bson group;
if (count) {
group = Aggregates.group(id, Accumulators.sum("count", 1));
} else {
group = Aggregates.group(id, Accumulators.addToSet("features", "$" + idField));
}
return Arrays.asList(match, project, group);
}
}
private static Pattern getPattern(QueryParam.Type type) {
Pattern pattern = null;
switch (type) {
case TEXT:
case TEXT_ARRAY:
pattern = OPERATION_STRING_PATTERN;
break;
case INTEGER:
case INTEGER_ARRAY:
case DECIMAL:
case DECIMAL_ARRAY:
pattern = OPERATION_NUMERIC_PATTERN;
break;
case BOOLEAN:
pattern = OPERATION_BOOLEAN_PATTERN;
break;
default:
break;
}
return pattern;
}
public static ComparisonOperator getComparisonOperator(String op, QueryParam.Type type) {
ComparisonOperator comparator = null;
if (op.isEmpty()) {
comparator = ComparisonOperator.EQUAL;
} else {
switch (type) {
case TEXT:
case TEXT_ARRAY:
switch(op) {
case "=":
case "==":
comparator = ComparisonOperator.EQUAL;
break;
case "!=":
comparator = ComparisonOperator.NOT_EQUAL;
break;
case "~":
case "=~":
comparator = ComparisonOperator.REGEX;
break;
default:
throw new IllegalStateException("Unknown string query operation " + op);
}
break;
case INTEGER:
case INTEGER_ARRAY:
case DECIMAL:
case DECIMAL_ARRAY:
switch(op) {
case "=":
case "==":
comparator = ComparisonOperator.EQUAL;
break;
case ">":
comparator = ComparisonOperator.GREATER_THAN;
break;
case ">=":
comparator = ComparisonOperator.GREATER_THAN_EQUAL;
break;
case "<":
comparator = ComparisonOperator.LESS_THAN;
break;
case "<=":
comparator = ComparisonOperator.LESS_THAN_EQUAL;
break;
case "!=":
comparator = ComparisonOperator.NOT_EQUAL;
break;
default:
throw new IllegalStateException("Unknown numerical query operation " + op);
}
break;
case BOOLEAN:
switch(op) {
case "=":
case "==":
comparator = ComparisonOperator.EQUAL;
break;
case "!=":
comparator = ComparisonOperator.NOT_EQUAL;
break;
default:
throw new IllegalStateException("Unknown boolean query operation " + op);
}
break;
default:
break;
}
}
return comparator;
}
}
|
package de.larmic.butterfaces.component.renderkit.html_basic.action;
import de.larmic.butterfaces.component.behavior.JsfAjaxRequest;
import de.larmic.butterfaces.component.html.action.HtmlCommandLink;
import de.larmic.butterfaces.resolver.AjaxClientIdResolver;
import de.larmic.butterfaces.resolver.ClientBehaviorResolver;
import de.larmic.butterfaces.resolver.WebXmlParameters;
import de.larmic.butterfaces.util.StringJoiner;
import de.larmic.butterfaces.util.StringUtils;
import javax.faces.component.*;
import javax.faces.component.behavior.AjaxBehavior;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.event.ActionEvent;
import javax.faces.render.FacesRenderer;
import java.io.IOException;
import java.util.Map;
/**
* @author Lars Michaelis
*/
@FacesRenderer(componentFamily = HtmlCommandLink.COMPONENT_FAMILY, rendererType = HtmlCommandLink.RENDERER_TYPE)
public class CommandLinkRenderer extends com.sun.faces.renderkit.html_basic.CommandLinkRenderer {
private WebXmlParameters webXmlParameters;
/**
* Will be set in renderAsActive if f:ajax child with onevent attribute exists.
*/
private String onEventCallback = null;
@Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
this.onEventCallback = null;
final HtmlCommandLink link = (HtmlCommandLink) component;
final ResponseWriter writer = context.getResponseWriter();
webXmlParameters = new WebXmlParameters(context.getExternalContext());
if (!link.isDisabled()) {
this.renderAsActive(context, component);
} else {
writer.startElement("span", component);
writeIdAttributeIfNecessary(context, writer, component);
writeCommonLinkAttributes(writer, component);
if (StringUtils.isNotEmpty(link.getStyle())) {
writer.writeAttribute("style", link.getStyle(), "style");
}
this.writeValue(component, writer);
}
}
@Override
protected boolean shouldWriteIdAttribute(UIComponent component) {
return true;
}
@Override
protected void writeCommonLinkAttributes(final ResponseWriter writer, final UIComponent component) throws IOException {
writeStyleClass(writer, component);
}
@Override
public void decode(FacesContext context, UIComponent component) {
final HtmlCommandLink link = (HtmlCommandLink) component;
if (link.isDisabled()) {
return;
}
final ExternalContext external = context.getExternalContext();
final Map<String, String> params = external.getRequestParameterMap();
final String resetValues = params.get("javax.faces.partial.resetValues");
final String render = params.get("javax.faces.partial.render");
if (StringUtils.isNotEmpty(resetValues) && StringUtils.isNotEmpty(render) && Boolean.valueOf(resetValues)) {
final String[] split = render.split(" ");
for (String clientId : split) {
final UIComponent renderComponent = context.getViewRoot().findComponent(clientId);
resetValues(renderComponent);
}
}
String clientId = decodeBehaviors(context, component);
if (clientId == null) {
clientId = component.getClientId(context);
}
if (params.containsKey(clientId) || isPartialOrBehaviorAction(clientId, params)) {
component.queueEvent(new ActionEvent(component));
}
}
private boolean isPartialOrBehaviorAction(String clientId, Map<String, String> requestParameter) {
if (clientId == null || clientId.length() == 0) {
return false;
}
if (!clientId.equals(requestParameter.get("javax.faces.source"))) {
return false;
}
// check for a behavior action event
final String behaviorEvent = requestParameter.get("javax.faces.behavior.event");
if (behaviorEvent != null) {
return "action".equals(behaviorEvent);
}
// Not a Behavior-related request. Check for jsf.ajax.request() request params
return ("click".equals(requestParameter.get("javax.faces.partial.event")));
}
private void resetValues(final UIComponent component) {
if (component == null) {
return;
}
for (UIComponent child : component.getChildren()) {
resetValues(child);
}
if (component instanceof UIOutput) {
((UIOutput) component).resetValue();
} else if (component instanceof EditableValueHolder) {
((EditableValueHolder) component).resetValue();
}
}
@Override
public void encodeEnd(final FacesContext context, final UIComponent component) throws IOException {
final HtmlCommandLink link = (HtmlCommandLink) component;
final ResponseWriter writer = context.getResponseWriter();
if (!link.isDisabled()) {
if (link.isAjaxDisableLinkOnRequest()) {
writer.startElement("script", component);
writer.writeText("function " + getOnEventListenerName(component) + "(data) {", null);
if (StringUtils.isNotEmpty(onEventCallback)) {
writer.writeText(" " + onEventCallback + "(data);", null);
}
final String processingText = createAjaxProcessingText(link);
final String processingGlyphicon = createAjaxProcessingGlypicon(link);
final AjaxClientIdResolver ajaxClientIdResolver = new AjaxClientIdResolver(link);
final String jQueryIDSelector = isAjaxDisableRenderReqionOnRequest(link, webXmlParameters)
? ajaxClientIdResolver.getjQueryRenderIDSelector() : "undefined";
writer.writeText(
createDisableOnClickFunctionCall(link, processingText, processingGlyphicon, jQueryIDSelector),
null
);
writer.writeText("}", null);
writer.endElement("script");
}
writer.endElement("a");
} else {
writer.endElement("span");
}
}
private Boolean isAjaxDisableRenderReqionOnRequest(final HtmlCommandLink link, final WebXmlParameters parameters) {
final Boolean disableRegion = link.isAjaxDisableRenderRegionsOnRequest();
return disableRegion != null ? disableRegion : parameters.isAjaxDisableRenderRegionsOnRequest();
}
private String createDisableOnClickFunctionCall(HtmlCommandLink link, String processingText,
String processingGlyphicon, String jQueryIDSelector) {
final StringBuilder sb = new StringBuilder();
sb.append(" butter.link.disableOnClick(data, ");
sb.append(link.isAjaxShowWaitingDotsOnRequest()).append(",");
if (link.getValue() != null) {
sb.append("'").append(link.getValue()).append("'");
} else {
sb.append("null");
}
sb.append(",'");
sb.append(processingText).append("','");
sb.append(link.getGlyphicon()).append("','");
sb.append(processingGlyphicon).append("',");
sb.append(link.isAjaxHideGlyphiconOnRequest()).append(",'");
sb.append(jQueryIDSelector).append("');");
return sb.toString();
}
private String createAjaxProcessingText(final HtmlCommandLink link) {
if (StringUtils.isNotEmpty(link.getAjaxProcessingTextOnRequest())) {
return link.getAjaxProcessingTextOnRequest();
}
return webXmlParameters.getAjaxProcessingTextOnRequest();
}
private String createAjaxProcessingGlypicon(final HtmlCommandLink link) {
if (StringUtils.isNotEmpty(link.getAjaxProcessingGlyphiconOnRequest())) {
return link.getAjaxProcessingGlyphiconOnRequest();
}
return webXmlParameters.getAjaxProcessingGlyphiconOnRequest();
}
@Override
protected void writeValue(final UIComponent component, final ResponseWriter writer) throws IOException {
final HtmlCommandLink commandLink = (HtmlCommandLink) component;
this.writeGlyphiconIfNecessary(commandLink, writer);
writer.startElement("span", component);
writer.writeAttribute("class", "butter-component-glyphicon-text", null);
final Object value = ((UICommand) component).getValue();
if (value != null) {
final String label = value.toString();
if (StringUtils.isNotEmpty(label)) {
writer.writeText(label, component, null);
}
}
writer.endElement("span");
this.writeWaitingDotsIfNecessary(commandLink, writer);
}
@Override
protected void renderAsActive(final FacesContext context,
final UIComponent component) throws IOException {
final HtmlCommandLink link = (HtmlCommandLink) component;
final ResponseWriter writer = context.getResponseWriter();
// TODO should this be working for multiple behaviors?
final AjaxBehavior ajaxBehavior = ClientBehaviorResolver.findFirstActiveAjaxBehavior(link, "action");
if (link.isAjaxDisableLinkOnRequest() && ajaxBehavior != null) {
if (StringUtils.isNotEmpty(ajaxBehavior.getOnevent())) {
onEventCallback = ajaxBehavior.getOnevent();
}
ajaxBehavior.setOnevent(getOnEventListenerName(component));
ajaxBehavior.setOnerror(getOnEventListenerName(component));
}
if (ajaxBehavior != null) {
final JsfAjaxRequest jsfAjaxRequest = new JsfAjaxRequest(link, ajaxBehavior, "action");
// TODO add delay support to ajax request
writer.startElement("a", link);
writeIdAttributeIfNecessary(context, writer, link);
writer.writeAttribute("href", "#", "href");
// TODO check passThruAttributes
//RenderKitUtils.renderPassThruAttributes(context, writer, command, ATTRIBUTES, getNonOnClickBehaviors(command));
this.renderBooleanValue(component, writer, "disabled");
this.renderBooleanValue(component, writer, "ismap");
this.renderStringValue(component, writer, "title");
this.renderStringValue(component, writer, "tabindex");
this.renderStringValue(component, writer, "style");
this.renderStringValue(component, writer, "target");
// html link attributes
this.renderStringValue(component, writer, "accesskey");
this.renderStringValue(component, writer, "charset");
// TODO check missing component attributes
// binding
// immediate
// actionListener
this.renderEventValue(component, writer, "onkeydown", "keydown");
this.renderEventValue(component, writer, "onkeyup", "keyup");
this.renderEventValue(component, writer, "onblur", "blur");
this.renderOnClickEventValue(component, writer, jsfAjaxRequest);
this.renderEventValue(component, writer, "ondblclick", "dblclick");
this.renderEventValue(component, writer, "onfocus", "focus");
this.renderEventValue(component, writer, "onkeypress", "keypress");
this.renderEventValue(component, writer, "onmousedown", "mousedown");
this.renderEventValue(component, writer, "onmousemove", "mousemove");
this.renderEventValue(component, writer, "onmouseout", "mouseout");
this.renderEventValue(component, writer, "onmouseover", "mouseover");
this.renderEventValue(component, writer, "onmouseup", "mouseup");
writeStyleClass(writer, link);
// render the current value as link text.
writeValue(link, writer);
} else {
// TODO replace it with custom implementation (replace mojarra.ab(...) by default jsf js api)
super.renderAsActive(context, component);
}
// reset ajax behaviour because otherwise a render of this component will not be work correctly (wrong js
// callback is registered if onevent is set on f:ajax.
if (ajaxBehavior != null) {
ajaxBehavior.setOnevent(onEventCallback);
}
}
private void renderOnClickEventValue(UIComponent component, ResponseWriter writer, JsfAjaxRequest jsfAjaxRequest) throws IOException {
final String componentEventFunction = createComponentEventFunction(component, "onclick");
if (componentEventFunction != null) {
writer.writeAttribute("onclick", jsfAjaxRequest.toString() + ";" + componentEventFunction, "onclick");
} else {
writer.writeAttribute("onclick", jsfAjaxRequest.toString(), "onclick");
}
}
private void writeStyleClass(final ResponseWriter writer, final UIComponent component) throws IOException {
final HtmlCommandLink link = (HtmlCommandLink) component;
final String styleClass = (String) component.getAttributes().get("styleClass");
StringJoiner generatedStyleClassJoiner = StringJoiner.on(' ').join(StringUtils.getNotNullValue(styleClass, ""));
if (link.isDisabled()) {
generatedStyleClassJoiner = generatedStyleClassJoiner.join("btn-disabled");
}
if (StringUtils.isEmpty(link.getGlyphicon())) {
generatedStyleClassJoiner = generatedStyleClassJoiner.join("no-glyphicon");
}
final String generatedStyleClass = generatedStyleClassJoiner.toString();
if (generatedStyleClass.length() > 0) {
writer.writeAttribute("class", generatedStyleClass, "styleClass");
}
}
private String getOnEventListenerName(final UIComponent component) {
final char separatorChar = UINamingContainer.getSeparatorChar(FacesContext.getCurrentInstance());
return "glyphiconLinkListener" + "_" + component.getClientId().replace(separatorChar + "", "_");
}
protected void writeWaitingDotsIfNecessary(final HtmlCommandLink commandLink,
final ResponseWriter writer) throws IOException {
if (commandLink.isAjaxDisableLinkOnRequest()) {
writer.startElement("span", commandLink);
writer.writeAttribute("class", "butter-component-glyphicon-processing", null);
writer.endElement("span");
}
}
protected void writeGlyphiconIfNecessary(final HtmlCommandLink commandLink,
final ResponseWriter writer) throws IOException {
final String glyphicon = StringUtils.getNotNullValue(commandLink.getGlyphicon(), "");
writer.startElement("span", commandLink);
writer.writeAttribute("class", "butter-component-glyphicon " + glyphicon, null);
writer.endElement("span");
}
/**
* Render boolean value if attribute is set to true.
*
* @param attributeName attribute name
* @param component the component
* @param writer html response writer
* @throws IOException thrown by writer
* @deprecated When moving this class to components {@link de.larmic.butterfaces.component.base.renderer.HtmlBasicRenderer} will prepare this method.
* TODO remove when moving class to components package (see deprecated)
*/
@Deprecated
protected void renderBooleanValue(final UIComponent component,
final ResponseWriter writer,
final String attributeName) throws IOException {
if (component.getAttributes().get(attributeName) != null
&& Boolean.valueOf(component.getAttributes().get(attributeName).toString())) {
writer.writeAttribute(attributeName, true, attributeName);
}
}
/**
* Render string value if attribute is not empty.
*
* @param attributeName attribute name
* @param component the component
* @param writer html response writer
* @throws IOException thrown by writer
* @deprecated When moving this class to components {@link de.larmic.butterfaces.component.base.renderer.HtmlBasicRenderer} will prepare this method.
* TODO remove when moving class to components package (see deprecated)
*/
@Deprecated
protected void renderStringValue(final UIComponent component,
final ResponseWriter writer,
final String attributeName) throws IOException {
if (component.getAttributes().get(attributeName) != null
&& StringUtils.isNotEmpty(component.getAttributes().get(attributeName).toString())
&& shouldRenderAttribute(component.getAttributes().get(attributeName))) {
writer.writeAttribute(attributeName, component.getAttributes().get(attributeName).toString().trim(), attributeName);
}
}
/**
* @deprecated When moving this class to components {@link de.larmic.butterfaces.component.base.renderer.HtmlBasicRenderer} will prepare this method.
* TODO remove when moving class to components package (see deprecated)
*/
@Deprecated
protected boolean shouldRenderAttribute(Object value) {
if (value == null)
return false;
if (value instanceof Boolean) {
return (Boolean) value;
} else if (value instanceof Number) {
final Number number = (Number) value;
if (value instanceof Integer)
return number.intValue() != Integer.MIN_VALUE;
else if (value instanceof Double)
return number.doubleValue() != Double.MIN_VALUE;
else if (value instanceof Long)
return number.longValue() != Long.MIN_VALUE;
else if (value instanceof Byte)
return number.byteValue() != Byte.MIN_VALUE;
else if (value instanceof Float)
return number.floatValue() != Float.MIN_VALUE;
else if (value instanceof Short)
return number.shortValue() != Short.MIN_VALUE;
}
return true;
}
/**
* @deprecated When moving this class to components {@link de.larmic.butterfaces.component.base.renderer.HtmlBasicRenderer} will prepare this method.
* TODO remove when moving class to components package (see deprecated)
*/
@Deprecated
protected void renderEventValue(final UIComponent component,
final ResponseWriter writer,
final String attributeName,
final String eventName) throws IOException {
final String componentEventFunction = createComponentEventFunction(component, attributeName);
final String ajaxEventFunction = createAjaxEventFunction((UIComponentBase) component, eventName);
if (componentEventFunction != null && ajaxEventFunction != null) {
writer.writeAttribute(attributeName, ajaxEventFunction + ";" + componentEventFunction, null);
} else if (componentEventFunction != null) {
writer.writeAttribute(attributeName, componentEventFunction, null);
} else if (ajaxEventFunction != null) {
writer.writeAttribute(attributeName, ajaxEventFunction, null);
}
}
/**
* @deprecated When moving this class to components {@link de.larmic.butterfaces.component.base.renderer.HtmlBasicRenderer} will prepare this method.
* TODO remove when moving class to components package (see deprecated)
*/
@Deprecated
private String createComponentEventFunction(UIComponent component, String attributeName) {
return component.getAttributes().get(attributeName) instanceof String ? (String) component.getAttributes().get(attributeName) : null;
}
/**
* @deprecated When moving this class to components {@link de.larmic.butterfaces.component.base.renderer.HtmlBasicRenderer} will prepare this method.
* TODO remove when moving class to components package (see deprecated)
*/
@Deprecated
private String createAjaxEventFunction(UIComponentBase component, String eventName) {
final AjaxBehavior ajaxBehavior = ClientBehaviorResolver.resolveActiveAjaxBehavior(component, eventName);
return ajaxBehavior != null ? new JsfAjaxRequest(component, ajaxBehavior, eventName).toString() : null;
}
}
|
public class Amount{
private int cents;
//@ invariant cents < 100 && cents > -100;
private int dollars;
//@ invariant dollars > 0 ==> cents >= 0;
//@ invariant dollars < 0 ==> cents <= 0;
//@ requires cents < 100 && cents > -100;
//@ requires dollars > 0 ==> cents >= 0;
//@ requires dollars < 0 ==> cents <= 0;
public Amount(int dollars, int cents){
this.dollars = dollars;
this.cents = cents;
}
//@ ensures \result != null;
public Amount negate(){
return new Amount(-this.dollars, -this.cents);
}
//@ requires a != null;
public Amount subtract(Amount a){
return this.add(a.negate());
}
//@ requires a != null;
public Amount add(Amount a){
int new_dollars = dollars + a.dollars;
int new_cents = cents + a.cents;
if (new_cents < -100) {
new_cents = new_cents + 100;
new_dollars = new_dollars - 1;
return new Amount(new_dollars,new_cents);
}
else if (new_cents > 100) {
new_cents = new_cents - 100;
new_dollars = new_dollars - 1;
return new Amount(new_dollars,new_cents);
}
else if (new_cents < 0 && new_dollars > 0) {
new_cents = new_cents + 100;
new_dollars = new_dollars - 1;
return new Amount(new_dollars,new_cents);
}
else if (new_cents > 0 && new_dollars < 0) {
new_cents = new_cents - 100;
new_dollars = new_dollars + 1;
return new Amount(new_dollars,new_cents);
}
}
public boolean equal(Amount a) {
if (a==null) return false;
else return (dollars == a.dollars && cents == a.cents);
}
}
|
package org.csstudio.utility.pvmanager.ui.toolbox;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IMenuCreator;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.jface.viewers.CellLabelProvider;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.IBaseLabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.jface.layout.TableColumnLayout;
import org.epics.pvmanager.ChannelHandler;
import org.epics.pvmanager.CompositeDataSource;
import org.epics.pvmanager.DataSource;
import org.epics.pvmanager.PVManager;
import org.epics.pvmanager.data.SimpleValueFormat;
import org.epics.pvmanager.data.ValueFormat;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.jface.action.Action;
import org.eclipse.wb.swt.ResourceManager;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormAttachment;
public class ToolboxView extends ViewPart {
public static final String ID = "org.csstudio.utility.pvmanager.ui.debug.ChannelListView"; //$NON-NLS-1$
private Table table;
private Action selectDataSourceAction;
private TableViewer tableViewer;
private Action refreshAction;
private Table summaryTable;
private TableViewer summaryTableViewer;
public ToolboxView() {
}
/**
* Create contents of the view part.
* @param parent
*/
@Override
public void createPartControl(Composite parent) {
parent.setLayout(new FormLayout());
Composite container = new Composite(parent, SWT.NONE);
FormData fd_container = new FormData();
fd_container.bottom = new FormAttachment(100, -10);
fd_container.left = new FormAttachment(0, 10);
container.setLayoutData(fd_container);
//container.setLayout(new FillLayout(SWT.HORIZONTAL));
tableViewer = new TableViewer(container, SWT.BORDER | SWT.FULL_SELECTION);
table = tableViewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
tableViewer.setContentProvider(new DataSourceContentProvider());
// Connected column
TableViewerColumn connectedViewerColumn = new TableViewerColumn(
tableViewer, SWT.NONE);
connectedViewerColumn.setLabelProvider(new CellLabelProvider() {
Image connected = ResourceManager.getPluginImageDescriptor("org.csstudio.utility.pvmanager.ui.toolbox", "icons/connected.png").createImage();
Image disconnected = ResourceManager.getPluginImageDescriptor("org.csstudio.utility.pvmanager.ui.toolbox", "icons/disconnected.png").createImage();
@Override
public void update(ViewerCell cell) {
if (((DataSourceChannel) cell.getElement()).isConnected()) {
cell.setImage(connected);
} else {
cell.setImage(disconnected);
}
}
@Override
public void dispose() {
connected.dispose();
super.dispose();
}
});
TableColumn connectedColumn = connectedViewerColumn.getColumn();
connectedColumn.setText("C");
connectedColumn.setToolTipText("Connected or disconnected");
// PV Name column
TableViewerColumn pvNameViewerColumn = new TableViewerColumn(
tableViewer, SWT.NONE);
pvNameViewerColumn.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
cell.setText(((DataSourceChannel) cell.getElement()).getFullChannelName());
}
});
TableColumn pvNameColumn = pvNameViewerColumn.getColumn();
pvNameColumn.setText("Channel name");
// Total usage count column
TableViewerColumn totalUsageViewerColumn = new TableViewerColumn(
tableViewer, SWT.NONE);
totalUsageViewerColumn.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
cell.setText(Integer.toString(((DataSourceChannel) cell.getElement()).getTotalUsageCounter()));
}
});
TableColumn totalUsageColumn = totalUsageViewerColumn.getColumn();
totalUsageColumn.setText("T");
totalUsageColumn.setToolTipText("Readers + Writers");
// Read usage count column
TableViewerColumn readUsageViewerColumn = new TableViewerColumn(
tableViewer, SWT.NONE);
readUsageViewerColumn.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
cell.setText(Integer.toString(((DataSourceChannel) cell.getElement()).getReadUsageCounter()));
}
});
TableColumn readUsageColumn = readUsageViewerColumn.getColumn();
readUsageColumn.setText("R");
readUsageColumn.setToolTipText("Readers");
// Write usage count column
TableViewerColumn writeUsageViewerColumn = new TableViewerColumn(
tableViewer, SWT.NONE);
writeUsageViewerColumn.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
cell.setText(Integer.toString(((DataSourceChannel) cell.getElement()).getWriteUsageCounter()));
}
});
TableColumn writeUsageColumn = writeUsageViewerColumn.getColumn();
writeUsageColumn.setText("W");
writeUsageColumn.setToolTipText("Writers");
// Layout
TableColumnLayout layout = new TableColumnLayout();
container.setLayout(layout);
layout.setColumnData(connectedViewerColumn.getColumn(), new ColumnWeightData(0, 24));
layout.setColumnData(pvNameViewerColumn.getColumn(), new ColumnWeightData(10, 200));
layout.setColumnData(totalUsageViewerColumn.getColumn(), new ColumnWeightData(0, 30));
layout.setColumnData(readUsageViewerColumn.getColumn(), new ColumnWeightData(0, 30));
layout.setColumnData(writeUsageViewerColumn.getColumn(), new ColumnWeightData(0, 30));
Composite summaryContainer = new Composite(parent, SWT.NONE);
fd_container.right = new FormAttachment(summaryContainer, 0, SWT.RIGHT);
fd_container.top = new FormAttachment(summaryContainer, 6);
FormData fd_summaryContainer = new FormData();
fd_summaryContainer.bottom = new FormAttachment(0, 153);
fd_summaryContainer.right = new FormAttachment(100, -10);
fd_summaryContainer.left = new FormAttachment(0, 10);
fd_summaryContainer.top = new FormAttachment(0, 10);
summaryContainer.setLayoutData(fd_summaryContainer);
summaryTableViewer = new TableViewer(summaryContainer, SWT.BORDER | SWT.FULL_SELECTION);
summaryTable = summaryTableViewer.getTable();
summaryTable.setHeaderVisible(true);
summaryTable.setLinesVisible(true);
summaryTableViewer.setContentProvider(new DataSourceSummaryContentProvider());
// DataSource Name column
TableViewerColumn dataSourceNameViewerColumn = new TableViewerColumn(
summaryTableViewer, SWT.NONE);
dataSourceNameViewerColumn.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
DataSource source = (DataSource) cell.getElement();
CompositeDataSource composite = (CompositeDataSource) PVManager.getDefaultDataSource();
String name = "";
for (Map.Entry<String, DataSource> entry : composite.getDataSources().entrySet()) {
if (entry.getValue() == source)
name = entry.getKey();
}
cell.setText(name);
}
});
TableColumn dataSourceNameColumn = dataSourceNameViewerColumn.getColumn();
dataSourceNameColumn.setText("Data Source");
// Total usage count column
TableViewerColumn totalChannelsViewerColumn = new TableViewerColumn(
summaryTableViewer, SWT.NONE);
totalChannelsViewerColumn.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
DataSource source = (DataSource) cell.getElement();
cell.setText(Integer.toString(source.getChannels().size()));
}
});
TableColumn totalChannelsUsageColumn = totalChannelsViewerColumn.getColumn();
totalChannelsUsageColumn.setText("TC");
totalChannelsUsageColumn.setToolTipText("Connected + Disconnected channels");
// Open channels column
TableViewerColumn connectedChannelsViewerColumn = new TableViewerColumn(
summaryTableViewer, SWT.NONE);
connectedChannelsViewerColumn.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
DataSource source = (DataSource) cell.getElement();
int count = 0;
for (ChannelHandler<?> channel : source.getChannels().values()) {
if (channel.isConnected())
count++;
}
cell.setText(Integer.toString(count));
}
});
TableColumn connectedChannelsUsageColumn = connectedChannelsViewerColumn.getColumn();
connectedChannelsUsageColumn.setText("CC");
connectedChannelsUsageColumn.setToolTipText("Connected channels");
// Total usage column
TableViewerColumn totalViewerColumn = new TableViewerColumn(
summaryTableViewer, SWT.NONE);
totalViewerColumn.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
DataSource source = (DataSource) cell.getElement();
int count = 0;
for (ChannelHandler<?> channel : source.getChannels().values()) {
count += channel.getUsageCounter();
}
cell.setText(Integer.toString(count));
}
});
TableColumn totalColumn = totalViewerColumn.getColumn();
totalColumn.setText("T");
totalColumn.setToolTipText("Readers + Writers");
// Readers column
TableViewerColumn readersViewerColumn = new TableViewerColumn(
summaryTableViewer, SWT.NONE);
readersViewerColumn.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
DataSource source = (DataSource) cell.getElement();
int count = 0;
for (ChannelHandler<?> channel : source.getChannels().values()) {
count += channel.getReadUsageCounter();
}
cell.setText(Integer.toString(count));
}
});
TableColumn readersColumn = readersViewerColumn.getColumn();
readersColumn.setText("R");
readersColumn.setToolTipText("Readers");
// Writers column
TableViewerColumn writersViewerColumn = new TableViewerColumn(
summaryTableViewer, SWT.NONE);
writersViewerColumn.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
DataSource source = (DataSource) cell.getElement();
int count = 0;
for (ChannelHandler<?> channel : source.getChannels().values()) {
count += channel.getWriteUsageCounter();
}
cell.setText(Integer.toString(count));
}
});
TableColumn writersColumn = writersViewerColumn.getColumn();
writersColumn.setText("W");
writersColumn.setToolTipText("Writers");
TableColumnLayout summaryLayout = new TableColumnLayout();
summaryContainer.setLayout(summaryLayout);
summaryLayout.setColumnData(dataSourceNameViewerColumn.getColumn(), new ColumnWeightData(10, 120));
summaryLayout.setColumnData(totalChannelsViewerColumn.getColumn(), new ColumnWeightData(0, 60));
summaryLayout.setColumnData(connectedChannelsViewerColumn.getColumn(), new ColumnWeightData(0, 60));
summaryLayout.setColumnData(totalViewerColumn.getColumn(), new ColumnWeightData(0, 60));
summaryLayout.setColumnData(readersViewerColumn.getColumn(), new ColumnWeightData(0, 60));
summaryLayout.setColumnData(writersViewerColumn.getColumn(), new ColumnWeightData(0, 60));
tableViewer.setInput(DataSourceContentProvider.ALL);
summaryTableViewer.setInput(DataSourceContentProvider.ALL);
createActions();
initializeToolBar();
initializeMenu();
}
private MenuItem createDataSourceMenuItem(Menu parent, final Object input) {
MenuItem item = new MenuItem(parent, SWT.RADIO);
item.setText(input.toString());
item.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
tableViewer.setInput(input);
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
// TODO Auto-generated method stub
}
});
return item;
}
/**
* Create the actions.
*/
private void createActions() {
// Create the actions
{
// Drop down menu to select data source
// First selection for All and then each datasource in alphabetical order
final Menu datasourceSelectionMenu = new Menu(table);
MenuItem allItem = createDataSourceMenuItem(datasourceSelectionMenu, DataSourceContentProvider.ALL);
allItem.setSelection(true);
List<String> dataSourceNames = new ArrayList<String>(((CompositeDataSource) PVManager.getDefaultDataSource()).getDataSources().keySet());
Collections.sort(dataSourceNames);
for (String dataSourceName : dataSourceNames) {
MenuItem dataSourceItem = createDataSourceMenuItem(datasourceSelectionMenu, dataSourceName);
}
selectDataSourceAction = new Action("Select Data Source", SWT.DROP_DOWN) {
@Override
public void runWithEvent(Event event) {
//Point point = event.
ToolItem toolItem = (ToolItem) event.widget;
Point point = toolItem.getParent().toDisplay(new Point(toolItem.getBounds().x, toolItem.getBounds().y + toolItem.getBounds().height));
datasourceSelectionMenu.setLocation(point.x, point.y); // waiting
datasourceSelectionMenu.setVisible(true);
}
};
selectDataSourceAction.setImageDescriptor(ResourceManager.getPluginImageDescriptor("org.csstudio.utility.pvmanager.ui.toolbox", "icons/source.png"));
selectDataSourceAction.setToolTipText("Select Data Source");
selectDataSourceAction.setMenuCreator(new IMenuCreator() {
@Override
public Menu getMenu(Menu parent) {
return datasourceSelectionMenu;
}
@Override
public Menu getMenu(Control parent) {
// TODO Auto-generated method stub
return datasourceSelectionMenu;
}
@Override
public void dispose() {
datasourceSelectionMenu.dispose();
}
});
}
{
refreshAction = new Action("Refresh data") {
@Override
public void run() {
tableViewer.refresh();
summaryTableViewer.refresh();
}
};
refreshAction.setToolTipText("Refresh data");
refreshAction.setImageDescriptor(ResourceManager.getPluginImageDescriptor("org.csstudio.utility.pvmanager.ui.toolbox", "icons/refresh.png"));
}
}
/**
* Initialize the toolbar.
*/
private void initializeToolBar() {
IToolBarManager toolbarManager = getViewSite().getActionBars()
.getToolBarManager();
toolbarManager.add(refreshAction);
toolbarManager.add(selectDataSourceAction);
}
/**
* Initialize the menu.
*/
private void initializeMenu() {
IMenuManager menuManager = getViewSite().getActionBars()
.getMenuManager();
}
@Override
public void setFocus() {
// Set the focus
}
}
|
package net.safedata.springboot.training.d01.s05.service;
import net.safedata.springboot.training.d01.s05.config.Profiles;
import net.safedata.springboot.training.d01.s05.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import javax.annotation.PostConstruct;
import java.util.Arrays;
/**
* A simple {@link ProductService}, which uses the {@link ProductRepository} as a manually wired collaborator
*
* @author bogdan.solga
*/
public class ProductService {
@Autowired
private Environment environment;
private final ProductRepository productRepository;
public ProductService(final ProductRepository productRepository) {
this.productRepository = productRepository;
}
@PostConstruct
public void displayProfiles() {
System.out.println("Running with the '" + Arrays.asList(environment.getActiveProfiles()) + "' profiles...");
System.out.println("Default profiles: '" + Arrays.asList(environment.getDefaultProfiles()) + "'");
}
public void displayProducts() {
if (environment.acceptsProfiles(Profiles.PROD)) {
System.out.println("Do something only when prod is enabled...");
}
productRepository.displayProducts();
}
}
|
package org.hisp.dhis.analytics.table;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hisp.dhis.analytics.AnalyticsIndex;
import org.hisp.dhis.analytics.AnalyticsTable;
import org.hisp.dhis.analytics.AnalyticsTableColumn;
import org.hisp.dhis.analytics.AnalyticsTableManager;
import org.hisp.dhis.analytics.partition.PartitionManager;
import org.hisp.dhis.calendar.Calendar;
import org.hisp.dhis.common.CodeGenerator;
import org.hisp.dhis.common.IdentifiableObjectManager;
import org.hisp.dhis.commons.collection.ListUtils;
import org.hisp.dhis.commons.collection.UniqueArrayList;
import org.hisp.dhis.commons.timer.SystemTimer;
import org.hisp.dhis.commons.timer.Timer;
import org.hisp.dhis.dataapproval.DataApprovalLevelService;
import org.hisp.dhis.dataelement.DataElementCategoryService;
import org.hisp.dhis.jdbc.StatementBuilder;
import org.hisp.dhis.organisationunit.OrganisationUnitService;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.period.PeriodType;
import org.hisp.dhis.resourcetable.ResourceTableService;
import org.hisp.dhis.setting.SettingKey;
import org.hisp.dhis.setting.SystemSettingManager;
import org.hisp.dhis.system.database.DatabaseInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
/**
* @author Lars Helge Overland
*/
public abstract class AbstractJdbcTableManager
implements AnalyticsTableManager
{
protected static final Log log = LogFactory.getLog( JdbcAnalyticsTableManager.class );
protected static final String DATE_REGEXP = "^\\d{4}-\\d{2}-\\d{2}(\\s|T)?(\\d{2}:\\d{2}:\\d{2})?$";
public static final String PREFIX_ORGUNITGROUPSET = "ougs_";
public static final String PREFIX_ORGUNITLEVEL = "uidlevel";
public static final String PREFIX_INDEX = "in_";
@Autowired
protected IdentifiableObjectManager idObjectManager;
@Autowired
protected OrganisationUnitService organisationUnitService;
@Autowired
protected DataElementCategoryService categoryService;
@Autowired
protected SystemSettingManager systemSettingManager;
@Autowired
protected DataApprovalLevelService dataApprovalLevelService;
@Autowired
protected ResourceTableService resourceTableService;
@Autowired
protected PartitionManager partitionManager;
@Autowired
protected StatementBuilder statementBuilder;
@Autowired
protected DatabaseInfo databaseInfo;
@Autowired
protected JdbcTemplate jdbcTemplate;
// Abstract methods
/**
* Returns a list of analytics table columns. Column names are quoted.
*/
protected abstract List<AnalyticsTableColumn> getDimensionColumns( AnalyticsTable table );
// Implementation
/**
* Override in order to perform work before tables are being generated.
*/
@Override
public void preCreateTables()
{
}
@Override
@Transactional
public List<AnalyticsTable> getTables( Date earliest )
{
log.info( "Get tables using earliest: " + earliest );
return getTables( getDataYears( earliest ) );
}
private List<AnalyticsTable> getTables( List<Integer> dataYears )
{
List<AnalyticsTable> tables = new UniqueArrayList<>();
Calendar calendar = PeriodType.getCalendar();
Collections.sort( dataYears );
String baseName = getAnalyticsTableType().getTableName();
for ( Integer year : dataYears )
{
Period period = PartitionUtils.getPeriod( calendar, year );
AnalyticsTable table = new AnalyticsTable( baseName, getDimensionColumns( null ), period );
tables.add( table );
}
return tables;
}
@Override
@Async
public Future<?> createIndexesAsync( ConcurrentLinkedQueue<AnalyticsIndex> indexes )
{
taskLoop : while ( true )
{
AnalyticsIndex inx = indexes.poll();
if ( inx == null )
{
break taskLoop;
}
final String indexName = getIndexName( inx );
final String indexType = inx.hasType() ? " using " + inx.getType() : "";
final String sql = "create index " + indexName + " on " + inx.getTable() + indexType + " (" + inx.getColumn() + ")";
log.debug( "Create index: " + indexName + " SQL: " + sql );
jdbcTemplate.execute( sql );
log.debug( "Created index: " + indexName );
}
return null;
}
@Override
public void swapTable( AnalyticsTable table )
{
final String tempTable = table.getTempTableName();
final String realTable = table.getTableName();
final String sqlDrop = "drop table " + realTable;
executeSilently( sqlDrop );
final String sqlAlter = "alter table " + tempTable + " rename to " + realTable;
executeSilently( sqlAlter );
}
@Override
public void dropTable( String tableName )
{
executeSilently( "drop table " + tableName );
}
@Override
public void analyzeTable( String tableName )
{
executeSilently( "analyze " + tableName );
}
@Override
@Async
public Future<?> populateTablesAsync( ConcurrentLinkedQueue<AnalyticsTable> tables )
{
taskLoop: while ( true )
{
AnalyticsTable table = tables.poll();
if ( table == null )
{
break taskLoop;
}
populateTable( table );
}
return null;
}
/**
* Populates the given analytics table.
*
* @param table the analytics table to populate.
*/
protected abstract void populateTable( AnalyticsTable table );
@Override
public void analyzeTables( List<AnalyticsTable> tables )
{
tables.forEach( table -> analyzeTable( table.getTempTableName() ) );
}
// Supportive methods
/**
* Returns the analytics table name.
*/
protected String getTableName()
{
return getAnalyticsTableType().getTableName();
}
/**
* Quotes the given column name.
*/
protected String quote( String column )
{
return statementBuilder.columnQuote( column );
}
/**
* Remove quotes from the given column name.
*/
private String removeQuote( String column )
{
return column != null ? column.replaceAll( statementBuilder.getColumnQuote(), StringUtils.EMPTY ) : null;
}
/**
* Shortens the given table name.
*/
private String shortenTableName( String table )
{
table = table.replaceAll( getAnalyticsTableType().getTableName(), "ax" );
table = table.replaceAll( TABLE_TEMP_SUFFIX, StringUtils.EMPTY );
return table;
}
/**
* Returns index name for column. Purpose of code suffix is to avoid uniqueness
* collision between indexes for temporary and real tables.
*/
protected String getIndexName( AnalyticsIndex inx )
{
return quote( PREFIX_INDEX + removeQuote( inx.getColumn() ) + "_" + shortenTableName( inx.getTable() ) + "_" + CodeGenerator.generateCode( 5 ) );
}
/**
* Indicates whether the given table exists and has at least one row.
*/
protected boolean hasRows( String tableName )
{
final String sql = "select * from " + tableName + " limit 1";
try
{
return jdbcTemplate.queryForRowSet( sql ).next();
}
catch ( BadSqlGrammarException ex )
{
return false;
}
}
/**
* Executes a SQL statement. Ignores existing tables/indexes when attempting
* to create new.
*/
protected void executeSilently( String sql )
{
try
{
jdbcTemplate.execute( sql );
}
catch ( BadSqlGrammarException ex )
{
log.debug( ex.getMessage() );
}
}
protected void validateDimensionColumns( List<AnalyticsTableColumn> columns )
{
if ( columns == null || columns.isEmpty() )
{
throw new IllegalStateException( "Analytics table dimensions are empty" );
}
List<String> columnNames = columns.stream().map( d -> d.getName() ).collect( Collectors.toList() );
Set<String> duplicates = ListUtils.getDuplicates( columnNames );
if ( !duplicates.isEmpty() )
{
throw new IllegalStateException( "Analytics table dimensions contain duplicates: " + duplicates );
}
}
/**
* Filters out analytics table columns which were created
* after the time of the last successful resource table update.
*
* @param columns the analytics table columns.
* @return
*/
protected List<AnalyticsTableColumn> filterDimensionColumns( List<AnalyticsTableColumn> columns )
{
Date lastResourceTableUpdate = (Date) systemSettingManager.getSystemSetting( SettingKey.LAST_SUCCESSFUL_RESOURCE_TABLES_UPDATE );
if ( lastResourceTableUpdate == null )
{
return columns;
}
return columns.stream()
.filter( c -> c.getCreated() == null || c.getCreated().before( lastResourceTableUpdate ) )
.collect( Collectors.toList() );
}
/**
* Executes the given table population SQL statement, log and times the operation.
*/
protected void populateAndLog( String sql, String tableName )
{
log.debug( String.format( "Populate table: %s with SQL: ", tableName, sql ) );
Timer timer = new SystemTimer().start();
jdbcTemplate.execute( sql );
log.info( String.format( "Populated table in %s: %s", timer.stop().toString(), tableName ) );
}
}
|
package org.eclipse.birt.report.engine.api.script.instance;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.IResultMetaData;
import org.eclipse.birt.data.engine.api.script.IDataSetInstanceHandle;
import org.eclipse.birt.data.engine.api.script.IDataSourceInstanceHandle;
import org.eclipse.birt.report.engine.api.script.IColumnMetaData;
import org.eclipse.birt.report.engine.api.script.ScriptException;
import org.eclipse.birt.report.engine.content.IForeignContent;
import org.eclipse.birt.report.engine.content.IImageContent;
import org.eclipse.birt.report.engine.content.IStyle;
import org.eclipse.birt.report.engine.content.impl.CellContent;
import org.eclipse.birt.report.engine.content.impl.DataContent;
import org.eclipse.birt.report.engine.content.impl.ForeignContent;
import org.eclipse.birt.report.engine.content.impl.ImageContent;
import org.eclipse.birt.report.engine.content.impl.LabelContent;
import org.eclipse.birt.report.engine.content.impl.ListContent;
import org.eclipse.birt.report.engine.content.impl.ReportContent;
import org.eclipse.birt.report.engine.content.impl.RowContent;
import org.eclipse.birt.report.engine.content.impl.TableContent;
import org.eclipse.birt.report.engine.ir.DataItemDesign;
import org.eclipse.birt.report.engine.ir.ImageItemDesign;
import org.eclipse.birt.report.engine.script.internal.instance.CellInstance;
import org.eclipse.birt.report.engine.script.internal.instance.DataItemInstance;
import org.eclipse.birt.report.engine.script.internal.instance.DataSetInstance;
import org.eclipse.birt.report.engine.script.internal.instance.DataSourceInstance;
import org.eclipse.birt.report.engine.script.internal.instance.DynamicTextInstance;
import org.eclipse.birt.report.engine.script.internal.instance.GridInstance;
import org.eclipse.birt.report.engine.script.internal.instance.ImageInstance;
import org.eclipse.birt.report.engine.script.internal.instance.LabelInstance;
import org.eclipse.birt.report.engine.script.internal.instance.ListInstance;
import org.eclipse.birt.report.engine.script.internal.instance.RowInstance;
import org.eclipse.birt.report.engine.script.internal.instance.RunningState;
import org.eclipse.birt.report.engine.script.internal.instance.StyleInstance;
import org.eclipse.birt.report.model.api.DataItemHandle;
import org.eclipse.birt.report.model.api.DesignConfig;
import org.eclipse.birt.report.model.api.DesignEngine;
import org.eclipse.birt.report.model.api.ElementFactory;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.SessionHandle;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.mozilla.javascript.Scriptable;
import com.ibm.icu.util.ULocale;
public class InstanceTest extends TestCase {
private static final String TYPE_NAME_2 = "type2";
private static final String TYPE_NAME_1 = "type1";
private static final String NATIVE2 = "native2";
private static final String NATIVE1 = "native1";
private static final String NAME2 = "name2";
private static final String NAME1 = "name1";
private static final String LABEL2 = "label2";
private static final String LABEL1 = "label1";
private static final String ALIAS2 = "alias2";
private static final String ALIAS1 = "alias1";
private static final String ALT_TEXT_KEY = "altTextKey";
private static final String ALT_TEXT = "altText";
private static final String WORD_SPACING = "30px";
private static final String TEXT_INDENT = WORD_SPACING;
private static final String SHOW_IF_BLANK = "true";
private static final String PADDING_TOP = "23px";
private static final String PADDING_RIGHT = "22px";
private static final String PADDING_LEFT = "21px";
private static final String PADDING_BOTTOM = "20px";
private static final String MASTER_PAGE = "masterPage";
private static final String MARGIN_TOP = "13px";
private static final String MARGIN_RIGHT = "12px";
private static final String MARGIN_LEFT = "11px";
private static final String MARGIN_BOTTOM = "10px";
private static final String LETTER_SPACING = MARGIN_BOTTOM;
private static final String YY_MM_DD = "YY-MM-DD";
private static final String WHITE = "white";
private static final String CAN_SHRINK = SHOW_IF_BLANK;
private static final String BORDER_TOP_WIDTH = "16cm";
private static final String GRAY = "gray";
private static final String BORDER_RIGHT_WIDTH = "15cm";
private static final String YELLOW = "yellow";
private static final String BORDER_LEFT_WIDTH = "14cm";
private static final String GREEN = "green";
private static final String BORDER_BOTTOM_WIDTH = "13cm";
private static final String BLUE = "blue";
private static final String BACKGROUND_POS_Y = "11cm";
private static final String BACKGROUND_POS_X = "10cm";
private static final String RED = "red";
private static final String BOOKMARK = "bookmark";
private static final String LABEL_TEXT = "labelText";
private static final String URI = "uri";
private static final String MIME_TYPE = "img/gif";
private static final String IMAGE_NAME = "imageName";
private static final String DYNAMIC_TEXT = "text";
private static final String QUERY_TEXT = "queryText";
private static final String EXT_PROP_VALUE1 = "propvalue1";
private static final String EXT_PROP1 = "prop1";
private static final String USER_PROP_VALUE = "userPropValue";
private static final String USER_PROP = "userProp";
private static final String HORIZONTAL_POSITION = MARGIN_LEFT;
private static final String HEIGHT = LETTER_SPACING;
private static final int COL_SPAN = 2;
private static final String EXPRESSION_VALUE = "expressionValue";
private static final String EXPRESSION = "expression";
private static final String EXTENSION_ID = "extensionId";
private static final String FAKE_NAME = "fakeName";
private static final byte[] DATA = new byte[] { 123 };
private static final int TYPE_2 = 2;
private static final int TYPE_1 = 1;
private static final String IMAGE_FILE = "imageFile";
private static final String IMAGE_URL = "imageURL";
private ReportContent reportContent;
private ElementFactory factory;
public void setUp() {
reportContent = new ReportContent();
SessionHandle sessionHandle = new DesignEngine( new DesignConfig( ) )
.newSessionHandle( ULocale.ENGLISH );
ReportDesignHandle designHandle = sessionHandle.createDesign();
factory = new ElementFactory(designHandle.getModule());
}
private void doTestReportElementInstance(IReportElementInstance element)
throws ScriptException {
element.setHeight(HEIGHT);
assertEquals(HEIGHT, element.getHeight());
element.setHorizontalPosition(HORIZONTAL_POSITION);
assertEquals(HORIZONTAL_POSITION, element.getHorizontalPosition());
element.setUserPropertyValue(USER_PROP, USER_PROP_VALUE);
// TODO: Fix
// assertEquals(USER_PROP_VALUE,
// element.getUserPropertyValue(USER_PROP));
}
public void testCellInstance() throws ScriptException {
CellContent cellContent = (CellContent) reportContent
.createCellContent();
cellContent.setColumn(1);
Map expressionMap = new HashMap();
expressionMap.put(EXPRESSION, EXPRESSION_VALUE);
//IRowData rowData = new FakeRowData(expressionMap);
ICellInstance cell = new CellInstance( cellContent, null, null, false );
cell.setColSpan(COL_SPAN);
assertEquals(COL_SPAN, cell.getColSpan());
//assertEquals(EXPRESSION_VALUE, cell.getRowData());
}
public void testDataItemInstance() throws ScriptException {
DataContent dataItemContent = (DataContent) reportContent
.createDataContent();
DataItemDesign dataItemDesign = new DataItemDesign();
DataItemHandle dataHandle = factory.newDataItem("DataItem");
dataItemDesign.setHandle(dataHandle);
dataItemContent.setGenerateBy(dataItemDesign);
IDataItemInstance dataItem = new DataItemInstance( dataItemContent,
null, null );
doTestReportElementInstance(dataItem);
}
public void testDataSetInstance() throws ScriptException {
IDataSetInstance dataSetInstance = new DataSetInstance(
new FakeDataSetHandle());
dataSetInstance.setExtensionProperty(EXT_PROP1, EXT_PROP_VALUE1);
assertEquals(EXT_PROP_VALUE1, dataSetInstance
.getExtensionProperty(EXT_PROP1));
dataSetInstance.setQueryText(QUERY_TEXT);
assertEquals(QUERY_TEXT, dataSetInstance.getQueryText());
assertEquals(FAKE_NAME, dataSetInstance.getName());
assertEquals(EXTENSION_ID, dataSetInstance.getExtensionID());
IColumnMetaData meta = dataSetInstance.getColumnMetaData();
assertEquals(ALIAS1, meta.getColumnAlias(1));
assertEquals(ALIAS2, meta.getColumnAlias(2));
assertEquals(LABEL1, meta.getColumnLabel(1));
assertEquals(LABEL2, meta.getColumnLabel(2));
assertEquals(NAME1, meta.getColumnName(1));
assertEquals(NAME2, meta.getColumnName(2));
assertEquals(NATIVE1, meta.getColumnNativeTypeName(1));
assertEquals(NATIVE2, meta.getColumnNativeTypeName(2));
assertEquals(TYPE_NAME_1, meta.getColumnTypeName(1));
assertEquals(TYPE_NAME_2, meta.getColumnTypeName(2));
assertTrue(meta.isComputedColumn(1));
assertFalse(meta.isComputedColumn(2));
assertEquals(2, meta.getColumnCount());
assertEquals(TYPE_1, meta.getColumnType(1));
assertEquals(TYPE_2, meta.getColumnType(2));
}
public void testDataSourceInstance() throws ScriptException {
IDataSourceInstance dataSourceInstance = new DataSourceInstance(
new FakeDataSourceHandle());
dataSourceInstance.setExtensionProperty(EXT_PROP1, EXT_PROP_VALUE1);
assertEquals(EXT_PROP_VALUE1, dataSourceInstance
.getExtensionProperty(EXT_PROP1));
assertEquals(FAKE_NAME, dataSourceInstance.getName());
assertEquals(EXTENSION_ID, dataSourceInstance.getExtensionID());
}
public void testDynamicTextInstance() throws ScriptException {
ForeignContent foreignContent = (ForeignContent) reportContent
.createForeignContent();
foreignContent.setRawType(IForeignContent.TEXT_TYPE);
IDynamicTextInstance textInstance = new DynamicTextInstance(
foreignContent, null, null );
textInstance.setText(DYNAMIC_TEXT);
assertEquals(DYNAMIC_TEXT, textInstance.getText());
}
public void testGridInstance() throws ScriptException {
TableContent content = (TableContent) reportContent
.createTableContent();
new GridInstance( content, null, null );
// No methods to test....
}
public void testImageInstance() throws ScriptException {
ImageContent imageContent = (ImageContent) reportContent
.createImageContent();
IImageInstance imageInstance = new ImageInstance( imageContent, null,
null );
imageInstance.setAltText(ALT_TEXT);
assertEquals(ALT_TEXT, imageInstance.getAltText());
imageInstance.setAltTextKey(ALT_TEXT_KEY);
assertEquals(ALT_TEXT_KEY, imageInstance.getAltTextKey());
imageInstance.setData(DATA);
assertEquals(DATA, imageInstance.getData());
imageInstance.setImageName(IMAGE_NAME);
assertEquals(IMAGE_NAME, imageInstance.getImageName());
assertEquals(ImageItemDesign.IMAGE_NAME, imageInstance.getImageSource());
imageInstance.setMimeType(MIME_TYPE);
assertEquals(MIME_TYPE, imageInstance.getMimeType());
imageInstance.setURL( IMAGE_URL );
assertEquals( IImageContent.IMAGE_URL, imageInstance.getImageSource() );
assertEquals( IMAGE_URL, imageInstance.getURL( ) );
imageInstance.setFile( IMAGE_FILE );
assertEquals( IImageContent.IMAGE_FILE, imageInstance.getImageSource() );
assertEquals( IMAGE_FILE, imageInstance.getFile( ) );
}
public void testLabelInstance() throws ScriptException {
LabelContent labelContent = (LabelContent) reportContent
.createLabelContent();
ILabelInstance labelInstance = new LabelInstance( labelContent, null,
null );
labelInstance.setText(LABEL_TEXT);
assertEquals(LABEL_TEXT, labelInstance.getText());
}
public void testListInstance() throws ScriptException {
ListContent listContent = (ListContent) reportContent
.createListContent();
new ListInstance( listContent, null, null );
// no methods to test...
}
public void testRowInstance() throws ScriptException {
RowContent rowContent = (RowContent) reportContent.createRowContent();
Map expressionMap = new HashMap();
expressionMap.put(EXPRESSION, EXPRESSION_VALUE);
IRowInstance rowInstance = new RowInstance( rowContent, null, null );
rowInstance.setBookmark(BOOKMARK);
assertEquals(BOOKMARK, rowInstance.getBookmarkValue());
rowInstance.setHeight(HEIGHT);
assertEquals(HEIGHT, rowInstance.getHeight());
//assertEquals(EXPRESSION_VALUE, rowInstance.getRowData().getExpressionValue(EXPRESSION));
}
public void testScriptStyle() throws ScriptException {
IStyle style = reportContent.createStyle();
IScriptStyle styleInstance = new StyleInstance( style, null );
styleInstance
.setBackgroundAttachment(DesignChoiceConstants.BACKGROUND_ATTACHMENT_SCROLL);
assertEquals(DesignChoiceConstants.BACKGROUND_ATTACHMENT_SCROLL,
styleInstance.getBackgroundAttachment());
styleInstance.setBackgroundColor(RED);
assertEquals(RED, styleInstance.getBackgroundColor());
styleInstance.setBackgroundImage(URI);
assertEquals(URI, styleInstance.getBackgroundImage());
styleInstance.setBackgroundPositionX(BACKGROUND_POS_X);
assertEquals(BACKGROUND_POS_X, styleInstance.getBackgroundPositionX());
styleInstance.setBackgroundPositionY(BACKGROUND_POS_Y);
assertEquals(BACKGROUND_POS_Y, styleInstance.getBackgroundPositionY());
styleInstance
.setBackgroundRepeat(DesignChoiceConstants.BACKGROUND_REPEAT_REPEAT_X);
assertEquals(DesignChoiceConstants.BACKGROUND_REPEAT_REPEAT_X,
styleInstance.getBackgroundRepeat());
styleInstance.setBorderBottomColor(BLUE);
assertEquals(BLUE, styleInstance.getBorderBottomColor());
styleInstance
.setBorderBottomStyle(DesignChoiceConstants.LINE_STYLE_SOLID);
assertEquals(DesignChoiceConstants.LINE_STYLE_SOLID, styleInstance
.getBorderBottomStyle());
styleInstance.setBorderBottomWidth(BORDER_BOTTOM_WIDTH);
assertEquals(BORDER_BOTTOM_WIDTH, styleInstance.getBorderBottomWidth());
styleInstance.setBorderLeftColor(GREEN);
assertEquals(GREEN, styleInstance.getBorderLeftColor());
styleInstance
.setBorderLeftStyle(DesignChoiceConstants.LINE_STYLE_DOTTED);
assertEquals(DesignChoiceConstants.LINE_STYLE_DOTTED, styleInstance
.getBorderLeftStyle());
styleInstance.setBorderLeftWidth(BORDER_LEFT_WIDTH);
assertEquals(BORDER_LEFT_WIDTH, styleInstance.getBorderLeftWidth());
styleInstance.setBorderRightColor(YELLOW);
assertEquals(YELLOW, styleInstance.getBorderRightColor());
styleInstance
.setBorderRightStyle(DesignChoiceConstants.LINE_STYLE_DASHED);
assertEquals(DesignChoiceConstants.LINE_STYLE_DASHED, styleInstance
.getBorderRightStyle());
styleInstance.setBorderRightWidth(BORDER_RIGHT_WIDTH);
assertEquals(BORDER_RIGHT_WIDTH, styleInstance.getBorderRightWidth());
styleInstance.setBorderTopColor(GRAY);
assertEquals(GRAY, styleInstance.getBorderTopColor());
styleInstance
.setBorderTopStyle(DesignChoiceConstants.LINE_STYLE_DOUBLE);
assertEquals(DesignChoiceConstants.LINE_STYLE_DOUBLE, styleInstance
.getBorderTopStyle());
styleInstance.setBorderTopWidth(BORDER_TOP_WIDTH);
assertEquals(BORDER_TOP_WIDTH, styleInstance.getBorderTopWidth());
styleInstance.setCanShrink(CAN_SHRINK);
assertEquals(CAN_SHRINK, styleInstance.getCanShrink());
styleInstance.setColor(WHITE);
assertEquals(WHITE, styleInstance.getColor());
styleInstance.setDateFormat(YY_MM_DD);
assertEquals(YY_MM_DD, styleInstance.getDateFormat());
styleInstance.setDisplay(DesignChoiceConstants.DISPLAY_INLINE);
assertEquals(DesignChoiceConstants.DISPLAY_INLINE, styleInstance
.getDisplay());
styleInstance
.setFontFamily(DesignChoiceConstants.FONT_FAMILY_SANS_SERIF);
assertEquals(DesignChoiceConstants.FONT_FAMILY_SANS_SERIF,
styleInstance.getFontFamily());
styleInstance.setFontSize(DesignChoiceConstants.FONT_SIZE_LARGE);
assertEquals(DesignChoiceConstants.FONT_SIZE_LARGE, styleInstance
.getFontSize());
styleInstance.setFontStyle(DesignChoiceConstants.FONT_STYLE_ITALIC);
assertEquals(DesignChoiceConstants.FONT_STYLE_ITALIC, styleInstance
.getFontStyle());
styleInstance
.setFontVariant(DesignChoiceConstants.FONT_VARIANT_SMALL_CAPS);
assertEquals(DesignChoiceConstants.FONT_VARIANT_SMALL_CAPS,
styleInstance.getFontVariant());
styleInstance.setFontWeight(DesignChoiceConstants.FONT_WEIGHT_BOLD);
assertEquals(DesignChoiceConstants.FONT_WEIGHT_BOLD, styleInstance
.getFontWeight());
styleInstance.setLetterSpacing(LETTER_SPACING);
assertEquals(LETTER_SPACING, styleInstance.getLetterSpacing());
styleInstance.setLineHeight(HEIGHT);
assertEquals(HEIGHT, styleInstance.getLineHeight());
styleInstance.setMarginBottom(MARGIN_BOTTOM);
assertEquals(MARGIN_BOTTOM, styleInstance.getMarginBottom());
styleInstance.setMarginLeft(MARGIN_LEFT);
assertEquals(MARGIN_LEFT, styleInstance.getMarginLeft());
styleInstance.setMarginRight(MARGIN_RIGHT);
assertEquals(MARGIN_RIGHT, styleInstance.getMarginRight());
styleInstance.setMarginTop(MARGIN_TOP);
assertEquals(MARGIN_TOP, styleInstance.getMarginTop());
styleInstance.setMasterPage(MASTER_PAGE);
assertEquals(MASTER_PAGE, styleInstance.getMasterPage());
styleInstance
.setNumberFormat(DesignChoiceConstants.NUMBER_FORMAT_TYPE_CURRENCY);
assertEquals(DesignChoiceConstants.NUMBER_FORMAT_TYPE_CURRENCY,
styleInstance.getNumberFormat());
styleInstance.setPaddingBottom(PADDING_BOTTOM);
assertEquals(PADDING_BOTTOM, styleInstance.getPaddingBottom());
styleInstance.setPaddingLeft(PADDING_LEFT);
assertEquals(PADDING_LEFT, styleInstance.getPaddingLeft());
styleInstance.setPaddingRight(PADDING_RIGHT);
assertEquals(PADDING_RIGHT, styleInstance.getPaddingRight());
styleInstance.setPaddingTop(PADDING_TOP);
assertEquals(PADDING_TOP, styleInstance.getPaddingTop());
styleInstance
.setPageBreakAfter(DesignChoiceConstants.PAGE_BREAK_AFTER_ALWAYS);
assertEquals(DesignChoiceConstants.PAGE_BREAK_AFTER_ALWAYS, styleInstance
.getPageBreakAfter());
styleInstance
.setPageBreakBefore(DesignChoiceConstants.PAGE_BREAK_BEFORE_AVOID);
assertEquals(DesignChoiceConstants.PAGE_BREAK_BEFORE_AVOID, styleInstance
.getPageBreakBefore());
styleInstance.setShowIfBlank(SHOW_IF_BLANK);
assertEquals(SHOW_IF_BLANK, styleInstance.getShowIfBlank());
styleInstance
.setStringFormat(DesignChoiceConstants.STRING_FORMAT_TYPE_ZIP_CODE);
assertEquals(DesignChoiceConstants.STRING_FORMAT_TYPE_ZIP_CODE,
styleInstance.getStringFormat());
styleInstance.setTextAlign(DesignChoiceConstants.TEXT_ALIGN_RIGHT);
assertEquals(DesignChoiceConstants.TEXT_ALIGN_RIGHT, styleInstance
.getTextAlign());
styleInstance.setTextIndent(TEXT_INDENT);
assertEquals(TEXT_INDENT, styleInstance.getTextIndent());
styleInstance
.setTextLineThrough(DesignChoiceConstants.TEXT_LINE_THROUGH_LINE_THROUGH);
assertEquals(DesignChoiceConstants.TEXT_LINE_THROUGH_LINE_THROUGH,
styleInstance.getTextLineThrough());
styleInstance
.setTextOverline(DesignChoiceConstants.TEXT_OVERLINE_OVERLINE);
assertEquals(DesignChoiceConstants.TEXT_OVERLINE_OVERLINE,
styleInstance.getTextOverline());
styleInstance
.setTextTransform(DesignChoiceConstants.TRANSFORM_UPPERCASE);
assertEquals(DesignChoiceConstants.TRANSFORM_UPPERCASE, styleInstance
.getTextTransform());
styleInstance
.setTextUnderline(DesignChoiceConstants.TEXT_UNDERLINE_UNDERLINE);
assertEquals(DesignChoiceConstants.TEXT_UNDERLINE_UNDERLINE,
styleInstance.getTextUnderline());
styleInstance
.setVerticalAlign(DesignChoiceConstants.VERTICAL_ALIGN_TOP);
assertEquals(DesignChoiceConstants.VERTICAL_ALIGN_TOP, styleInstance
.getVerticalAlign());
styleInstance.setVisibleFormat(DesignChoiceConstants.FORMAT_TYPE_ALL);
assertEquals(DesignChoiceConstants.FORMAT_TYPE_ALL, styleInstance
.getVisibleFormat());
styleInstance.setWhiteSpace(DesignChoiceConstants.WHITE_SPACE_NOWRAP);
assertEquals(DesignChoiceConstants.WHITE_SPACE_NOWRAP, styleInstance
.getWhiteSpace());
styleInstance.setWordSpacing(WORD_SPACING);
assertEquals(WORD_SPACING, styleInstance.getWordSpacing());
}
public void testPageBreak( ) throws Throwable
{
IStyle style = reportContent.createStyle( );
StyleInstance styleInstance = new StyleInstance( style,
RunningState.CREATE );
styleInstance.setPageBreakAfter( "always" );
styleInstance.setPageBreakBefore( "always" );
styleInstance.setPageBreakInside( "always" );
styleInstance = new StyleInstance( style, RunningState.RENDER );
testMethod( styleInstance, "setPageBreakAfter" );
testMethod( styleInstance, "setPageBreakBefore" );
testMethod( styleInstance, "setPageBreakInside" );
styleInstance = new StyleInstance( style, RunningState.PAGEBREAK );
testMethod( styleInstance, "setPageBreakAfter" );
testMethod( styleInstance, "setPageBreakBefore" );
testMethod( styleInstance, "setPageBreakInside" );
}
private void testMethod( StyleInstance styleInstance, String methodName )
throws Throwable
{
try
{
Method method = StyleInstance.class.getMethod( methodName,
String.class );
method.invoke( styleInstance, "always" );
fail( );
}
catch ( InvocationTargetException expected )
{
Throwable targetException = expected.getTargetException( );
if ( targetException instanceof UnsupportedOperationException )
{
assertTrue( true );
return;
}
throw targetException;
}
}
private abstract class FakeBaseData {
private Map extProps = new HashMap();
public String getName() {
return FAKE_NAME;
}
public String getExtensionID() {
return EXTENSION_ID;
}
public String getExtensionProperty(String name) {
return (String) extProps.get(name);
}
public void setExtensionProperty(String name, String value) {
extProps.put(name, value);
}
public Map getAllExtensionProperties() {
return extProps;
}
public Scriptable getScriptScope() {
return null;
}
}
private class FakeDataSourceHandle extends FakeBaseData implements
IDataSourceInstanceHandle {
}
private class FakeDataSetHandle extends FakeBaseData
implements
IDataSetInstanceHandle
{
private String queryText;
private Map inputParamValues = new HashMap( );
public IDataSourceInstanceHandle getDataSource( )
{
return null;
}
public IResultMetaData getResultMetaData( ) throws BirtException
{
return new FakeResultMetadata( );
}
public String getQueryText( )
{
return queryText;
}
public void setQueryText( String queryText ) throws BirtException
{
this.queryText = queryText;
}
public Object getInputParameterValue( String paramName )
throws BirtException
{
return null;
}
public void setInputParameterValue( String paramName, Object paramValue )
throws BirtException
{
}
public Map getInputParameters( )
{
return null;
}
public Object getOutputParameterValue( String paramName )
throws BirtException
{
return null;
}
public void setOutputParameterValue( String paramName, Object paramValue )
throws BirtException
{
}
public Map getOutputParameters( )
{
return null;
}
}
// This class never been used locally. Comment this class to fix the warning.
// private class FakeRowData implements IRowData {
// private Map expressionMap;
// public FakeRowData(Map expressionMap) {
// this.expressionMap = expressionMap;
// public Object getExpressionValue(String expression)
// throws ScriptException {
// return expressionMap.get(expression);
// public Object getExpressionValue(int i) throws ScriptException {
// Set keySet = expressionMap.keySet();
// Object[] expressions = keySet.toArray();
// Object key = expressions[i - 2];
// return expressionMap.get(key);
// public int getExpressionCount() {
// return expressionMap.size();
// public Object getColumnValue( String name )
// // TODO Auto-generated method stub
// return null;
// public Object getColumnValue( int index )
// // TODO Auto-generated method stub
// return null;
// public String getColumnName( int index )
// // TODO Auto-generated method stub
// return null;
// public int getColumnCount( )
// // TODO Auto-generated method stub
// return 0;
private class FakeResultMetadata implements IResultMetaData {
private List columns;
public FakeResultMetadata() {
columns = new ArrayList();
columns.add(new Column(NAME1, ALIAS1, TYPE_1, TYPE_NAME_1, NATIVE1,
LABEL1, true));
columns.add(new Column(NAME2, ALIAS2, TYPE_2, TYPE_NAME_2, NATIVE2,
LABEL2, false));
}
private class Column {
String name;
String alias;
int type;
String typeName;
String nativeTypeName;
String label;
boolean computed;
public Column(String name, String alias, int type, String typeName,
String nativeTypeName, String label, boolean computed) {
this.name = name;
this.alias = alias;
this.type = type;
this.typeName = typeName;
this.nativeTypeName = nativeTypeName;
this.label = label;
this.computed = computed;
}
}
public int getColumnCount() {
return columns.size();
}
public String getColumnName(int index) throws BirtException {
Column c = (Column) columns.get(index - 1);
return c.name;
}
public String getColumnAlias(int index) throws BirtException {
Column c = (Column) columns.get(index - 1);
return c.alias;
}
public int getColumnType(int index) throws BirtException {
Column c = (Column) columns.get(index - 1);
return c.type;
}
public String getColumnTypeName(int index) throws BirtException {
Column c = (Column) columns.get(index - 1);
return c.typeName;
}
public String getColumnNativeTypeName(int index) throws BirtException {
Column c = (Column) columns.get(index - 1);
return c.nativeTypeName;
}
public String getColumnLabel(int index) throws BirtException {
Column c = (Column) columns.get(index - 1);
return c.label;
}
public boolean isComputedColumn(int index) throws BirtException {
Column c = (Column) columns.get(index - 1);
return c.computed;
}
}
}
|
package org.eclipse.birt.report.engine.api.script.instance;
public interface IReportItemInstance extends IReportElementInstance
{
/**
* Get the hyperlink
*
* @return the hyperlink
*/
String getHyperlink( );
/**
* Get the name
*/
String getName( );
/**
* Set the name
*/
void setName( String name );
/**
* Get the help text
*/
String getHelpText( );
/**
* Set the help text
*/
void setHelpText( String helpText );
}
|
package org.innovateuk.ifs.testdata.services;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.innovateuk.ifs.BaseBuilder;
import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.application.resource.ApplicationState;
import org.innovateuk.ifs.application.resource.FundingDecision;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.resource.CompetitionStatus;
import org.innovateuk.ifs.finance.resource.BaseFinanceResource;
import org.innovateuk.ifs.finance.resource.OrganisationSize;
import org.innovateuk.ifs.finance.resource.cost.AdditionalCompanyCost;
import org.innovateuk.ifs.finance.resource.cost.FinanceRowType;
import org.innovateuk.ifs.finance.resource.cost.KtpTravelCost;
import org.innovateuk.ifs.form.resource.*;
import org.innovateuk.ifs.organisation.domain.Organisation;
import org.innovateuk.ifs.organisation.resource.OrganisationResource;
import org.innovateuk.ifs.organisation.resource.OrganisationTypeEnum;
import org.innovateuk.ifs.testdata.builders.*;
import org.innovateuk.ifs.testdata.builders.data.*;
import org.innovateuk.ifs.user.resource.UserResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import static java.lang.Boolean.TRUE;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.innovateuk.ifs.finance.resource.OrganisationSize.SMALL;
import static org.innovateuk.ifs.testdata.builders.ApplicationDataBuilder.newApplicationData;
import static org.innovateuk.ifs.testdata.builders.ApplicationFinanceDataBuilder.newApplicationFinanceData;
import static org.innovateuk.ifs.testdata.builders.CompetitionDataBuilder.newCompetitionData;
import static org.innovateuk.ifs.testdata.builders.ProcurementMilestoneDataBuilder.newProcurementMilestoneDataBuilder;
import static org.innovateuk.ifs.testdata.builders.QuestionResponseDataBuilder.newApplicationQuestionResponseData;
import static org.innovateuk.ifs.testdata.services.CsvUtils.*;
import static org.innovateuk.ifs.util.CollectionFunctions.*;
/**
* A service that {@link org.innovateuk.ifs.testdata.BaseGenerateTestData} uses to generate Application data. While
* {@link org.innovateuk.ifs.testdata.BaseGenerateTestData} is responsible for gathering CSV information and
* orchestarting the building of it, this service is responsible for taking the CSV data passed to it and using
* the appropriate builders to generate and update entities.
*/
@Component
@Lazy
public class ApplicationDataBuilderService extends BaseDataBuilderService {
private static final Logger LOG = LoggerFactory.getLogger(ApplicationDataBuilderService.class);
@Autowired
private GenericApplicationContext applicationContext;
private ApplicationDataBuilder applicationDataBuilder;
private CompetitionDataBuilder competitionDataBuilder;
private ApplicationFinanceDataBuilder applicationFinanceDataBuilder;
private ProcurementMilestoneDataBuilder procurementMilestoneDataBuilder;
private QuestionResponseDataBuilder questionResponseDataBuilder;
@PostConstruct
public void readCsvs() {
ServiceLocator serviceLocator = new ServiceLocator(applicationContext, COMP_ADMIN_EMAIL, PROJECT_FINANCE_EMAIL);
applicationDataBuilder = newApplicationData(serviceLocator);
competitionDataBuilder = newCompetitionData(serviceLocator);
applicationFinanceDataBuilder = newApplicationFinanceData(serviceLocator);
questionResponseDataBuilder = newApplicationQuestionResponseData(serviceLocator);
procurementMilestoneDataBuilder = newProcurementMilestoneDataBuilder(serviceLocator);
}
public List<ApplicationQuestionResponseData> createApplicationQuestionResponses(
ApplicationData applicationData,
ApplicationLine applicationLine,
List<ApplicationQuestionResponseLine> questionResponseLines) {
QuestionResponseDataBuilder baseBuilder =
questionResponseDataBuilder.withApplication(applicationData.getApplication());
if (!applicationLine.createApplicationResponses) {
return emptyList();
}
List<CsvUtils.ApplicationQuestionResponseLine> responsesForApplication =
simpleFilter(questionResponseLines, r ->
r.competitionName.equals(applicationLine.competitionName) &&
r.applicationName.equals(applicationLine.title));
// if we have specific answers for questions in the application-questions.csv file, fill them in here now
if (!responsesForApplication.isEmpty()) {
List<QuestionResponseDataBuilder> responseBuilders = questionResponsesFromCsv(
baseBuilder,
applicationLine.leadApplicant,
responsesForApplication);
return simpleMap(responseBuilders, BaseBuilder::build);
}
// otherwise provide a default set of marked as complete questions if the application is to be submitted
else if (applicationLine.markQuestionsComplete || applicationLine.submittedDate != null) {
Long competitionId = applicationData.getCompetition().getId();
List<QuestionResource> competitionQuestions = retrieveCachedQuestionsByCompetitionId(competitionId);
List<QuestionResource> questionsToAnswer = simpleFilter(competitionQuestions, q ->
!q.getMultipleStatuses() &&
q.getMarkAsCompletedEnabled() &&
q.getQuestionSetupType().hasFormInputResponses());
List<QuestionResponseDataBuilder> responseBuilders = simpleMap(questionsToAnswer, question -> {
String answerValue = "This is the applicant response for " + question.getName().toLowerCase() + ".";
String leadApplicantEmail = applicationData.getLeadApplicant().getEmail();
QuestionResponseDataBuilder responseBuilder = baseBuilder.
forQuestion(question.getName()).
withAssignee(leadApplicantEmail);
List<FormInputResource> formInputs = retrieveCachedFormInputsByQuestionId(question);
if (formInputs.stream().anyMatch(fi -> fi.getScope().equals(FormInputScope.APPLICATION) && fi.getType().equals(FormInputType.TEXTAREA))) {
responseBuilder = responseBuilder.withAnswer(answerValue, leadApplicantEmail);
}
if (formInputs.stream().anyMatch(fi -> fi.getScope().equals(FormInputScope.APPLICATION) && fi.getType().equals(FormInputType.MULTIPLE_CHOICE))) {
FormInputResource multipleChoice = formInputs.stream().filter(fi -> fi.getType().equals(FormInputType.MULTIPLE_CHOICE)).findFirst().get();
List<MultipleChoiceOptionResource> choices = multipleChoice.getMultipleChoiceOptions();
String applicationName = applicationData.getApplication().getName();
String questionName = question.getName();
//Pick a choice based on the application name and question name. Ensures we have a random choice, but is the same choice each time generator is ran.
int choice = (applicationName + questionName).length() % choices.size();
responseBuilder = responseBuilder.withChoice(choices.get(choice), leadApplicantEmail);
}
if (formInputs.stream().anyMatch(fi -> fi.getScope().equals(FormInputScope.APPLICATION) && fi.getType().equals(FormInputType.FILEUPLOAD))) {
String applicationName = applicationData.getApplication().getName();
String questionName = question.getShortName().toLowerCase();
String fileUploadName = (applicationName + "-" + questionName + ".pdf")
.toLowerCase().replace(' ', '-') ;
responseBuilder = responseBuilder.
withFileUploads(singletonList(fileUploadName), leadApplicantEmail);
}
return responseBuilder;
});
return simpleMap(responseBuilders, BaseBuilder::build);
}
return emptyList();
}
public List<ApplicationFinanceData> createApplicationFinances(
ApplicationData applicationData,
ApplicationLine applicationLine,
List<ApplicationOrganisationFinanceBlock> applicationFinanceLines,
List<ExternalUserLine> externalUsers) {
if (!applicationLine.createFinanceResponses) {
return emptyList();
}
Map<String, String> usersOrganisations = simpleToMap(externalUsers, user -> user.emailAddress, user -> user.organisationName);
List<String> applicants = combineLists(applicationLine.leadApplicant, applicationLine.collaborators);
List<Triple<String, String, OrganisationTypeEnum>> organisations = simpleMap(applicants, email -> {
UserResource user = retrieveUserByEmail(email);
OrganisationResource organisation = organisationByName(usersOrganisations.get(email));
return Triple.of(user.getEmail(), organisation.getName(),
OrganisationTypeEnum.getFromId(organisation.getOrganisationType()));
});
List<Triple<String, String, OrganisationTypeEnum>> uniqueOrganisations = simpleFilter(organisations, triple ->
isUniqueOrFirstDuplicateOrganisation(triple, organisations));
List<ApplicationFinanceDataBuilder> builders = simpleMap(uniqueOrganisations, orgDetails -> {
String user = orgDetails.getLeft();
String organisationName = orgDetails.getMiddle();
OrganisationTypeEnum organisationType = orgDetails.getRight();
Optional<CsvUtils.ApplicationOrganisationFinanceBlock> organisationFinances =
simpleFindFirst(applicationFinanceLines, finances ->
finances.competitionName.equals(applicationLine.competitionName) &&
finances.applicationName.equals(applicationLine.title) &&
finances.organisationName.equals(organisationName));
if (applicationData.getCompetition().applicantShouldUseJesFinances(organisationType)) {
return organisationFinances.map(suppliedFinances ->
generateAcademicFinancesFromSuppliedData(
applicationData.getApplication(),
applicationData.getCompetition(),
user,
organisationName)
).orElseGet(() ->
generateAcademicFinances(
applicationData.getApplication(),
applicationData.getCompetition(),
user,
organisationName)
);
} else {
return organisationFinances.map(suppliedFinances ->
generateIndustrialCostsFromSuppliedData(
applicationData.getApplication(),
applicationData.getCompetition(),
user,
organisationName,
suppliedFinances)
).orElseGet(() ->
generateIndustrialCosts(
applicationData.getApplication(),
applicationData.getCompetition(),
user,
organisationName,
organisationType)
);
}
});
return simpleMap(builders, BaseBuilder::build);
}
public List<ProcurementMilestoneData> createProcurementMilestones(
ApplicationData applicationData,
ApplicationLine applicationLine,
List<ExternalUserLine> externalUsers) {
if (applicationData.getCompetition().isProcurement() && applicationLine.createFinanceResponses) {
Map<String, String> usersOrganisations = simpleToMap(externalUsers, user -> user.emailAddress, user -> user.organisationName);
List<String> applicants = combineLists(applicationLine.leadApplicant, applicationLine.collaborators);
List<Triple<String, String, OrganisationTypeEnum>> organisations = simpleMap(applicants, email -> {
UserResource user = retrieveUserByEmail(email);
OrganisationResource organisation = organisationByName(usersOrganisations.get(email));
return Triple.of(user.getEmail(), organisation.getName(),
OrganisationTypeEnum.getFromId(organisation.getOrganisationType()));
});
List<Triple<String, String, OrganisationTypeEnum>> uniqueOrganisations = simpleFilter(organisations, triple ->
isUniqueOrFirstDuplicateOrganisation(triple, organisations));
List<ProcurementMilestoneDataBuilder> builders = simpleMap(uniqueOrganisations, orgDetails -> {
String user = orgDetails.getLeft();
String organisationName = orgDetails.getMiddle();
return procurementMilestoneDataBuilder
.withApplication(applicationData.getApplication())
.withCompetition(applicationData.getCompetition())
.withOrganisation(organisationName)
.withUser(user)
.withMilestones();
});
return simpleMap(builders, BaseBuilder::build);
} else {
return emptyList();
}
}
public void completeApplication(
ApplicationData applicationData,
ApplicationLine applicationLine,
List<ApplicationQuestionResponseData> questionResponseData,
List<ApplicationFinanceData> financeData) {
if (applicationLine.markQuestionsComplete) {
forEachWithIndex(questionResponseData, (i, response) -> {
boolean lastElement = i == questionResponseData.size() - 1;
questionResponseDataBuilder.
withExistingResponse(response).
markAsComplete(lastElement).
build();
});
}
if (applicationLine.markFinancesComplete) {
forEachWithIndex(financeData, (i, finance) -> {
boolean lastElement = i == financeData.size() - 1;
applicationFinanceDataBuilder.
withExistingFinances(
finance.getApplication(),
finance.getCompetition(),
finance.getUser(),
finance.getOrganisation()).
markAsComplete(true, lastElement).
build();
});
}
ApplicationDataBuilder applicationBuilder = this.applicationDataBuilder.
withExistingApplication(applicationData).
markApplicationDetailsComplete(applicationLine.markQuestionsComplete).
markEdiComplete(applicationLine.markQuestionsComplete).
markApplicationTeamComplete(applicationLine.markQuestionsComplete).
markResearchCategoryComplete(applicationLine.markQuestionsComplete);
if (applicationLine.submittedDate != null) {
applicationBuilder = applicationBuilder.submitApplication();
}
if (asLinkedSet(ApplicationState.INELIGIBLE, ApplicationState.INELIGIBLE_INFORMED).
contains(applicationLine.status)) {
applicationBuilder = applicationBuilder.markApplicationIneligible(applicationLine.ineligibleReason);
if (applicationLine.status == ApplicationState.INELIGIBLE_INFORMED) {
applicationBuilder = applicationBuilder.informApplicationIneligible();
}
}
applicationBuilder.build();
}
public void createFundingDecisions(
CompetitionData competition,
CompetitionLine competitionLine,
List<ApplicationLine> applicationLines) {
CompetitionDataBuilder basicCompetitionInformation = competitionDataBuilder.withExistingCompetition(competition);
if (!competition.getCompetition().isKtp() && asList(CompetitionStatus.PROJECT_SETUP, CompetitionStatus.ASSESSOR_FEEDBACK).contains(competitionLine.competitionStatus)) {
basicCompetitionInformation.
moveCompetitionIntoFundersPanelStatus().
sendFundingDecisions(createFundingDecisionsFromCsv(competitionLine.name, applicationLines)).
build();
}
}
private List<Pair<String, FundingDecision>> createFundingDecisionsFromCsv(
String competitionName,
List<ApplicationLine> applicationLines) {
List<CsvUtils.ApplicationLine> matchingApplications = simpleFilter(applicationLines, a ->
a.competitionName.equals(competitionName));
List<CsvUtils.ApplicationLine> applicationsWithDecisions = simpleFilter(matchingApplications, a ->
asList(ApplicationState.APPROVED, ApplicationState.REJECTED).contains(a.status));
return simpleMap(applicationsWithDecisions, ma -> {
FundingDecision fundingDecision = ma.status == ApplicationState.APPROVED ? FundingDecision.FUNDED : FundingDecision.UNFUNDED;
return Pair.of(ma.title, fundingDecision);
});
}
private List<QuestionResponseDataBuilder> questionResponsesFromCsv(
QuestionResponseDataBuilder baseBuilder,
String leadApplicant,
List<CsvUtils.ApplicationQuestionResponseLine> responsesForApplication) {
return simpleMap(responsesForApplication, line -> {
String answeringUser = !isBlank(line.answeredBy) ? line.answeredBy : (!isBlank(line.assignedTo) ? line.assignedTo : leadApplicant);
UnaryOperator<QuestionResponseDataBuilder> withQuestion = builder -> builder.forQuestion(line.questionName);
UnaryOperator<QuestionResponseDataBuilder> answerIfNecessary = builder ->
!isBlank(line.value) ? builder.withAssignee(answeringUser).withAnswer(line.value, answeringUser)
: builder;
UnaryOperator<QuestionResponseDataBuilder> uploadFilesIfNecessary = builder ->
!line.filesUploaded.isEmpty() ?
builder.withAssignee(answeringUser).withFileUploads(line.filesUploaded, answeringUser) :
builder;
UnaryOperator<QuestionResponseDataBuilder> assignIfNecessary = builder ->
!isBlank(line.assignedTo) ? builder.withAssignee(line.assignedTo) : builder;
return withQuestion.
andThen(answerIfNecessary).
andThen(uploadFilesIfNecessary).
andThen(assignIfNecessary).
apply(baseBuilder);
});
}
public ApplicationData createApplication(
CompetitionData competition,
ApplicationLine line,
List<InviteLine> inviteLines,
List<ExternalUserLine> externalUsers) {
UserResource leadApplicant = retrieveUserByEmail(line.leadApplicant);
Map<String, String> usersOrganisations = simpleToMap(externalUsers, user -> user.emailAddress, user -> user.organisationName);
Organisation org = organisationRepository.findOneByName(usersOrganisations.get(line.leadApplicant));
ApplicationDataBuilder baseBuilder = applicationDataBuilder.withCompetition(competition.getCompetition()).
withBasicDetails(leadApplicant, line.title, line.researchCategory, line.resubmission, org.getId()).
withInnovationArea(line.innovationArea).
withStartDate(line.startDate).
withDurationInMonths(line.durationInMonths);
for (String collaborator : line.collaborators) {
baseBuilder = baseBuilder.inviteCollaborator(retrieveUserByEmail(collaborator), organisationRepository.findOneByName(usersOrganisations.get(collaborator)));
}
if (competition.getCompetition().isKtp() && line.submittedDate != null) {
baseBuilder = baseBuilder.inviteKta();
}
List<CsvUtils.InviteLine> pendingInvites = simpleFilter(inviteLines,
invite -> "APPLICATION".equals(invite.type) && line.title.equals(invite.targetName));
for (CsvUtils.InviteLine invite : pendingInvites) {
baseBuilder = baseBuilder.inviteCollaboratorNotYetRegistered(invite.email, invite.hash, invite.name,
invite.ownerName);
}
if (line.status != ApplicationState.CREATED) {
baseBuilder = baseBuilder.beginApplication();
}
return baseBuilder.build();
}
private boolean isUniqueOrFirstDuplicateOrganisation(
Triple<String, String, OrganisationTypeEnum> currentOrganisation,
List<Triple<String, String, OrganisationTypeEnum>> organisationList) {
Triple<String, String, OrganisationTypeEnum> matchingRecord = simpleFindFirstMandatory(organisationList, triple ->
triple.getMiddle().equals(currentOrganisation.getMiddle()));
return matchingRecord.equals(currentOrganisation);
}
private IndustrialCostDataBuilder addFinanceRow(
IndustrialCostDataBuilder builder,
CsvUtils.ApplicationFinanceRow financeRow) {
switch (financeRow.category) {
case "Working days per year":
return builder.withWorkingDaysPerYear(Integer.valueOf(financeRow.metadata.get(0)));
case "Grant claim":
return builder.withGrantClaim(BigDecimal.valueOf(Integer.valueOf(financeRow.metadata.get(0))));
case "Organisation size":
return builder.withOrganisationSize(OrganisationSize.findById(Long.valueOf(financeRow.metadata.get(0))));
case "Work postcode":
return builder.withWorkPostcode(financeRow.metadata.get(0));
case "Fec model enabled":
return builder.withFecEnabled(Boolean.valueOf(financeRow.metadata.get(0)));
case "Fec file uploaded":
return builder.withUploadedFecFile();
case "Labour":
return builder.withLabourEntry(
financeRow.metadata.get(0),
Integer.valueOf(financeRow.metadata.get(1)),
Integer.valueOf(financeRow.metadata.get(2)));
case "Overheads":
switch (financeRow.metadata.get(0).toLowerCase()) {
case "total":
return builder.withAdministrationSupportCostsTotalRate(
Integer.valueOf(financeRow.metadata.get(1)));
case "default":
return builder.withAdministrationSupportCostsDefaultRate();
case "none":
return builder.withAdministrationSupportCostsNone();
default:
throw new RuntimeException("Unknown rate type " + financeRow.metadata.get(0).toLowerCase());
}
case "Materials":
return builder.withMaterials(
financeRow.metadata.get(0),
bd(financeRow.metadata.get(1)),
Integer.valueOf(financeRow.metadata.get(2)));
case "Capital usage":
return builder.withCapitalUsage(
Integer.valueOf(financeRow.metadata.get(4)),
financeRow.metadata.get(0),
Boolean.parseBoolean(financeRow.metadata.get(1)),
bd(financeRow.metadata.get(2)),
bd(financeRow.metadata.get(3)),
Integer.valueOf(financeRow.metadata.get(5)));
case "Subcontracting":
return builder.withSubcontractingCost(
financeRow.metadata.get(0),
financeRow.metadata.get(1),
financeRow.metadata.get(2),
bd(financeRow.metadata.get(3)));
case "Travel and subsistence":
return builder.withTravelAndSubsistence(
financeRow.metadata.get(0),
Integer.valueOf(financeRow.metadata.get(1)),
bd(financeRow.metadata.get(2)));
case "Other costs":
return builder.withOtherCosts(
financeRow.metadata.get(0),
bd(financeRow.metadata.get(1)));
case "Other funding":
return builder.withOtherFunding(
financeRow.metadata.get(0),
LocalDate.parse(financeRow.metadata.get(1), DATE_PATTERN),
bd(financeRow.metadata.get(2)));
default:
throw new RuntimeException("Unknown category " + financeRow.category);
}
}
private ApplicationFinanceDataBuilder generateIndustrialCostsFromSuppliedData(
ApplicationResource application,
CompetitionResource competition,
String user,
String organisationName,
CsvUtils.ApplicationOrganisationFinanceBlock organisationFinances) {
ApplicationFinanceDataBuilder finance = this.applicationFinanceDataBuilder.
withApplication(application).
withCompetition(competition).
withOrganisation(organisationName).
withUser(user);
List<CsvUtils.ApplicationFinanceRow> financeRows = organisationFinances.rows;
UnaryOperator<IndustrialCostDataBuilder> costBuilder = costs -> {
IndustrialCostDataBuilder costsWithData = costs;
for (CsvUtils.ApplicationFinanceRow financeRow : financeRows) {
costsWithData = addFinanceRow(costsWithData, financeRow);
}
return costsWithData;
};
return finance.
withIndustrialCosts(costBuilder);
}
private ApplicationFinanceDataBuilder generateIndustrialCosts(
ApplicationResource application,
CompetitionResource competition,
String user,
String organisationName,
OrganisationTypeEnum organisationType) {
LOG.info("In generateIndustrialCosts");
UnaryOperator<IndustrialCostDataBuilder> costBuilder = costs -> {
final IndustrialCostDataBuilder[] builder = {costs};
Consumer<? super FinanceRowType> costPopulator = type -> {
switch(type) {
case LABOUR:
builder[0] = builder[0].withWorkingDaysPerYear(123).
withLabourEntry("Role 1", 200, 200).
withLabourEntry("Role 2", 400, 300).
withLabourEntry("Role 3", 600, 365);
break;
case OVERHEADS:
builder[0] = builder[0].withAdministrationSupportCostsNone();
break;
case PROCUREMENT_OVERHEADS:
builder[0] = builder[0].withProcurementOverheads("procurement overhead" , 1000, 2000);
break;
case MATERIALS:
builder[0] = builder[0].withMaterials("Generator", bd("10020"), 10);
break;
case CAPITAL_USAGE:
builder[0] = builder[0].withCapitalUsage(12, "Depreciating Stuff", true, bd("2120"), bd("1200"), 60);
break;
case SUBCONTRACTING_COSTS:
builder[0] = builder[0].withSubcontractingCost("Developers", "UK", "To develop stuff", bd("90000"));
break;
case TRAVEL:
builder[0] = builder[0].withTravelAndSubsistence("To visit colleagues", 15, bd("398"));
break;
case OTHER_COSTS:
builder[0] = builder[0].withOtherCosts("Some more costs", bd("1100"));
break;
case VAT:
builder[0] = builder[0].withVat(true);
break;
case FINANCE:
if (!competition.isFullyFunded()) {
builder[0] = builder[0].withGrantClaim(BigDecimal.valueOf(30));
}
break;
case GRANT_CLAIM_AMOUNT:
builder[0] = builder[0].withGrantClaimAmount(12000);
break;
case OTHER_FUNDING:
if (!competition.isFullyFunded()) {
builder[0] = builder[0].withOtherFunding("Lottery", LocalDate.of(2016, 4, 1), bd("2468"));
}
break;
case YOUR_FINANCE:
//none for industrial costs.
break;
case ASSOCIATE_SALARY_COSTS:
builder[0] = builder[0].withAssociateSalaryCosts("role", 4, new BigInteger("6"));
break;
case ASSOCIATE_DEVELOPMENT_COSTS:
builder[0] = builder[0].withAssociateDevelopmentCosts("role", 4, new BigInteger("7"));
break;
case CONSUMABLES:
builder[0] = builder[0].withConsumables("item", new BigInteger("8"), 3);
break;
case ASSOCIATE_SUPPORT:
builder[0] = builder[0].withAssociateSupport("supp", new BigInteger("13"));
break;
case KNOWLEDGE_BASE:
builder[0] = builder[0].withKnowledgeBase("desc", new BigInteger("15"));
break;
case ESTATE_COSTS:
builder[0] = builder[0].withEstateCosts("desc", new BigInteger("16"));
break;
case KTP_TRAVEL:
builder[0] = builder[0].withKtpTravel(KtpTravelCost.KtpTravelCostType.ASSOCIATE, "desc", new BigDecimal("17.00"), 1);
break;
case ADDITIONAL_COMPANY_COSTS:
builder[0] = builder[0].withAdditionalCompanyCosts(AdditionalCompanyCost.AdditionalCompanyCostType.ASSOCIATE_SALARY, "desc", new BigInteger("18"));
break;
case PREVIOUS_FUNDING:
builder[0] = builder[0].withPreviousFunding("a", "b", "c", new BigDecimal("23"));
break;
case ACADEMIC_AND_SECRETARIAL_SUPPORT:
builder[0] = builder[0].withAcademicAndSecretarialSupport(new BigDecimal("18.00"));
break;
case INDIRECT_COSTS:
builder[0] = builder[0].withIndirectCosts(new BigDecimal("19.00"));
break;
}
};
if (competition.isKtp()) {
if (OrganisationTypeEnum.KNOWLEDGE_BASE == organisationType) {
getFinanceRowTypes(competition, true).forEach(costPopulator);
}
} else {
competition.getFinanceRowTypes().forEach(costPopulator);
if (TRUE.equals(competition.getIncludeProjectGrowthTable())) {
builder[0] = builder[0].withProjectGrowthTable(YearMonth.of(2020, 1),
60L,
new BigDecimal("100000"),
new BigDecimal("200000"),
new BigDecimal("300000"),
new BigDecimal("400000"));
} else {
builder[0] = builder[0].withEmployeesAndTurnover(50L,
new BigDecimal("700000"));
}
}
if (organisationType == OrganisationTypeEnum.KNOWLEDGE_BASE) {
return builder[0].withOrganisationSize(SMALL)
.withLocation()
.withFecEnabled(true)
.withUploadedFecFile();
} else {
return builder[0].withOrganisationSize(SMALL)
.withLocation();
}
};
return applicationFinanceDataBuilder.
withApplication(application).
withCompetition(competition).
withOrganisation(organisationName).
withUser(user).
withIndustrialCosts(costBuilder);
}
private List<FinanceRowType> getFinanceRowTypes(CompetitionResource competition, Boolean fecModelEnabled) {
return competition.getFinanceRowTypes().stream()
.filter(financeRowType -> BooleanUtils.isFalse(fecModelEnabled)
? !FinanceRowType.getFecSpecificFinanceRowTypes().contains(financeRowType)
: !FinanceRowType.getNonFecSpecificFinanceRowTypes().contains(financeRowType))
.collect(Collectors.toList());
}
private ApplicationFinanceDataBuilder generateAcademicFinances(
ApplicationResource application,
CompetitionResource competition,
String user,
String organisationName) {
return applicationFinanceDataBuilder.
withApplication(application).
withCompetition(competition).
withOrganisation(organisationName).
withUser(user).
withAcademicCosts(costs -> costs.
withTsbReference("My REF").
withGrantClaim(BigDecimal.valueOf(100)).
withOtherFunding("Lottery", LocalDate.of(2016, 4, 1), bd("2468")).
withDirectlyIncurredStaff(bd("22")).
withDirectlyIncurredTravelAndSubsistence(bd("44")).
withDirectlyIncurredOtherCosts(bd("66")).
withDirectlyAllocatedInvestigators(bd("88")).
withDirectlyAllocatedEstateCosts(bd("110")).
withDirectlyAllocatedOtherCosts(bd("132")).
withIndirectCosts(bd("154")).
withExceptionsStaff(bd("176")).
withExceptionsOtherCosts(bd("198")).
withUploadedJesForm().
withLocation());
}
private ApplicationFinanceDataBuilder generateAcademicFinancesFromSuppliedData(
ApplicationResource application,
CompetitionResource competition,
String user,
String organisationName) {
return applicationFinanceDataBuilder.
withApplication(application).
withCompetition(competition).
withOrganisation(organisationName).
withUser(user).
withAcademicCosts(costs -> costs.
withTsbReference("My REF").
withUploadedJesForm());
}
private BigDecimal bd(String value) {
return new BigDecimal(value);
}
}
|
package org.innovateuk.ifs.application.transactional;
import org.innovateuk.ifs.application.domain.Application;
import org.innovateuk.ifs.application.mapper.ApplicationMapper;
import org.innovateuk.ifs.application.repository.ApplicationRepository;
import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.category.domain.InnovationArea;
import org.innovateuk.ifs.category.mapper.InnovationAreaMapper;
import org.innovateuk.ifs.category.repository.InnovationAreaRepository;
import org.innovateuk.ifs.category.resource.InnovationAreaResource;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.transactional.BaseTransactionalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;
import static org.innovateuk.ifs.commons.error.CommonFailureKeys.GENERAL_FORBIDDEN;
import static org.innovateuk.ifs.commons.error.CommonFailureKeys.GENERAL_NOT_FOUND;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.util.EntityLookupCallbacks.find;
/**
* Transactional service implementation for linking an {@link Application} to an {@link InnovationArea}.
*/
@Service
public class ApplicationInnovationAreaServiceImpl extends BaseTransactionalService implements ApplicationInnovationAreaService {
@Autowired
private ApplicationRepository applicationRepository;
@Autowired
private InnovationAreaRepository innovationAreaRepository;
@Autowired
private ApplicationMapper applicationMapper;
@Autowired
private InnovationAreaMapper innovationAreaMapper;
@Override
public ServiceResult<ApplicationResource> setInnovationArea(Long applicationId, Long innovationAreaId) {
return find(application(applicationId)).andOnSuccess(application ->
findInnovationAreaInAllowedList(application, innovationAreaId).andOnSuccess(innovationArea ->
saveApplicationWithInnovationArea(application, innovationArea))).andOnSuccess(application -> serviceSuccess(applicationMapper.mapToResource(application)));
}
@Override
public ServiceResult<ApplicationResource> setNoInnovationAreaApplies(Long applicationId) {
return find(application(applicationId)).andOnSuccess(this::saveWithNoInnovationAreaApplies)
.andOnSuccess(application -> serviceSuccess(applicationMapper.mapToResource(application)));
}
@Override
public ServiceResult<List<InnovationAreaResource>> getAvailableInnovationAreas(Long applicationId) {
return find(application(applicationId)).andOnSuccess(this::getAllowedInnovationAreas)
.andOnSuccess(areas -> serviceSuccess(innovationAreaMapper.mapToResource(areas)));
}
private ServiceResult<InnovationArea> findInnovationAreaInAllowedList(Application application, Long innovationAreaId) {
return getAllowedInnovationAreas(application).andOnSuccess(areas ->
findInnovationAreaInList(areas, innovationAreaId));
}
private ServiceResult<List<InnovationArea>> getAllowedInnovationAreas(Application application) {
if (application.getCompetition() !=null
&& application.getCompetition().getInnovationSector() !=null
&& application.getCompetition().getInnovationSector().getChildren() !=null) {
return serviceSuccess(application.getCompetition().getInnovationAreas()
.stream()
.sorted(comparing(InnovationArea::getName))
.collect(toList()));
} else {
return serviceFailure(GENERAL_NOT_FOUND);
}
}
private ServiceResult<InnovationArea> findInnovationAreaInList(List<InnovationArea> innovationAreasList, Long innovationAreaId) {
Optional<InnovationArea> allowedInnovationArea = innovationAreasList.stream().filter(area ->
area.getId().equals(innovationAreaId)).findAny();
if (allowedInnovationArea.isPresent()) {
return serviceSuccess(allowedInnovationArea.get());
}
else {
return serviceFailure(GENERAL_FORBIDDEN);
}
}
private ServiceResult<Application> saveWithNoInnovationAreaApplies(Application application) {
application.setInnovationArea(null);
application.setNoInnovationAreaApplicable(true);
return serviceSuccess(applicationRepository.save(application));
}
private ServiceResult<Application> saveApplicationWithInnovationArea(Application application, InnovationArea innovationArea) {
application.setNoInnovationAreaApplicable(false);
application.setInnovationArea(innovationArea);
return serviceSuccess(applicationRepository.save(application));
}
}
|
package org.jenkinsci.plugins.pipeline.maven.listeners;
import hudson.Extension;
import hudson.console.ModelHyperlinkNote;
import hudson.model.CauseAction;
import hudson.model.Job;
import hudson.model.Queue;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.model.listeners.RunListener;
import jenkins.model.Jenkins;
import jenkins.model.ParameterizedJobMixIn;
import org.jenkinsci.plugins.pipeline.maven.GlobalPipelineMavenConfig;
import org.jenkinsci.plugins.pipeline.maven.MavenArtifact;
import org.jenkinsci.plugins.pipeline.maven.cause.MavenDependencyCauseHelper;
import org.jenkinsci.plugins.pipeline.maven.cause.MavenDependencyUpstreamCause;
import org.jenkinsci.plugins.pipeline.maven.trigger.WorkflowJobDependencyTrigger;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.inject.Inject;
/**
* Trigger downstream pipelines.
*
* @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
*/
@Extension
public class DownstreamPipelineTriggerRunListener extends RunListener<WorkflowRun> {
private final static Logger LOGGER = Logger.getLogger(DownstreamPipelineTriggerRunListener.class.getName());
@Inject
public GlobalPipelineMavenConfig globalPipelineMavenConfig;
@Override
public void onCompleted(WorkflowRun upstreamBuild, @Nonnull TaskListener listener) {
LOGGER.log(Level.FINER, "onCompleted({0})", new Object[]{upstreamBuild});
long startTimeInNanos = System.nanoTime();
if(LOGGER.isLoggable(Level.FINER)) {
listener.getLogger().println("[withMaven] pipelineGraphPublisher - triggerDownstreamPipelines");
}
if (!globalPipelineMavenConfig.getTriggerDownstreamBuildsResultsCriteria().contains(upstreamBuild.getResult())) {
if (LOGGER.isLoggable(Level.FINER)) {
listener.getLogger().println("[withMaven] Skip triggering downstream jobs for upstream build with ignored result status " + upstreamBuild + ": " + upstreamBuild.getResult());
}
return;
}
try {
this.globalPipelineMavenConfig.getPipelineTriggerService().checkNoInfiniteLoopOfUpstreamCause(upstreamBuild);
} catch (IllegalStateException e) {
listener.getLogger().println("[withMaven] WARNING abort infinite build trigger loop. Please consider opening a Jira issue: " + e.getMessage());
return;
}
WorkflowJob upstreamPipeline = upstreamBuild.getParent();
String upstreamPipelineFullName = upstreamPipeline.getFullName();
int upstreamBuildNumber = upstreamBuild.getNumber();
Map<MavenArtifact, SortedSet<String>> downstreamPipelinesByArtifact = globalPipelineMavenConfig.getDao().listDownstreamJobsByArtifact(upstreamPipelineFullName, upstreamBuildNumber);
Map<String, Set<MavenArtifact>> jobsToTrigger = new TreeMap<>();
// build the list of pipelines to trigger
for(Map.Entry<MavenArtifact, SortedSet<String>> entry: downstreamPipelinesByArtifact.entrySet()) {
MavenArtifact mavenArtifact = entry.getKey();
SortedSet<String> downstreamPipelines = entry.getValue();
downstreamPipelinesLoop:
for (String downstreamPipelineFullName : downstreamPipelines) {
if (jobsToTrigger.containsKey(downstreamPipelineFullName)) {
// downstream pipeline has already been added to the list of pipelines to trigger,
// we have already verified that it's meeting requirements (not an infinite loop, authorized by security, not excessive triggering, buildable...)
if (LOGGER.isLoggable(Level.FINEST)) {
listener.getLogger().println("[withMaven - DownstreamPipelineTriggerRunListener] Skip eligibility check of pipeline " + downstreamPipelineFullName + " for artifact " + mavenArtifact.getShortDescription() + ", eligibility already confirmed");
}
Set<MavenArtifact> mavenArtifacts = jobsToTrigger.get(downstreamPipelineFullName);
if (mavenArtifacts == null) {
listener.getLogger().println("[withMaven - DownstreamPipelineTriggerRunListener] Invalid state, no artifacts found for pipeline '" + downstreamPipelineFullName + "' while evaluating " + mavenArtifact.getShortDescription());
} else {
mavenArtifacts.add(mavenArtifact);
}
continue;
}
if (Objects.equals(downstreamPipelineFullName, upstreamPipelineFullName)) {
// Don't trigger myself
continue;
}
final WorkflowJob downstreamPipeline = Jenkins.getInstance().getItemByFullName(downstreamPipelineFullName, WorkflowJob.class);
if (downstreamPipeline == null || downstreamPipeline.getLastBuild() == null) {
LOGGER.log(Level.FINE, "Downstream pipeline {0} or downstream pipeline last build not found from upstream build {1}. Database synchronization issue or security restriction?",
new Object[]{downstreamPipelineFullName, upstreamBuild.getFullDisplayName(), Jenkins.getAuthentication()});
continue;
}
int downstreamBuildNumber = downstreamPipeline.getLastBuild().getNumber();
Map<MavenArtifact, SortedSet<String>> downstreamDownstreamPipelinesByArtifact = globalPipelineMavenConfig.getDao().listDownstreamJobsByArtifact(downstreamPipelineFullName, downstreamBuildNumber);
for (Map.Entry<MavenArtifact, SortedSet<String>> entry2 : downstreamDownstreamPipelinesByArtifact.entrySet()) {
SortedSet<String> downstreamDownstreamPipelines = entry2.getValue();
if (downstreamDownstreamPipelines.contains(upstreamPipelineFullName)) {
listener.getLogger().println("[withMaven] Infinite loop detected: skip triggering " + ModelHyperlinkNote.encodeTo(downstreamPipeline) + " " +
" (dependency: " + mavenArtifact.getShortDescription() + ") because it is itself triggering this pipeline " +
ModelHyperlinkNote.encodeTo(upstreamPipeline) + " (dependency: " + entry2.getKey().getShortDescription() + ")");
// prevent infinite loop
continue downstreamPipelinesLoop;
}
}
// Avoid excessive triggering
// See #46313
Map<String, Integer> transitiveUpstreamPipelines = globalPipelineMavenConfig.getDao().listTransitiveUpstreamJobs(downstreamPipelineFullName, downstreamBuildNumber);
for (String transitiveUpstreamPipelineName : transitiveUpstreamPipelines.keySet()) {
// Skip if one of the downstream's upstream is already building or in queue
// Then it will get triggered anyway by that upstream, we don't need to trigger it again
WorkflowJob transitiveUpstreamPipeline = Jenkins.getInstance().getItemByFullName(transitiveUpstreamPipelineName, WorkflowJob.class);
if (transitiveUpstreamPipeline == null) {
// security: not allowed to view this transitive upstream pipeline, continue to loop
continue;
} else if (transitiveUpstreamPipeline.getFullName().equals(upstreamPipeline.getFullName())) {
// this upstream pipeline of the current downstreamPipeline is the upstream pipeline itself, continue to loop
continue;
} else if (transitiveUpstreamPipeline.isBuilding()) {
listener.getLogger().println("[withMaven] Skip triggering " + ModelHyperlinkNote.encodeTo(downstreamPipeline) +
" because it has a dependency already building: " + ModelHyperlinkNote.encodeTo(transitiveUpstreamPipeline));
continue downstreamPipelinesLoop;
} else if (transitiveUpstreamPipeline.isInQueue()) {
listener.getLogger().println("[withMaven] Skip triggering " + ModelHyperlinkNote.encodeTo(downstreamPipeline) +
" because it has a dependency already building or in queue: " + ModelHyperlinkNote.encodeTo(transitiveUpstreamPipeline));
continue downstreamPipelinesLoop;
} else if (downstreamPipelines.contains(transitiveUpstreamPipelineName)) {
// Skip if this downstream pipeline will be triggered by another one of our downstream pipelines
// That's the case when one of the downstream's transitive upstream is our own downstream
listener.getLogger().println("[withMaven] Skip triggering " + ModelHyperlinkNote.encodeTo(downstreamPipeline) +
" because it has a dependency on a pipeline that will be triggered by this build: " + ModelHyperlinkNote.encodeTo(transitiveUpstreamPipeline));
continue downstreamPipelinesLoop;
}
}
if (!downstreamPipeline.isBuildable()) {
LOGGER.log(Level.FINE, "Skip triggering of non buildable (disabled: {0}, isHoldOffBuildUntilSave: {1}) downstream pipeline {2} from upstream build {3}",
new Object[]{downstreamPipeline.isDisabled(), downstreamPipeline.isHoldOffBuildUntilSave(), downstreamPipeline.getFullName(), upstreamBuild.getFullDisplayName()});
continue;
}
WorkflowJobDependencyTrigger downstreamPipelineTrigger = this.globalPipelineMavenConfig.getPipelineTriggerService().getWorkflowJobDependencyTrigger(downstreamPipeline);
if (downstreamPipelineTrigger == null) {
LOGGER.log(Level.FINE, "Skip triggering of downstream pipeline {0} from upstream build {1}: dependency trigger not configured", new Object[]{downstreamPipeline.getFullName(), upstreamBuild.getFullDisplayName()});
continue;
}
boolean downstreamVisibleByUpstreamBuildAuth = this.globalPipelineMavenConfig.getPipelineTriggerService().isDownstreamVisibleByUpstreamBuildAuth(downstreamPipeline);
boolean upstreamVisibleByDownstreamBuildAuth = this.globalPipelineMavenConfig.getPipelineTriggerService().isUpstreamBuildVisibleByDownstreamBuildAuth(upstreamPipeline, downstreamPipeline);
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.log(Level.FINER,
"upstreamPipeline (" + upstreamPipelineFullName + ", visibleByDownstreamBuildAuth: " + upstreamVisibleByDownstreamBuildAuth + "), " +
" downstreamPipeline (" + downstreamPipeline.getFullName() + ", visibleByUpstreamBuildAuth: " + downstreamVisibleByUpstreamBuildAuth + "), " +
"upstreamBuildAuth: " + Jenkins.getAuthentication());
}
if (downstreamVisibleByUpstreamBuildAuth && upstreamVisibleByDownstreamBuildAuth) {
Set<MavenArtifact> mavenArtifacts = jobsToTrigger.get(downstreamPipelineFullName);
if (mavenArtifacts == null) {
mavenArtifacts = new TreeSet<>();
jobsToTrigger.put(downstreamPipelineFullName, mavenArtifacts);
}
if(mavenArtifacts.contains(mavenArtifact)) {
// TODO display warning
} else {
mavenArtifacts.add(mavenArtifact);
}
} else {
LOGGER.log(Level.FINE, "Skip triggering of {0} by {1}: downstreamVisibleByUpstreamBuildAuth: {2}, upstreamVisibleByDownstreamBuildAuth: {3}",
new Object[]{downstreamPipeline.getFullName(), upstreamBuild.getFullDisplayName(), downstreamVisibleByUpstreamBuildAuth, upstreamVisibleByDownstreamBuildAuth});
}
}
}
// trigger the pipelines
for (Map.Entry<String, Set<MavenArtifact>> entry: jobsToTrigger.entrySet()) {
String downstreamJobFullName = entry.getKey();
Job downstreamJob = Jenkins.getInstance().getItemByFullName(downstreamJobFullName, Job.class);
if (downstreamJob == null) {
listener.getLogger().println("[withMaven] Illegal state: " + downstreamJobFullName + " not resolved");
continue;
}
Set<MavenArtifact> mavenArtifacts = entry.getValue();
// See jenkins.triggers.ReverseBuildTrigger.RunListenerImpl.onCompleted(Run, TaskListener)
MavenDependencyUpstreamCause cause = new MavenDependencyUpstreamCause(upstreamBuild, mavenArtifacts);
Run downstreamJobLastBuild = downstreamJob.getLastBuild();
if (downstreamJobLastBuild == null) {
// should never happen, we need at least one build to know the dependencies
} else {
List<MavenArtifact> matchingMavenDependencies = MavenDependencyCauseHelper.isSameCause(cause, downstreamJobLastBuild.getCauses());
if (matchingMavenDependencies.size() > 0) {
downstreamJobLastBuild.addAction(new CauseAction(cause));
listener.getLogger().println("[withMaven] Skip triggering downstream pipeline " + ModelHyperlinkNote.encodeTo(downstreamJob) + " as it was already triggered for Maven dependencies: " +
matchingMavenDependencies.stream().map(mavenDependency -> mavenDependency == null ? null : mavenDependency.getShortDescription()).collect(Collectors.joining(", ")));
try {
downstreamJobLastBuild.save();
} catch (IOException e) {
listener.getLogger().println("[withMaven] Failure to update build " + downstreamJobLastBuild.getFullDisplayName() + ": " + e.toString());
}
continue;
}
}
Queue.Item queuedItem = ParameterizedJobMixIn.scheduleBuild2(downstreamJob, -1, new CauseAction(cause));
String dependenciesMessage = cause.getMavenArtifactsDescription();
if (queuedItem == null) {
listener.getLogger().println("[withMaven] Skip triggering downstream pipeline " + ModelHyperlinkNote.encodeTo(downstreamJob) + " due to dependencies on " +
dependenciesMessage + ", invocation rejected.");
} else {
listener.getLogger().println("[withMaven] Triggering downstream pipeline " + ModelHyperlinkNote.encodeTo(downstreamJob) + "#" + downstreamJob.getNextBuildNumber() + " due to dependency on " +
dependenciesMessage + " ...");
}
}
long durationInMillis = TimeUnit.MILLISECONDS.convert(System.nanoTime() - startTimeInNanos, TimeUnit.NANOSECONDS);
if (durationInMillis > TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS) || LOGGER.isLoggable(Level.FINE)) {
listener.getLogger().println("[withMaven] triggerDownstreamPipelines completed in " + durationInMillis + " ms");
}
}
}
|
package org.eclipse.kura.linux.position;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.kura.comm.CommConnection;
import org.eclipse.kura.core.testutil.TestUtil;
import org.eclipse.kura.net.modem.ModemGpsEnabledEvent;
import org.eclipse.kura.position.PositionLockedEvent;
import org.eclipse.kura.usb.UsbDeviceAddedEvent;
import org.eclipse.kura.usb.UsbDeviceRemovedEvent;
import org.eclipse.kura.usb.UsbService;
import org.eclipse.kura.usb.UsbTtyDevice;
import org.junit.Test;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.service.event.EventHandler;
import org.osgi.service.io.ConnectionFactory;
public class PositionServiceTest {
private static final double EPS = 0.000001;
@Test
public void testActivateStatic() {
PositionServiceImpl ps = new PositionServiceImpl();
EventAdmin eventAdminMock = mock(EventAdmin.class);
ps.setEventAdmin(eventAdminMock);
BundleContext bundleContextMock = mock(BundleContext.class);
when(bundleContextMock.registerService(eq(EventHandler.class.getName()), anyObject(), anyObject()))
.thenReturn(null);
ComponentContext ctxMock = mock(ComponentContext.class);
when(ctxMock.getBundleContext()).thenReturn(bundleContextMock);
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("enabled", true);
properties.put("static", true);
properties.put("longitude", 15.0);
properties.put("latitude", 46.0);
properties.put("altitude", 300.0);
ps.activate(ctxMock, properties);
verify(eventAdminMock, times(1)).postEvent((PositionLockedEvent) anyObject());
ps.deactivate(ctxMock);
}
@Test
public void testActivateDefault() throws IOException {
PositionServiceImpl ps = new PositionServiceImpl();
EventAdmin eventAdminMock = mock(EventAdmin.class);
ps.setEventAdmin(eventAdminMock);
UsbService usbServiceMock = mock(UsbService.class);
ps.setUsbService(usbServiceMock);
List<UsbTtyDevice> usbDevices = new ArrayList<UsbTtyDevice>();
UsbTtyDevice usbDev = mock(UsbTtyDevice.class);
when(usbDev.getUsbPort()).thenReturn("port");
when(usbDev.getDeviceNode()).thenReturn("node");
usbDevices.add(usbDev);
when(usbServiceMock.getUsbTtyDevices()).thenReturn(usbDevices);
ConnectionFactory connFactoryMock = mock(ConnectionFactory.class);
CommConnection connMock = mock(CommConnection.class);
when(connFactoryMock.createConnection(anyString(), eq(1), eq(false))).thenReturn(connMock);
ps.setConnectionFactory(connFactoryMock);
BundleContext bundleContextMock = mock(BundleContext.class);
when(bundleContextMock.registerService(eq(EventHandler.class.getName()), anyObject(), anyObject()))
.thenReturn(null);
ComponentContext ctxMock = mock(ComponentContext.class);
when(ctxMock.getBundleContext()).thenReturn(bundleContextMock);
InputStream is = new ByteArrayInputStream("".getBytes());
when(connMock.openInputStream()).thenReturn(is);
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("enabled", true);
properties.put("static", false);
properties.put("port", "port");
properties.put("baudRate", 9600);
properties.put("stopBits", 0);
properties.put("parity", 0);
properties.put("bitsPerWord", 1);
ps.activate(ctxMock, properties);
assertFalse(ps.isLocked());
assertNotNull(ps.getPosition());
assertEquals(0.0, ps.getPosition().getLatitude().getValue(), EPS);
assertEquals(0.0, ps.getPosition().getLongitude().getValue(), EPS);
assertEquals(0.0, ps.getPosition().getAltitude().getValue(), EPS);
ps.deactivate(ctxMock);
}
@Test
public void testActivateDeactivate() throws IOException, InterruptedException {
PositionServiceImpl ps = new PositionServiceImpl();
EventAdmin eventAdminMock = mock(EventAdmin.class);
ps.setEventAdmin(eventAdminMock);
UsbService usbServiceMock = mock(UsbService.class);
ps.setUsbService(usbServiceMock);
List<UsbTtyDevice> usbDevices = new ArrayList<UsbTtyDevice>();
UsbTtyDevice usbDev = mock(UsbTtyDevice.class);
when(usbDev.getUsbPort()).thenReturn("port");
when(usbDev.getDeviceNode()).thenReturn("node");
usbDevices.add(usbDev);
when(usbServiceMock.getUsbTtyDevices()).thenReturn(usbDevices);
ConnectionFactory connFactoryMock = mock(ConnectionFactory.class);
CommConnection connMock = mock(CommConnection.class);
when(connFactoryMock.createConnection(anyString(), eq(1), eq(false))).thenReturn(connMock);
ps.setConnectionFactory(connFactoryMock);
BundleContext bundleContextMock = mock(BundleContext.class);
when(bundleContextMock.registerService(eq(EventHandler.class.getName()), anyObject(), anyObject()))
.thenReturn(null);
ComponentContext ctxMock = mock(ComponentContext.class);
when(ctxMock.getBundleContext()).thenReturn(bundleContextMock);
String nmeaStr = "$GPGGA,121041.000,4655.3772,N,01513.6390,E,1,06,1.7,478.3,M,44.7,M,,0000*5d\n";
InputStream is = new ByteArrayInputStream(nmeaStr.getBytes());
when(connMock.openInputStream()).thenReturn(is);
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("enabled", true);
properties.put("static", false);
properties.put("port", "port");
properties.put("baudRate", 9600);
properties.put("stopBits", 0);
properties.put("parity", 0);
properties.put("bitsPerWord", 1);
final Object o = new Object();
doAnswer(invocation -> {
synchronized (o) {
o.notifyAll();
}
return null;
}).when(eventAdminMock).postEvent(anyObject());
ps.activate(ctxMock, properties);
// it takes some time for the event to be sent...
synchronized (o) {
o.wait(10000);
}
verify(eventAdminMock, times(1)).postEvent(anyObject());
assertTrue(ps.isLocked());
assertNotNull(ps.getNmeaPosition());
assertEquals(46.922953, ps.getNmeaPosition().getLatitude(), 0.000001);
ps.deactivate(ctxMock);
assertFalse(ps.isLocked());
}
@Test
public void testHandleEventUsb() throws IOException, NoSuchFieldException {
PositionServiceImpl ps = new PositionServiceImpl();
EventAdmin eventAdminMock = mock(EventAdmin.class);
ps.setEventAdmin(eventAdminMock);
UsbService usbServiceMock = mock(UsbService.class);
ps.setUsbService(usbServiceMock);
List<UsbTtyDevice> usbDevices = new ArrayList<UsbTtyDevice>();
UsbTtyDevice usbDev = mock(UsbTtyDevice.class);
when(usbDev.getUsbPort()).thenReturn("port").thenReturn("port");
when(usbDev.getDeviceNode()).thenReturn("node").thenReturn("node");
usbDevices.add(usbDev);
when(usbServiceMock.getUsbTtyDevices()).thenReturn(usbDevices).thenReturn(usbDevices).thenReturn(usbDevices)
.thenReturn(new ArrayList<UsbTtyDevice>());
ConnectionFactory connFactoryMock = mock(ConnectionFactory.class);
CommConnection connMock = mock(CommConnection.class);
when(connFactoryMock.createConnection(anyString(), eq(1), eq(false))).thenReturn(connMock);
ps.setConnectionFactory(connFactoryMock);
BundleContext bundleContextMock = mock(BundleContext.class);
when(bundleContextMock.registerService(eq(EventHandler.class.getName()), anyObject(), anyObject()))
.thenReturn(null);
ComponentContext ctxMock = mock(ComponentContext.class);
when(ctxMock.getBundleContext()).thenReturn(bundleContextMock);
InputStream is = new ByteArrayInputStream("".getBytes());
when(connMock.openInputStream()).thenReturn(is);
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("enabled", true);
properties.put("static", false);
properties.put("port", "port");
properties.put("baudRate", 9600);
properties.put("stopBits", 0);
properties.put("parity", 0);
properties.put("bitsPerWord", 1);
ps.activate(ctxMock, properties);
TestUtil.setFieldValue(ps, "isRunning", false);
String topic = UsbDeviceAddedEvent.USB_EVENT_DEVICE_ADDED_TOPIC;
properties = new HashMap<String, Object>();
Event event = new Event(topic, properties);
ps.handleEvent(event);
assertTrue((boolean) TestUtil.getFieldValue(ps, "isRunning"));
topic = UsbDeviceRemovedEvent.USB_EVENT_DEVICE_REMOVED_TOPIC;
properties = new HashMap<String, Object>();
event = new Event(topic, properties);
ps.handleEvent(event);
assertFalse((boolean) TestUtil.getFieldValue(ps, "isRunning"));
assertFalse(ps.isLocked());
ps.deactivate(ctxMock);
}
@Test
public void testHandleEventModem() throws IOException, NoSuchFieldException {
PositionServiceImpl ps = new PositionServiceImpl();
EventAdmin eventAdminMock = mock(EventAdmin.class);
ps.setEventAdmin(eventAdminMock);
UsbService usbServiceMock = mock(UsbService.class);
ps.setUsbService(usbServiceMock);
List<UsbTtyDevice> usbDevices = new ArrayList<UsbTtyDevice>();
UsbTtyDevice usbDev = mock(UsbTtyDevice.class);
when(usbDev.getUsbPort()).thenReturn("port").thenReturn("port");
when(usbDev.getDeviceNode()).thenReturn("node").thenReturn("node");
usbDevices.add(usbDev);
when(usbServiceMock.getUsbTtyDevices()).thenReturn(usbDevices).thenReturn(usbDevices).thenReturn(usbDevices)
.thenReturn(new ArrayList<UsbTtyDevice>());
ConnectionFactory connFactoryMock = mock(ConnectionFactory.class);
CommConnection connMock = mock(CommConnection.class);
when(connFactoryMock.createConnection(anyString(), eq(1), eq(false))).thenReturn(connMock);
ps.setConnectionFactory(connFactoryMock);
BundleContext bundleContextMock = mock(BundleContext.class);
when(bundleContextMock.registerService(eq(EventHandler.class.getName()), anyObject(), anyObject()))
.thenReturn(null);
ComponentContext ctxMock = mock(ComponentContext.class);
when(ctxMock.getBundleContext()).thenReturn(bundleContextMock);
InputStream is = new ByteArrayInputStream("".getBytes());
when(connMock.openInputStream()).thenReturn(is);
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("enabled", true);
properties.put("static", false);
properties.put("port", "port");
properties.put("baudRate", 9600);
properties.put("stopBits", 0);
properties.put("parity", 0);
properties.put("bitsPerWord", 1);
ps.activate(ctxMock, properties);
TestUtil.setFieldValue(ps, "isRunning", false);
String topic = ModemGpsEnabledEvent.MODEM_EVENT_GPS_ENABLED_TOPIC;
properties = new HashMap<String, Object>();
properties.put("enabled", true);
properties.put("static", false);
properties.put("port", "portt");
properties.put("baudRate", 19200);
properties.put("stopBits", 1);
properties.put("parity", 1);
properties.put("bitsPerWord", 8);
Event event = new Event(topic, properties);
ps.handleEvent(event);
Map<String, Object> props = (Map<String, Object>) TestUtil.getFieldValue(ps, "properties");
assertEquals("portt", properties.get("port"));
assertEquals(19200, properties.get("baudRate"));
assertEquals(1, properties.get("stopBits"));
assertEquals(1, properties.get("parity"));
assertEquals(8, properties.get("bitsPerWord"));
}
}
|
package flounder.post;
import flounder.fbos.*;
import flounder.helpers.*;
import flounder.loaders.*;
import flounder.resources.*;
import flounder.shaders.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL20.*;
/**
* Represents a post effect shader and on application saves the result into a FBO.
*/
public abstract class PostFilter {
public static final MyFile POST_LOC = new MyFile(FlounderShaders.SHADERS_LOC, "filters");
public static final MyFile VERTEX_LOCATION = new MyFile(POST_LOC, "defaultVertex.glsl");
private static float[] POSITIONS = {0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f};
private static int VAO = FlounderLoader.createInterleavedVAO(POSITIONS, 2);
public ShaderObject shader;
public FBO fbo;
public PostFilter(String filterName, MyFile fragmentShader) {
this(ShaderFactory.newBuilder().setName(filterName).addType(new ShaderType(GL_VERTEX_SHADER, VERTEX_LOCATION)).addType(new ShaderType(GL_FRAGMENT_SHADER, fragmentShader)).create(), FBO.newFBO(1.0f).disableTextureWrap().create());
}
public PostFilter(ShaderObject shader) {
this(shader, FBO.newFBO(1.0f).disableTextureWrap().create());
}
public PostFilter(ShaderObject shader, FBO fbo) {
this.shader = shader;
this.fbo = fbo;
}
/**
* Renders the filter to its FBO.
*
* @param textures A list of textures in indexed order to be bound for the shader program.
*/
public void applyFilter(int... textures) {
if (!shader.isLoaded()) {
return;
}
boolean lastWireframe = OpenGlUtils.isInWireframe();
fbo.bindFrameBuffer();
OpenGlUtils.prepareNewRenderParse(1.0f, 1.0f, 1.0f);
shader.start();
storeValues();
OpenGlUtils.antialias(false);
OpenGlUtils.disableDepthTesting();
OpenGlUtils.cullBackFaces(true);
OpenGlUtils.goWireframe(false);
OpenGlUtils.bindVAO(VAO, 0);
for (int i = 0; i < textures.length; i++) {
OpenGlUtils.bindTexture(textures[i], GL_TEXTURE_2D, i);
}
glDrawArrays(GL_TRIANGLE_STRIP, 0, POSITIONS.length); // Render post filter.
OpenGlUtils.unbindVAO(0);
OpenGlUtils.goWireframe(lastWireframe);
shader.stop();
OpenGlUtils.disableBlending();
OpenGlUtils.enableDepthTesting();
fbo.unbindFrameBuffer();
}
/**
* Can be used to store values into the shader, this is called when the filter is applied and the shader has been already started.
*/
public abstract void storeValues();
/**
* Cleans up all of the filter processes and images.
*/
public void dispose() {
fbo.delete();
shader.delete();
}
}
|
package org.nuxeo.ecm.platform.picture;
import static org.nuxeo.ecm.platform.picture.api.ImagingConvertConstants.CONVERSION_FORMAT;
import static org.nuxeo.ecm.platform.picture.api.ImagingConvertConstants.JPEG_CONVERSATION_FORMAT;
import static org.nuxeo.ecm.platform.picture.api.ImagingConvertConstants.OPERATION_RESIZE;
import static org.nuxeo.ecm.platform.picture.api.ImagingConvertConstants.OPTION_RESIZE_DEPTH;
import static org.nuxeo.ecm.platform.picture.api.ImagingConvertConstants.OPTION_RESIZE_HEIGHT;
import static org.nuxeo.ecm.platform.picture.api.ImagingConvertConstants.OPTION_RESIZE_WIDTH;
import java.awt.Point;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.ecm.core.api.Blob;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.blobholder.BlobHolder;
import org.nuxeo.ecm.core.api.blobholder.SimpleBlobHolder;
import org.nuxeo.ecm.core.api.impl.blob.BlobWrapper;
import org.nuxeo.ecm.core.api.impl.blob.FileBlob;
import org.nuxeo.ecm.core.convert.api.ConversionService;
import org.nuxeo.ecm.platform.commandline.executor.api.CommandException;
import org.nuxeo.ecm.platform.commandline.executor.api.CommandNotAvailable;
import org.nuxeo.ecm.platform.mimetype.interfaces.MimetypeRegistry;
import org.nuxeo.ecm.platform.picture.api.BlobHelper;
import org.nuxeo.ecm.platform.picture.api.ImageInfo;
import org.nuxeo.ecm.platform.picture.api.ImagingConfigurationDescriptor;
import org.nuxeo.ecm.platform.picture.api.ImagingService;
import org.nuxeo.ecm.platform.picture.api.PictureTemplate;
import org.nuxeo.ecm.platform.picture.api.PictureView;
import org.nuxeo.ecm.platform.picture.api.PictureViewImpl;
import org.nuxeo.ecm.platform.picture.core.libraryselector.LibrarySelector;
import org.nuxeo.ecm.platform.picture.magick.utils.ImageIdentifier;
import org.nuxeo.runtime.api.Framework;
import org.nuxeo.runtime.model.ComponentInstance;
import org.nuxeo.runtime.model.DefaultComponent;
public class ImagingComponent extends DefaultComponent implements
ImagingService {
private static final Log log = LogFactory.getLog(ImagingComponent.class);
public static final String CONFIGURATION_PARAMETERS_EP = "configuration";
protected Map<String, String> configurationParameters = new HashMap<String, String>();
private LibrarySelector librarySelector;
@Override
public Blob crop(Blob blob, int x, int y, int width, int height) {
try {
return getLibrarySelectorService().getImageUtils().crop(blob, x, y,
width, height);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return blob;
}
@Override
public Blob resize(Blob blob, String finalFormat, int width, int height,
int depth) {
try {
return getLibrarySelectorService().getImageUtils().resize(blob,
finalFormat, width, height, depth);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return blob;
}
@Override
public Blob rotate(Blob blob, int angle) {
try {
return getLibrarySelectorService().getImageUtils().rotate(blob,
angle);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return blob;
}
@Override
public Map<String, Object> getImageMetadata(Blob blob) {
try {
return getLibrarySelectorService().getMetadataUtils().getImageMetadata(
blob);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
@Override
public String getImageMimeType(File file) {
try {
MimetypeRegistry mimetypeRegistry = Framework.getLocalService(MimetypeRegistry.class);
if (file.getName() != null) {
return mimetypeRegistry.getMimetypeFromFilenameAndBlobWithDefault(
file.getName(), new FileBlob(file), "image/jpeg");
} else {
return mimetypeRegistry.getMimetypeFromFile(file);
}
} catch (Exception e) {
log.error("Unable to retrieve mime type", e);
}
return null;
}
@Override
public String getImageMimeType(Blob blob) {
try {
MimetypeRegistry mimetypeRegistry = Framework.getLocalService(MimetypeRegistry.class);
if (blob.getFilename() != null) {
return mimetypeRegistry.getMimetypeFromFilenameAndBlobWithDefault(
blob.getFilename(), blob, "image/jpeg");
} else {
return mimetypeRegistry.getMimetypeFromBlob(blob);
}
} catch (Exception e) {
log.error("Unable to retrieve mime type", e);
}
return null;
}
@Override
@Deprecated
public String getImageMimeType(InputStream in) {
try {
return getLibrarySelectorService().getMimeUtils().getImageMimeType(
in);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
private LibrarySelector getLibrarySelectorService() throws ClientException {
if (librarySelector == null) {
librarySelector = Framework.getRuntime().getService(
LibrarySelector.class);
}
if (librarySelector == null) {
log.error("Unable to get LibrarySelector runtime service");
throw new ClientException(
"Unable to get LibrarySelector runtime service");
}
return librarySelector;
}
@Override
public ImageInfo getImageInfo(Blob blob) {
ImageInfo imageInfo = null;
File tmpFile = null;
try {
File file = BlobHelper.getFileFromBlob(blob);
if (file == null) {
tmpFile = File.createTempFile(
"nuxeoImageInfo",
blob.getFilename() != null ? "."
+ FilenameUtils.getExtension(blob.getFilename())
: ".tmp");
blob.transferTo(tmpFile);
file = tmpFile;
}
imageInfo = ImageIdentifier.getInfo(file.getAbsolutePath());
} catch (CommandNotAvailable | CommandException e) {
log.error("Failed to get ImageInfo for file " + blob.getFilename(),
e);
} catch (IOException e) {
log.error("Failed to transfer file " + blob.getFilename(), e);
} finally {
if (tmpFile != null) {
tmpFile.delete();
}
}
return imageInfo;
}
@Override
public void registerContribution(Object contribution,
String extensionPoint, ComponentInstance contributor)
throws Exception {
if (CONFIGURATION_PARAMETERS_EP.equals(extensionPoint)) {
ImagingConfigurationDescriptor desc = (ImagingConfigurationDescriptor) contribution;
configurationParameters.putAll(desc.getParameters());
}
}
@Override
public void unregisterContribution(Object contribution,
String extensionPoint, ComponentInstance contributor)
throws Exception {
if (CONFIGURATION_PARAMETERS_EP.equals(extensionPoint)) {
ImagingConfigurationDescriptor desc = (ImagingConfigurationDescriptor) contribution;
for (String configuration : desc.getParameters().keySet()) {
configurationParameters.remove(configuration);
}
}
}
@Override
public String getConfigurationValue(String configurationName) {
return configurationParameters.get(configurationName);
}
@Override
public String getConfigurationValue(String configurationName,
String defaultValue) {
return configurationParameters.containsKey(configurationName) ? configurationParameters.get(configurationName)
: defaultValue;
}
@Override
public void setConfigurationValue(String configurationName,
String configurationValue) {
configurationParameters.put(configurationName, configurationValue);
}
@Override
public PictureView computeViewFor(Blob blob,
PictureTemplate pictureTemplate, boolean convert)
throws IOException, ClientException {
return computeViewFor(blob, pictureTemplate, null, convert);
}
@Override
public PictureView computeViewFor(Blob blob,
PictureTemplate pictureTemplate, ImageInfo imageInfo,
boolean convert) throws IOException, ClientException {
String mimeType = blob.getMimeType();
if (mimeType == null) {
blob.setMimeType(getImageMimeType(blob));
}
if (imageInfo == null) {
imageInfo = getImageInfo(blob);
}
return computeView(blob, pictureTemplate, imageInfo, convert);
}
@Override
public List<PictureView> computeViewsFor(Blob blob,
List<PictureTemplate> pictureTemplates, boolean convert)
throws IOException, ClientException {
return computeViewsFor(blob, pictureTemplates, null, convert);
}
@Override
public List<PictureView> computeViewsFor(Blob blob,
List<PictureTemplate> pictureTemplates, ImageInfo imageInfo,
boolean convert) throws IOException, ClientException {
String mimeType = blob.getMimeType();
if (mimeType == null) {
blob.setMimeType(getImageMimeType(blob));
}
if (imageInfo == null) {
imageInfo = getImageInfo(blob);
}
List<PictureView> views = new ArrayList<PictureView>();
for (PictureTemplate pictureTemplate : pictureTemplates) {
views.add(computeView(blob, pictureTemplate, imageInfo, convert));
}
return views;
}
protected PictureView computeView(Blob blob,
PictureTemplate pictureTemplate, ImageInfo imageInfo,
boolean convert) throws IOException, ClientException {
if (convert) {
String title = pictureTemplate.getTitle();
if ("Original".equals(title)) {
return computeOriginalView(blob, pictureTemplate, imageInfo);
} else if ("OriginalJpeg".equals(title)) {
return computeOriginalJpegView(blob, pictureTemplate, imageInfo);
} else {
return computeView(blob, pictureTemplate, imageInfo);
}
} else {
return computeViewWithoutConversion(blob, pictureTemplate,
imageInfo);
}
}
protected PictureView computeOriginalView(Blob blob,
PictureTemplate pictureTemplate, ImageInfo imageInfo)
throws IOException {
String filename = blob.getFilename();
String title = pictureTemplate.getTitle();
String viewFilename = title + "_" + filename;
Map<String, Serializable> map = new HashMap<String, Serializable>();
map.put(PictureView.FIELD_TITLE, pictureTemplate.getTitle());
map.put(PictureView.FIELD_DESCRIPTION, pictureTemplate.getDescription());
map.put(PictureView.FIELD_FILENAME, viewFilename);
map.put(PictureView.FIELD_TAG, pictureTemplate.getTag());
map.put(PictureView.FIELD_WIDTH, imageInfo.getWidth());
map.put(PictureView.FIELD_HEIGHT, imageInfo.getHeight());
Blob originalViewBlob = wrapBlob(blob);
originalViewBlob.setFilename(viewFilename);
map.put(PictureView.FIELD_CONTENT, (Serializable) originalViewBlob);
return new PictureViewImpl(map);
}
/**
* @deprecated 5.9.2. Use {@link #wrapBlob(org.nuxeo.ecm.core.api.Blob)}.
*/
@Deprecated
protected Blob copyBlob(Blob blob) throws IOException {
return wrapBlob(blob);
}
protected Blob wrapBlob(Blob blob) throws IOException {
return new BlobWrapper(blob);
}
protected PictureView computeOriginalJpegView(Blob blob,
PictureTemplate pictureTemplate, ImageInfo imageInfo)
throws ClientException, IOException {
String filename = blob.getFilename();
String title = pictureTemplate.getTitle();
int width = imageInfo.getWidth();
int height = imageInfo.getHeight();
Map<String, Serializable> map = new HashMap<String, Serializable>();
map.put(PictureView.FIELD_TITLE, pictureTemplate.getTitle());
map.put(PictureView.FIELD_DESCRIPTION, pictureTemplate.getDescription());
map.put(PictureView.FIELD_TAG, pictureTemplate.getTag());
map.put(PictureView.FIELD_WIDTH, width);
map.put(PictureView.FIELD_HEIGHT, height);
Map<String, Serializable> options = new HashMap<String, Serializable>();
options.put(OPTION_RESIZE_WIDTH, width);
options.put(OPTION_RESIZE_HEIGHT, height);
options.put(OPTION_RESIZE_DEPTH, imageInfo.getDepth());
// always convert to jpeg
options.put(CONVERSION_FORMAT, JPEG_CONVERSATION_FORMAT);
BlobHolder bh = new SimpleBlobHolder(blob);
ConversionService conversionService = Framework.getLocalService(ConversionService.class);
bh = conversionService.convert(OPERATION_RESIZE, bh, options);
Blob originalJpegBlob = bh.getBlob();
if (originalJpegBlob == null) {
originalJpegBlob = wrapBlob(blob);
}
String viewFilename = computeViewFilename(filename,
JPEG_CONVERSATION_FORMAT);
viewFilename = title + "_" + viewFilename;
map.put(PictureView.FIELD_FILENAME, viewFilename);
originalJpegBlob.setFilename(viewFilename);
map.put(PictureView.FIELD_CONTENT, (Serializable) originalJpegBlob);
return new PictureViewImpl(map);
}
protected String computeViewFilename(String filename, String format) {
int index = filename.lastIndexOf(".");
if (index == -1) {
return filename + "." + format;
} else {
return filename.substring(0, index + 1) + format;
}
}
protected PictureView computeView(Blob blob,
PictureTemplate pictureTemplate, ImageInfo imageInfo)
throws ClientException, IOException {
String filename = blob.getFilename();
String title = pictureTemplate.getTitle();
int width = imageInfo.getWidth();
int height = imageInfo.getHeight();
Map<String, Serializable> map = new HashMap<String, Serializable>();
map.put(PictureView.FIELD_TITLE, pictureTemplate.getTitle());
map.put(PictureView.FIELD_DESCRIPTION, pictureTemplate.getDescription());
map.put(PictureView.FIELD_TAG, pictureTemplate.getTag());
Point size = new Point(width, height);
size = getSize(size, pictureTemplate.getMaxSize());
map.put(PictureView.FIELD_WIDTH, size.x);
map.put(PictureView.FIELD_HEIGHT, size.y);
Map<String, Serializable> options = new HashMap<String, Serializable>();
options.put(OPTION_RESIZE_WIDTH, size.x);
options.put(OPTION_RESIZE_HEIGHT, size.y);
options.put(OPTION_RESIZE_DEPTH, imageInfo.getDepth());
// use the registered conversion format for 'Medium' and 'Thumbnail'
// views
String conversionFormat = getConfigurationValue(CONVERSION_FORMAT,
JPEG_CONVERSATION_FORMAT);
options.put(CONVERSION_FORMAT, conversionFormat);
BlobHolder bh = new SimpleBlobHolder(blob);
ConversionService conversionService = Framework.getLocalService(ConversionService.class);
bh = conversionService.convert(OPERATION_RESIZE, bh, options);
Blob viewBlob = bh.getBlob();
if (viewBlob == null) {
viewBlob = wrapBlob(blob);
}
String viewFilename = computeViewFilename(filename, conversionFormat);
viewFilename = title + "_" + viewFilename;
map.put(PictureView.FIELD_FILENAME, viewFilename);
viewBlob.setFilename(viewFilename);
map.put(PictureView.FIELD_CONTENT, (Serializable) viewBlob);
return new PictureViewImpl(map);
}
protected PictureView computeViewWithoutConversion(Blob blob,
PictureTemplate pictureTemplate, ImageInfo imageInfo) {
PictureView view = new PictureViewImpl();
view.setBlob(blob);
view.setWidth(imageInfo.getWidth());
view.setHeight(imageInfo.getHeight());
view.setFilename(blob.getFilename());
view.setTitle(pictureTemplate.getTitle());
view.setDescription(pictureTemplate.getDescription());
view.setTag(pictureTemplate.getTag());
return view;
}
protected static Point getSize(Point current, int max) {
int x = current.x;
int y = current.y;
int newX;
int newY;
if (x > y) { // landscape
newY = (y * max) / x;
newX = max;
} else { // portrait
newX = (x * max) / y;
newY = max;
}
if (newX > x || newY > y) {
return current;
}
return new Point(newX, newY);
}
@Override
public List<List<PictureView>> computeViewsFor(List<Blob> blobs,
List<PictureTemplate> pictureTemplates, boolean convert)
throws IOException, ClientException {
return computeViewsFor(blobs, pictureTemplates, null, convert);
}
@Override
public List<List<PictureView>> computeViewsFor(List<Blob> blobs,
List<PictureTemplate> pictureTemplates, ImageInfo imageInfo,
boolean convert) throws IOException, ClientException {
List<List<PictureView>> allViews = new ArrayList<List<PictureView>>();
for (Blob blob : blobs) {
allViews.add(computeViewsFor(blob, pictureTemplates, imageInfo,
convert));
}
return allViews;
}
}
|
package com.mjrichardson.teamCity.buildTriggers;
import com.intellij.openapi.diagnostic.Logger;
import jetbrains.buildServer.ServiceLocator;
import jetbrains.buildServer.buildTriggers.BuildTriggerException;
import jetbrains.buildServer.buildTriggers.PolledTriggerContext;
import jetbrains.buildServer.buildTriggers.async.CheckJobStatusStorage;
import jetbrains.buildServer.buildTriggers.async.CheckResult;
import jetbrains.buildServer.buildTriggers.async.DetectionException;
import jetbrains.buildServer.buildTriggers.async.impl.AsyncPolledBuildTrigger;
import jetbrains.buildServer.serverSide.*;
import jetbrains.buildServer.users.SUser;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ExecutorService;
public class CustomAsyncPolledBuildTrigger<TItem> extends AsyncPolledBuildTrigger<TItem> {
final Logger log;
final CustomAsyncBuildTrigger<TItem> asyncBuildTrigger;
final ServiceLocator serviceLocator;
public CustomAsyncPolledBuildTrigger(ExecutorService executorService,
Logger log,
CheckJobStatusStorage<TItem> storage,
int pollInterval,
CustomAsyncBuildTrigger<TItem> asyncBuildTrigger,
ServiceLocator serviceLocator) {
super(executorService, log, storage, pollInterval, asyncBuildTrigger);
this.log = log;
this.asyncBuildTrigger = asyncBuildTrigger;
this.serviceLocator = serviceLocator;
}
@Override
public void triggerBuild(@NotNull PolledTriggerContext context) throws BuildTriggerException {
CheckResult result = checkJobStatus(context.getBuildType(), context.getTriggerDescriptor(), context.getCustomDataStorage());
if (result != null) {
JobResult jobResult = mapCheckResultToJobResult(result);
if (jobResult.shouldTriggerBuild()) {
SBuildType buildType = serviceLocator.getSingletonService(ProjectManager.class)
.findBuildTypeByExternalId(context.getBuildType().getExternalId());
SUser user = null;
final BuildCustomizer customizer = serviceLocator.getSingletonService(BuildCustomizerFactory.class)
.createBuildCustomizer(buildType, user);
customizer.setParameters(jobResult.properties);
try {
log.debug("Creating build promotion");
BuildPromotionEx promotion = (BuildPromotionEx)customizer.createPromotion();
log.debug("Build promotion " + promotion.getId() + " created");
log.debug("Adding '" + buildType.toString() + "' to queue");
SQueuedBuild addResult = ((BuildTypeEx)buildType).addToQueue(promotion, jobResult.triggeredBy);
log.info("Added '" + addResult.toString() + "' to queue");
}
catch(Exception e) {
log.error("Failed to create the build promotion", e);
}
}
if(jobResult.ex != null) {
throw jobResult.ex;
}
}
}
@NotNull
private JobResult mapCheckResultToJobResult(@NotNull CheckResult<TItem> checkResult) {
JobResult summary = new JobResult();
Throwable generalError = checkResult.getGeneralError();
if(generalError != null) {
summary.ex = asyncBuildTrigger.makeTriggerException(generalError);
} else {
Collection<DetectionException> errors = checkResult.getCheckErrors().values();
if(!errors.isEmpty()) {
DetectionException cause = errors.iterator().next();
summary.ex = asyncBuildTrigger.makeTriggerException(cause);
}
}
Collection<TItem> updated = checkResult.getUpdated();
if (!updated.isEmpty()) {
this.log.debug("changes detected in " + updated);
TItem update = updated.iterator().next();
summary.triggeredBy = asyncBuildTrigger.getRequestorString(update);
summary.properties = asyncBuildTrigger.getProperties(update);
} else {
this.log.debug("changes not detected");
}
return summary;
}
private class JobResult {
@Nullable
private String triggeredBy;
@Nullable
private BuildTriggerException ex;
@NotNull
private Map<String, String> properties;
public boolean shouldTriggerBuild() {
return triggeredBy != null;
}
}
}
|
package org.eclipse.mylar.internal.bugzilla.ui.tasklist;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import javax.security.auth.login.LoginException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.mylar.internal.bugzilla.core.BugzillaServerFacade;
import org.eclipse.mylar.internal.bugzilla.core.IBugzillaConstants;
import org.eclipse.mylar.internal.tasks.core.WebClientUtil;
import org.eclipse.mylar.internal.tasks.ui.wizards.AbstractRepositorySettingsPage;
import org.eclipse.mylar.tasks.core.RepositoryTemplate;
import org.eclipse.mylar.tasks.ui.AbstractRepositoryConnector;
import org.eclipse.mylar.tasks.ui.TasksUiPlugin;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
/**
* @author Mik Kersten
*/
public class BugzillaRepositorySettingsPage extends AbstractRepositorySettingsPage {
private static final String MESSAGE_FAILURE_UNKNOWN = "Unknown error occured. Check that server url and credentials are valid.";
private static final String TITLE = "Bugzilla Repository Settings";
private static final String DESCRIPTION = "Example: https://bugs.eclipse.org/bugs (do not include index.cgi)";
protected Combo repositoryVersionCombo;
public BugzillaRepositorySettingsPage(AbstractRepositoryConnector connector) {
super(TITLE, DESCRIPTION, connector);
setNeedsAnonymousLogin(true);
setNeedsEncoding(true);
setNeedsTimeZone(false);
}
protected void createAdditionalControls(Composite parent) {
for (RepositoryTemplate template : connector.getTemplates()) {
repositoryLabelCombo.add(template.label);
}
repositoryLabelCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String text = repositoryLabelCombo.getText();
RepositoryTemplate template = connector.getTemplate(text);
if(template != null) {
setUrl(template.repositoryUrl);
// setAnonymous(info.anonymous);
setBugzillaVersion(template.version);
getContainer().updateButtons();
return;
}
}
});
Label repositoryVersionLabel = new Label(parent, SWT.NONE);
repositoryVersionLabel.setText("Repository Version: ");
repositoryVersionCombo = new Combo(parent, SWT.READ_ONLY);
for (String version : getConnector().getSupportedVersions()) {
repositoryVersionCombo.add(version);
}
if (repository != null && repositoryVersionCombo.indexOf(repository.getVersion()) >= 0) {
repositoryVersionCombo.select(repositoryVersionCombo.indexOf(repository.getVersion()));
} else {
int defaultIndex = getConnector().getSupportedVersions().size() - 1;
repositoryVersionCombo.select(defaultIndex);
setVersion(repositoryVersionCombo.getItem(defaultIndex));
}
repositoryVersionCombo.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
if (repositoryVersionCombo.getSelectionIndex() >= 0) {
setVersion(repositoryVersionCombo.getItem(repositoryVersionCombo.getSelectionIndex()));
}
}
public void widgetDefaultSelected(SelectionEvent e) {
// ignore
}
});
}
public void setBugzillaVersion(String version) {
if (version == null) {
repositoryVersionCombo.select(0);
} else {
int i = repositoryVersionCombo.indexOf(version.toString());
if (i != -1) {
repositoryVersionCombo.select(i);
}
setVersion(version);
}
}
@Override
public boolean isPageComplete() {
return super.isPageComplete();
}
protected boolean isValidUrl(String name) {
if (name.startsWith(URL_PREFIX_HTTPS) || name.startsWith(URL_PREFIX_HTTP)) {
try {
new URL(name);
return true;
} catch (MalformedURLException e) {
}
}
return false;
}
protected void validateSettings() {
try {
final URL serverURL = new URL(super.getServerUrl());
final String serverUrl = getServerUrl();
final String newUserId = getUserName();
final String newPassword = getPassword();
getWizard().getContainer().run(true, false, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
monitor.beginTask("Validating server settings", IProgressMonitor.UNKNOWN);
try {
Proxy proxySettings = TasksUiPlugin.getDefault().getProxySettings();
URLConnection cntx = WebClientUtil.getUrlConnection(serverURL, proxySettings, false);
if (cntx == null || !(cntx instanceof HttpURLConnection)) {
throw new MalformedURLException();
}
HttpURLConnection serverConnection = (HttpURLConnection) cntx;
serverConnection.connect();
BugzillaServerFacade.validateCredentials(serverUrl, newUserId, newPassword);
} catch (Exception e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
}
});
MessageDialog.openInformation(null, IBugzillaConstants.TITLE_MESSAGE_DIALOG,
"Authentication credentials are valid.");
} catch (InvocationTargetException e) {
if (e.getCause() instanceof MalformedURLException) {
MessageDialog.openWarning(null, IBugzillaConstants.TITLE_MESSAGE_DIALOG, "Server URL is invalid.");
} else if (e.getCause() instanceof LoginException) {
MessageDialog.openWarning(null, IBugzillaConstants.TITLE_MESSAGE_DIALOG,
"Unable to authenticate with server. Login credentials invalid.");
} else if (e.getCause() instanceof IOException) {
MessageDialog.openWarning(null, IBugzillaConstants.TITLE_MESSAGE_DIALOG,
"No Bugzilla server found at url");
} else {
MessageDialog.openWarning(null, IBugzillaConstants.TITLE_MESSAGE_DIALOG, MESSAGE_FAILURE_UNKNOWN);
}
} catch (MalformedURLException e) {
MessageDialog.openWarning(null, IBugzillaConstants.TITLE_MESSAGE_DIALOG, "Server URL is invalid.");
} catch (InterruptedException e) {
MessageDialog.openWarning(null, IBugzillaConstants.TITLE_MESSAGE_DIALOG, MESSAGE_FAILURE_UNKNOWN);
}
super.getWizard().getContainer().updateButtons();
}
}
|
package org.opentosca.bus.management.service.impl;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.ProducerTemplate;
import org.opentosca.bus.management.header.MBHeader;
import org.opentosca.bus.management.plugins.service.IManagementBusPluginService;
import org.opentosca.bus.management.service.IManagementBusService;
import org.opentosca.bus.management.service.impl.servicehandler.ServiceHandler;
import org.opentosca.bus.management.utils.MBUtils;
import org.opentosca.container.core.engine.IToscaEngineService;
import org.opentosca.container.core.model.csar.id.CSARID;
import org.opentosca.container.core.model.endpoint.wsdl.WSDLEndpoint;
import org.opentosca.container.core.service.ICoreEndpointService;
import org.opentosca.container.core.tosca.convention.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ManagementBusServiceImpl implements IManagementBusService {
private static String BPMNNS = "http:
private final static Logger LOG = LoggerFactory.getLogger(ManagementBusServiceImpl.class);
@Override
public void invokeIA(Exchange exchange) {
ManagementBusServiceImpl.LOG.debug("Starting Management Bus: InvokeIA");
final Message message = exchange.getIn();
final CSARID csarID = message.getHeader(MBHeader.CSARID.toString(), CSARID.class);
ManagementBusServiceImpl.LOG.debug("CSARID: {}", csarID.toString());
final URI serviceInstanceID = message.getHeader(MBHeader.SERVICEINSTANCEID_URI.toString(), URI.class);
ManagementBusServiceImpl.LOG.debug("serviceInstanceID: {}", serviceInstanceID);
final String nodeInstanceID = message.getHeader(MBHeader.NODEINSTANCEID_STRING.toString(), String.class);
ManagementBusServiceImpl.LOG.debug("nodeInstanceID: {}", nodeInstanceID);
final QName serviceTemplateID = message.getHeader(MBHeader.SERVICETEMPLATEID_QNAME.toString(), QName.class);
ManagementBusServiceImpl.LOG.debug("serviceTemplateID: {}", serviceTemplateID);
final String nodeTemplateID = message.getHeader(MBHeader.NODETEMPLATEID_STRING.toString(), String.class);
ManagementBusServiceImpl.LOG.debug("nodeTemplateID: {}", nodeTemplateID);
final String relationshipTemplateID =
message.getHeader(MBHeader.RELATIONSHIPTEMPLATEID_STRING.toString(), String.class);
ManagementBusServiceImpl.LOG.debug("relationshipTemplateID: {}", relationshipTemplateID);
final String neededInterface = message.getHeader(MBHeader.INTERFACENAME_STRING.toString(), String.class);
ManagementBusServiceImpl.LOG.debug("Interface: {}", neededInterface);
final String neededOperation = message.getHeader(MBHeader.OPERATIONNAME_STRING.toString(), String.class);
ManagementBusServiceImpl.LOG.debug("Operation: {}", neededOperation);
boolean wasFound = false;
String invocationType = null;
if (nodeTemplateID != null) {
final QName nodeTypeID =
ServiceHandler.toscaEngineService.getNodeTypeOfNodeTemplate(csarID, serviceTemplateID, nodeTemplateID);
if (message.getBody() instanceof HashMap) {
@SuppressWarnings("unchecked")
HashMap<String, String> inputParams = (HashMap<String, String>) message.getBody();
// update inputParams with instance data
inputParams = updateInputParams(inputParams, csarID, serviceTemplateID, nodeTypeID, nodeTemplateID,
neededInterface, neededOperation, serviceInstanceID);
message.setBody(inputParams);
} else {
ManagementBusServiceImpl.LOG.warn("There are no input parameters specified.");
}
ManagementBusServiceImpl.LOG.debug("Getting information about the ImplementationArtifact from TOSCA Engine...");
ManagementBusServiceImpl.LOG.debug("Getting nodeTypeImplementationIDs of NodeType: {} from CSAR: {}",
nodeTypeID, csarID);
final List<QName> nodeTypeImplementationIDs =
ServiceHandler.toscaEngineService.getNodeTypeImplementationsOfNodeType(csarID, nodeTypeID);
ManagementBusServiceImpl.LOG.debug("nodeTypeImplementationIDs: {}", nodeTypeImplementationIDs.toString());
// Jump-Label to stop both loops at once
searchIA: for (final QName nodeTypeImplementationID : nodeTypeImplementationIDs) {
final List<String> implementationArtifactNames =
ServiceHandler.toscaEngineService.getImplementationArtifactNamesOfNodeTypeImplementation(csarID,
nodeTypeImplementationID);
ManagementBusServiceImpl.LOG.debug("implementationArtifactNames: {}",
implementationArtifactNames.toString());
for (final String implementationArtifactName : implementationArtifactNames) {
// Check if needed interface/operation is provided
if (isCorrectIA(csarID, nodeTypeID, nodeTypeImplementationID, null, null,
implementationArtifactName, neededOperation, neededInterface)) {
final QName artifactTemplateID =
ServiceHandler.toscaEngineService.getArtifactTemplateOfAImplementationArtifactOfANodeTypeImplementation(csarID,
nodeTypeImplementationID,
implementationArtifactName);
ManagementBusServiceImpl.LOG.debug("artifactTemplateID: {}", artifactTemplateID.toString());
final String artifactType =
ServiceHandler.toscaEngineService.getArtifactTypeOfAImplementationArtifactOfANodeTypeImplementation(csarID,
nodeTypeImplementationID,
implementationArtifactName)
.toString();
invocationType = isSupported(artifactType, csarID, artifactTemplateID);
if (invocationType != null) {
ManagementBusServiceImpl.LOG.debug("InvocationType found: {} ", invocationType);
ManagementBusServiceImpl.LOG.debug("Getting Endpoint for ImplementationArtifact: {} from NodeTypeImplementation: {}",
implementationArtifactName, nodeTypeImplementationID);
// EndpointService needs to be refactored.
// Distinction of WSDL &
// REST Endpoints is obsolete.
final WSDLEndpoint wsdlEndpoint =
ServiceHandler.endpointService.getWSDLEndpointForIa(csarID, nodeTypeImplementationID,
implementationArtifactName);
// Check if implementation artifact has a stored
// endpoint and thus was deployed
if (wsdlEndpoint != null) {
URI endpoint = wsdlEndpoint.getURI();
// if endpoint has placeholder, replace it with
// a matching property value
if (endpoint.toString().contains("/PLACEHOLDER_")
&& endpoint.toString().contains("_PLACEHOLDER/")) {
endpoint = replacePlaceholderWithInstanceData(endpoint, csarID, serviceTemplateID,
nodeTemplateID, serviceInstanceID);
}
ManagementBusServiceImpl.LOG.debug("Endpoint: " + endpoint.toString());
message.setHeader(MBHeader.ENDPOINT_URI.toString(), endpoint);
final boolean hasInputParams =
ServiceHandler.toscaEngineService.hasOperationOfANodeTypeSpecifiedInputParams(csarID,
nodeTypeID,
neededInterface,
neededOperation);
final boolean hasOutputParams =
ServiceHandler.toscaEngineService.hasOperationOfANodeTypeSpecifiedOutputParams(csarID,
nodeTypeID,
neededInterface,
neededOperation);
if (hasInputParams && !hasOutputParams) {
message.setHeader(MBHeader.HASOUTPUTPARAMS_BOOLEAN.toString(), false);
} else {
message.setHeader(MBHeader.HASOUTPUTPARAMS_BOOLEAN.toString(), true);
}
final Document specificContent =
ServiceHandler.toscaEngineService.getArtifactSpecificContentOfAImplementationArtifactOfANodeTypeImplementation(csarID,
nodeTypeImplementationID,
implementationArtifactName);
if (specificContent != null) {
ManagementBusServiceImpl.LOG.debug("ArtifactSpecificContent specified!");
message.setHeader(MBHeader.SPECIFICCONTENT_DOCUMENT.toString(), specificContent);
}
message.setHeader(MBHeader.ARTIFACTTEMPLATEID_QNAME.toString(), artifactTemplateID);
message.setHeader(MBHeader.NODETYPEID_QNAME.toString(), nodeTypeID);
wasFound = true;
// Invokable implementation artifact that
// provides correct
// interface/operation found. Stop loops.
break searchIA;
}
}
}
}
}
} else if (relationshipTemplateID != null) {
ManagementBusServiceImpl.LOG.debug("Getting information about the ImplementationArtifact from TOSCA Engine...");
final QName relationshipTypeID =
ServiceHandler.toscaEngineService.getRelationshipTypeOfRelationshipTemplate(csarID, serviceTemplateID,
relationshipTemplateID);
ManagementBusServiceImpl.LOG.debug("Getting RelationshipTypeImplementationIDs of RelationshipType: {} from CSAR: {}",
relationshipTypeID, csarID);
final List<QName> relationshipTypeImplementationIDs =
ServiceHandler.toscaEngineService.getRelationshipTypeImplementationsOfRelationshipType(csarID,
relationshipTypeID);
ManagementBusServiceImpl.LOG.debug("relationshipTypeImplementationIDs: {}",
relationshipTypeImplementationIDs.toString());
// Jump-Label to stop both loops at once
searchIA: for (final QName relationshipTypeImplementationID : relationshipTypeImplementationIDs) {
final List<String> implementationArtifactNames =
ServiceHandler.toscaEngineService.getImplementationArtifactNamesOfRelationshipTypeImplementation(csarID,
relationshipTypeImplementationID);
ManagementBusServiceImpl.LOG.debug("implementationArtifactNames: {}",
implementationArtifactNames.toString());
for (final String implementationArtifactName : implementationArtifactNames) {
// Check if needed interface/operation is provided
if (isCorrectIA(csarID, null, null, relationshipTypeID, relationshipTypeImplementationID,
implementationArtifactName, neededOperation, neededInterface)) {
final QName artifactTemplateID =
ServiceHandler.toscaEngineService.getArtifactTemplateOfAImplementationArtifactOfARelationshipTypeImplementation(csarID,
relationshipTypeImplementationID,
implementationArtifactName);
ManagementBusServiceImpl.LOG.debug("artifactTemplateID: {}", artifactTemplateID.toString());
final String artifactType =
ServiceHandler.toscaEngineService.getArtifactTypeOfAImplementationArtifactOfARelationshipTypeImplementation(csarID,
relationshipTypeImplementationID,
implementationArtifactName)
.toString();
invocationType = isSupported(artifactType, csarID, artifactTemplateID);
if (invocationType != null) {
ManagementBusServiceImpl.LOG.debug("InvocationType found: {} ", invocationType);
ManagementBusServiceImpl.LOG.debug("Getting Endpoint for ImplementationArtifact: {} from RelationshipTypeImplementation: {}",
implementationArtifactName,
relationshipTypeImplementationID);
// EndpointService needs to be refactored.
// Distinction of WSDL &
// REST Endpoints is obsolete.
final WSDLEndpoint wsdlEndpoint =
ServiceHandler.endpointService.getWSDLEndpointForIa(csarID,
relationshipTypeImplementationID,
implementationArtifactName);
// Check if implementation artifact has a stored
// endpoint and thus was deployed
if (wsdlEndpoint != null) {
final URI endpoint = wsdlEndpoint.getURI();
ManagementBusServiceImpl.LOG.debug("Endpoint: " + endpoint.toString());
message.setHeader(MBHeader.ENDPOINT_URI.toString(), endpoint);
final boolean hasInputParams =
ServiceHandler.toscaEngineService.hasOperationOfARelationshipTypeSpecifiedInputParams(csarID,
relationshipTypeID,
neededInterface,
neededOperation);
final boolean hasOutputParams =
ServiceHandler.toscaEngineService.hasOperationOfARelationshipTypeSpecifiedOutputParams(csarID,
relationshipTypeID,
neededInterface,
neededOperation);
if (hasInputParams && !hasOutputParams) {
message.setHeader(MBHeader.HASOUTPUTPARAMS_BOOLEAN.toString(), false);
} else {
message.setHeader(MBHeader.HASOUTPUTPARAMS_BOOLEAN.toString(), true);
}
final Document specificContent =
ServiceHandler.toscaEngineService.getArtifactSpecificContentOfAImplementationArtifactOfARelationshipTypeImplementation(csarID,
relationshipTypeImplementationID,
implementationArtifactName);
if (specificContent != null) {
ManagementBusServiceImpl.LOG.debug("ArtifactSpecificContent specified!");
message.setHeader(MBHeader.SPECIFICCONTENT_DOCUMENT.toString(), specificContent);
}
ManagementBusServiceImpl.LOG.debug("ArtifactSpecificContent specified!");
message.setHeader(MBHeader.ARTIFACTTEMPLATEID_QNAME.toString(), artifactTemplateID);
message.setHeader(MBHeader.RELATIONSHIPTYPEID_QNAME.toString(), relationshipTypeID);
wasFound = true;
// Invokable implementation artifact that
// provides correct
// interface/operation found. Stop loops.
break searchIA;
}
}
}
}
}
}
if (wasFound) {
exchange = callMatchingPlugin(exchange, invocationType);
} else {
ManagementBusServiceImpl.LOG.warn("No invokable implementation artifact found that provides required interface/operation");
}
handleResponse(exchange);
}
@Override
public void invokePlan(Exchange exchange) {
ManagementBusServiceImpl.LOG.debug("Starting Management Bus: InvokePlan");
final Message message = exchange.getIn();
final CSARID csarID = message.getHeader(MBHeader.CSARID.toString(), CSARID.class);
ManagementBusServiceImpl.LOG.debug("CSARID: " + csarID.toString());
final URI serviceInstanceID = message.getHeader(MBHeader.SERVICEINSTANCEID_URI.toString(), URI.class);
ManagementBusServiceImpl.LOG.debug("csarInstanceID: {}", serviceInstanceID);
final QName planID = message.getHeader(MBHeader.PLANID_QNAME.toString(), QName.class);
ManagementBusServiceImpl.LOG.debug("planID: {}", planID.toString());
final String nodeTemplateID = message.getHeader(MBHeader.NODETEMPLATEID_STRING.toString(), String.class);
ManagementBusServiceImpl.LOG.debug("nodeTemplateID: {}", nodeTemplateID);
ManagementBusServiceImpl.LOG.debug("Getting Endpoint for Plan {} from CSAR: {}", planID, csarID);
ServiceHandler.endpointService.printPlanEndpoints();
final WSDLEndpoint WSDLendpoint = ServiceHandler.endpointService.getWSDLEndpointForPlanId(csarID, planID);
final String planLanguage = message.getHeader("PlanLanguage", String.class);
ManagementBusServiceImpl.LOG.debug("plan language is: {}", planLanguage);
if (planLanguage.startsWith(BPMNNS)) {
final URI endpoint = WSDLendpoint.getURI();
ManagementBusServiceImpl.LOG.debug("Endpoint for Plan {} : {} ", planID, endpoint);
message.setHeader(MBHeader.ENDPOINT_URI.toString(), endpoint);
// Assumption. Should be checked with ToscaEngine
message.setHeader(MBHeader.HASOUTPUTPARAMS_BOOLEAN.toString(), true);
exchange = callMatchingPlugin(exchange, "REST");
} else if (WSDLendpoint != null) {
final URI endpoint = WSDLendpoint.getURI();
ManagementBusServiceImpl.LOG.debug("Endpoint for Plan {} : {} ", planID, endpoint);
message.setHeader(MBHeader.ENDPOINT_URI.toString(), endpoint);
// Assumption. Should be checked with ToscaEngine
message.setHeader(MBHeader.HASOUTPUTPARAMS_BOOLEAN.toString(), true);
exchange = callMatchingPlugin(exchange, "SOAP/HTTP");
} else {
ManagementBusServiceImpl.LOG.warn("No endpoint found for specified plan: {} of csar: {}. Invoking aborted!",
planID, csarID);
}
handleResponse(exchange);
}
/**
* Calls the plug-in that supports the specific invocation-type.
*
* @param exchange to be given the plug-in.
* @param invokeType that a plug-in is searched for.
*
* @return the response of the called plug-in.
*
*/
private Exchange callMatchingPlugin(Exchange exchange, final String invokeType) {
ManagementBusServiceImpl.LOG.debug("Searching a matching SI-Plug-in for InvocationType: {}...", invokeType);
ManagementBusServiceImpl.LOG.debug("Available plug-ins: {}", ServiceHandler.pluginServices.toString());
IManagementBusPluginService plugin;
synchronized (ServiceHandler.pluginServices) {
plugin = ServiceHandler.pluginServices.get(invokeType);
}
if (plugin != null) {
ManagementBusServiceImpl.LOG.debug("Matching SI-Plug-in found: {}. Calling it.", plugin.toString());
exchange = plugin.invoke(exchange);
} else {
ManagementBusServiceImpl.LOG.warn("No matching plugin found!");
}
return exchange;
}
/**
* Checks if the defined implementation artifact provides the needed interface/operation.
*
* @param csarID of the implementation artifact to check
* @param nodeTypeID of the implementation artifact to check
* @param nodeTypeImplementationID of the implementation artifact to check
* @param relationshipTypeID of the implementation artifact to check
* @param relationshipTypeImplementationID of the implementation artifact to check
* @param implementationArtifactName of the implementation artifact to check
* @param neededOperation specifies the operation the implementation artifact should provide
* @param neededInterface specifies the interface the implementation artifact should provide
*
* @return <code>true</code> if the specified implementation artifact provides needed
* interface/operation. Otherwise <code>false</code> .
*/
private boolean isCorrectIA(final CSARID csarID, final QName nodeTypeID, final QName nodeTypeImplementationID,
final QName relationshipTypeID, final QName relationshipTypeImplementationID,
final String implementationArtifactName, final String neededOperation,
final String neededInterface) {
String providedInterface = null;
String providedOperation = null;
if (nodeTypeID != null && nodeTypeImplementationID != null) {
ManagementBusServiceImpl.LOG.debug("Checking if IA: {} of NodeTypeImpl: {} is the correct one.",
implementationArtifactName, nodeTypeImplementationID);
providedInterface =
ServiceHandler.toscaEngineService.getInterfaceOfAImplementationArtifactOfANodeTypeImplementation(csarID,
nodeTypeImplementationID,
implementationArtifactName);
providedOperation =
ServiceHandler.toscaEngineService.getOperationOfAImplementationArtifactOfANodeTypeImplementation(csarID,
nodeTypeImplementationID,
implementationArtifactName);
} else if (relationshipTypeID != null && relationshipTypeImplementationID != null) {
ManagementBusServiceImpl.LOG.debug("Checking if IA: {} of RelationshipTypeImpl: {} is the correct one.",
implementationArtifactName, relationshipTypeImplementationID);
providedInterface =
ServiceHandler.toscaEngineService.getInterfaceOfAImplementationArtifactOfARelationshipTypeImplementation(csarID,
relationshipTypeImplementationID,
implementationArtifactName);
providedOperation =
ServiceHandler.toscaEngineService.getOperationOfAImplementationArtifactOfARelationshipTypeImplementation(csarID,
relationshipTypeImplementationID,
implementationArtifactName);
}
ManagementBusServiceImpl.LOG.debug("Needed interface: {}. Provided interface: {}", neededInterface,
providedInterface);
ManagementBusServiceImpl.LOG.debug("Needed operation: {}. Provided operation: {}", neededOperation,
providedOperation);
// IA implements all operations of all interfaces defined in NodeType
if (providedInterface == null && providedOperation == null) {
ManagementBusServiceImpl.LOG.debug("Correct IA found. IA: {} implements all operations of all interfaces defined in NodeType.",
implementationArtifactName);
return true;
}
// IA implements all operations of one interface defined in NodeType
if (providedInterface != null && providedOperation == null && providedInterface.equals(neededInterface)) {
ManagementBusServiceImpl.LOG.debug("Correct IA found. IA: {} implements all operations of one interface defined in NodeType.",
implementationArtifactName);
return true;
}
// IA implements one operation of an interface defined in NodeType
if (providedInterface != null && providedOperation != null && providedInterface.equals(neededInterface)
&& providedOperation.equals(neededOperation)) {
ManagementBusServiceImpl.LOG.debug("Correct IA found. IA: {} implements one operation of an interface defined in NodeType.",
implementationArtifactName);
return true;
}
// In this case - if there is no interface specified - the operation
// should be unique within the NodeType
if (neededInterface == null && neededOperation != null && providedInterface != null
&& providedOperation == null) {
if (nodeTypeID != null) {
return ServiceHandler.toscaEngineService.doesInterfaceOfNodeTypeContainOperation(csarID, nodeTypeID,
providedInterface,
neededOperation);
}
if (relationshipTypeID != null) {
return ServiceHandler.toscaEngineService.doesInterfaceOfRelationshipTypeContainOperation(csarID,
relationshipTypeID,
providedInterface,
neededOperation);
}
}
ManagementBusServiceImpl.LOG.debug("ImplementationArtifact {} does not provide needed interface/operation",
implementationArtifactName);
return false;
}
/**
* Checks if a plugin is available that supports the specified artifact and returns the
* invocationType.
*
* @param artifactType to check if supported.
* @param csarID to get properties to check for InvocationType.
* @param artifactTemplateID to get properties to check for InvocationTyp.
* @return the invocationType or otherwise <tt>null</tt>.
*/
private String isSupported(final String artifactType, final CSARID csarID, final QName artifactTemplateID) {
ManagementBusServiceImpl.LOG.debug("Searching if a plugin supports the type {}", artifactType);
ManagementBusServiceImpl.LOG.debug("All supported Types: {}", ServiceHandler.pluginServices.toString());
// First check if a plugin is registered that supports the
// ArtifactType.
if (ServiceHandler.pluginServices.containsKey(artifactType)) {
return artifactType;
} else {
final Document properties =
ServiceHandler.toscaEngineService.getPropertiesOfAArtifactTemplate(csarID, artifactTemplateID);
// Second check if a invocation-type is specified in
// TOSCA definition
final String invocationType = getInvocationType(properties);
if (invocationType != null) {
if (ServiceHandler.pluginServices.containsKey(invocationType)) {
return invocationType;
}
}
}
return null;
}
/**
* Checks if a InvocationType was specified in the Tosca.xml and returns it if so.
*
* @param properties to check for InvocationType.
* @return InvocationType if specified. Otherwise <tt>null</tt>.
*/
private String getInvocationType(final Document properties) {
// Checks if there are specified properties at all.
if (properties != null) {
final NodeList list = properties.getFirstChild().getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
final Node propNode = list.item(i);
if (containsInvocationType(propNode)) {
final String invocationType = propNode.getTextContent().trim();
return invocationType;
}
}
}
ManagementBusServiceImpl.LOG.debug("No InvocationType found!");
return null;
}
/**
* Checks if the Node contains a InvocationType. A InvocationType has to be specified within
* <tt>{@literal <}namespace:InvocationType{@literal >}...
* {@literal <}/namespace:InvocationType{@literal >}</tt>.
*
* @param currentNode to check.
* @return if currentNode contains a InvocationType.
*/
private boolean containsInvocationType(final Node currentNode) {
final String localName = currentNode.getLocalName();
if (localName != null) {
return localName.equals("InvocationType");
}
return false;
}
/**
*
* Updates the input parameters. If instance data are available the provided input parameters will
* be overwritten with them.
*
* @param inputParams
* @param csarID
* @param serviceTemplateID
* @param nodeTypeID
* @param nodeTemplateID
* @param neededInterface
* @param neededOperation
* @param serviceInstanceID
*
*
* @return the updated input parameters.
*/
private HashMap<String, String> updateInputParams(HashMap<String, String> inputParams, final CSARID csarID,
final QName serviceTemplateID, QName nodeTypeID,
String nodeTemplateID, final String neededInterface,
final String neededOperation, final URI serviceInstanceID) {
ManagementBusServiceImpl.LOG.debug("{} inital input parameters for operation: {} found: {}", inputParams.size(),
neededOperation, inputParams.toString());
nodeTypeID =
ServiceHandler.toscaEngineService.getNodeTypeOfNodeTemplate(csarID, serviceTemplateID, nodeTemplateID);
final List<String> expectedParams =
getExpectedInputParams(csarID, nodeTypeID, neededInterface, neededOperation);
ManagementBusServiceImpl.LOG.debug("Operation: {} expects {} parameters: {}", neededOperation,
expectedParams.size(), expectedParams.toString());
boolean update = true;
if (!expectedParams.isEmpty()) {
while (update) {
// Check if instanceID is set and merge input params with
// instance data. Priority on instance data.
if (serviceInstanceID != null && !serviceInstanceID.toString().equals("?")) {
ManagementBusServiceImpl.LOG.debug("Getting InstanceData for NodeTemplate: {} and ServiceInstanceID: {} ...",
nodeTemplateID.trim(), serviceInstanceID);
final HashMap<String, String> propertiesMap =
MBUtils.getInstanceDataProperties(csarID, serviceTemplateID, nodeTemplateID.trim(),
serviceInstanceID);
ManagementBusServiceImpl.LOG.debug("Found following properties: ");
for (final String key : propertiesMap.keySet()) {
ManagementBusServiceImpl.LOG.debug("Prop: " + key + " Val: " + propertiesMap.get(key));
}
if (propertiesMap != null) {
inputParams = updateInputParams(expectedParams, inputParams, propertiesMap);
}
}
// If not all params are filled, check if properties of nodes below are matching.
if (expectedParams.size() != inputParams.size()) {
ManagementBusServiceImpl.LOG.debug("Not all expected Params are filled. Checking for nodes below...");
nodeTemplateID = MBUtils.getHostedOnNodeTemplateID(csarID, serviceTemplateID, nodeTemplateID);
if (nodeTemplateID != null) {
ManagementBusServiceImpl.LOG.debug("Node found: {}", nodeTemplateID);
} else {
ManagementBusServiceImpl.LOG.debug("No operating system node found.");
update = false;
}
} else {
update = false;
}
}
}
ManagementBusServiceImpl.LOG.debug("Final {} input parameters for operation {} : {}", inputParams.size(),
neededOperation, inputParams.toString());
return inputParams;
}
private HashMap<String, String> updateInputParams(final List<String> expectedParams,
final HashMap<String, String> inputParams,
final HashMap<String, String> propertiesMap) {
final List<String> supportedIPPropertyNames = Utils.getSupportedVirtualMachineIPPropertyNames();
final List<String> supportedInstanceIdPropertyNames = Utils.getSupportedVirtualMachineInstanceIdPropertyNames();
final List<String> supportedPasswordPropertyNames =
Utils.getSupportedVirtualMachineLoginPasswordPropertyNames();
final List<String> supportedUsernamePropertyNames =
Utils.getSupportedVirtualMachineLoginUserNamePropertyNames();
String prop;
// Check for property convention
for (final String expectedParam : expectedParams) {
if (supportedIPPropertyNames.contains(expectedParam)) {
ManagementBusServiceImpl.LOG.debug("Supported IP-Property found.");
prop = getSupportedProperty(supportedIPPropertyNames, propertiesMap);
if (prop != null) {
putOnlyIfNotSet(inputParams, expectedParam, prop);
}
} else if (supportedInstanceIdPropertyNames.contains(expectedParam)) {
ManagementBusServiceImpl.LOG.debug("Supported InstanceID-Property found.");
prop = getSupportedProperty(supportedInstanceIdPropertyNames, propertiesMap);
if (prop != null) {
putOnlyIfNotSet(inputParams, expectedParam, prop);
}
} else if (supportedPasswordPropertyNames.contains(expectedParam)) {
ManagementBusServiceImpl.LOG.debug("Supported Password-Property found.");
prop = getSupportedProperty(supportedPasswordPropertyNames, propertiesMap);
if (prop != null) {
putOnlyIfNotSet(inputParams, expectedParam, prop);
}
} else if (supportedUsernamePropertyNames.contains(expectedParam)) {
ManagementBusServiceImpl.LOG.debug("Supported Username-Property found.");
prop = getSupportedProperty(supportedUsernamePropertyNames, propertiesMap);
if (prop != null) {
putOnlyIfNotSet(inputParams, expectedParam, prop);
}
} else {
for (final String propName : propertiesMap.keySet()) {
if (expectedParam.equals(propName)) {
putOnlyIfNotSet(inputParams, expectedParam, propertiesMap.get(propName));
}
}
}
}
return inputParams;
}
private void putOnlyIfNotSet(final Map<String, String> inputParams, final String key, final String value) {
if (!inputParams.containsKey(key)) {
inputParams.put(key, value);
}
}
/**
* @param supportedProperties
* @param propertiesMap
*
*
* @return convention defined properties.
*/
private String getSupportedProperty(final List<String> supportedProperties,
final HashMap<String, String> propertiesMap) {
String prop;
for (final String supportedProperty : supportedProperties) {
if (propertiesMap.containsKey(supportedProperty)) {
prop = propertiesMap.get(supportedProperty);
ManagementBusServiceImpl.LOG.debug("Supported convention property: {} found: {}", supportedProperty,
prop);
return prop;
}
}
return null;
}
/**
*
* Replaces placeholder with a matching instance data value. Placeholder is defined like
* "/PLACEHOLDER_VMIP_IP_PLACEHOLDER/".
*
* @param endpoint
* @param csarID
* @param serviceTemplateID
* @param nodeTemplateID
* @param serviceInstanceID
*
* @return URI with replaced placeholder.
*/
private URI replacePlaceholderWithInstanceData(URI endpoint, final CSARID csarID, final QName serviceTemplateID,
final String nodeTemplateID, final URI serviceInstanceID) {
final String placeholderBegin = "/PLACEHOLDER_";
final String placeholderEnd = "_PLACEHOLDER/";
final String placeholder =
endpoint.toString().substring(endpoint.toString().lastIndexOf(placeholderBegin),
endpoint.toString().lastIndexOf(placeholderEnd) + placeholderEnd.length());
ManagementBusServiceImpl.LOG.debug("Placeholder: {} detected in Endpoint: {}", placeholder,
endpoint.toString());
final String[] placeholderProperties =
placeholder.replace(placeholderBegin, "").replace(placeholderEnd, "").split("_");
String propertyValue = null;
for (final String placeholderProperty : placeholderProperties) {
ManagementBusServiceImpl.LOG.debug("Searching instance data value for property {} ...",
placeholderProperty);
propertyValue = MBUtils.searchProperty(placeholderProperty, csarID, serviceTemplateID, nodeTemplateID,
serviceInstanceID);
if (propertyValue != null) {
ManagementBusServiceImpl.LOG.debug("Value for property {} found: {}.", placeholderProperty,
propertyValue);
try {
endpoint = new URI(endpoint.toString().replace(placeholder, propertyValue));
}
catch (final URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
} else {
ManagementBusServiceImpl.LOG.debug("Value for property {} not found.", placeholderProperty);
}
}
if (propertyValue == null) {
ManagementBusServiceImpl.LOG.warn("No instance data value for placeholder {} found!", placeholder);
}
return endpoint;
}
/**
*
* Returns the input parameters that are specified in the TOSCA of the definied operation.
*
* @param csarID
* @param nodeTypeID
* @param interfaceName
* @param operationName
*
*
* @return specified input parameters of the operation
*/
private List<String> getExpectedInputParams(final CSARID csarID, final QName nodeTypeID, final String interfaceName,
final String operationName) {
ManagementBusServiceImpl.LOG.debug("Fetching expected input params of " + operationName + " in interface "
+ interfaceName);
final List<String> inputParams = new ArrayList<>();
ManagementBusServiceImpl.LOG.debug("Checking for params with NodeType " + nodeTypeID);
if (ServiceHandler.toscaEngineService.hasOperationOfANodeTypeSpecifiedInputParams(csarID, nodeTypeID,
interfaceName,
operationName)) {
final Node definedInputParameters =
ServiceHandler.toscaEngineService.getInputParametersOfANodeTypeOperation(csarID, nodeTypeID,
interfaceName, operationName);
if (definedInputParameters != null) {
final NodeList definedInputParameterList = definedInputParameters.getChildNodes();
for (int i = 0; i < definedInputParameterList.getLength(); i++) {
final Node currentNode = definedInputParameterList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
final String name = ((Element) currentNode).getAttribute("name");
inputParams.add(name);
}
}
}
// found operation and its potential params -> exit loop
}
return inputParams;
}
/**
* Handles the response from the plug-in. If needed the response is sent back to the api.
*
*
* @param exchange to handle.
*/
private void handleResponse(Exchange exchange) {
if (exchange != null) {
// Response message back to caller.
final ProducerTemplate template = Activator.camelContext.createProducerTemplate();
final String caller = exchange.getIn().getHeader(MBHeader.APIID_STRING.toString(), String.class);
if (caller != null) {
ManagementBusServiceImpl.LOG.debug("Sending response message back to api: {}", caller);
exchange = template.send("direct-vm:" + caller, exchange);
if (exchange.isFailed()) {
ManagementBusServiceImpl.LOG.error("Sending exchange message failed! {}",
exchange.getException().getMessage());
}
} else {
ManagementBusServiceImpl.LOG.debug("Invocation was InOnly. No response message will be sent to the caller.");
}
}
}
}
|
package fr.openwide.core.jpa.junit;
import java.beans.PropertyDescriptor;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.EntityType;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import fr.openwide.core.jpa.business.generic.model.GenericEntity;
import fr.openwide.core.jpa.business.generic.service.IGenericEntityService;
import fr.openwide.core.jpa.exception.SecurityServiceException;
import fr.openwide.core.jpa.exception.ServiceException;
import fr.openwide.core.jpa.util.EntityManagerUtils;
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
DependencyInjectionTestExecutionListener.class,
EntityManagerExecutionListener.class
})
public abstract class AbstractTestCase {
@Autowired
private EntityManagerUtils entityManagerUtils;
protected abstract void cleanAll() throws ServiceException, SecurityServiceException;
protected static <E extends GenericEntity<?, ? super E>> void cleanEntities(IGenericEntityService<?, E> service) throws ServiceException, SecurityServiceException {
for (E entity : service.list()) {
service.delete(entity);
}
}
@Before
public void init() throws ServiceException, SecurityServiceException {
cleanAll();
checkEmptyDatabase();
}
@After
public void close() throws ServiceException, SecurityServiceException {
cleanAll();
checkEmptyDatabase();
}
protected <E extends GenericEntity<Long, E>> void testEntityStringFields(E entity, IGenericEntityService<Long, E> service)
throws ServiceException, SecurityServiceException {
BeanWrapper source = PropertyAccessorFactory.forBeanPropertyAccess(entity);
PropertyDescriptor[] fields = source.getPropertyDescriptors();
String[] ignoredFields = { };
for (PropertyDescriptor field : fields) {
String fieldName = field.getName();
if (source.isWritableProperty(fieldName) && String.class.isAssignableFrom(field.getPropertyType())) {
if (!ArrayUtils.contains(ignoredFields, fieldName) && source.isReadableProperty(fieldName)) {
source.setPropertyValue(fieldName, fieldName);
}
}
}
service.create(entity);
for (PropertyDescriptor field : fields) {
String fieldName = field.getName();
if (source.isWritableProperty(fieldName) && String.class.isAssignableFrom(field.getPropertyType())) {
if (!ArrayUtils.contains(ignoredFields, fieldName) && source.isReadableProperty(fieldName)) {
Assert.assertEquals(fieldName, source.getPropertyValue(fieldName));
}
}
}
}
private void checkEmptyDatabase() {
Set<EntityType<?>> entityTypes = getEntityManager().getEntityManagerFactory().getMetamodel().getEntities();
for (EntityType<?> entityType : entityTypes) {
List<?> entities = listEntities(entityType.getBindableJavaType());
if (entities.size() > 0) {
Assert.fail(String.format("Il reste des objets de type %1$s", entities.get(0).getClass().getSimpleName()));
}
}
}
protected <E> List<E> listEntities(Class<E> clazz) {
CriteriaBuilder cb = entityManagerUtils.getEntityManager().getCriteriaBuilder();
CriteriaQuery<E> cq = cb.createQuery(clazz);
cq.from(clazz);
return entityManagerUtils.getEntityManager().createQuery(cq).getResultList();
}
protected <E extends GenericEntity<?, ?>> Long countEntities(Class<E> clazz) {
CriteriaBuilder cb = entityManagerUtils.getEntityManager().getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<E> root = cq.from(clazz);
cq.select(cb.count(root));
return (Long) entityManagerUtils.getEntityManager().createQuery(cq).getSingleResult();
}
protected void assertDatesWithinXSeconds(Date date1, Date date2, Integer delayInSeconds) {
Assert.assertTrue(Math.abs(date1.getTime() - date2.getTime()) < delayInSeconds * 1000l);
}
protected EntityManager getEntityManager() {
return entityManagerUtils.getEntityManager();
}
protected void entityManagerOpen() {
entityManagerUtils.openEntityManager();
}
protected void entityManagerClose() {
entityManagerUtils.closeEntityManager();
}
protected void entityManagerReset() {
entityManagerClose();
entityManagerOpen();
}
protected void entityManagerClear() {
entityManagerUtils.getEntityManager().clear();
}
protected void entityManagerDetach(Object object) {
entityManagerUtils.getEntityManager().detach(object);
}
}
|
package nl.idgis.publisher.provider.database;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import nl.idgis.publisher.database.JdbcTransaction;
import nl.idgis.publisher.database.messages.Query;
import nl.idgis.publisher.database.messages.StreamingQuery;
import nl.idgis.publisher.domain.service.Type;
import nl.idgis.publisher.provider.database.messages.CompoundFilter;
import nl.idgis.publisher.provider.database.messages.DatabaseColumnInfo;
import nl.idgis.publisher.provider.database.messages.DatabaseTableInfo;
import nl.idgis.publisher.provider.database.messages.DescribeTable;
import nl.idgis.publisher.provider.database.messages.FetchTable;
import nl.idgis.publisher.provider.database.messages.Filter;
import nl.idgis.publisher.provider.database.messages.PerformCount;
import nl.idgis.publisher.provider.database.messages.ColumnFilter;
import nl.idgis.publisher.provider.database.messages.TableNotFound;
import nl.idgis.publisher.utils.UniqueNameGenerator;
public class DatabaseTransaction extends JdbcTransaction {
private final LoggingAdapter log = Logging.getLogger(getContext().system(), this);
private final UniqueNameGenerator nameGenerator = new UniqueNameGenerator();
public DatabaseTransaction(Connection connection) {
super(connection);
}
public static Props props(Connection connection) {
return Props.create(DatabaseTransaction.class, connection);
}
@Override
protected Object executeQuery(Query query) throws Exception {
if(query instanceof DescribeTable) {
return handleDescribeTable((DescribeTable)query);
} else if(query instanceof PerformCount){
return handlePerformCount((PerformCount)query);
} else {
return null;
}
}
@Override
protected ActorRef executeQuery(StreamingQuery query) throws Exception {
if(query instanceof FetchTable) {
return handleFetchTable((FetchTable)query);
} else {
return null;
}
}
private Object handleDescribeTable(DescribeTable query) throws SQLException {
String requestedTableName = query.getTableName();
final String sql;
int separatorIndex = requestedTableName.indexOf(".");
if(separatorIndex == -1) {
sql = "select column_name, data_type from user_tab_columns "
+ "where table_name = '" + requestedTableName.toUpperCase() + "' "
+ "order by column_id";
} else {
String owner = requestedTableName.substring(0, separatorIndex);
String tableName = requestedTableName.substring(separatorIndex + 1);
sql = "select column_name, data_type from all_tab_columns "
+ "where owner = '" + owner.toUpperCase() + "' and table_name = '" + tableName.toUpperCase()
+ "' " + "order by column_id";
}
log.debug("executing data dictionary query: {}", sql);
ArrayList<DatabaseColumnInfo> columns = new ArrayList<>();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
String name = rs.getString(1);
String typeName = rs.getString(2);
DatabaseColumnInfo columnInfo = new DatabaseColumnInfo(name, typeName);
// not reporting columns with unsupported data types
if("CLOB".equals(typeName) || columnInfo.getType() == null) {
log.debug("unsupported data type: " + columnInfo.getTypeName());
} else {
columns.add(columnInfo);
}
}
rs.close();
stmt.close();
if(columns.isEmpty()) {
return new TableNotFound();
} else {
return new DatabaseTableInfo(columns.toArray(new DatabaseColumnInfo[columns.size()]));
}
}
private Object handlePerformCount(PerformCount query) throws SQLException {
String sql = "select count(*) from " + query.getTableName();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
rs.next();
Object retval = rs.getLong(1);
rs.close();
stmt.close();
return retval;
}
private static void writeFilter(Filter filter, StringBuilder sb) {
if(filter instanceof CompoundFilter) {
CompoundFilter compoundFilter = (CompoundFilter)filter;
String filterSeparator = " " + compoundFilter.getOperator() + " ";
String separator = "";
for(Filter compoundFilterItem : compoundFilter.getFilters()) {
sb
.append(separator)
.append("(");
writeFilter(compoundFilterItem, sb);
sb.append(")");
separator = filterSeparator;
}
} else if(filter instanceof ColumnFilter) {
ColumnFilter columnFilter = (ColumnFilter)filter;
DatabaseColumnInfo column = columnFilter.getColumn();
sb
.append("\"")
.append(column.getName())
.append("\" ")
.append(columnFilter.getOperator())
.append(" ");
columnFilter.getOperand().ifPresent(operand -> {
if(column.getType() == Type.TEXT) {
sb
.append("'")
.append(operand.toString().replace("'", "''"))
.append("'");
} else {
sb.append(operand);
}
});
} else {
throw new IllegalArgumentException("unknown filter type: " + filter.getClass().getCanonicalName());
}
}
private ActorRef handleFetchTable(FetchTable msg) throws SQLException {
log.debug("fetch table: " + msg);
StringBuilder sb = new StringBuilder("SELECT ");
String separator = "";
for(DatabaseColumnInfo columnInfo : msg.getColumns()) {
sb.append(separator);
String typeName = columnInfo.getTypeName();
String columnName = columnInfo.getName();
if("SDO_GEOMETRY".equals(typeName)) {
sb
.append("SDO_UTIL.TO_WKBGEOMETRY(")
.append("CASE ")
.append("WHEN T.\"").append(columnName).append("\".GET_LRS_DIM() = 0 THEN ")
.append("CASE ")
.append("WHEN T.\"").append(columnName).append("\".GET_DIMS() = 3 THEN SDO_CS.MAKE_2D(T.\"").append(columnName).append("\") ")
.append("ELSE T.\"").append(columnName).append("\" ")
.append("END ")
.append("ELSE ")
.append("CASE ")
.append("WHEN T.\"").append(columnName).append("\".GET_DIMS() = 3 THEN SDO_LRS.CONVERT_TO_STD_GEOM(T.\"").append(columnName).append("\") ")
.append("WHEN T.\"").append(columnName).append("\".GET_DIMS() = 4 THEN SDO_LRS.CONVERT_TO_STD_GEOM(SDO_CS.MAKE_2D(T.\"").append(columnName).append("\")) ")
.append("END ")
.append("END)");
} else if("ST_GEOMETRY".equals(typeName)) {
sb
.append("SDE.ST_ASBINARY")
.append("(\"")
.append(columnName)
.append("\")");
} else {
sb
.append("\"")
.append(columnName)
.append("\"");
}
separator = ", ";
}
sb.append(" FROM \"");
String tableName = msg.getTableName();
int separatorIdx = tableName.indexOf(".");
if(separatorIdx == -1) {
sb.append(tableName);
} else {
sb
.append(tableName.substring(0, separatorIdx))
.append("\".\"")
.append(tableName.substring(separatorIdx + 1));
}
sb.append("\" T");
msg.getFilter().ifPresent(filter -> {
sb.append(" WHERE ");
writeFilter(filter, sb);
});
String query = sb.toString();
log.debug("executing query: {}", query);
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
ActorRef cursor = getContext().actorOf(
DatabaseCursor.props(rs, msg, executorService),
nameGenerator.getName(DatabaseCursor.class));
return cursor;
}
}
|
package com.vip.saturn.job.console.service.impl.statistics;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.vip.saturn.job.console.domain.*;
import com.vip.saturn.job.console.exception.SaturnJobConsoleException;
import com.vip.saturn.job.console.mybatis.entity.DashboardHistory;
import com.vip.saturn.job.console.mybatis.entity.SaturnStatistics;
import com.vip.saturn.job.console.mybatis.service.SaturnStatisticsService;
import com.vip.saturn.job.console.repository.zookeeper.CuratorRepository;
import com.vip.saturn.job.console.service.*;
import com.vip.saturn.job.console.service.helper.DashboardConstants;
import com.vip.saturn.job.console.service.helper.ZkClusterMappingUtils;
import com.vip.saturn.job.console.service.impl.DashboardServiceImpl;
import com.vip.saturn.job.console.service.impl.statistics.analyzer.*;
import com.vip.saturn.job.console.utils.ConsoleThreadFactory;
import com.vip.saturn.job.console.utils.JobNodePath;
import com.vip.saturn.job.console.utils.StatisticsTableKeyConstant;
import com.vip.saturn.job.integrate.service.ReportAlarmService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.*;
import java.util.concurrent.ExecutorService;
/**
* @author timmy.hu
*/
public class StatisticsRefreshServiceImpl implements StatisticsRefreshService {
private static final Logger log = LoggerFactory.getLogger(StatisticsRefreshServiceImpl.class);
private static final int CONNECT_TIMEOUT_MS = 10000;
private static final int SO_TIMEOUT_MS = 180_000;
private static final int STAT_THREAD_NUM = 20;
private Timer refreshStatisticsTimer;
private Timer cleanAbnormalShardingCacheTimer;
private Map<String/** domainName_jobName_shardingItemStr **/
, AbnormalShardingState /** abnormal sharding state */> abnormalShardingStateCache = new ConcurrentHashMap<>();
@Resource
private SaturnStatisticsService saturnStatisticsService;
@Resource
private StatisticsPersistence statisticsPersistence;
@Resource
private SystemConfigService systemConfigService;
@Resource
private RegistryCenterService registryCenterService;
@Resource
private JobService jobService;
@Resource
private ReportAlarmService reportAlarmService;
private ExecutorService statExecutorService;
@Resource
private DashboardService dashboardService;
@PostConstruct
public void init() {
initStatExecutorService();
startRefreshStatisticsTimer();
startCleanAbnormalShardingCacheTimer();
}
@PreDestroy
public void destroy() {
if (statExecutorService != null) {
statExecutorService.shutdownNow();
}
if (refreshStatisticsTimer != null) {
refreshStatisticsTimer.cancel();
}
if (cleanAbnormalShardingCacheTimer != null) {
cleanAbnormalShardingCacheTimer.cancel();
}
}
private void initStatExecutorService() {
if (statExecutorService != null) {
statExecutorService.shutdownNow();
}
ThreadPoolExecutor tp = new ThreadPoolExecutor(STAT_THREAD_NUM, STAT_THREAD_NUM,
DashboardConstants.REFRESH_INTERVAL_IN_MINUTE + 1, TimeUnit.MINUTES,
new LinkedBlockingQueue<Runnable>(), new ConsoleThreadFactory("dashboard-statistics-thread", true));
tp.allowCoreThreadTimeOut(true);
statExecutorService = tp;
}
private void startRefreshStatisticsTimer() {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
try {
log.info("start refresh statistics on timer");
Date start = new Date();
Collection<ZkCluster> zkClusterList = registryCenterService.getZkClusterList();
if (zkClusterList != null) {
for (ZkCluster zkCluster : zkClusterList) {
if (zkCluster.isOffline()) {
log.info("zkcluster:{} is offline, skip statistics refresh.",
zkCluster.getZkClusterKey());
continue;
}
if (registryCenterService.isDashboardLeader(zkCluster.getZkClusterKey())) {
refreshStatistics2DB(zkCluster);
}
}
}
log.info("end refresh statistics on timer which takes {}ms",
new Date().getTime() - start.getTime());
} catch (Throwable t) {
log.error(t.getMessage(), t);
}
}
};
refreshStatisticsTimer = new Timer("refresh-statistics-to-db-timer", true);
refreshStatisticsTimer
.scheduleAtFixedRate(timerTask, 1000L * 15, 1000L * 60 * DashboardConstants.REFRESH_INTERVAL_IN_MINUTE);
}
private void startCleanAbnormalShardingCacheTimer() {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
try {
for (Entry<String, AbnormalShardingState> entrySet : abnormalShardingStateCache.entrySet()) {
AbnormalShardingState shardingState = entrySet.getValue();
if (shardingState.getAlertTime() + DashboardConstants.ALLOW_DELAY_MILLIONSECONDS * 2 < System
.currentTimeMillis()) {
abnormalShardingStateCache.remove(entrySet.getKey());
log.info("Clean AbnormalShardingCache with key: {}, alertTime: {}, zkNodeCVersion: {}: ",
entrySet.getKey(), shardingState.getAlertTime(), shardingState.getZkNodeCVersion());
}
}
} catch (Throwable t) {
log.error("Clean AbnormalShardingCache error", t);
}
}
};
cleanAbnormalShardingCacheTimer = new Timer("clean-abnormalShardingCache-timer", true);
cleanAbnormalShardingCacheTimer
.scheduleAtFixedRate(timerTask, 0, DashboardConstants.ALLOW_DELAY_MILLIONSECONDS);
}
@Override
public void refresh(String zkClusterKey, boolean isForce) throws SaturnJobConsoleException {
if (isForce) {
refresh(zkClusterKey);
return;
}
boolean isSameIdc = ZkClusterMappingUtils.isCurrentConsoleInTheSameIdc(systemConfigService, zkClusterKey);
if (isSameIdc) {
log.info("the zk and the console are in the same IDC, refreshStatistics in the current Console");
refresh(zkClusterKey);
} else {
log.info("the zk and the console are in different IDC, forward the refresh request to remote console");
try {
forwardDashboardRefreshToRemote(zkClusterKey);
} catch (SaturnJobConsoleException e) {
log.warn("remote refresh request error, so refreshStatistics in the current Console, cause by {}", e);
refresh(zkClusterKey);
}
}
}
private void refresh(String zkClusterKey) throws SaturnJobConsoleException {
ZkCluster zkCluster = registryCenterService.getZkCluster(zkClusterKey);
if (zkCluster != null) {
refreshStatistics2DB(zkCluster);
} else {
throw new SaturnJobConsoleException("zk cluster not found by zkClusterKey:" + zkClusterKey);
}
}
protected void postRefreshStatistics2DB(StatisticsModel statisticsModel, ZkCluster zkCluster) {
statisticsModel.getOutdatedNoRunningJobAnalyzer().reportAlarmOutdatedNoRunningJobs();
List<DashboardHistory> dashboardHistories = new ArrayList<>();
Date currentDate = new Date();
long successCount = statisticsModel.getZkClusterDailyCountAnalyzer().getTotalCount();
long failCount = statisticsModel.getZkClusterDailyCountAnalyzer().getErrorCount();
Map<String, Long> content = new HashMap<>(2);
content.put("count", successCount);
content.put("failCount", failCount);
DashboardHistory allDomainHistory = new DashboardHistory(zkCluster.getZkClusterKey(),
DashboardServiceImpl.DashboardType.DOMAIN.name(),
DashboardServiceImpl.DashboardTopic.DOMAIN_OVERALL_COUNT.name(), JSON.toJSONString(content),
currentDate);
dashboardHistories.add(allDomainHistory);
// dashboardService
// .saveDashboardHistory(zkCluster.getZkClusterKey(), DashboardServiceImpl.DashboardType.DOMAIN.name(),
// DashboardServiceImpl.DashboardTopic.DOMAIN_OVERALL_COUNT.name(), JSON.toJSONString(content));
Map<String, Integer> executorContent = new HashMap<>(2);
int inDocker = statisticsModel.getExecutorInfoAnalyzer().getExeInDocker();
int notInDocker = statisticsModel.getExecutorInfoAnalyzer().getExeNotInDocker();
executorContent.put("dockerCount", inDocker);
executorContent.put("otherCount", notInDocker);
DashboardHistory executorHistory = new DashboardHistory(zkCluster.getZkClusterKey(),
DashboardServiceImpl.DashboardType.EXECUTOR.name(),
DashboardServiceImpl.DashboardTopic.EXECUTOR_COUNT.name(), JSON.toJSONString(executorContent),
currentDate);
dashboardHistories.add(executorHistory);
// dashboardService
// .saveDashboardHistory(zkCluster.getZkClusterKey(), DashboardServiceImpl.DashboardType.EXECUTOR.name(),
// DashboardServiceImpl.DashboardTopic.EXECUTOR_COUNT.name(), JSON.toJSONString(executorContent));
Map<String, Integer> jobContent = new HashMap<>(1);
int jobCount = statisticsModel.getJobStatisticsAnalyzer().getJobList().size();
jobContent.put("jobCount", jobCount);
DashboardHistory jobHistory = new DashboardHistory(zkCluster.getZkClusterKey(),
DashboardServiceImpl.DashboardType.JOB.name(), DashboardServiceImpl.DashboardTopic.JOB_COUNT.name(),
JSON.toJSONString(jobContent), currentDate);
dashboardHistories.add(jobHistory);
// dashboardService
// .saveDashboardHistory(zkCluster.getZkClusterKey(), DashboardServiceImpl.DashboardType.JOB.name(),
// DashboardServiceImpl.DashboardTopic.JOB_COUNT.name(), JSON.toJSONString(jobContent));
Map<String, Integer> domainContent = new HashMap<>(1);
int domainCount = registryCenterService.domainCount(zkCluster.getZkClusterKey());
domainContent.put("domainCount", domainCount);
DashboardHistory domainHistory = new DashboardHistory(zkCluster.getZkClusterKey(),
DashboardServiceImpl.DashboardType.DOMAIN.name(),
DashboardServiceImpl.DashboardTopic.DOMAIN_COUNT.name(), JSON.toJSONString(domainContent), currentDate);
dashboardHistories.add(domainHistory);
dashboardService.batchSaveDashboardHistory(dashboardHistories);
// dashboardService
// .saveDashboardHistory(zkCluster.getZkClusterKey(), DashboardServiceImpl.DashboardType.DOMAIN.name(),
// DashboardServiceImpl.DashboardTopic.DOMAIN_COUNT.name(), JSON.toJSONString(domainContent));
}
private void forwardDashboardRefreshToRemote(String zkClusterKey) throws SaturnJobConsoleException {
CloseableHttpClient httpClient = null;
String url = null;
try {
String domain = ZkClusterMappingUtils.getConsoleDomainByZkClusterKey(systemConfigService, zkClusterKey);
if (StringUtils.isBlank(domain)) {
throw new SaturnJobConsoleException(
String.format("The console domain is not found by zkClusterKey(%s)", zkClusterKey));
}
url = domain + "/rest/v1/dashboard/refresh?zkClusterKey=" + zkClusterKey;
httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = createHttpRequest(url);
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
handleResponse(url, httpResponse);
} catch (SaturnJobConsoleException se) {
throw se;
} catch (Exception e) {
throw new SaturnJobConsoleException("Fail to execute forwardDashboardRefreshToRemote, Url: " + url, e);
} finally {
IOUtils.closeQuietly(httpClient);
}
}
private void handleResponse(String url, CloseableHttpResponse httpResponse)
throws IOException, SaturnJobConsoleException {
StatusLine statusLine = httpResponse.getStatusLine();
Integer statusCode = statusLine != null ? statusLine.getStatusCode() : null;
log.info("the statusCode of remote request is:" + statusCode);
if (statusLine != null && statusCode == HttpStatus.SC_OK) {
String takeTime = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");
log.info("forwardDashboardRefreshToRemote Url " + url + ", spend time:" + takeTime);
return;
}
if (statusCode >= HttpStatus.SC_BAD_REQUEST && statusCode <= HttpStatus.SC_INTERNAL_SERVER_ERROR) {
String responseBody = EntityUtils.toString(httpResponse.getEntity());
if (StringUtils.isNotBlank(responseBody)) {
String errMsg = JSONObject.parseObject(responseBody).getString("message");
throw new SaturnJobConsoleException(errMsg);
} else {
throw new SaturnJobConsoleException("internal server error");
}
} else {
throw new SaturnJobConsoleException("unexpected status returned from Saturn Server.");
}
}
private HttpPost createHttpRequest(String url) {
HttpPost httpPost = new HttpPost(url);
RequestConfig cfg = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT_MS).setSocketTimeout(SO_TIMEOUT_MS)
.build();
httpPost.setConfig(cfg);
return httpPost;
}
private void refreshStatistics2DB(ZkCluster zkCluster) {
log.info("start refresh statistics by zkClusterKey:{}", zkCluster.getZkClusterKey());
Date start = new Date();
StatisticsModel statisticsModel = initStatisticsModel();
List<Callable<Boolean>> callableList = getStatCallableList(zkCluster, statisticsModel);
try {
if (callableList != null && !callableList.isEmpty()) {
statExecutorService.invokeAll(callableList);
}
statisticsPersistence.persist(statisticsModel, zkCluster);
postRefreshStatistics2DB(statisticsModel, zkCluster);
} catch (InterruptedException e) {
log.warn("the refreshStatistics2DB thread is interrupted", e);
Thread.currentThread().interrupt();
}
log.info("end refresh statistics by zkClusterKey:{}, takes {}", zkCluster.getZkClusterKey(),
new Date().getTime() - start.getTime());
}
private List<Callable<Boolean>> getStatCallableList(final ZkCluster zkCluster,
final StatisticsModel statisticsModel) {
List<Callable<Boolean>> callableList = Lists.newArrayList();
for (final RegistryCenterConfiguration config : zkCluster.getRegCenterConfList()) {
if (!zkCluster.getZkAddr().equals(config.getZkAddressList())) {
continue;
}
Callable<Boolean> callable = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return analyzeStatistics(statisticsModel, zkCluster, config);
}
};
callableList.add(callable);
}
return callableList;
}
private boolean analyzeStatistics(StatisticsModel statisticsModel, ZkCluster zkCluster,
RegistryCenterConfiguration config) {
String namespace = config.getNamespace();
try {
DomainStatistics domain = statisticsModel.getDomainStatisticsAnalyzer().initDomain(zkCluster, config);
CuratorRepository.CuratorFrameworkOp curatorFrameworkOp = registryCenterService
.getCuratorFrameworkOp(namespace);
List<AbnormalJob> oldAbnormalJobs = getOldAbnormalJobs(zkCluster);
List<Timeout4AlarmJob> oldTimeout4AlarmJobs = getOldTimeout4AlarmJobs(zkCluster);
statisticsModel.analyzeExecutor(curatorFrameworkOp, config);
List<String> jobs = jobService.getUnSystemJobNames(config.getNamespace());
for (String job : jobs) {
if (!curatorFrameworkOp.checkExists(JobNodePath.getConfigNodePath(job))) {
continue;
}
try {
Boolean localMode = Boolean
.valueOf(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(job, "localMode")));
JobStatistics jobStatistics = statisticsModel
.analyzeJobStatistics(curatorFrameworkOp, job, localMode, config);
String jobDegree = String.valueOf(jobStatistics.getJobDegree());
statisticsModel.analyzeShardingCount(curatorFrameworkOp, domain);
if (!localMode) {
statisticsModel.analyzeOutdatedNoRunningJob(curatorFrameworkOp, oldAbnormalJobs, job, jobDegree,
config);
}
statisticsModel
.analyzeTimeout4AlarmJob(curatorFrameworkOp, oldTimeout4AlarmJobs, job, jobDegree, config);
statisticsModel.analyzeUnableFailoverJob(curatorFrameworkOp, job, jobDegree, config);
} catch (Exception e) {
log.info(String.format("analyzeStatistics namespace(%s) jobName(%s) error", namespace, job), e);
}
}
statisticsModel.analyzeProcessCount(domain, jobs, config);
} catch (Exception e) {
log.info(String.format("analyzeStatistics namespace(%s) error", namespace), e);
return false;
}
return true;
}
private List<AbnormalJob> getOldAbnormalJobs(ZkCluster zkCluster) {
SaturnStatistics saturnStatistics = saturnStatisticsService
.findStatisticsByNameAndZkList(StatisticsTableKeyConstant.UNNORMAL_JOB, zkCluster.getZkAddr());
List<AbnormalJob> oldAbnormalJobs = new ArrayList<>();
if (saturnStatistics != null) {
String result = saturnStatistics.getResult();
if (StringUtils.isNotBlank(result)) {
oldAbnormalJobs = JSON.parseArray(result, AbnormalJob.class);
}
}
return oldAbnormalJobs;
}
private List<Timeout4AlarmJob> getOldTimeout4AlarmJobs(ZkCluster zkCluster) {
SaturnStatistics saturnStatistics = saturnStatisticsService
.findStatisticsByNameAndZkList(StatisticsTableKeyConstant.TIMEOUT_4_ALARM_JOB, zkCluster.getZkAddr());
List<Timeout4AlarmJob> oldTimeout4AlarmJobs = new ArrayList<>();
if (saturnStatistics != null) {
String result = saturnStatistics.getResult();
if (StringUtils.isNotBlank(result)) {
oldTimeout4AlarmJobs = JSON.parseArray(result, Timeout4AlarmJob.class);
}
}
return oldTimeout4AlarmJobs;
}
protected StatisticsModel initStatisticsModel() {
StatisticsModel statisticsModel = new StatisticsModel();
ExecutorInfoAnalyzer executorInfoAnalyzer = new ExecutorInfoAnalyzer();
executorInfoAnalyzer.setReportAlarmService(reportAlarmService);
statisticsModel.setExecutorInfoAnalyzer(executorInfoAnalyzer);
OutdatedNoRunningJobAnalyzer outdatedNoRunningJobAnalyzer = new OutdatedNoRunningJobAnalyzer();
outdatedNoRunningJobAnalyzer.setAbnormalShardingStateCache(abnormalShardingStateCache);
outdatedNoRunningJobAnalyzer.setReportAlarmService(reportAlarmService);
outdatedNoRunningJobAnalyzer.setJobService(jobService);
statisticsModel.setOutdatedNoRunningJobAnalyzer(outdatedNoRunningJobAnalyzer);
UnableFailoverJobAnalyzer unableFailoverJobAnalyzer = new UnableFailoverJobAnalyzer();
unableFailoverJobAnalyzer.setJobService(jobService);
statisticsModel.setUnableFailoverJobAnalyzer(unableFailoverJobAnalyzer);
Timeout4AlarmJobAnalyzer timeout4AlarmJobAnalyzer = new Timeout4AlarmJobAnalyzer();
timeout4AlarmJobAnalyzer.setReportAlarmService(reportAlarmService);
statisticsModel.setTimeout4AlarmJobAnalyzer(timeout4AlarmJobAnalyzer);
JobStatisticsAnalyzer jobStatisticsAnalyzer = new JobStatisticsAnalyzer();
statisticsModel.setJobStatisticsAnalyzer(jobStatisticsAnalyzer);
DomainStatisticsAnalyzer domainStatisticsAnalyzer = new DomainStatisticsAnalyzer();
statisticsModel.setDomainStatisticsAnalyzer(domainStatisticsAnalyzer);
ZkClusterDailyCountAnalyzer zkClusterDailyCountAnalyzer = new ZkClusterDailyCountAnalyzer();
statisticsModel.setZkClusterDailyCountAnalyzer(zkClusterDailyCountAnalyzer);
return statisticsModel;
}
}
|
package gamepack;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Random;
import org.newdawn.slick.geom.Rectangle;
public class TileListManager
{
private TileList tileList;
private ArrayList<Point> goodPositions;
private final int tileSize;
//Will compute the goodPositins where Tiles will be
public TileListManager(int tileSize, Collection<Rectangle> rectangleList)
{
tileList = new TileList();
this.tileSize = tileSize;
this.goodPositions = new ArrayList<Point>();
for(Rectangle curRect : rectangleList){
this.goodPositions.add(new Point((int)curRect.getX(), (int)curRect.getY()));
}
}
//Return the TileList of the TileListManager to display it
public TileList getTileList()
{
return tileList;
}
//Create new tiles at the right positions
public boolean generateNewTile()
{
Random alea = new Random();
boolean isFree = true;
Point currentGoodPosition;
Tile currentTile;
ArrayList<Point> goodFreeTile = new ArrayList<Point>();
//Construction of a new TileList which contain only free space for new Tile
for (int i = 0; i < goodPositions.size(); i++) {
currentGoodPosition = goodPositions.get(i);
for (int j = 0; j < tileList.getSize(); j++) {
currentTile = tileList.getTile(j);
if (currentGoodPosition.getX() == currentTile.getX() && currentGoodPosition.getY() == currentTile.getY())
{
isFree = false;
}
}
if (isFree) { //If any Tile in tileList is equal to the current goodPosition so it's a free tile
goodFreeTile.add(new Point(currentGoodPosition.getX(),currentGoodPosition.getY()));
isFree = true;
}
}
//If after traversing all the goodPosition any Tile is free so we return an error
if (goodFreeTile.isEmpty()) {
return false;
}else{
//Choose randomly a free space and add the new Tile
int tmp = alea.nextInt(goodFreeTile.size());
tileList.add(new Tile(goodFreeTile.get(tmp).getX(), goodFreeTile.get(tmp).getY(),tileSize));
return true;
}
}
//Give each tile his direction and his arrived Tile(null if no arrived tile, None if no Direction)
//Then it will set the arrived point (coordinnates of the arrivedTile if there is one)
public void initMovement(Direction d)
{
ArrayList<TileList> swagList = new ArrayList<TileList>();
ArrayList<Integer> listX = new ArrayList<Integer>();
ArrayList<Integer> listY = new ArrayList<Integer>();
System.out.println(d);
int curX = 0;
int curY = 0;
for(Point curPoint : this.goodPositions){
int xOfCurPoint = curPoint.getX();
int yOfCurPoint = curPoint.getY();
if(xOfCurPoint>curX){
listX.add(xOfCurPoint);
if(d == Direction.Right){Collections.reverse(listX);}
curX = xOfCurPoint;
}
if(yOfCurPoint>curY){
listY.add(yOfCurPoint);
curY = yOfCurPoint;
}
}
//Gestion de l'appui sur la touche droite et gauche
if(d == Direction.Left || d == Direction.Right){
this.tileList.sortY(); //Tri sur Y de la liste de tuiles afin de les regrouper par lignes
int i = 0;
curY = (int)this.tileList.getTile(0).getY();
swagList.add(new TileList());
//On trie toutes les tuiles par ligne
for(Tile curTile : this.tileList.gettList()){
if(curY != curTile.getY()){
i++;
swagList.add(new TileList());
curY = (int)curTile.getY();
}
swagList.get(i).add(curTile);
}
//On veut maintenant grer le dplacement proprement parler
for(TileList curTileList : swagList){
curTileList.sortX();//Tri de chaque ligne
if(d == Direction.Right){Collections.reverse(curTileList.gettList());}
Tile precTile = null;//La tuile prcdente qui sert aux fusions
boolean precTilefus = false;//un boolen qui vite de faire des fusions en chaine
int collumn=0;
//On condidre chaque tuile
for(Tile curTile : curTileList.gettList()){
curTile.setDirection(d);//On dfini la direction
if(precTile == null){
curTile.setArrivedTile(null);
curTile.setArrivedPoint(new Point(listX.get(collumn), (int)curTile.getY()));
precTile = curTile;
precTilefus = false;
}
else{
//On check si les valeurs sont gales et si on avait pas dj fait une fusion avant
if(curTile.getValue() == precTile.getValue() && !precTilefus){
curTile.setArrivedTile(precTile);
curTile.setArrivedPoint(precTile.getArrivedPoint());
precTile = curTile;
precTilefus = true;
}
else{
curTile.setArrivedTile(null);//On se retrouve sur une case vide du coup
//On rcupre le point de la tuile prcdente dans la liste des X possibles et on prend le suivant
curTile.setArrivedPoint(new Point(listX.get(listX.indexOf(precTile.getArrivedPoint().getX())+1), (int)curTile.getY()));
precTile = curTile;
precTilefus = false;
collumn++;
}
}
}
}
}
else if(d == Direction.Down || d == Direction.Up){
this.tileList.sortY();
}
}
//Move each Tile in the right direction and set them at the good position if they passe their good position
//return true if there is movement, false otherwise
public boolean manageMovement(int FPS)
{
//init
boolean trueIfMovement = false; //For the state modification in WindowGame
final float movementDurationInSec = 1.0f;
float pixelPerFrame = 0; //Speed of the tile
for(int i = 0; i < tileList.getSize(); i++)
{
//current Tile in the list
Tile currentTile = tileList.getTile(i);
Direction currentDirection = currentTile.getDirection();
//if the tile has to move
if(currentDirection != Direction.None)
{
trueIfMovement = true;
//if the tile is not arrived
if(!currentTile.isArrived())
{
//move the tile depending on the FPS
pixelPerFrame = FPS/movementDurationInSec;
if(currentDirection == Direction.Left)
currentTile.move(-pixelPerFrame,0);
else if(currentDirection == Direction.Right)
currentTile.move(pixelPerFrame,0);
else if(currentDirection == Direction.Down)
currentTile.move(0,+pixelPerFrame);
else if(currentDirection == Direction.Up)
currentTile.move(0,-pixelPerFrame);
//if the tile has gone too far (because of low framerate etc..)
if(pixelPerFrame > 1)
currentTile.improvePosition();
}
//if the tile is arrived, then its Direction will be set to None
else
currentTile.setDirection(Direction.None);
}
}
return trueIfMovement;
}
//call the function refreshFusion for each tile
//if refreshFusion return true, delete the current tile from the list (null + remove)
public void manageFusion()
{
for(int i = 0; i < tileList.getSize(); i++)
{
Tile t = this.tileList.getTile(i);
if (t.getArrivedTile() != null && t.refreshFusion())
{
this.tileList.remove(i);
}
}
}
}
|
package gestock.window;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
public class Interface extends JFrame implements ActionListener {
public Interface(){
super("gestock");
// The main panel
JPanel mainPanel = new JPanel(new BorderLayout());
setContentPane(mainPanel);
JPanel menuUp = new JPanel();
menuUp.setLayout(new BoxLayout(menuUp, BoxLayout.X_AXIS));
mainPanel.add(menuUp, BorderLayout.NORTH);
menuUp.setBackground(Color.white);
JPanel tables = new JPanel(new FlowLayout());
mainPanel.add(tables, BorderLayout.CENTER);
tables.setBackground(Color.white);
JPanel bottomButtonPanel = new JPanel(new BorderLayout());
mainPanel.add(bottomButtonPanel, BorderLayout.SOUTH);
bottomButtonPanel.setBackground(Color.white);
JPanel space = new JPanel();
bottomButtonPanel.add(space, BorderLayout.SOUTH);
space.setBackground(Color.white);
AbstractButton bottomButton = new JButton("Je viens d'acheter");
bottomButton.setBackground(Color.white);
bottomButtonPanel.add(bottomButton, BorderLayout.WEST);
bottomButton.setBackground(Color.WHITE);
bottomButton.setContentAreaFilled(false);
bottomButton.setOpaque(true);
bottomButton.setPressedIcon(new ImageIcon());
try {
Image img = ImageIO.read(getClass().getResource("../resources/add64.png"));
Image newImg = img.getScaledInstance(48, 48, Image.SCALE_SMOOTH);
bottomButton.setIcon(new ImageIcon(newImg));
} catch (IOException ex) {
}
bottomButton.setVerticalTextPosition(SwingConstants.BOTTOM);
bottomButton.setHorizontalTextPosition(SwingConstants.CENTER);
AbstractButton catalogue = new JButton("Catalogue");
menuUp.add(catalogue);
catalogue.setBackground(Color.WHITE);
catalogue.setContentAreaFilled(false);
catalogue.setOpaque(true);
catalogue.setPressedIcon(new ImageIcon());
try {
Image img = ImageIO.read(getClass().getResource("../resources/data110.png"));
Image newImg = img.getScaledInstance(48, 48, Image.SCALE_SMOOTH);
catalogue.setIcon(new ImageIcon(newImg));
} catch (IOException ex) {
}
catalogue.setVerticalTextPosition(SwingConstants.BOTTOM);
catalogue.setHorizontalTextPosition(SwingConstants.CENTER);
AbstractButton gardeManger = new JButton("Garde-manger");
menuUp.add(gardeManger);
gardeManger.setBackground(Color.WHITE);
gardeManger.setContentAreaFilled(false);
gardeManger.setOpaque(true);
gardeManger.setPressedIcon(new ImageIcon());
try {
Image img = ImageIO.read(getClass().getResource("../resources/cutlery23.png"));
Image newImg = img.getScaledInstance(48, 48, Image.SCALE_SMOOTH);
gardeManger.setIcon(new ImageIcon(newImg));
} catch (IOException ex) {
}
gardeManger.setVerticalTextPosition(SwingConstants.BOTTOM);
gardeManger.setHorizontalTextPosition(SwingConstants.CENTER);
AbstractButton listeAchats = new JButton("Liste achats");
listeAchats.setBackground(Color.WHITE);
listeAchats.setContentAreaFilled(false);
listeAchats.setOpaque(true);
listeAchats.setPressedIcon(new ImageIcon());
menuUp.add(listeAchats);
try {
Image img = ImageIO.read(getClass().getResource("../resources/shopping122.png"));
Image newImg = img.getScaledInstance(48, 48, Image.SCALE_SMOOTH);
listeAchats.setIcon(new ImageIcon(newImg));
} catch (IOException ex) {
}
listeAchats.setVerticalTextPosition(SwingConstants.BOTTOM);
listeAchats.setHorizontalTextPosition(SwingConstants.CENTER);
AbstractButton chercher = new JButton("Chercher");
chercher.setBackground(Color.WHITE);
chercher.setContentAreaFilled(false);
chercher.setOpaque(true);
chercher.setPressedIcon(new ImageIcon());
menuUp.add(chercher);
try {
Image img = ImageIO.read(getClass().getResource("../resources/search100.png"));
Image newImg = img.getScaledInstance(48, 48, Image.SCALE_SMOOTH);
chercher.setIcon(new ImageIcon(newImg));
} catch (IOException ex) {
}
chercher.setVerticalTextPosition(SwingConstants.BOTTOM);
chercher.setHorizontalTextPosition(SwingConstants.CENTER);
menuUp.add(Box.createHorizontalGlue());
AbstractButton parametres = new JButton("Parametres");
parametres.setBackground(Color.WHITE);
parametres.setContentAreaFilled(false);
parametres.setOpaque(true);
parametres.setPressedIcon(new ImageIcon());
menuUp.add(parametres);
try {
Image img = ImageIO.read(getClass().getResource("../resources/network60.png"));
Image newImg = img.getScaledInstance(48, 48, Image.SCALE_SMOOTH);
parametres.setIcon(new ImageIcon(newImg));
} catch (IOException ex) {
}
parametres.setVerticalTextPosition(SwingConstants.BOTTOM);
parametres.setHorizontalTextPosition(SwingConstants.CENTER);
JPanel log = new JPanel();
log.setLayout(new BoxLayout(log, BoxLayout.Y_AXIS));
menuUp.add(log);
log.setBackground(Color.white);
JLabel user = new JLabel("User");
log.add(user);
AbstractButton logout = new JButton("Logout");
logout.setBackground(Color.WHITE);
logout.setContentAreaFilled(false);
logout.setOpaque(true);
logout.setPressedIcon(new ImageIcon());
logout.setBorderPainted(true);
log.add(logout);
try {
Image img = ImageIO.read(getClass().getResource("../resources/network60.png"));
Image newImg = img.getScaledInstance(48, 48, Image.SCALE_SMOOTH);
logout.setIcon(new ImageIcon(newImg));
} catch (IOException ex) {
}
logout.setVerticalTextPosition(SwingConstants.CENTER);
logout.setHorizontalTextPosition(SwingConstants.RIGHT);
createMenuBar();
try {
Image img = ImageIO.read(getClass().getResource("../resources/gestock-blue.png"));
setIconImage(img);
} catch (Exception e) {
}
setSize(700, 700);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private void createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenu helpMenu = new JMenu("Help");
fileMenu.setMnemonic(KeyEvent.VK_F);
helpMenu.setMnemonic(KeyEvent.VK_H);
JMenuItem exit = new JMenuItem("Exit");
JMenuItem licences = new JMenuItem("Licences");
exit.addActionListener((ActionEvent e) -> {
System.exit(0);
});
licences.addActionListener((ActionEvent e) -> {
new LicensesWindow();
});
fileMenu.add(exit);
helpMenu.add(licences);
menubar.add(fileMenu);
menubar.add(helpMenu);
setJMenuBar(menubar);
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getSource());
}
}
|
package com.sri.ai.test.grinder.library.equality.cardinality.plaindpll;
import static com.sri.ai.expresso.helper.Expressions.apply;
import static com.sri.ai.expresso.helper.Expressions.parse;
import static com.sri.ai.util.Util.list;
import java.util.Collection;
import org.junit.Test;
import com.google.common.annotations.Beta;
import com.sri.ai.expresso.api.Expression;
import com.sri.ai.expresso.api.IndexExpressionsSet;
import com.sri.ai.expresso.core.DefaultIntensionalMultiSet;
import com.sri.ai.expresso.helper.Expressions;
import com.sri.ai.grinder.api.Rewriter;
import com.sri.ai.grinder.helper.GrinderUtil;
import com.sri.ai.grinder.library.FunctorConstants;
import com.sri.ai.grinder.plaindpll.core.SGDPLLT;
import com.sri.ai.grinder.plaindpll.problemtype.ModelCounting;
import com.sri.ai.grinder.plaindpll.theory.EqualityConstraintTheory;
import com.sri.ai.grinder.plaindpll.theory.term.SymbolTermTheory;
@Beta
public class SymbolEqualityModelCountingDPLLTest extends AbstractSymbolicSymbolEqualityDPLLTest {
@Override
protected Expression makeProblem(Expression expression, IndexExpressionsSet indexExpressions) {
Expression set = new DefaultIntensionalMultiSet(indexExpressions, Expressions.ONE, expression);
Expression problem = apply(FunctorConstants.CARDINALITY, set);
return problem;
}
@Override
protected Rewriter makeRewriter() {
return new SGDPLLT(new EqualityConstraintTheory(new SymbolTermTheory()), new ModelCounting());
}
@Test
public void test() {
Expression expression;
Expression expected;
Collection<String> indices;
GrinderUtil.setTraceAndJustificationOffAndTurnOffConcurrency();
// this example tests whether conditioning an index to a value considers previous disequalities on that index,
// because X is split on b first, and then the algorithm attempts to condition on X = Y, but that requires Y to be != b.
expression = parse("X != b and X = Y");
indices = list("X");
expected = parse("if Y = b then 0 else 1");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
// tests elimination for quantified sub-expressions
expression = parse("for all Y : X = Y");
indices = list("X");
expected = parse("if | type(Y) | - 1 = 0 then | Everything | else 0");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
// tests case in which symbolic solutions with conditions that are not splitters need to be combined
// Combination must discriminate between splitters and not splitters.
// In this example, we get solutions with a condition on | Everything | - 1 > 0.
expression = parse(""
+ "(X = a and (Z = a and there exists Y in Everything : Y != b) or (Z != a and there exists Y in Everything : Y != c and Y != d))"
+ "or"
+ "(X != a and (Z = a and there exists Y in Everything : Y != e and Y != f and Y != g) or (Z != a and there exists Y in Everything : Y != c and Y != d))");
indices = list("X");
expected = parse("if Z = a then (if | Everything | - 1 > 0 then 1 else 0) + if | Everything | - 3 > 0 then | Everything | - 1 else 0 else (if | Everything | - 2 > 0 then 1 else 0) + if | Everything | - 2 > 0 then | Everything | - 1 else 0");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
expression = parse("true");
indices = null; // means all variables
expected = parse("1");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
expression = parse("false");
indices = null; // means all variables
expected = parse("0");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
// tests answer completeness
expression = parse("(Y = a and X = T) or (Y != a and X = T1 and T = T1)");
indices = list("Y");
// original algorithm provided this incomplete solution due to incomplete condition-applying-on-solution algorithm used in externalization
// expected = parse("if X = T then if T = T1 then if T = T1 then 10 else 1 else 1 else (if X = T1 then if T = T1 then 9 else 0 else 0)");
expected = parse("if X = T then if T = T1 then | Everything | else 1 else 0");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
expression = parse("X != Y");
indices = list("X");
expected = parse("| Everything | - 1");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
expression = parse("X != Y and X != a");
indices = list("X");
expected = parse("if Y = a then | Everything | - 1 else | Everything | - 2");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
expression = parse("X != Y and X != Z and X != a");
indices = list("X");
expected = parse("if Z = Y then if Y = a then | Everything | - 1 else | Everything | - 2 else if Y = a then | Everything | - 2 else if Z = a then | Everything | - 2 else | Everything | - 3");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
expression = parse("Y = a and X != Y and X != a");
indices = list("X");
expected = parse("if Y = a then | Everything | - 1 else 0");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
expression = parse("X1 != X2 and (X2 = X3 or X2 = X4) and X3 = X1 and X4 = X1");
indices = null; // means all variables
expected = parse("0");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
expression = parse("X1 != X2 and X2 != X0 and X1 != X0");
indices = null; // means all variables
expected = parse("(| Everything | - 1) * | Everything | * (| Everything | - 2)");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
expression = parse("true");
indices = null; // means all variables
expected = parse("1");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
expression = parse("true");
indices = list("X", "Y");
expected = parse("| Everything | * | Everything |");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
expression = parse("false");
indices = null; // means all variables
expected = parse("0");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
expression = parse("false");
indices = list("X", "Y");
expected = parse("0");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
expression = parse("X = a");
indices = null; // means all variables
expected = parse("1");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
expression = parse("X != a");
indices = null; // means all variables
expected = parse("| Everything | - 1");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
expression = parse("X = a");
indices = list("X", "Y");
expected = parse("| Everything |");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
expression = parse("X != a");
indices = list("X", "Y");
expected = parse("(| Everything | - 1)*| Everything |");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
expression = parse("X = a and Y != b");
indices = list("X", "Y");
expected = parse("| Everything | - 1");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
expression = parse("X != a and Y != b");
indices = list("X", "Y");
expected = parse("(| Everything | - 1)*(| Everything | - 1)");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
expression = parse("X != a or Y != b");
indices = list("X", "Y");
expected = parse("| Everything | + -1 + (| Everything | - 1) * | Everything |");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
expression = parse("X != a and X != Y and Y != a");
indices = null;
expected = parse("(| Everything | - 2) * (| Everything | - 1)");
runSymbolicAndNonSymbolicTests(expression, indices, expected);
}
}
|
package com.tlear.pegasus;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
public class Pegasus extends ApplicationAdapter {
public Pegasus(int width, int height) {
this.windowWidth = width;
this.windowHeight = height;
}
private int windowWidth;
private int windowHeight;
BitmapFont font;
// Camera init
private OrthographicCamera camera;
private SpriteBatch batch;
private ShapeRenderer shapeRenderer;
// Texture init
// Model init
private Ship ship;
@Override
public void create () {
batch = new SpriteBatch();
shapeRenderer = new ShapeRenderer();
font = new BitmapFont();
font.setColor(Color.RED);
// Initialise camera
camera = new OrthographicCamera();
camera.setToOrtho(false, windowWidth, windowHeight);
// Initialise ship
ship = new Ship(windowWidth, windowHeight);
}
@Override
public void render () {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// Update the camera.
camera.update();
batch.setProjectionMatrix(camera.combined);
shapeRenderer.setProjectionMatrix(camera.combined);
// Render the ship
ship.draw(batch, shapeRenderer);
// Checking for keyboard input
if (Gdx.input.isKeyPressed(Keys.A)) ship.addAngle(1);
if (Gdx.input.isKeyPressed(Keys.D)) ship.addAngle(-1);
if (Gdx.input.isKeyPressed(Keys.S)) ship.addSpeed(-5);
if (Gdx.input.isKeyPressed(Keys.W)) ship.addSpeed(5);
}
@Override
public void dispose() {
batch.dispose();
}
@Override
public void resize(int width, int height) {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
}
|
package TobleMiner.MineFight;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.ItemDespawnEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.inventory.ItemStack;
import TobleMiner.MineFight.Util.Util;
public class EventListener implements Listener
{
final Main mane;
public EventListener(Main p)
{
this.mane = p;
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event)
{
Main.gameEngine.playerInteract(event);
Player p = event.getPlayer();
ItemStack is = p.getInventory().getItemInHand();
if(event.getAction().equals(Action.RIGHT_CLICK_BLOCK))
{
Material material = event.getClickedBlock().getType();
if(material.equals(Material.SIGN) || material.equals(Material.SIGN_POST) || material.equals(Material.WALL_SIGN))
{
Main.gameEngine.rightClickSign(p,event.getClickedBlock());
}
if(is != null && is.getType().equals(Material.INK_SACK) && is.getDurability() == (short)4)
{
Main.gameEngine.rightClickBlockWithLapis(p,event.getClickedBlock(),p.getInventory());
}
}
if(is != null)
{
if(event.getAction().equals(Action.RIGHT_CLICK_AIR) || event.getAction().equals(Action.RIGHT_CLICK_BLOCK))
{
if(is.getType().equals(Material.STICK))
{
Main.gameEngine.rightClickWithStick(p);
}
if(is.getType().equals(Material.DIAMOND))
{
Main.gameEngine.rightClickWithDiamond(p);
}
else if(is.getType().equals(Material.BONE))
{
Main.gameEngine.rightClickWithBone(p);
}
}
if(is.getType().equals(Material.WOOD_SWORD))
{
if(event.getAction().equals(Action.RIGHT_CLICK_AIR))
{
Main.gameEngine.ClickWithWoodenSword(p,true);
}
else if(event.getAction().equals(Action.LEFT_CLICK_AIR) || event.getAction().equals(Action.LEFT_CLICK_BLOCK))
{
Main.gameEngine.ClickWithWoodenSword(p,false);
}
}
}
}
@EventHandler
public void onPlayerDropItem(PlayerDropItemEvent event)
{
if(Main.gameEngine.configuration.isMpvpEnabled(event.getPlayer().getWorld()))
{
Location l = event.getItemDrop().getLocation();
boolean isItemAllowed = false;
if(event.getItemDrop().getItemStack().getType().equals(Material.IRON_INGOT))
{
isItemAllowed = Main.gameEngine.configuration.getHandGrenadeAllowedInsideProtection();
}
else if(event.getItemDrop().getItemStack().getType().equals(Material.REDSTONE))
{
isItemAllowed = Main.gameEngine.configuration.getIMSAllowedInsideProtection();
}
else if(event.getItemDrop().getItemStack().getType().equals(Material.INK_SACK))
{
isItemAllowed = Main.gameEngine.configuration.getC4allowedInsideProtection();
}
else if(event.getItemDrop().getItemStack().getType().equals(Material.CLAY_BALL))
{
isItemAllowed = Main.gameEngine.configuration.getM18allowedInsideProtection();
}
if(Util.protect.isLocProtected(l) && (!isItemAllowed))
{
event.setCancelled(true);
}
else
{
event.setCancelled(Main.gameEngine.playerDroppedItem(event.getItemDrop(),event.getPlayer()));
}
}
}
@EventHandler
public void onPlayerPickupItem(PlayerPickupItemEvent event)
{
Material mat = event.getItem().getItemStack().getType();
if(mat.equals(Material.REDSTONE) || mat.equals(Material.CLAY_BALL) || mat.equals(Material.IRON_INGOT) || mat.equals(Material.INK_SACK))
{
event.setCancelled(Main.gameEngine.playerPickUpItem(event.getItem(),event.getPlayer()));
}
}
@EventHandler
public void onItemDespawn(ItemDespawnEvent event)
{
Material mat = event.getEntity().getItemStack().getType();
if(mat.equals(Material.REDSTONE) || mat.equals(Material.CLAY_BALL))
{
event.setCancelled(Main.gameEngine.itemDespawn(event.getEntity()));
}
}
@EventHandler
public void onEntityDamage(EntityDamageEvent event)
{
if(event.getEntity() instanceof Item)
{
Material mat = ((Item)event.getEntity()).getItemStack().getType();
if(mat.equals(Material.REDSTONE) || mat.equals(Material.CLAY_BALL) || mat.equals(Material.INK_SACK))
{
event.setCancelled(Main.gameEngine.itemDamage((Item)event.getEntity(),event.getCause()));
}
}
else if(event.getEntity() instanceof Player)
{
event.setCancelled(Main.gameEngine.playerDamage((Player)event.getEntity(),event.getCause()));
}
}
@EventHandler
public void onEntityCombust(EntityCombustEvent event)
{
if(event.getEntity() instanceof Item)
{
Material mat = ((Item)event.getEntity()).getItemStack().getType();
if(mat.equals(Material.REDSTONE) || mat.equals(Material.CLAY_BALL) || mat.equals(Material.INK_SACK))
{
event.setCancelled(Main.gameEngine.itemDamage((Item)event.getEntity(),DamageCause.MELTING));
}
}
}
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event)
{
event.setDeathMessage(Main.gameEngine.playerDeath(event.getEntity(),event.getDeathMessage(),event.getDrops()));
}
@EventHandler
public void onPlayerChangedWorld(PlayerChangedWorldEvent event)
{
Main.gameEngine.playerChangedWorld(event.getPlayer(),event.getFrom());
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event)
{
Main.gameEngine.playerQuit(event.getPlayer());
}
@EventHandler
public void onProjectileLaunch(ProjectileLaunchEvent event)
{
Projectile proj = event.getEntity();
if(proj instanceof Arrow)
{
Arrow arrow = (Arrow)proj;
LivingEntity shooter = arrow.getShooter();
if(shooter instanceof Player)
{
Player p = (Player)shooter;
event.setCancelled(Main.gameEngine.arrowLaunchedByPlayer(p,arrow));
}
}
}
@EventHandler
public void onBlockPlace(BlockPlaceEvent event)
{
Player p = event.getPlayer();
Block b = event.getBlock();
/*List<ProtectedArea> lpa = Main.gameEngine.configuration.protectionRegions.get(b.getWorld());
boolean isBlockProtected = false;
if(lpa != null)
{
for(ProtectedArea pa : lpa)
{
isBlockProtected = pa.isBlockInsideRegion(b);
}
}
if(!isBlockProtected)
{
if(p != null && b != null)
{
if(b.getType().equals(Material.DISPENSER))
{*/
event.setCancelled(Main.gameEngine.blockPlace(p,b));
/*}
}
}
event.setCancelled(isBlockProtected);*/
}
@EventHandler
public void onBlockBreak(BlockBreakEvent event)
{
event.setCancelled(Main.gameEngine.blockBreak(event.getPlayer(),event.getBlock()));
/*Block b = event.getBlock();
List<ProtectedArea> lpa = Main.gameEngine.configuration.protectionRegions.get(b.getWorld());
if(lpa != null)
{
for(ProtectedArea pa : lpa)
{
event.setCancelled(pa.isBlockInsideRegion(b));
}
}*/
}
@EventHandler
public void onBlockDamage(BlockDamageEvent event)
{
event.setCancelled(Main.gameEngine.blockBreak(event.getPlayer(),event.getBlock()));
/*Block b = event.getBlock();
List<ProtectedArea> lpa = Main.gameEngine.configuration.protectionRegions.get(b.getWorld());
if(lpa != null)
{
for(ProtectedArea pa : lpa)
{
event.setCancelled(pa.isBlockInsideRegion(b));
}
}*/
}
@EventHandler
public void onEntityChangeBlock(EntityChangeBlockEvent event)
{
if(event.getEntity() instanceof Player)
{
event.setCancelled(Main.gameEngine.blockBreak((Player)event.getEntity(),event.getBlock()));
}
}
@EventHandler
public void onEntityDamageByEntity(EntityDamageByEntityEvent event)
{
if(event.getDamager() instanceof Arrow && event.getEntity() instanceof Player)
{
event.setCancelled(Main.gameEngine.arrowHitPlayer((Arrow)event.getDamager(),(Player)event.getEntity(),event.getDamage()));
if(event.isCancelled()) event.setDamage(0d);
}
else if(event.getDamager() instanceof Player && event.getEntity() instanceof Player)
{
event.setCancelled(Main.gameEngine.playerDamagePlayer((Player)event.getDamager(),(Player)event.getEntity(),event.getDamage()));
if(event.isCancelled()) event.setDamage(0d);
}
}
@EventHandler
public void onPlayerRespawn(PlayerRespawnEvent event)
{
event.setRespawnLocation(Main.gameEngine.playerRespawn(event.getPlayer(),event.getRespawnLocation()));
}
@EventHandler
public void onProjectileHit(ProjectileHitEvent event)
{
if(event.getEntity() instanceof Arrow)
{
Main.gameEngine.arrowHit((Arrow)event.getEntity());
}
}
@EventHandler
public void onAsyncPlayerChat(AsyncPlayerChatEvent apce)
{
apce.setFormat(Main.gameEngine.playerChat(apce.getFormat(),apce.getPlayer()));
}
@EventHandler
public void onFoodLevelChange(FoodLevelChangeEvent event)
{
if(event.getEntity() instanceof Player)
{
event.setCancelled(Main.gameEngine.foodLevelChange((Player)event.getEntity()));
}
}
@EventHandler
public void onEntityExplode(EntityExplodeEvent event)
{
event.setCancelled(Main.gameEngine.entityExplosion(event));
}
}
|
package VASSAL.build.module.map;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.datatransfer.StringSelection;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DragSourceMotionListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.dnd.InvalidDnDOperationException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import VASSAL.build.AbstractBuildable;
import VASSAL.build.Buildable;
import VASSAL.build.GameModule;
import VASSAL.build.module.GameComponent;
import VASSAL.build.module.GlobalOptions;
import VASSAL.build.module.Map;
import VASSAL.build.module.map.boardPicker.Board;
import VASSAL.command.ChangeTracker;
import VASSAL.command.Command;
import VASSAL.command.NullCommand;
import VASSAL.configure.BooleanConfigurer;
import VASSAL.counters.BasicPiece;
import VASSAL.counters.BoundsTracker;
import VASSAL.counters.Deck;
import VASSAL.counters.DeckVisitor;
import VASSAL.counters.DeckVisitorDispatcher;
import VASSAL.counters.Decorator;
import VASSAL.counters.DragBuffer;
import VASSAL.counters.EventFilter;
import VASSAL.counters.GamePiece;
import VASSAL.counters.Highlighter;
import VASSAL.counters.KeyBuffer;
import VASSAL.counters.PieceCloner;
import VASSAL.counters.PieceFinder;
import VASSAL.counters.PieceIterator;
import VASSAL.counters.PieceSorter;
import VASSAL.counters.PieceVisitorDispatcher;
import VASSAL.counters.Properties;
import VASSAL.counters.Stack;
import VASSAL.tools.LaunchButton;
import VASSAL.tools.image.ImageUtils;
import VASSAL.tools.imageop.Op;
/**
* This is a MouseListener that moves pieces onto a Map window
*/
public class PieceMover extends AbstractBuildable
implements MouseListener,
GameComponent,
Comparator<GamePiece> {
/** The Preferences key for autoreporting moves. */
public static final String AUTO_REPORT = "autoReport"; //$NON-NLS-1$
public static final String NAME = "name";
public static final String HOTKEY = "hotkey";
protected Map map;
protected Point dragBegin;
protected GamePiece dragging;
protected LaunchButton markUnmovedButton;
protected String markUnmovedText;
protected String markUnmovedIcon;
public static final String ICON_NAME = "icon"; //$NON-NLS-1$
protected String iconName;
// Selects drag target from mouse click on the Map
protected PieceFinder dragTargetSelector;
// Selects piece to merge with at the drop destination
protected PieceFinder dropTargetSelector;
// Processes drag target after having been selected
protected PieceVisitorDispatcher selectionProcessor;
protected Comparator<GamePiece> pieceSorter = new PieceSorter();
public void addTo(Buildable b) {
dragTargetSelector = createDragTargetSelector();
dropTargetSelector = createDropTargetSelector();
selectionProcessor = createSelectionProcessor();
map = (Map) b;
map.addLocalMouseListener(this);
GameModule.getGameModule().getGameState().addGameComponent(this);
map.setDragGestureListener(DragHandler.getTheDragHandler());
map.setPieceMover(this);
setAttribute(Map.MARK_UNMOVED_TEXT,
map.getAttributeValueString(Map.MARK_UNMOVED_TEXT));
setAttribute(Map.MARK_UNMOVED_ICON,
map.getAttributeValueString(Map.MARK_UNMOVED_ICON));
}
protected MovementReporter createMovementReporter(Command c) {
return new MovementReporter(c);
}
/**
* When the user completes a drag-drop operation, the pieces being
* dragged will either be combined with an existing piece on the map
* or else placed on the map without stack. This method returns a
* {@link PieceFinder} instance that determines which {@link GamePiece}
* (if any) to combine the being-dragged pieces with.
*
* @return
*/
protected PieceFinder createDropTargetSelector() {
return new PieceFinder.Movable() {
public Object visitDeck(Deck d) {
final Point pos = d.getPosition();
final Point p = new Point(pt.x - pos.x, pt.y - pos.y);
if (d.getShape().contains(p)) {
return d;
}
else {
return null;
}
}
public Object visitDefault(GamePiece piece) {
GamePiece selected = null;
if (this.map.getStackMetrics().isStackingEnabled() &&
this.map.getPieceCollection().canMerge(dragging, piece)) {
if (this.map.isLocationRestricted(pt)) {
final Point snap = this.map.snapTo(pt);
if (piece.getPosition().equals(snap)) {
selected = piece;
}
}
else {
selected = (GamePiece) super.visitDefault(piece);
}
}
if (selected != null &&
DragBuffer.getBuffer().contains(selected) &&
selected.getParent() != null &&
selected.getParent().topPiece() == selected) {
selected = null;
}
return selected;
}
public Object visitStack(Stack s) {
GamePiece selected = null;
if (this.map.getStackMetrics().isStackingEnabled() &&
this.map.getPieceCollection().canMerge(dragging, s) &&
!DragBuffer.getBuffer().contains(s) &&
s.topPiece() != null) {
if (this.map.isLocationRestricted(pt) && !s.isExpanded()) {
if (s.getPosition().equals(this.map.snapTo(pt))) {
selected = s;
}
}
else {
selected = (GamePiece) super.visitStack(s);
}
}
return selected;
}
};
}
/**
* When the user clicks on the map, a piece from the map is selected by
* the dragTargetSelector. What happens to that piece is determined by
* the {@link PieceVisitorDispatcher} instance returned by this method.
* The default implementation does the following: If a Deck, add the top
* piece to the drag buffer If a stack, add it to the drag buffer.
* Otherwise, add the piece and any other multi-selected pieces to the
* drag buffer.
*
* @see #createDragTargetSelector
* @return
*/
protected PieceVisitorDispatcher createSelectionProcessor() {
return new DeckVisitorDispatcher(new DeckVisitor() {
public Object visitDeck(Deck d) {
DragBuffer.getBuffer().clear();
for (PieceIterator it = d.drawCards(); it.hasMoreElements();) {
DragBuffer.getBuffer().add(it.nextPiece());
}
return null;
}
public Object visitStack(Stack s) {
DragBuffer.getBuffer().clear();
// RFE 1629255 - Only add selected pieces within the stack to the DragBuffer
// Add whole stack if all pieces are selected - better drag cursor
int selectedCount = 0;
for (int i = 0; i < s.getPieceCount(); i++) {
if (Boolean.TRUE.equals(s.getPieceAt(i)
.getProperty(Properties.SELECTED))) {
selectedCount++;
}
}
if (((Boolean) GameModule.getGameModule().getPrefs().getValue(Map.MOVING_STACKS_PICKUP_UNITS)).booleanValue() || s.getPieceCount() == 1 || s.getPieceCount() == selectedCount) {
DragBuffer.getBuffer().add(s);
}
else {
for (int i = 0; i < s.getPieceCount(); i++) {
final GamePiece p = s.getPieceAt(i);
if (Boolean.TRUE.equals(p.getProperty(Properties.SELECTED))) {
DragBuffer.getBuffer().add(p);
}
}
}
// End RFE 1629255
if (KeyBuffer.getBuffer().containsChild(s)) {
// If clicking on a stack with a selected piece, put all selected
// pieces in other stacks into the drag buffer
KeyBuffer.getBuffer().sort(PieceMover.this);
for (Iterator<GamePiece> i =
KeyBuffer.getBuffer().getPiecesIterator(); i.hasNext();) {
final GamePiece piece = i.next();
if (piece.getParent() != s) {
DragBuffer.getBuffer().add(piece);
}
}
}
return null;
}
public Object visitDefault(GamePiece selected) {
DragBuffer.getBuffer().clear();
if (KeyBuffer.getBuffer().contains(selected)) {
// If clicking on a selected piece, put all selected pieces into the
// drag buffer
KeyBuffer.getBuffer().sort(PieceMover.this);
for (Iterator<GamePiece> i =
KeyBuffer.getBuffer().getPiecesIterator(); i.hasNext();) {
DragBuffer.getBuffer().add(i.next());
}
}
else {
DragBuffer.getBuffer().clear();
DragBuffer.getBuffer().add(selected);
}
return null;
}
});
}
/**
* Returns the {@link PieceFinder} instance that will select a
* {@link GamePiece} for processing when the user clicks on the map.
* The default implementation is to return the first piece whose shape
* contains the point clicked on.
*
* @return
*/
protected PieceFinder createDragTargetSelector() {
return new PieceFinder.Movable() {
public Object visitDeck(Deck d) {
final Point pos = d.getPosition();
final Point p = new Point(pt.x - pos.x, pt.y - pos.y);
if (d.boundingBox().contains(p) && d.getPieceCount() > 0) {
return d;
}
else {
return null;
}
}
};
}
public void setup(boolean gameStarting) {
if (gameStarting) {
initButton();
}
}
public Command getRestoreCommand() {
return null;
}
private Image loadIcon(String name) {
if (name == null || name.length() == 0) return null;
return Op.load(name).getImage();
}
protected void initButton() {
final String value = getMarkOption();
if (GlobalOptions.PROMPT.equals(value)) {
BooleanConfigurer config = new BooleanConfigurer(
Map.MARK_MOVED, "Mark Moved Pieces", Boolean.TRUE);
GameModule.getGameModule().getPrefs().addOption(config);
}
if (!GlobalOptions.NEVER.equals(value)) {
if (markUnmovedButton == null) {
final ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
final GamePiece[] p = map.getAllPieces();
final Command c = new NullCommand();
for (int i = 0; i < p.length; ++i) {
c.append(markMoved(p[i], false));
}
GameModule.getGameModule().sendAndLog(c);
map.repaint();
}
};
markUnmovedButton =
new LaunchButton("", NAME, HOTKEY, Map.MARK_UNMOVED_ICON, al);
Image img = null;
if (iconName != null && iconName.length() > 0) {
img = loadIcon(iconName);
if (img != null) {
markUnmovedButton.setAttribute(Map.MARK_UNMOVED_ICON, iconName);
}
}
if (img == null) {
img = loadIcon(markUnmovedIcon);
if (img != null) {
markUnmovedButton.setAttribute(Map.MARK_UNMOVED_ICON, markUnmovedIcon);
}
}
markUnmovedButton.setAlignmentY(0.0F);
markUnmovedButton.setText(markUnmovedText);
markUnmovedButton.setToolTipText(
map.getAttributeValueString(Map.MARK_UNMOVED_TOOLTIP));
map.getToolBar().add(markUnmovedButton);
}
}
else if (markUnmovedButton != null) {
map.getToolBar().remove(markUnmovedButton);
markUnmovedButton = null;
}
}
private String getMarkOption() {
String value = map.getAttributeValueString(Map.MARK_MOVED);
if (value == null) {
value = GlobalOptions.getInstance()
.getAttributeValueString(GlobalOptions.MARK_MOVED);
}
return value;
}
public String[] getAttributeNames() {
return new String[]{ICON_NAME};
}
public String getAttributeValueString(String key) {
return ICON_NAME.equals(key) ? iconName : null;
}
public void setAttribute(String key, Object value) {
if (ICON_NAME.equals(key)) {
iconName = (String) value;
}
else if (Map.MARK_UNMOVED_TEXT.equals(key)) {
if (markUnmovedButton != null) {
markUnmovedButton.setAttribute(NAME, value);
}
markUnmovedText = (String) value;
}
else if (Map.MARK_UNMOVED_ICON.equals(key)) {
if (markUnmovedButton != null) {
markUnmovedButton.setAttribute(Map.MARK_UNMOVED_ICON, value);
}
markUnmovedIcon = (String) value;
}
}
protected boolean isMultipleSelectionEvent(MouseEvent e) {
return e.isShiftDown();
}
/** Invoked just before a piece is moved */
protected Command movedPiece(GamePiece p, Point loc) {
setOldLocation(p);
Command c = null;
if (!loc.equals(p.getPosition())) {
c = markMoved(p, true);
}
if (p.getParent() != null) {
final Command removedCommand = p.getParent().pieceRemoved(p);
c = c == null ? removedCommand : c.append(removedCommand);
}
return c;
}
protected void setOldLocation(GamePiece p) {
if (p instanceof Stack) {
for (int i = 0; i < ((Stack) p).getPieceCount(); i++) {
Decorator.setOldProperties(((Stack) p).getPieceAt(i));
}
}
else Decorator.setOldProperties(p);
}
public Command markMoved(GamePiece p, boolean hasMoved) {
if (GlobalOptions.NEVER.equals(getMarkOption())) {
hasMoved = false;
}
Command c = new NullCommand();
if (!hasMoved || shouldMarkMoved()) {
if (p instanceof Stack) {
for (Iterator<GamePiece> i = ((Stack) p).getPiecesIterator();
i.hasNext();) {
c.append(markMoved(i.next(), hasMoved));
}
}
else if (p.getProperty(Properties.MOVED) != null) {
if (p.getId() != null) {
final ChangeTracker comm = new ChangeTracker(p);
p.setProperty(Properties.MOVED,
hasMoved ? Boolean.TRUE : Boolean.FALSE);
c = comm.getChangeCommand();
}
}
}
return c;
}
protected boolean shouldMarkMoved() {
final String option = getMarkOption();
if (GlobalOptions.ALWAYS.equals(option)) {
return true;
}
else if (GlobalOptions.NEVER.equals(option)) {
return false;
}
else {
return Boolean.TRUE.equals(
GameModule.getGameModule().getPrefs().getValue(Map.MARK_MOVED));
}
}
/**
* Moves pieces in DragBuffer to point p by generating a Command for
* each element in DragBuffer
*
* @param map
* Map
* @param p
* Point mouse released
*/
public Command movePieces(Map map, Point p) {
final List<GamePiece> allDraggedPieces = new ArrayList<GamePiece>();
final PieceIterator it = DragBuffer.getBuffer().getIterator();
if (!it.hasMoreElements()) return null;
Point offset = null;
Command comm = new NullCommand();
final BoundsTracker tracker = new BoundsTracker();
// Map of Point->List<GamePiece> of pieces to merge with at a given
// location. There is potentially one piece for each Game Piece Layer.
final HashMap<Point,List<GamePiece>> mergeTargets =
new HashMap<Point,List<GamePiece>>();
while (it.hasMoreElements()) {
dragging = it.nextPiece();
tracker.addPiece(dragging);
/*
* Take a copy of the pieces in dragging.
* If it is a stack, it is cleared by the merging process.
*/
final ArrayList<GamePiece> draggedPieces = new ArrayList<GamePiece>(0);
if (dragging instanceof Stack) {
int size = ((Stack) dragging).getPieceCount();
for (int i = 0; i < size; i++) {
draggedPieces.add(((Stack) dragging).getPieceAt(i));
}
}
else {
draggedPieces.add(dragging);
}
if (offset != null) {
p = new Point(dragging.getPosition().x + offset.x,
dragging.getPosition().y + offset.y);
}
List<GamePiece> mergeCandidates = mergeTargets.get(p);
GamePiece mergeWith = null;
// Find an already-moved piece that we can merge with at the destination
// point
if (mergeCandidates != null) {
for (int i = 0, n = mergeCandidates.size(); i < n; ++i) {
final GamePiece candidate = mergeCandidates.get(i);
if (map.getPieceCollection().canMerge(candidate, dragging)) {
mergeWith = candidate;
mergeCandidates.set(i, dragging);
break;
}
}
}
// Now look for an already-existing piece at the destination point
if (mergeWith == null) {
mergeWith = map.findAnyPiece(p, dropTargetSelector);
if (mergeWith == null && !Boolean.TRUE.equals(
dragging.getProperty(Properties.IGNORE_GRID))) {
p = map.snapTo(p);
}
if (offset == null) {
offset = new Point(p.x - dragging.getPosition().x,
p.y - dragging.getPosition().y);
}
if (mergeWith != null && map.getStackMetrics().isStackingEnabled()) {
mergeCandidates = new ArrayList<GamePiece>();
mergeCandidates.add(dragging);
mergeCandidates.add(mergeWith);
mergeTargets.put(p, mergeCandidates);
}
}
if (mergeWith == null) {
comm = comm.append(movedPiece(dragging, p));
comm = comm.append(map.placeAt(dragging, p));
if (!(dragging instanceof Stack) &&
!Boolean.TRUE.equals(dragging.getProperty(Properties.NO_STACK))) {
final Stack parent = map.getStackMetrics().createStack(dragging);
if (parent != null) {
comm = comm.append(map.placeAt(parent, p));
}
}
}
else {
// Do not add pieces to the Deck that are Obscured to us, or that the Deck
// does not want to contain. Removing them from the draggedPieces list will
// cause them to be left behind where the drag started.
// NB. Pieces that have been dragged from a face-down Deck will be be Obscued to us,
// but will be Obscured by the dummy user Deck.NO_USER
if (mergeWith instanceof Deck) {
final ArrayList<GamePiece> newList = new ArrayList<GamePiece>(0);
for (GamePiece piece : draggedPieces) {
if (((Deck) mergeWith).mayContain(piece)) {
final boolean isObscuredToMe = Boolean.TRUE.equals(piece.getProperty(Properties.OBSCURED_TO_ME));
if (! isObscuredToMe || (isObscuredToMe && Deck.NO_USER.equals(piece.getProperty(Properties.OBSCURED_BY)))) {
newList.add(piece);
}
}
}
if (newList.size() != draggedPieces.size()) {
draggedPieces.clear();
for (GamePiece piece : newList) {
draggedPieces.add(piece);
}
}
}
for (GamePiece piece : draggedPieces) {
comm = comm.append(movedPiece(piece, mergeWith.getPosition()));
comm = comm.append(map.getStackMetrics().merge(mergeWith, piece));
}
}
for (GamePiece piece : draggedPieces) {
KeyBuffer.getBuffer().add(piece);
}
// Record each individual piece moved
for (GamePiece piece : draggedPieces) {
allDraggedPieces.add(piece);
}
tracker.addPiece(dragging);
}
if (GlobalOptions.getInstance().autoReportEnabled()) {
final Command report = createMovementReporter(comm).getReportCommand().append(new MovementReporter.HiddenMovementReporter(comm).getReportCommand());
report.execute();
comm = comm.append(report);
}
// Apply key after move to each moved piece
if (map.getMoveKey() != null) {
applyKeyAfterMove(allDraggedPieces, comm, map.getMoveKey());
}
tracker.repaint();
return comm;
}
protected void applyKeyAfterMove(List<GamePiece> pieces,
Command comm, KeyStroke key) {
for (GamePiece piece : pieces) {
if (piece.getProperty(Properties.SNAPSHOT) == null) {
piece.setProperty(Properties.SNAPSHOT,
PieceCloner.getInstance().clonePiece(piece));
}
comm.append(piece.keyEvent(key));
}
}
/**
* This listener is used for faking drag-and-drop on Java 1.1 systems
*
* @param e
*/
public void mousePressed(MouseEvent e) {
if (canHandleEvent(e)) {
selectMovablePieces(e);
}
}
/** Place the clicked-on piece into the {@link DragBuffer} */
protected void selectMovablePieces(MouseEvent e) {
final GamePiece p = map.findPiece(e.getPoint(), dragTargetSelector);
dragBegin = e.getPoint();
if (p != null) {
final EventFilter filter =
(EventFilter) p.getProperty(Properties.MOVE_EVENT_FILTER);
if (filter == null || !filter.rejectEvent(e)) {
selectionProcessor.accept(p);
}
else {
DragBuffer.getBuffer().clear();
}
}
else {
DragBuffer.getBuffer().clear();
}
// show/hide selection boxes
map.repaint();
}
/** @deprecated Use {@link #selectMovablePieces(MouseEvent)}. */
@Deprecated
protected void selectMovablePieces(Point point) {
final GamePiece p = map.findPiece(point, dragTargetSelector);
dragBegin = point;
selectionProcessor.accept(p);
// show/hide selection boxes
map.repaint();
}
protected boolean canHandleEvent(MouseEvent e) {
return !e.isShiftDown() &&
!e.isControlDown() &&
!e.isMetaDown() &&
e.getClickCount() < 2 &&
!e.isConsumed();
}
/**
* Return true if this point is "close enough" to the point at which
* the user pressed the mouse to be considered a mouse click (such
* that no moves are done)
*/
public boolean isClick(Point pt) {
boolean isClick = false;
if (dragBegin != null) {
final Board b = map.findBoard(pt);
boolean useGrid = b != null && b.getGrid() != null;
if (useGrid) {
final PieceIterator it = DragBuffer.getBuffer().getIterator();
final GamePiece dragging = it.hasMoreElements() ? it.nextPiece() : null;
useGrid =
dragging != null &&
!Boolean.TRUE.equals(dragging.getProperty(Properties.IGNORE_GRID)) &&
(dragging.getParent() == null || !dragging.getParent().isExpanded());
}
if (useGrid) {
if (map.equals(DragBuffer.getBuffer().getFromMap())) {
if (map.snapTo(pt).equals(map.snapTo(dragBegin))) {
isClick = true;
}
}
}
else {
if (Math.abs(pt.x - dragBegin.x) <= 5 &&
Math.abs(pt.y - dragBegin.y) <= 5) {
isClick = true;
}
}
}
return isClick;
}
public void mouseReleased(MouseEvent e) {
if (canHandleEvent(e)) {
if (!isClick(e.getPoint())) {
performDrop(e.getPoint());
}
}
dragBegin = null;
map.getView().setCursor(null);
}
protected void performDrop(Point p) {
final Command move = movePieces(map, p);
GameModule.getGameModule().sendAndLog(move);
if (move != null) {
DragBuffer.getBuffer().clear();
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
/**
* Implement Comparator to sort the contents of the drag buffer before
* completing the drag. This sorts the contents to be in the same order
* as the pieces were in their original parent stack.
*/
public int compare(GamePiece p1, GamePiece p2) {
return pieceSorter.compare(p1, p2);
}
// We force the loading of these classes because otherwise they would
// be loaded when the user initiates the first drag, which makes the
// start of the drag choppy.
static {
try {
Class.forName(MovementReporter.class.getName(),
true, MovementReporter.class.getClassLoader());
Class.forName(KeyBuffer.class.getName(),
true, KeyBuffer.class.getClassLoader());
}
catch (ClassNotFoundException e) {
throw new IllegalStateException(e); // impossible
}
}
/** Common functionality for DragHandler for cases with and without
* drag image support. <p>
* NOTE: DragSource.isDragImageSupported() returns false for j2sdk1.4.2_02 on
* Windows 2000
*
* @author Pieter Geerkens
*/
abstract static public class AbstractDragHandler
implements DragGestureListener, DragSourceListener,
DragSourceMotionListener, DropTargetListener
{
final static private AbstractDragHandler theDragHandler =
DragSource.isDragImageSupported() ? new DragHandler()
: new DragHandlerNoImage();
/** returns the singleton DragHandler instance */
static public AbstractDragHandler getTheDragHandler() {
return theDragHandler;
}
final static int CURSOR_ALPHA = 127; // psuedo cursor is 50% transparent
final static int EXTRA_BORDER = 4; // psuedo cursor is includes a 4 pixel border
protected JLabel dragCursor; // An image label. Lives on current DropTarget's
// LayeredPane.
// private BufferedImage dragImage; // An image label. Lives on current DropTarget's LayeredPane.
private Point drawOffset = new Point(); // translates event coords to local
// drawing coords
private Rectangle boundingBox; // image bounds
private int originalPieceOffsetX; // How far drag STARTED from gamepiece's
// center
private int originalPieceOffsetY; // I.e. on original map
protected double dragPieceOffCenterZoom = 1.0; // zoom at start of drag
private int currentPieceOffsetX; // How far cursor is CURRENTLY off-center,
// a function of
// dragPieceOffCenter{X,Y,Zoom}
private int currentPieceOffsetY; // I.e. on current map (which may have
// different zoom
protected double dragCursorZoom = 1.0; // Current cursor scale (zoom)
Component dragWin; // the component that initiated the drag operation
Component dropWin; // the drop target the mouse is currently over
JLayeredPane drawWin; // the component that owns our psuedo-cursor
// Seems there can be only one DropTargetListener a drop target. After we
// process a drop target
// event, we manually pass the event on to this listener.
java.util.Map<Component,DropTargetListener> dropTargetListeners =
new HashMap<Component,DropTargetListener>();
abstract protected int getOffsetMult();
/**
* Creates a new DropTarget and hooks us into the beginning of a
* DropTargetListener chain. DropTarget events are not multicast;
* there can be only one "true" listener.
*/
static public DropTarget makeDropTarget(Component theComponent, int dndContants, DropTargetListener dropTargetListener) {
if (dropTargetListener != null) {
DragHandler.getTheDragHandler()
.dropTargetListeners.put(theComponent, dropTargetListener);
}
return new DropTarget(theComponent, dndContants,
DragHandler.getTheDragHandler());
}
static public void removeDropTarget(Component theComponent) {
DragHandler.getTheDragHandler().dropTargetListeners.remove(theComponent);
}
protected DropTargetListener getListener(DropTargetEvent e) {
final Component component = e.getDropTargetContext().getComponent();
return dropTargetListeners.get(component);
}
/** Moves the drag cursor on the current draw window */
protected void moveDragCursor(int dragX, int dragY) {
if (drawWin != null) {
dragCursor.setLocation(dragX - drawOffset.x, dragY - drawOffset.y);
}
}
/** Removes the drag cursor from the current draw window */
protected void removeDragCursor() {
if (drawWin != null) {
if (dragCursor != null) {
dragCursor.setVisible(false);
drawWin.remove(dragCursor);
}
drawWin = null;
}
}
/** calculates the offset between cursor dragCursor positions */
private void calcDrawOffset() {
if (drawWin != null) {
// drawOffset is the offset between the mouse location during a drag
// and the upper-left corner of the cursor
// accounts for difference between event point (screen coords)
// and Layered Pane position, boundingBox and off-center drag
drawOffset.x = -boundingBox.x - currentPieceOffsetX + EXTRA_BORDER;
drawOffset.y = -boundingBox.y - currentPieceOffsetY + EXTRA_BORDER;
SwingUtilities.convertPointToScreen(drawOffset, drawWin);
}
}
/**
* creates or moves cursor object to given JLayeredPane. Usually called by setDrawWinToOwnerOf()
*/
private void setDrawWin(JLayeredPane newDrawWin) {
if (newDrawWin != drawWin) {
// remove cursor from old window
if (dragCursor.getParent() != null) {
dragCursor.getParent().remove(dragCursor);
}
if (drawWin != null) {
drawWin.repaint(dragCursor.getBounds());
}
drawWin = newDrawWin;
calcDrawOffset();
dragCursor.setVisible(false);
drawWin.add(dragCursor, JLayeredPane.DRAG_LAYER);
}
}
/**
* creates or moves cursor object to given window. Called when drag operation begins in a window or the cursor is
* dragged over a new drop-target window
*/
public void setDrawWinToOwnerOf(Component newDropWin) {
if (newDropWin != null) {
final JRootPane rootWin = SwingUtilities.getRootPane(newDropWin);
if (rootWin != null) {
setDrawWin(rootWin.getLayeredPane());
}
}
}
/** Common functionality abstracted from makeDragImage and makeDragCursor
*
* @param zoom
* @param doOffset
* @param target
* @param setSize
* @return
*/
BufferedImage makeDragImageCursorCommon(double zoom, boolean doOffset,
Component target, boolean setSize) {
// FIXME: Should be an ImageOp.
dragCursorZoom = zoom;
final List<Point> relativePositions = buildBoundingBox(zoom, doOffset);
final int w = boundingBox.width + EXTRA_BORDER * 2;
final int h = boundingBox.height + EXTRA_BORDER * 2;
BufferedImage image = ImageUtils.createCompatibleTranslucentImage(w, h);
drawDragImage(image, target, relativePositions, zoom);
if (setSize) dragCursor.setSize(w, h);
image = featherDragImage(image, w, h, EXTRA_BORDER);
return image;
}
/**
* Creates the image to use when dragging based on the zoom factor
* passed in.
*
* @param zoom DragBuffer.getBuffer
* @return dragImage
*/
private BufferedImage makeDragImage(double zoom) {
return makeDragImageCursorCommon(zoom, false, null, false);
}
/**
* Installs the cursor image into our dragCursor JLabel.
* Sets current zoom. Should be called at beginning of drag
* and whenever zoom changes. INPUT: DragBuffer.getBuffer OUTPUT:
* dragCursorZoom cursorOffCenterX cursorOffCenterY boundingBox
* @param zoom DragBuffer.getBuffer
*
*/
protected void makeDragCursor(double zoom) {
// create the cursor if necessary
if (dragCursor == null) {
dragCursor = new JLabel();
dragCursor.setVisible(false);
}
dragCursor.setIcon(new ImageIcon(
makeDragImageCursorCommon(zoom, true, dragCursor, true)));
}
private List<Point> buildBoundingBox(double zoom, boolean doOffset) {
final ArrayList<Point> relativePositions = new ArrayList<Point>();
final PieceIterator dragContents = DragBuffer.getBuffer().getIterator();
final GamePiece firstPiece = dragContents.nextPiece();
GamePiece lastPiece = firstPiece;
currentPieceOffsetX =
(int) (originalPieceOffsetX / dragPieceOffCenterZoom * zoom + 0.5);
currentPieceOffsetY =
(int) (originalPieceOffsetY / dragPieceOffCenterZoom * zoom + 0.5);
boundingBox = firstPiece.getShape().getBounds();
boundingBox.width *= zoom;
boundingBox.height *= zoom;
boundingBox.x *= zoom;
boundingBox.y *= zoom;
if (doOffset) {
calcDrawOffset();
}
relativePositions.add(new Point(0,0));
int stackCount = 0;
while (dragContents.hasMoreElements()) {
final GamePiece nextPiece = dragContents.nextPiece();
final Rectangle r = nextPiece.getShape().getBounds();
r.width *= zoom;
r.height *= zoom;
r.x *= zoom;
r.y *= zoom;
final Point p = new Point(
(int) Math.round(
zoom * (nextPiece.getPosition().x - firstPiece.getPosition().x)),
(int) Math.round(
zoom * (nextPiece.getPosition().y - firstPiece.getPosition().y)));
r.translate(p.x, p.y);
if (nextPiece.getPosition().equals(lastPiece.getPosition())) {
stackCount++;
final StackMetrics sm = getStackMetrics(nextPiece);
r.translate(sm.unexSepX*stackCount,-sm.unexSepY*stackCount);
}
boundingBox.add(r);
relativePositions.add(p);
lastPiece = nextPiece;
}
return relativePositions;
}
private void drawDragImage(BufferedImage image, Component target,
List<Point> relativePositions, double zoom) {
final Graphics2D g = image.createGraphics();
int index = 0;
Point lastPos = null;
int stackCount = 0;
for (PieceIterator dragContents = DragBuffer.getBuffer().getIterator();
dragContents.hasMoreElements(); ) {
final GamePiece piece = dragContents.nextPiece();
final Point pos = relativePositions.get(index++);
final Map map = piece.getMap();
if (piece instanceof Stack){
stackCount = 0;
piece.draw(g, EXTRA_BORDER - boundingBox.x + pos.x,
EXTRA_BORDER - boundingBox.y + pos.y,
map == null ? target : map.getView(), zoom);
}
else {
final Point offset = new Point(0,0);
if (pos.equals(lastPos)) {
stackCount++;
final StackMetrics sm = getStackMetrics(piece);
offset.x = sm.unexSepX * stackCount;
offset.y = sm.unexSepY * stackCount;
}
else {
stackCount = 0;
}
final int x = EXTRA_BORDER - boundingBox.x + pos.x + offset.x;
final int y = EXTRA_BORDER - boundingBox.y + pos.y - offset.y;
piece.draw(g, x, y, map == null ? target : map.getView(), zoom);
final Highlighter highlighter = map == null ?
BasicPiece.getHighlighter() : map.getHighlighter();
highlighter.draw(piece, g, x, y, null, zoom);
}
lastPos = pos;
}
g.dispose();
}
private StackMetrics getStackMetrics(GamePiece piece) {
StackMetrics sm = null;
final Map map = piece.getMap();
if (map != null) {
sm = map.getStackMetrics();
}
if (sm == null) {
sm = new StackMetrics();
}
return sm;
}
private BufferedImage featherDragImage(BufferedImage src,
int w, int h, int b) {
// FIXME: This should be redone so that we draw the feathering onto the
// destination first, and then pass the Graphics2D on to draw the pieces
// directly over it. Presently this doesn't work because some of the
// pieces screw up the Graphics2D when passed it... The advantage to doing
// it this way is that we create only one BufferedImage instead of two.
final BufferedImage dst =
ImageUtils.createCompatibleTranslucentImage(w, h);
final Graphics2D g = dst.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// paint the rectangle occupied by the piece at specified alpha
g.setColor(new Color(0xff, 0xff, 0xff, CURSOR_ALPHA));
g.fillRect(0, 0, w, h);
// feather outwards
for (int f = 0; f < b; ++f) {
final int alpha = CURSOR_ALPHA * (f + 1) / b;
g.setColor(new Color(0xff, 0xff, 0xff, alpha));
g.drawRect(f, f, w-2*f, h-2*f);
}
// paint in the source image
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN));
g.drawImage(src, 0, 0, null);
g.dispose();
return dst;
}
// DRAG GESTURE LISTENER INTERFACE
// EVENT uses SCALED, DRAG-SOURCE coordinate system.
// PIECE uses SCALED, OWNER (arbitrary) coordinate system
/** Fires after user begins moving the mouse several pixels over a map. */
public void dragGestureRecognized(DragGestureEvent dge) {
try {
beginDragging(dge);
}
// FIXME: Fix by replacing AWT Drag 'n Drop with Swing DnD.
// Catch and ignore spurious DragGestures
catch (InvalidDnDOperationException e) {
}
}
protected Point dragGestureRecognizedPrep(DragGestureEvent dge) {
// Ensure the user has dragged on a counter before starting the drag.
final DragBuffer db = DragBuffer.getBuffer();
if (db.isEmpty()) return null;
// Remove any Immovable pieces from the DragBuffer that were
// selected in a selection rectangle, unless they are being
// dragged from a piece palette (i.e., getMap() == null).
final List<GamePiece> pieces = new ArrayList<GamePiece>();
for (PieceIterator i = db.getIterator();
i.hasMoreElements(); pieces.add(i.nextPiece()));
for (GamePiece piece : pieces) {
if (piece.getMap() != null &&
Boolean.TRUE.equals(piece.getProperty(Properties.NON_MOVABLE))) {
db.remove(piece);
}
}
// Bail out if this leaves no pieces to drag.
if (db.isEmpty()) return null;
final GamePiece piece = db.getIterator().nextPiece();
final Map map = dge.getComponent() instanceof Map.View ?
((Map.View) dge.getComponent()).getMap() : null;
final Point mousePosition = (map == null)
? dge.getDragOrigin()
: map.componentCoordinates(dge.getDragOrigin());
Point piecePosition = (map == null)
? piece.getPosition()
: map.componentCoordinates(piece.getPosition());
// If DragBuffer holds a piece with invalid coordinates (for example, a
// card drawn from a deck), drag from center of piece
if (piecePosition.x <= 0 || piecePosition.y <= 0) {
piecePosition = mousePosition;
}
// Account for offset of piece within stack
// We do this even for un-expanded stacks, since the offset can
// still be significant if the stack is large
dragPieceOffCenterZoom = map == null ? 1.0 : map.getZoom();
if (piece.getParent() != null && map != null) {
final Point offset = piece.getParent()
.getStackMetrics()
.relativePosition(piece.getParent(), piece);
piecePosition.translate(
(int) Math.round(offset.x * dragPieceOffCenterZoom),
(int) Math.round(offset.y * dragPieceOffCenterZoom));
}
// dragging from UL results in positive offsets
originalPieceOffsetX = piecePosition.x - mousePosition.x;
originalPieceOffsetY = piecePosition.y - mousePosition.y;
dragWin = dge.getComponent();
drawWin = null;
dropWin = null;
return mousePosition;
}
protected void beginDragging(DragGestureEvent dge) {
// this call is needed to instantiate the boundingBox object
final BufferedImage bImage = makeDragImage(dragPieceOffCenterZoom);
final Point dragPointOffset = new Point(
getOffsetMult() * (boundingBox.x + currentPieceOffsetX - EXTRA_BORDER),
getOffsetMult() * (boundingBox.y + currentPieceOffsetY - EXTRA_BORDER)
);
dge.startDrag(
Cursor.getPredefinedCursor(Cursor.HAND_CURSOR),
bImage,
dragPointOffset,
new StringSelection(""),
this
);
dge.getDragSource().addDragSourceMotionListener(this);
}
// DRAG SOURCE LISTENER INTERFACE
public void dragDropEnd(DragSourceDropEvent e) {
final DragSource ds = e.getDragSourceContext().getDragSource();
ds.removeDragSourceMotionListener(this);
}
public void dragEnter(DragSourceDragEvent e) {}
public void dragExit(DragSourceEvent e) {}
public void dragOver(DragSourceDragEvent e) {}
public void dropActionChanged(DragSourceDragEvent e) {}
// DRAG SOURCE MOTION LISTENER INTERFACE
// EVENT uses UNSCALED, SCREEN coordinate system
// Used to check for real mouse movement.
// Warning: dragMouseMoved fires 8 times for each point on development
// system (Win2k)
Point lastDragLocation = new Point();
/** Moves cursor after mouse */
abstract public void dragMouseMoved(DragSourceDragEvent e);
// DROP TARGET INTERFACE
// EVENT uses UNSCALED, DROP-TARGET coordinate system
/** switches current drawWin when mouse enters a new DropTarget */
public void dragEnter(DropTargetDragEvent e) {
final DropTargetListener forward = getListener(e);
if (forward != null) forward.dragEnter(e);
}
/**
* Last event of the drop operation. We adjust the drop point for
* off-center drag, remove the cursor, and pass the event along
* listener chain.
*/
public void drop(DropTargetDropEvent e) {
// EVENT uses UNSCALED, DROP-TARGET coordinate system
e.getLocation().translate(currentPieceOffsetX, currentPieceOffsetY);
final DropTargetListener forward = getListener(e);
if (forward != null) forward.drop(e);
}
/** ineffectual. Passes event along listener chain */
public void dragExit(DropTargetEvent e) {
final DropTargetListener forward = getListener(e);
if (forward != null) forward.dragExit(e);
}
/** ineffectual. Passes event along listener chain */
public void dragOver(DropTargetDragEvent e) {
final DropTargetListener forward = getListener(e);
if (forward != null) forward.dragOver(e);
}
/** ineffectual. Passes event along listener chain */
public void dropActionChanged(DropTargetDragEvent e) {
final DropTargetListener forward = getListener(e);
if (forward != null) forward.dropActionChanged(e);
}
}
/**
* Implements a psudo-cursor that follows the mouse cursor when user
* drags gamepieces. Supports map zoom by resizing cursor when it enters
* a drop target of type Map.View.
*
* @author Jim Urbas
* @version 0.4.2
*
*/
static public class DragHandlerNoImage extends AbstractDragHandler {
@Override
public void dragGestureRecognized(DragGestureEvent dge) {
final Point mousePosition = dragGestureRecognizedPrep(dge);
if (mousePosition == null) return;
makeDragCursor(dragPieceOffCenterZoom);
setDrawWinToOwnerOf(dragWin);
SwingUtilities.convertPointToScreen(mousePosition, drawWin);
moveDragCursor(mousePosition.x, mousePosition.y);
super.dragGestureRecognized(dge);
}
protected int getOffsetMult() {
return 1;
}
@Override
public void dragDropEnd(DragSourceDropEvent e) {
removeDragCursor();
super.dragDropEnd(e);
}
public void dragMouseMoved(DragSourceDragEvent e) {
if (!e.getLocation().equals(lastDragLocation)) {
lastDragLocation = e.getLocation();
moveDragCursor(e.getX(), e.getY());
if (dragCursor != null && !dragCursor.isVisible()) {
dragCursor.setVisible(true);
}
}
}
public void dragEnter(DropTargetDragEvent e) {
final Component newDropWin = e.getDropTargetContext().getComponent();
if (newDropWin != dropWin) {
final double newZoom = newDropWin instanceof Map.View
? ((Map.View) newDropWin).getMap().getZoom() : 1.0;
if (Math.abs(newZoom - dragCursorZoom) > 0.01) {
makeDragCursor(newZoom);
}
setDrawWinToOwnerOf(e.getDropTargetContext().getComponent());
dropWin = newDropWin;
}
super.dragEnter(e);
}
public void drop(DropTargetDropEvent e) {
removeDragCursor();
super.drop(e);
}
}
/** Implementation of AbstractDragHandler when DragImage is supported by JRE
*
* @Author Pieter Geerkens
*/
static public class DragHandler extends AbstractDragHandler {
public void dragGestureRecognized(DragGestureEvent dge) {
if (dragGestureRecognizedPrep(dge) == null) return;
super.dragGestureRecognized(dge);
}
protected int getOffsetMult() {
return -1;
}
public void dragMouseMoved(DragSourceDragEvent e) {}
}
}
|
package org.jasig.portal;
import java.io.Serializable;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.Map;
import java.util.Hashtable;
import java.util.HashSet;
import java.util.Collections;
import java.util.Locale;
import java.util.Random;
import java.util.Set;
import java.net.URL;
import java.lang.SecurityManager;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.AccessController;
import org.jasig.portal.services.LogService;
import org.jasig.portal.jndi.JNDIManager;
import org.jasig.portal.utils.SubstitutionWriter;
import org.jasig.portal.utils.SubstitutionServletOutputStream;
import com.oreilly.servlet.multipart.MultipartParser;
import com.oreilly.servlet.multipart.FilePart;
import com.oreilly.servlet.multipart.ParamPart;
public class PortalSessionManager extends HttpServlet {
// public static final String SESSION_TAG_VARIABLE="uP_session_tag";
public static final String INTERNAL_TAG_VALUE=Long.toHexString((new Random()).nextLong());
public static final String IDEMPOTENT_URL_TAG="idempotent";
private static final int sizeLimit = PropertiesManager.getPropertyAsInt("org.jasig.portal.PortalSessionManager.File_upload_max_size");
private static boolean initialized = false;
private static ServletContext servletContext = null;
// Following flag allows to disable features that prevent
// repeated requests from going through. This is useful
// when debugging and typing things in on a command line.
// Otherwise, the flag should be set to false.
private static final boolean ALLOW_REPEATED_REQUESTS=false;
// random number generator
private static final Random randomGenerator= new Random();
static {
LogService.instance().log(LogService.INFO, "uPortal started");
}
/**
* Initialize the PortalSessionManager servlet
* @throws ServletException
*/
public void init() throws ServletException {
if(!initialized) {
// Retrieve the servlet configuration object from the servlet container
// and make sure it's available
ServletConfig sc = getServletConfig();
if (sc == null) {
throw new ServletException("PortalSessionManager.init(): ServletConfig object was returned as null");
}
servletContext = sc.getServletContext();
try {
JNDIManager.initializePortalContext();
} catch (PortalException pe) {
if(pe.getRecordedException()!=null) {
StringWriter sw=new StringWriter();
pe.getRecordedException().printStackTrace(new PrintWriter(sw));
sw.flush();
LogService.instance().log(LogService.ERROR,"PortalSessionManager::doGet() : a PortalException has occurred : "+sw.toString());
throw new ServletException(pe.getRecordedException());
} else {
StringWriter sw=new StringWriter();
pe.printStackTrace(new PrintWriter(sw));
sw.flush();
LogService.instance().log(LogService.ERROR,"PortalSessionManager::doGet() : an unknown exception occurred : "+sw.toString());
throw new ServletException(pe);
}
}
// Flag that the portal has been initialized
initialized = true;
// Get the SAX implementation
if (System.getProperty("org.xml.sax.driver") == null) {
System.setProperty("org.xml.sax.driver", PropertiesManager.getProperty("org.xml.sax.driver"));
}
}
}
/**
* Process HTTP POST request
*
* @param req an incoming <code>HttpServletRequest</code> value
* @param res an outgoing <code>HttpServletResponse</code> value
* @exception ServletException if an error occurs
* @exception IOException if an error occurs
*/
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
doGet(req, res);
}
/**
* Process HTTP GET request.
*
* @param req an incoming <code>HttpServletRequest</code>
* @param res an outgoing <code>HttpServletResponse</code>
* @exception ServletException if an error occurs
* @exception IOException if an error occurs
*/
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// Disable page caching
res.setHeader("pragma", "no-cache");
res.setHeader("Cache-Control", "no-cache, max-age=0, must-revalidate");
res.setHeader("uPortal-version", "uPortal_2-0+");
res.setDateHeader("Expires", 0);
HttpSession session = req.getSession();
if (session != null) {
// obtain a tag table
Set requestTags=null;
synchronized(session) {
requestTags=(Set)session.getAttribute("uP_requestTags");
if(requestTags==null) {
requestTags=Collections.synchronizedSet(new HashSet());
session.setAttribute("uP_requestTags",requestTags);
}
}
// determine current tag
UPFileSpec upfs=new UPFileSpec(req);
String tag=upfs.getTagId();
// see if the tag was registered
boolean request_verified=false;
if(tag!=null) {
request_verified=(tag.equals(IDEMPOTENT_URL_TAG) || requestTags.remove(tag));
}
LogService.instance().log(LogService.DEBUG, "PortalSessionManager::doGet() : request verified: "+request_verified);
try {
UserInstance userInstance = null;
try {
// Retrieve the user's UserInstance object
userInstance = UserInstanceManager.getUserInstance(req);
} catch(Exception e) {
// NOTE: Should probably be forwarded to error page if the user instance could not be properly retrieved.
LogService.instance().log(LogService.ERROR, e);
// invalidate session, throw exception
if(session!=null) {
session.invalidate();
}
if(e instanceof PortalException) {
Exception ie=((PortalException) e).getRecordedException();
if(ie!=null) {
throw new ServletException(ie);
}
}
throw new ServletException(e);
}
// generate and register a new tag
String newTag=Long.toHexString(randomGenerator.nextLong());
LogService.instance().log(LogService.DEBUG,"PortalSessionManager::doGet() : generated new tag \""+newTag+"\" for the session "+req.getSession(false).getId());
// no need to check for duplicates :) we'd have to wait a lifetime of a universe for this time happen
if(!requestTags.add(newTag)) {
LogService.instance().log(LogService.ERROR,"PortalSessionManager::doGet() : a duplicate tag has been generated ! Time's up !");
}
// fire away
if(ALLOW_REPEATED_REQUESTS) {
userInstance.writeContent(new RequestParamWrapper(req,true),res);
} else {
userInstance.writeContent(new RequestParamWrapper(req,request_verified), new ResponseSubstitutionWrapper(res,INTERNAL_TAG_VALUE,newTag));
}
} catch (PortalException pe) {
StringWriter sw=new StringWriter();
pe.printStackTrace(new PrintWriter(sw));
sw.flush();
LogService.instance().log(LogService.ERROR,"PortalSessionManager::doGet() : a PortalException has occurred : "+sw.toString());
if(pe.getRecordedException()!=null) {
StringWriter sw2=new StringWriter();
pe.getRecordedException().printStackTrace(new PrintWriter(sw2));
sw2.flush();
LogService.instance().log(LogService.ERROR,"PortalSessionManager::doGet() : an encolsed PortalException stated : "+sw2.toString());
throw new ServletException(pe.getRecordedException());
}
} catch (Exception e) {
StringWriter sw=new StringWriter();
e.printStackTrace(new PrintWriter(sw));
sw.flush();
LogService.instance().log(LogService.ERROR,"PortalSessionManager::doGet() : an unknown exception occurred : "+sw.toString());
throw new ServletException(e);
}
} else {
throw new ServletException("Session object is null !");
}
}
/**
* Gets a URL associated with the named resource.
* Call this to access files with paths relative to the
* document root. Paths should begin with a "/".
* @param resource relative to the document root
* @return a URL associated with the named resource or null if the URL isn't accessible
* @throws java.net.MalformedURLException
*/
public static URL getResourceAsURL(String resource) {
//Make sure resource string starts with a "/"
if (!resource.startsWith("/"))
resource = "/" + resource;
URL url = null;
try {
url = servletContext.getResource(resource);
} catch (java.net.MalformedURLException murle) {
// if the URL is bad, just return null
}
return url;
}
/**
* Gets an input stream associated with the named resource.
* Call this to access files with paths relative to the
* document root. Paths should begin with a "/".
* @param resource relative to the document root
* @return an input stream assosiated with the named resource
*/
public static java.io.InputStream getResourceAsStream(String resource) {
//Make sure resource string starts with a "/"
if (!resource.startsWith("/"))
resource = "/" + resource;
return servletContext.getResourceAsStream(resource);
}
public class ResponseSubstitutionWrapper implements HttpServletResponse {
protected final HttpServletResponse res;
protected String sessionTag;
protected String newTag;
public ResponseSubstitutionWrapper(HttpServletResponse res,String sessionTag, String newTag) {
this.res=res;
this.sessionTag=sessionTag;
this.newTag=newTag;
}
public ServletOutputStream getOutputStream() throws IOException {
String encoding=this.getCharacterEncoding();
byte[] target,substitute;
if(encoding!=null) {
// use specified encoding
target=sessionTag.getBytes(encoding);
substitute=newTag.getBytes(encoding);
} else {
// use default system encoding
target=sessionTag.getBytes();
substitute=newTag.getBytes();
}
return new SubstitutionServletOutputStream(res.getOutputStream(),target,substitute,this.getBufferSize());
}
public PrintWriter getWriter() throws IOException {
return new PrintWriter(new SubstitutionWriter(res.getWriter(),sessionTag.toCharArray(),newTag.toCharArray(),this.getBufferSize()));
}
// pass-through implementation methods
// implementation of javax.servlet.ServletResponse interface
public String getCharacterEncoding() {
return res.getCharacterEncoding();
}
public void reset() {
res.reset();
}
public void flushBuffer() throws IOException {
res.flushBuffer();
}
public void setContentType(String type) {
res.setContentType(type);
}
public void setContentLength(int len) {
res.setContentLength(len);
}
public void setBufferSize(int size) {
res.setBufferSize(size);
}
public int getBufferSize() {
return res.getBufferSize();
}
public boolean isCommitted() {
return res.isCommitted();
}
public void setLocale(Locale loc) {
res.setLocale(loc);
}
public Locale getLocale() {
return res.getLocale();
}
// servlet 2.3 methods, inderect invokation:
public void resetBuffer() {
try {
java.lang.reflect.Method m = res.getClass().getMethod("reseBuffer", null);
m.invoke(res, null);
} catch (Exception e) {
}
}
// implementation of javax.servlet.http.HttpServletResponse interface
public void addCookie(Cookie cookie) {
this.res.addCookie(cookie);
}
public boolean containsHeader(String name) {
return this.res.containsHeader(name);
}
public String encodeURL(String url) {
return this.res.encodeURL(url);
}
public String encodeRedirectURL(String url) {
return this.res.encodeRedirectURL(url);
}
public String encodeUrl(String url) {
return this.res.encodeUrl(url);
}
public String encodeRedirectUrl(String url) {
return this.res.encodeRedirectUrl(url);
}
public void sendError(int sc, String msg) throws IOException {
this.res.sendError(sc, msg);
}
public void sendError(int sc) throws IOException {
this.res.sendError(sc);
}
public void sendRedirect(String location) throws IOException {
this.res.sendRedirect(location);
}
public void setDateHeader(String name, long date) {
this.res.setDateHeader(name, date);
}
public void addDateHeader(String name, long date) {
this.res.addDateHeader(name, date);
}
public void setHeader(String name, String value) {
this.res.setHeader(name, value);
}
public void addHeader(String name, String value) {
this.res.addHeader(name, value);
}
public void setIntHeader(String name, int value) {
this.res.setIntHeader(name, value);
}
public void addIntHeader(String name, int value) {
this.res.addIntHeader(name, value);
}
public void setStatus(int sc) {
this.res.setStatus(sc);
}
public void setStatus(int sc, String sm) {
this.res.setStatus(sc, sm);
}
}
/**
* A wrapper around http request object to prevent unverified requests from
* accessing any of the request parameters.
*
* @author <a href="mailto:pkharchenko@interactivebusiness.com">Peter Kharchenko</a>
*/
public class RequestParamWrapper implements HttpServletRequest {
// the request being wrapped
protected final HttpServletRequest req;
protected Hashtable parameters;
protected boolean request_verified;
/**
* Creates a new <code>RequestParamWrapper</code> instance.
*
* @param source an <code>HttpServletRequest</code> value that's being wrapped.
* @param request_verified a <code>boolean</code> flag that determines if the request params should be accessable.
*/
public RequestParamWrapper (HttpServletRequest source,boolean request_verified) {
// leech all of the information from the source request
this.req=source;
this.request_verified=request_verified;
parameters = new Hashtable();
// only bother with parameter work if should be accessable
if(request_verified) {
// parse request body
String contentType = source.getContentType();
if (contentType != null && contentType.startsWith("multipart/form-data")) {
com.oreilly.servlet.multipart.Part attachmentPart;
try {
MultipartParser multi = new MultipartParser(source, sizeLimit, true, true);
while ((attachmentPart = multi.readNextPart()) != null) {
String partName = attachmentPart.getName();
if (attachmentPart.isParam()) {
ParamPart parameterPart = (ParamPart)attachmentPart;
String paramValue = parameterPart.getStringValue();
if (parameters.containsKey(partName)) {
/* Assume they meant a multivalued tag, like a checkbox */
String[] oldValueArray = (String[])parameters.get(partName);
String[] valueArray = new String[oldValueArray.length + 1];
for (int i = 0; i < oldValueArray.length; i++) {
valueArray[i] = oldValueArray[i];
}
valueArray[oldValueArray.length] = paramValue;
parameters.put(partName, valueArray);
}
else {
String[] valueArray = new String[1];
valueArray[0] = paramValue;
parameters.put(partName, valueArray);
}
}
else if (attachmentPart.isFile()) {
FilePart filePart = (FilePart)attachmentPart;
String filename = filePart.getFileName();
if (filename != null) {
MultipartDataSource fileUpload = new MultipartDataSource(filePart);
if (parameters.containsKey(partName)) {
MultipartDataSource[] oldValueArray = (MultipartDataSource[])parameters.get(partName);
MultipartDataSource[] valueArray = new MultipartDataSource[oldValueArray.length + 1];
for (int i = 0; i < oldValueArray.length; i++) {
valueArray[i] = oldValueArray[i];
}
valueArray[oldValueArray.length] = fileUpload;
parameters.put(partName, valueArray);
}
else {
MultipartDataSource[] valueArray = new MultipartDataSource[1];
valueArray[0] = fileUpload;
parameters.put(partName, valueArray);
}
}
}
}
} catch (Exception e) {
LogService.instance().log(LogService.ERROR, e);
}
}
// regular params
Enumeration en = source.getParameterNames();
if (en != null) {
while (en.hasMoreElements()) {
String pName = (String)en.nextElement();
parameters.put(pName, source.getParameterValues(pName));
}
}
}
}
/**
* Overloaded method
* @param name
* @return parameter
*/
public String getParameter(String name) {
String[] value_array = this.getParameterValues(name);
if ((value_array != null) && (value_array.length > 0)) {
return value_array[0];
} else {
return null;
}
}
/**
* Overloaded method
* @return parameter names
*/
public Enumeration getParameterNames() {
return this.parameters.keys();
}
/**
* Return a String[] for this parameter
* @param parameter name
* @result String[] if parameter is not an Object[]
*/
public String[] getParameterValues(String name) {
Object[] pars = (Object[])this.parameters.get(name);
if (pars!=null && pars instanceof String[]) {
return (String[])this.parameters.get(name);
} else {
return null;
}
}
/**
* Overloaded method
*
* @return a <code>Map</code> value
*/
public Map getParameterMap() {
return parameters;
}
/**
* Return the Object represented by this parameter name
* @param parameter name
* @result Object
*/
public Object[] getObjectParameterValues(String name) {
return (Object[])this.parameters.get(name);
}
// this method should be overloaded, otherwise params will be visible
public String getRequestURI() {
return req.getRequestURI();
}
// pass through methods
public String getPathInfo() {
return req.getPathInfo();
}
public String getPathTranslated() {
return req.getPathTranslated();
}
public String getContextPath() {
return req.getContextPath();
}
public String getQueryString() {
return req.getQueryString();
}
public String getServletPath() {
return req.getServletPath();
}
// This method is new in Servlet 2.3.
// java.lang.reflect methods are used here in an effort
// to be compatible with older servlet APIs.
public StringBuffer getRequestURL() {
try {
java.lang.reflect.Method m = req.getClass().getMethod("getRequestURL", null);
return (StringBuffer)m.invoke(req, null);
} catch (Exception e) {
return null;
}
}
// peterk: this won't work. Spec says that this method has to be executed prior to
// reading request body, and we do exactly this in the constructor of this class :(
// This method is new in Servlet 2.3.
// java.lang.reflect methods are used here in an effort
// to be compatible with older servlet APIs.
public void setCharacterEncoding(String env) throws java.io.UnsupportedEncodingException {
try {
Class[] paramTypes = new Class[] { new String().getClass() };
java.lang.reflect.Method m = req.getClass().getMethod("setCharacterEncoding", paramTypes);
Object[] args = new Object[] { env };
m.invoke(req, args);
} catch (Exception e) {
}
}
public String getAuthType() {
return req.getAuthType();
}
public Cookie[] getCookies() {
return req.getCookies();
}
public long getDateHeader(String name) {
return req.getDateHeader(name);
}
public String getHeader(String name) {
return req.getHeader(name);
}
public Enumeration getHeaders(String name) {
return req.getHeaders(name);
}
public Enumeration getHeaderNames() {
return req.getHeaderNames();
}
public int getIntHeader(String name) {
return req.getIntHeader(name);
}
public String getMethod() {
return req.getMethod();
}
public String getRemoteUser() {
return req.getRemoteUser();
}
public boolean isUserInRole(String role) {
return req.isUserInRole(role);
}
public java.security.Principal getUserPrincipal() {
return req.getUserPrincipal();
}
public String getRequestedSessionId() {
return req.getRequestedSessionId();
}
public HttpSession getSession(boolean create) {
return req.getSession(create);
}
public HttpSession getSession() {
return req.getSession();
}
public boolean isRequestedSessionIdValid() {
return req.isRequestedSessionIdValid();
}
public boolean isRequestedSessionIdFromCookie() {
return req.isRequestedSessionIdFromCookie();
}
public boolean isRequestedSessionIdFromURL() {
return req.isRequestedSessionIdFromURL();
}
public boolean isRequestedSessionIdFromUrl() {
return req.isRequestedSessionIdFromURL();
}
public Object getAttribute(String name) {
return req.getAttribute(name);
}
public Enumeration getAttributeNames() {
return req.getAttributeNames();
}
public String getCharacterEncoding() {
return req.getCharacterEncoding();
}
public int getContentLength() {
return req.getContentLength();
}
public String getContentType() {
return req.getContentType();
}
public ServletInputStream getInputStream() throws IOException {
return req.getInputStream();
}
public String getProtocol() {
return req.getProtocol();
}
public String getScheme() {
return req.getScheme();
}
public String getServerName() {
return req.getServerName();
}
public int getServerPort() {
return req.getServerPort();
}
public BufferedReader getReader() throws IOException {
return req.getReader();
}
public String getRemoteAddr() {
return req.getRemoteAddr();
}
public String getRemoteHost() {
return req.getRemoteHost();
}
public void setAttribute(String name, Object o) {
req.setAttribute(name, o);
}
public void removeAttribute(String name) {
req.removeAttribute(name);
}
public Locale getLocale() {
return req.getLocale();
}
public Enumeration getLocales() {
return req.getLocales();
}
public boolean isSecure() {
return req.isSecure();
}
public RequestDispatcher getRequestDispatcher(String path) {
return req.getRequestDispatcher(path);
}
public String getRealPath(String path) {
throw new RuntimeException("HttpServletRequest.getRealPath(String path) is deprectated! Use ServletContext.getRealPath(String path) instead.");
}
}
}
|
package abstractTypes;
import java.nio.ByteOrder;
import common.DataType;
import common.MxClassID;
import subelements.common.ArrayFlagsSubelement;
import subelements.common.ArrayNameSubelement;
import subelements.common.DimensionsArraySubelement;
public abstract class AbstractArrayElement extends AbstractDataElement
{
private ArrayFlagsSubelement arrayFlagsSubelement;
private DimensionsArraySubelement dimensionsArraySubelement;
private ArrayNameSubelement arrayNameSubelement;
/*
* Number of bytes of the array-specific Data Element
*/
private int size_ArraySpecificDataPart;
protected final boolean matlabNameConvention = true;
public AbstractArrayElement()
{
this(false);
}
public AbstractArrayElement(boolean compFlag)
{
super(DataType.miMATRIX,compFlag);
arrayFlagsSubelement = new ArrayFlagsSubelement();
dimensionsArraySubelement = new DimensionsArraySubelement();
arrayNameSubelement = new ArrayNameSubelement();
size_ArraySpecificDataPart = 0;
}
public void setDimensions(int[] dims)
{
dimensionsArraySubelement.setData(dims);
// Since the DimensionsArraySubelement has been changed,
// force an update of the calculation of number of bytes
// needed to represent the array-specific data and
// the array common fields.
setNumOfSpecDataBytes(size_ArraySpecificDataPart);
}
public void setName(String name)
{
arrayNameSubelement.setData(name);
// Since the ArrayNameSubelement has been changed,
// force an update of the calculation of number of bytes
// needed to represent the array-specific data and
// the array common fields.
setNumOfSpecDataBytes(size_ArraySpecificDataPart);
}
public void setClassType(MxClassID type)
{
arrayFlagsSubelement.setClassType(type);
}
public void setSparseFlag(boolean flag)
{
arrayFlagsSubelement.setSparseFlag(flag);
}
public void setComplexFlag(boolean flag)
{
arrayFlagsSubelement.setComplexFlag(flag);
}
public void setGlobalFlag(boolean flag)
{
arrayFlagsSubelement.setGlobalFlag(flag);
}
public void setLogicalFlag(boolean flag)
{
arrayFlagsSubelement.setLogicalFlag(flag);
}
public void setNzMax(int n)
{
arrayFlagsSubelement.setNzMax(n);
}
/**
* Set the number of bytes needed to represent the array-specific
* data and the array common fields ( Array Flags, Dimensions Array
* and Array Name) in binary form.
* @param size
*/
protected void setNumOfSpecDataBytes(int size)
{
size_ArraySpecificDataPart = size;
/*
* Update the overall size of the Data Part (including
* Array Flags, Dimensions Array and Array Name)
*/
int numBytes = size_ArraySpecificDataPart;
numBytes += arrayFlagsSubelement.getTotalElementLength();
numBytes += dimensionsArraySubelement.getTotalElementLength();
numBytes += arrayNameSubelement.getTotalElementLength();
super.setNumOfDataElementBytes(numBytes);
}
protected int getNumOfSpecDataBytes()
{
return size_ArraySpecificDataPart;
}
public String toString()
{
String str = "";
str += "arrayFlagsSubelement = " + arrayFlagsSubelement.toString();
str += "dimensionsArraySubelement = " + dimensionsArraySubelement.toString();
str += "arrayNameSubelement = " + arrayNameSubelement.toString();
str += " data length = " + super.getDataLength();
return str;
}
/**
* Returns an array of bytes representing the array-specific
* Data Part (only) of derived Array classes.
*/
protected abstract byte[] specDataToByteArray(ByteOrder byte_order);
/**
* Returns an array of bytes representing the Data Part (only) of
* derived Array classes (consisting of Array Flags, Dimensions array,
* Array Name and array-specific Data Element).
*/
public byte[] dataToByteArray(ByteOrder byte_order)
{
byte[] data = specDataToByteArray(byte_order);
byte[] dest = new byte[super.getDataLength()];
int offset = 0;
byte[] tmp;
tmp = arrayFlagsSubelement.toByteArray(byte_order);
System.arraycopy(tmp, 0, dest, offset, tmp.length);
offset += tmp.length;
tmp = dimensionsArraySubelement.toByteArray(byte_order);
System.arraycopy(tmp, 0, dest, offset, tmp.length);
offset += tmp.length;
tmp = arrayNameSubelement.toByteArray(byte_order);
System.arraycopy(tmp, 0, dest, offset, tmp.length);
offset += tmp.length;
System.arraycopy(data, 0, dest, offset, data.length);
return dest;
}
}
|
package org.pentaho.di.core.database;
import java.io.StringReader;
import java.sql.BatchUpdateException;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Counter;
import org.pentaho.di.core.DBCache;
import org.pentaho.di.core.DBCacheEntry;
import org.pentaho.di.core.ProgressMonitorListener;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.database.map.DatabaseConnectionMap;
import org.pentaho.di.core.encryption.Encr;
import org.pentaho.di.core.exception.KettleDatabaseBatchException;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.logging.DefaultLogLevel;
import org.pentaho.di.core.logging.LogChannel;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.logging.LogLevel;
import org.pentaho.di.core.logging.LogStatus;
import org.pentaho.di.core.logging.LogTableField;
import org.pentaho.di.core.logging.LogTableInterface;
import org.pentaho.di.core.logging.LoggingObjectInterface;
import org.pentaho.di.core.logging.LoggingObjectType;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.variables.Variables;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.ObjectRevision;
import org.pentaho.di.repository.RepositoryDirectory;
/**
* Database handles the process of connecting to, reading from, writing to and updating databases.
* The database specific parameters are defined in DatabaseInfo.
*
* @author Matt
* @since 05-04-2003
*
*/
public class Database implements VariableSpace, LoggingObjectInterface
{
private static Class<?> PKG = Database.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private DatabaseMeta databaseMeta;
private int rowlimit;
private int commitsize;
private Connection connection;
private Statement sel_stmt;
private PreparedStatement pstmt;
private PreparedStatement prepStatementLookup;
private PreparedStatement prepStatementUpdate;
private PreparedStatement prepStatementInsert;
private PreparedStatement pstmt_seq;
private CallableStatement cstmt;
// private ResultSetMetaData rsmd;
private DatabaseMetaData dbmd;
private RowMetaInterface rowMeta;
private int written;
private LogChannelInterface log;
private LoggingObjectInterface parentLoggingObject;
/**
* Number of times a connection was opened using this object.
* Only used in the context of a database connection map
*/
private int opened;
/**
* The copy is equal to opened at the time of creation.
*/
private int copy;
private String connectionGroup;
private String partitionId;
private VariableSpace variables = new Variables();
private LogLevel logLevel = DefaultLogLevel.getLogLevel();
private String containerObjectId;
/**
* Construct a new Database Connection
* @param databaseMeta The Database Connection Info to construct the connection with.
* @deprecated Please specify the parent object so that we can see which object is initiating a database connection
*/
public Database(DatabaseMeta databaseMeta)
{
this.parentLoggingObject = null;
this.databaseMeta = databaseMeta;
shareVariablesWith(databaseMeta);
// In this case we don't have the parent object, so we don't know which object makes the connection.
// We also don't know what log level to attach to it, so we have to stick to the default
// As such, this constructor is @deprecated.
log=new LogChannel(this);
logLevel = log.getLogLevel();
containerObjectId = log.getContainerObjectId();
pstmt = null;
rowMeta = null;
dbmd = null;
rowlimit=0;
written=0;
if(log.isDetailed()) log.logDetailed("New database connection defined");
}
/**
* Construct a new Database Connection
* @param databaseMeta The Database Connection Info to construct the connection with.
*/
public Database(LoggingObjectInterface parentObject, DatabaseMeta databaseMeta)
{
this.parentLoggingObject = parentObject;
this.databaseMeta = databaseMeta;
shareVariablesWith(databaseMeta);
log=new LogChannel(this, parentObject);
this.containerObjectId = log.getContainerObjectId();
this.logLevel = log.getLogLevel();
pstmt = null;
rowMeta = null;
dbmd = null;
rowlimit=0;
written=0;
if(log.isDetailed()) log.logDetailed("New database connection defined");
}
public boolean equals(Object obj)
{
Database other = (Database) obj;
return other.databaseMeta.equals(other.databaseMeta);
}
/**
* Allows for the injection of a "life" connection, generated by a piece of software outside of Kettle.
* @param connection
*/
public void setConnection(Connection connection) {
this.connection = connection;
}
/**
* @return Returns the connection.
*/
public Connection getConnection()
{
return connection;
}
/**
* Set the maximum number of records to retrieve from a query.
* @param rows
*/
public void setQueryLimit(int rows)
{
rowlimit = rows;
}
/**
* @return Returns the prepStatementInsert.
*/
public PreparedStatement getPrepStatementInsert()
{
return prepStatementInsert;
}
/**
* @return Returns the prepStatementLookup.
*/
public PreparedStatement getPrepStatementLookup()
{
return prepStatementLookup;
}
/**
* @return Returns the prepStatementUpdate.
*/
public PreparedStatement getPrepStatementUpdate()
{
return prepStatementUpdate;
}
/**
* Open the database connection.
* @throws KettleDatabaseException if something went wrong.
*/
public void connect() throws KettleDatabaseException
{
connect(null);
}
/**
* Open the database connection.
* @param partitionId the partition ID in the cluster to connect to.
* @throws KettleDatabaseException if something went wrong.
*/
public void connect(String partitionId) throws KettleDatabaseException
{
connect(null, partitionId);
}
public synchronized void connect(String group, String partitionId) throws KettleDatabaseException
{
// Before anything else, let's see if we already have a connection defined for this group/partition!
// The group is called after the thread-name of the transformation or job that is running
// The name of that threadname is expected to be unique (it is in Kettle)
// So the deal is that if there is another thread using that, we go for it.
if (!Const.isEmpty(group))
{
this.connectionGroup = group;
this.partitionId = partitionId;
DatabaseConnectionMap map = DatabaseConnectionMap.getInstance();
// Try to find the connection for the group
Database lookup = map.getDatabase(group, partitionId, this);
if (lookup==null) // We already opened this connection for the partition & database in this group
{
// Do a normal connect and then store this database object for later re-use.
normalConnect(partitionId);
opened++;
copy = opened;
map.storeDatabase(group, partitionId, this);
}
else
{
connection = lookup.getConnection();
lookup.setOpened(lookup.getOpened()+1); // if this counter hits 0 again, close the connection.
copy = lookup.getOpened();
}
}
else
{
// Proceed with a normal connect
normalConnect(partitionId);
}
}
/**
* Open the database connection.
* @param partitionId the partition ID in the cluster to connect to.
* @throws KettleDatabaseException if something went wrong.
*/
public void normalConnect(String partitionId) throws KettleDatabaseException
{
if (databaseMeta==null)
{
throw new KettleDatabaseException("No valid database connection defined!");
}
try
{
// First see if we use connection pooling...
if ( databaseMeta.isUsingConnectionPool() && // default = false for backward compatibility
databaseMeta.getAccessType()!=DatabaseMeta.TYPE_ACCESS_JNDI // JNDI does pooling on it's own.
)
{
try
{
this.connection = ConnectionPoolUtil.getConnection(log, databaseMeta, partitionId);
}
catch (Exception e)
{
throw new KettleDatabaseException("Error occured while trying to connect to the database", e);
}
}
else
{
connectUsingClass(databaseMeta.getDriverClass(), partitionId );
if(log.isDetailed()) log.logDetailed("Connected to database.");
// See if we need to execute extra SQL statemtent...
String sql = environmentSubstitute( databaseMeta.getConnectSQL() );
// only execute if the SQL is not empty, null and is not just a bunch of spaces, tabs, CR etc.
if (!Const.isEmpty(sql) && !Const.onlySpaces(sql))
{
execStatements(sql);
if(log.isDetailed()) log.logDetailed("Executed connect time SQL statements:"+Const.CR+sql);
}
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Error occured while trying to connect to the database", e);
}
}
/**
* Initialize by getting the connection from a javax.sql.DataSource. This method uses the
* DataSourceProviderFactory to get the provider of DataSource objects.
* @param dataSourceName
* @throws KettleDatabaseException
*/
private void initWithNamedDataSource(String dataSourceName) throws KettleDatabaseException {
connection = null;
DataSource dataSource = DataSourceProviderFactory.getDataSourceProviderInterface().getNamedDataSource(dataSourceName);
if (dataSource != null) {
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
throw new KettleDatabaseException( "Invalid JNDI connection "+ dataSourceName + " : " + e.getMessage()); //$NON-NLS-1$
}
if (connection == null) {
throw new KettleDatabaseException( "Invalid JNDI connection "+ dataSourceName); //$NON-NLS-1$
}
} else {
throw new KettleDatabaseException( "Invalid JNDI connection "+ dataSourceName); //$NON-NLS-1$
}
}
/**
* Connect using the correct classname
* @param classname for example "org.gjt.mm.mysql.Driver"
* @return true if the connect was succesfull, false if something went wrong.
*/
private void connectUsingClass(String classname, String partitionId) throws KettleDatabaseException
{
// Install and load the jdbc Driver
// first see if this is a JNDI connection
if( databaseMeta.getAccessType() == DatabaseMeta.TYPE_ACCESS_JNDI ) {
initWithNamedDataSource( environmentSubstitute(databaseMeta.getDatabaseName()) );
return;
}
try
{
Class.forName(classname);
}
catch(NoClassDefFoundError e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
catch(ClassNotFoundException e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
catch(Exception e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
try
{
String url;
if (databaseMeta.isPartitioned() && !Const.isEmpty(partitionId))
{
url = environmentSubstitute(databaseMeta.getURL(partitionId));
}
else
{
url = environmentSubstitute(databaseMeta.getURL());
}
String clusterUsername=null;
String clusterPassword=null;
if (databaseMeta.isPartitioned() && !Const.isEmpty(partitionId))
{
// Get the cluster information...
PartitionDatabaseMeta partition = databaseMeta.getPartitionMeta(partitionId);
if (partition!=null)
{
clusterUsername = partition.getUsername();
clusterPassword = Encr.decryptPasswordOptionallyEncrypted(partition.getPassword());
}
}
String username;
String password;
if (!Const.isEmpty(clusterUsername))
{
username = clusterUsername;
password = clusterPassword;
}
else
{
username = environmentSubstitute(databaseMeta.getUsername());
password = Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(databaseMeta.getPassword()));
}
if (databaseMeta.supportsOptionsInURL())
{
if (!Const.isEmpty(username) || !Const.isEmpty(password))
{
// also allow for empty username with given password, in this case username must be given with one space
connection = DriverManager.getConnection(url, Const.NVL(username, " "), Const.NVL(password, ""));
}
else
{
// Perhaps the username is in the URL or no username is required...
connection = DriverManager.getConnection(url);
}
}
else
{
Properties properties = databaseMeta.getConnectionProperties();
if (!Const.isEmpty(username)) properties.put("user", username);
if (!Const.isEmpty(password)) properties.put("password", password);
connection = DriverManager.getConnection(url, properties);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e);
}
catch(Throwable e)
{
throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e);
}
}
/**
* Disconnect from the database and close all open prepared statements.
*/
public synchronized void disconnect()
{
try
{
if (connection==null)
{
return ; // Nothing to do...
}
if (connection.isClosed())
{
return ; // Nothing to do...
}
if (pstmt !=null)
{
pstmt.close();
pstmt=null;
}
if (prepStatementLookup!=null)
{
prepStatementLookup.close();
prepStatementLookup=null;
}
if (prepStatementInsert!=null)
{
prepStatementInsert.close();
prepStatementInsert=null;
}
if (prepStatementUpdate!=null)
{
prepStatementUpdate.close();
prepStatementUpdate=null;
}
if (pstmt_seq!=null)
{
pstmt_seq.close();
pstmt_seq=null;
}
// See if there are other steps using this connection in a connection group.
// If so, we will hold commit & connection close until then.
if (!Const.isEmpty(connectionGroup))
{
return;
}
else
{
if (!isAutoCommit()) // Do we really still need this commit??
{
commit();
}
}
closeConnectionOnly();
}
catch(SQLException ex)
{
log.logError("Error disconnecting from database:"+Const.CR+ex.getMessage());
log.logError(Const.getStackTracker(ex));
}
catch(KettleDatabaseException dbe)
{
log.logError("Error disconnecting from database:"+Const.CR+dbe.getMessage());
log.logError(Const.getStackTracker(dbe));
}
}
/**
* Only for unique connections usage, typically you use disconnect() to disconnect() from the database.
* @throws KettleDatabaseException in case there is an error during connection close.
*/
public synchronized void closeConnectionOnly() throws KettleDatabaseException {
try
{
if (connection!=null)
{
connection.close();
if (!databaseMeta.isUsingConnectionPool())
{
connection=null;
}
}
if(log.isDetailed()) log.logDetailed("Connection to database closed!");
}
catch(SQLException e) {
throw new KettleDatabaseException("Error disconnecting from database '"+toString()+"'", e);
}
}
/**
* Cancel the open/running queries on the database connection
* @throws KettleDatabaseException
*/
public void cancelQuery() throws KettleDatabaseException
{
cancelStatement(pstmt);
cancelStatement(sel_stmt);
}
/**
* Cancel an open/running SQL statement
* @param statement the statement to cancel
* @throws KettleDatabaseException
*/
public void cancelStatement(Statement statement) throws KettleDatabaseException
{
try
{
if (statement!=null)
{
statement.cancel();
}
if(log.isDebug()) log.logDebug("Statement canceled!");
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error cancelling statement", ex);
}
}
/**
* Specify after how many rows a commit needs to occur when inserting or updating values.
* @param commsize The number of rows to wait before doing a commit on the connection.
*/
public void setCommit(int commsize)
{
commitsize=commsize;
String onOff = (commitsize<=0?"on":"off");
try
{
connection.setAutoCommit(commitsize<=0);
if(log.isDetailed()) log.logDetailed("Auto commit "+onOff);
}
catch(Exception e)
{
if (log.isDebug()) log.logDebug("Can't turn auto commit "+onOff);
}
}
public void setAutoCommit(boolean useAutoCommit) throws KettleDatabaseException {
try {
connection.setAutoCommit(useAutoCommit);
} catch (SQLException e) {
if (useAutoCommit) {
throw new KettleDatabaseException(BaseMessages.getString(PKG, "Database.Exception.UnableToEnableAutoCommit", toString()));
} else {
throw new KettleDatabaseException(BaseMessages.getString(PKG, "Database.Exception.UnableToDisableAutoCommit", toString()));
}
}
}
/**
* Perform a commit the connection if this is supported by the database
*/
public void commit() throws KettleDatabaseException
{
commit(false);
}
public void commit(boolean force) throws KettleDatabaseException
{
try
{
// Don't do the commit, wait until the end of the transformation.
// When the last database copy (opened counter) is about to be closed, we do a commit
// There is one catch, we need to catch the rollback
// The transformation will stop everything and then we'll do the rollback.
// The flag is in "performRollback", private only
if (!Const.isEmpty(connectionGroup) && !force)
{
return;
}
if (getDatabaseMetaData().supportsTransactions())
{
if (log.isDebug()) log.logDebug("Commit on database connection ["+toString()+"]");
connection.commit();
}
else
{
if(log.isDetailed()) log.logDetailed("No commit possible on database connection ["+toString()+"]");
}
}
catch(Exception e)
{
if (databaseMeta.supportsEmptyTransactions())
throw new KettleDatabaseException("Error comitting connection", e);
}
}
public void rollback() throws KettleDatabaseException
{
rollback(false);
}
public void rollback(boolean force) throws KettleDatabaseException
{
try
{
if (!Const.isEmpty(connectionGroup) && !force)
{
return; // Will be handled by Trans --> endProcessing()
}
if (getDatabaseMetaData().supportsTransactions())
{
if (connection!=null) {
if (log.isDebug()) log.logDebug("Rollback on database connection ["+toString()+"]");
connection.rollback();
}
}
else
{
if(log.isDetailed()) log.logDetailed("No rollback possible on database connection ["+toString()+"]");
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error performing rollback on connection", e);
}
}
/**
* Prepare inserting values into a table, using the fields & values in a Row
* @param rowMeta The row metadata to determine which values need to be inserted
* @param table The name of the table in which we want to insert rows
* @throws KettleDatabaseException if something went wrong.
*/
public void prepareInsert(RowMetaInterface rowMeta, String tableName) throws KettleDatabaseException
{
prepareInsert(rowMeta, null, tableName);
}
/**
* Prepare inserting values into a table, using the fields & values in a Row
* @param rowMeta The metadata row to determine which values need to be inserted
* @param schemaName The name of the schema in which we want to insert rows
* @param tableName The name of the table in which we want to insert rows
* @throws KettleDatabaseException if something went wrong.
*/
public void prepareInsert(RowMetaInterface rowMeta, String schemaName, String tableName) throws KettleDatabaseException
{
if (rowMeta.size()==0)
{
throw new KettleDatabaseException("No fields in row, can't insert!");
}
String ins = getInsertStatement(schemaName, tableName, rowMeta);
if(log.isDetailed()) log.logDetailed("Preparing statement: "+Const.CR+ins);
prepStatementInsert=prepareSQL(ins);
}
/**
* Prepare a statement to be executed on the database. (does not return generated keys)
* @param sql The SQL to be prepared
* @return The PreparedStatement object.
* @throws KettleDatabaseException
*/
public PreparedStatement prepareSQL(String sql)
throws KettleDatabaseException
{
return prepareSQL(sql, false);
}
/**
* Prepare a statement to be executed on the database.
* @param sql The SQL to be prepared
* @param returnKeys set to true if you want to return generated keys from an insert statement
* @return The PreparedStatement object.
* @throws KettleDatabaseException
*/
public PreparedStatement prepareSQL(String sql, boolean returnKeys) throws KettleDatabaseException
{
try
{
if (returnKeys)
{
return connection.prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS);
}
else
{
return connection.prepareStatement(databaseMeta.stripCR(sql));
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't prepare statement:"+Const.CR+sql, ex);
}
}
public void closeLookup() throws KettleDatabaseException
{
closePreparedStatement(pstmt);
pstmt=null;
}
public void closePreparedStatement(PreparedStatement ps) throws KettleDatabaseException
{
if (ps!=null)
{
try
{
ps.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing prepared statement", e);
}
}
}
public void closeInsert() throws KettleDatabaseException
{
if (prepStatementInsert!=null)
{
try
{
prepStatementInsert.close();
prepStatementInsert = null;
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing insert prepared statement.", e);
}
}
}
public void closeUpdate() throws KettleDatabaseException
{
if (prepStatementUpdate!=null)
{
try
{
prepStatementUpdate.close();
prepStatementUpdate=null;
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing update prepared statement.", e);
}
}
}
public void setValues(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, pstmt);
}
public void setValues(RowMetaAndData row) throws KettleDatabaseException
{
setValues(row.getRowMeta(), row.getData());
}
public void setValuesInsert(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, prepStatementInsert);
}
public void setValuesInsert(RowMetaAndData row) throws KettleDatabaseException
{
setValues(row.getRowMeta(), row.getData(), prepStatementInsert);
}
public void setValuesUpdate(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, prepStatementUpdate);
}
public void setValuesLookup(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, prepStatementLookup);
}
public void setProcValues(RowMetaInterface rowMeta, Object[] data, int argnrs[], String argdir[], boolean result) throws KettleDatabaseException
{
int pos;
if (result) pos=2; else pos=1;
for (int i=0;i<argnrs.length;i++)
{
if (argdir[i].equalsIgnoreCase("IN") || argdir[i].equalsIgnoreCase("INOUT"))
{
ValueMetaInterface valueMeta = rowMeta.getValueMeta(argnrs[i]);
Object value = data[argnrs[i]];
setValue(cstmt, valueMeta, value, pos);
pos++;
} else {
pos++; //next parameter when OUT
}
}
}
public void setValue(PreparedStatement ps, ValueMetaInterface v, Object object, int pos) throws KettleDatabaseException
{
String debug = "";
try
{
switch(v.getType())
{
case ValueMetaInterface.TYPE_NUMBER :
if (!v.isNull(object))
{
debug="Number, not null, getting number from value";
double num = v.getNumber(object).doubleValue();
if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0)
{
debug="Number, rounding to precision ["+v.getPrecision()+"]";
num = Const.round(num, v.getPrecision());
}
debug="Number, setting ["+num+"] on position #"+pos+" of the prepared statement";
ps.setDouble(pos, num);
}
else
{
ps.setNull(pos, java.sql.Types.DOUBLE);
}
break;
case ValueMetaInterface.TYPE_INTEGER:
debug="Integer";
if (!v.isNull(object))
{
if (databaseMeta.supportsSetLong())
{
ps.setLong(pos, v.getInteger(object).longValue() );
}
else
{
double d = v.getNumber(object).doubleValue();
if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0)
{
ps.setDouble(pos, d );
}
else
{
ps.setDouble(pos, Const.round( d, v.getPrecision() ) );
}
}
}
else
{
ps.setNull(pos, java.sql.Types.INTEGER);
}
break;
case ValueMetaInterface.TYPE_STRING :
debug="String";
if (v.getLength()<DatabaseMeta.CLOB_LENGTH)
{
if (!v.isNull(object))
{
ps.setString(pos, v.getString(object));
}
else
{
ps.setNull(pos, java.sql.Types.VARCHAR);
}
}
else
{
if (!v.isNull(object))
{
String string = v.getString(object);
int maxlen = databaseMeta.getMaxTextFieldLength();
int len = string.length();
// Take the last maxlen characters of the string...
int begin = len - maxlen;
if (begin<0) begin=0;
// Get the substring!
String logging = string.substring(begin);
if (databaseMeta.supportsSetCharacterStream())
{
StringReader sr = new StringReader(logging);
ps.setCharacterStream(pos, sr, logging.length());
}
else
{
ps.setString(pos, logging);
}
}
else
{
ps.setNull(pos, java.sql.Types.VARCHAR);
}
}
break;
case ValueMetaInterface.TYPE_DATE :
debug="Date";
if (!v.isNull(object))
{
long dat = v.getInteger(object).longValue(); // converts using Date.getTime()
if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion())
{
// Convert to DATE!
java.sql.Date ddate = new java.sql.Date(dat);
ps.setDate(pos, ddate);
}
else
{
java.sql.Timestamp sdate = new java.sql.Timestamp(dat);
ps.setTimestamp(pos, sdate);
}
}
else
{
if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion())
{
ps.setNull(pos, java.sql.Types.DATE);
}
else
{
ps.setNull(pos, java.sql.Types.TIMESTAMP);
}
}
break;
case ValueMetaInterface.TYPE_BOOLEAN:
debug="Boolean";
if (databaseMeta.supportsBooleanDataType())
{
if (!v.isNull(object))
{
ps.setBoolean(pos, v.getBoolean(object).booleanValue());
}
else
{
ps.setNull(pos, java.sql.Types.BOOLEAN);
}
}
else
{
if (!v.isNull(object))
{
ps.setString(pos, v.getBoolean(object).booleanValue()?"Y":"N");
}
else
{
ps.setNull(pos, java.sql.Types.CHAR);
}
}
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
debug="BigNumber";
if (!v.isNull(object))
{
ps.setBigDecimal(pos, v.getBigNumber(object));
}
else
{
ps.setNull(pos, java.sql.Types.DECIMAL);
}
break;
case ValueMetaInterface.TYPE_BINARY:
debug="Binary";
if (!v.isNull(object))
{
ps.setBytes(pos, v.getBinary(object));
}
else
{
ps.setNull(pos, java.sql.Types.BINARY);
}
break;
default:
debug="default";
// placeholder
ps.setNull(pos, java.sql.Types.VARCHAR);
break;
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error setting value #"+pos+" ["+v.toString()+"] on prepared statement ("+debug+")"+Const.CR+ex.toString(), ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Error setting value #"+pos+" ["+(v==null?"NULL":v.toString())+"] on prepared statement ("+debug+")"+Const.CR+e.toString(), e);
}
}
public void setValues(RowMetaAndData row, PreparedStatement ps) throws KettleDatabaseException
{
setValues(row.getRowMeta(), row.getData(), ps);
}
public void setValues(RowMetaInterface rowMeta, Object[] data, PreparedStatement ps) throws KettleDatabaseException
{
// now set the values in the row!
for (int i=0;i<rowMeta.size();i++)
{
ValueMetaInterface v = rowMeta.getValueMeta(i);
Object object = data[i];
try
{
setValue(ps, v, object, i+1);
}
catch(KettleDatabaseException e)
{
throw new KettleDatabaseException("offending row : "+rowMeta, e);
}
}
}
/**
* Sets the values of the preparedStatement pstmt.
* @param rowMeta
* @param data
*/
public void setValues(RowMetaInterface rowMeta, Object[] data, PreparedStatement ps, int ignoreThisValueIndex) throws KettleDatabaseException
{
// now set the values in the row!
int index=0;
for (int i=0;i<rowMeta.size();i++)
{
if (i!=ignoreThisValueIndex)
{
ValueMetaInterface v = rowMeta.getValueMeta(i);
Object object = data[i];
try
{
setValue(ps, v, object, index+1);
index++;
}
catch(KettleDatabaseException e)
{
throw new KettleDatabaseException("offending row : "+rowMeta, e);
}
}
}
}
/**
* @param ps The prepared insert statement to use
* @return The generated keys in auto-increment fields
* @throws KettleDatabaseException in case something goes wrong retrieving the keys.
*/
public RowMetaAndData getGeneratedKeys(PreparedStatement ps) throws KettleDatabaseException
{
ResultSet keys = null;
try
{
keys=ps.getGeneratedKeys(); // 1 row of keys
ResultSetMetaData resultSetMetaData = keys.getMetaData();
if (resultSetMetaData==null) {
resultSetMetaData = ps.getMetaData();
}
RowMetaInterface rowMeta;
if (resultSetMetaData==null) {
rowMeta = new RowMeta();
rowMeta.addValueMeta(new ValueMeta("ai-key", ValueMetaInterface.TYPE_INTEGER));
} else {
rowMeta = getRowInfo(resultSetMetaData, false, false);
}
return new RowMetaAndData(rowMeta, getRow(keys, resultSetMetaData, rowMeta));
}
catch(Exception ex)
{
throw new KettleDatabaseException("Unable to retrieve key(s) from auto-increment field(s)", ex);
}
finally
{
if (keys!=null)
{
try
{
keys.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to close resultset of auto-generated keys", e);
}
}
}
}
public Long getNextSequenceValue(String sequenceName, String keyfield) throws KettleDatabaseException
{
return getNextSequenceValue(null, sequenceName, keyfield);
}
public Long getNextSequenceValue(String schemaName, String sequenceName, String keyfield) throws KettleDatabaseException
{
Long retval=null;
String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName);
try
{
if (pstmt_seq==null)
{
pstmt_seq=connection.prepareStatement(databaseMeta.getSeqNextvalSQL(databaseMeta.stripCR(schemaSequence)));
}
ResultSet rs=null;
try
{
rs = pstmt_seq.executeQuery();
if (rs.next())
{
retval = Long.valueOf( rs.getLong(1) );
}
}
finally
{
if ( rs != null ) rs.close();
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to get next value for sequence : "+schemaSequence, ex);
}
return retval;
}
public void insertRow(String tableName, RowMetaInterface fields, Object[] data) throws KettleDatabaseException
{
insertRow(null, tableName, fields, data);
}
public void insertRow(String schemaName, String tableName, RowMetaInterface fields, Object[] data) throws KettleDatabaseException
{
prepareInsert(fields, schemaName, tableName);
setValuesInsert(fields, data);
insertRow();
closeInsert();
}
public String getInsertStatement(String tableName, RowMetaInterface fields)
{
return getInsertStatement(null, tableName, fields);
}
public String getInsertStatement(String schemaName, String tableName, RowMetaInterface fields)
{
StringBuffer ins=new StringBuffer(128);
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
ins.append("INSERT INTO ").append(schemaTable).append(" (");
// now add the names in the row:
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(", ");
String name = fields.getValueMeta(i).getName();
ins.append(databaseMeta.quoteField(name));
}
ins.append(") VALUES (");
// Add placeholders...
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(", ");
ins.append(" ?");
}
ins.append(')');
return ins.toString();
}
public void insertRow()
throws KettleDatabaseException
{
insertRow(prepStatementInsert);
}
public void insertRow(boolean batch) throws KettleDatabaseException
{
insertRow(prepStatementInsert, batch);
}
public void updateRow()
throws KettleDatabaseException
{
insertRow(prepStatementUpdate);
}
public void insertRow(PreparedStatement ps)
throws KettleDatabaseException
{
insertRow(ps, false);
}
/**
* Insert a row into the database using a prepared statement that has all values set.
* @param ps The prepared statement
* @param batch True if you want to use batch inserts (size = commit size)
* @return true if the rows are safe: if batch of rows was sent to the database OR if a commit was done.
* @throws KettleDatabaseException
*/
public boolean insertRow(PreparedStatement ps, boolean batch) throws KettleDatabaseException
{
return insertRow(ps, false, true);
}
/**
* Insert a row into the database using a prepared statement that has all values set.
* @param ps The prepared statement
* @param batch True if you want to use batch inserts (size = commit size)
* @param handleCommit True if you want to handle the commit here after the commit size (False e.g. in case the step handles this, see TableOutput)
* @return true if the rows are safe: if batch of rows was sent to the database OR if a commit was done.
* @throws KettleDatabaseException
*/
public boolean insertRow(PreparedStatement ps, boolean batch, boolean handleCommit) throws KettleDatabaseException
{
String debug="insertRow start";
boolean rowsAreSafe=false;
try
{
// Unique connections and Batch inserts don't mix when you want to roll back on certain databases.
// That's why we disable the batch insert in that case.
boolean useBatchInsert = batch && getDatabaseMetaData().supportsBatchUpdates() && databaseMeta.supportsBatchUpdates() && Const.isEmpty(connectionGroup);
// Add support for batch inserts...
if (!isAutoCommit())
{
if (useBatchInsert)
{
debug="insertRow add batch";
ps.addBatch(); // Add the batch, but don't forget to run the batch
}
else
{
debug="insertRow exec update";
ps.executeUpdate();
}
}
else
{
ps.executeUpdate();
}
written++;
if (handleCommit) { // some steps handle the commit themselves (see e.g. TableOutput step)
if (!isAutoCommit() && (written%commitsize)==0)
{
if (useBatchInsert)
{
debug="insertRow executeBatch commit";
ps.executeBatch();
commit();
ps.clearBatch();
}
else
{
debug="insertRow normal commit";
commit();
}
rowsAreSafe=true;
}
}
return rowsAreSafe;
}
catch(BatchUpdateException ex)
{
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex);
kdbe.setUpdateCounts(ex.getUpdateCounts());
List<Exception> exceptions = new ArrayList<Exception>();
// 'seed' the loop with the root exception
SQLException nextException = ex;
do
{
exceptions.add(nextException);
// while current exception has next exception, add to list
}
while ((nextException = nextException.getNextException())!=null);
kdbe.setExceptionsList(exceptions);
throw kdbe;
}
catch(SQLException ex)
{
// log.logError(Const.getStackTracker(ex));
throw new KettleDatabaseException("Error inserting/updating row", ex);
}
catch(Exception e)
{
// System.out.println("Unexpected exception in ["+debug+"] : "+e.getMessage());
throw new KettleDatabaseException("Unexpected error inserting/updating row in part ["+debug+"]", e);
}
}
/**
* Clears batch of insert prepared statement
* @deprecated
* @throws KettleDatabaseException
*/
public void clearInsertBatch() throws KettleDatabaseException
{
clearBatch(prepStatementInsert);
}
public void clearBatch(PreparedStatement preparedStatement) throws KettleDatabaseException
{
try
{
preparedStatement.clearBatch();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to clear batch for prepared statement", e);
}
}
public void insertFinished(boolean batch) throws KettleDatabaseException
{
insertFinished(prepStatementInsert, batch);
prepStatementInsert = null;
}
/**
* Close the prepared statement of the insert statement.
*
* @param ps The prepared statement to empty and close.
* @param batch true if you are using batch processing
* @param psBatchCounter The number of rows on the batch queue
* @throws KettleDatabaseException
*/
public void emptyAndCommit(PreparedStatement ps, boolean batch, int batchCounter) throws KettleDatabaseException {
try
{
if (ps!=null)
{
if (!isAutoCommit())
{
// Execute the batch or just perform a commit.
if (batch && getDatabaseMetaData().supportsBatchUpdates() && batchCounter>0)
{
// The problem with the batch counters is that you can't just execute the current batch.
// Certain databases have a problem if you execute the batch and if there are no statements in it.
// You can't just catch the exception either because you would have to roll back on certain databases before you can then continue to do anything.
// That leaves the task of keeping track of the number of rows up to our responsibility.
ps.executeBatch();
commit();
}
else
{
commit();
}
}
// Let's not forget to close the prepared statement.
ps.close();
}
}
catch(BatchUpdateException ex)
{
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex);
kdbe.setUpdateCounts(ex.getUpdateCounts());
List<Exception> exceptions = new ArrayList<Exception>();
SQLException nextException = ex.getNextException();
SQLException oldException = null;
// This construction is specifically done for some JDBC drivers, these drivers
// always return the same exception on getNextException() (and thus go into an infinite loop).
// So it's not "equals" but != (comments from Sven Boden).
while ( (nextException != null) && (oldException != nextException) )
{
exceptions.add(nextException);
oldException = nextException;
nextException = nextException.getNextException();
}
kdbe.setExceptionsList(exceptions);
throw kdbe;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to empty ps and commit connection.", ex);
}
}
/**
* Close the prepared statement of the insert statement.
*
* @param ps The prepared statement to empty and close.
* @param batch true if you are using batch processing (typically true for this method)
* @param psBatchCounter The number of rows on the batch queue
* @throws KettleDatabaseException
*
* @deprecated use emptyAndCommit() instead (pass in the number of rows left in the batch)
*/
public void insertFinished(PreparedStatement ps, boolean batch) throws KettleDatabaseException
{
try
{
if (ps!=null)
{
if (!isAutoCommit())
{
// Execute the batch or just perform a commit.
if (batch && getDatabaseMetaData().supportsBatchUpdates())
{
// The problem with the batch counters is that you can't just execute the current batch.
// Certain databases have a problem if you execute the batch and if there are no statements in it.
// You can't just catch the exception either because you would have to roll back on certain databases before you can then continue to do anything.
// That leaves the task of keeping track of the number of rows up to our responsibility.
ps.executeBatch();
commit();
}
else
{
commit();
}
}
// Let's not forget to close the prepared statement.
ps.close();
}
}
catch(BatchUpdateException ex)
{
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex);
kdbe.setUpdateCounts(ex.getUpdateCounts());
List<Exception> exceptions = new ArrayList<Exception>();
SQLException nextException = ex.getNextException();
SQLException oldException = null;
// This construction is specifically done for some JDBC drivers, these drivers
// always return the same exception on getNextException() (and thus go into an infinite loop).
// So it's not "equals" but != (comments from Sven Boden).
while ( (nextException != null) && (oldException != nextException) )
{
exceptions.add(nextException);
oldException = nextException;
nextException = nextException.getNextException();
}
kdbe.setExceptionsList(exceptions);
throw kdbe;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to commit connection after having inserted rows.", ex);
}
}
/**
* Execute an SQL statement on the database connection (has to be open)
* @param sql The SQL to execute
* @return a Result object indicating the number of lines read, deleted, inserted, updated, ...
* @throws KettleDatabaseException in case anything goes wrong.
*/
public Result execStatement(String sql) throws KettleDatabaseException
{
return execStatement(sql, null, null);
}
public Result execStatement(String sql, RowMetaInterface params, Object[] data) throws KettleDatabaseException
{
Result result = new Result();
try
{
boolean resultSet;
int count;
if (params!=null)
{
PreparedStatement prep_stmt = connection.prepareStatement(databaseMeta.stripCR(sql));
setValues(params, data, prep_stmt); // set the parameters!
resultSet = prep_stmt.execute();
count = prep_stmt.getUpdateCount();
prep_stmt.close();
}
else
{
String sqlStripped = databaseMeta.stripCR(sql);
// log.logDetailed("Executing SQL Statement: ["+sqlStripped+"]");
Statement stmt = connection.createStatement();
resultSet = stmt.execute(sqlStripped);
count = stmt.getUpdateCount();
stmt.close();
}
if (resultSet)
{
// the result is a resultset, but we don't do anything with it!
// You should have called something else!
// log.logDetailed("What to do with ResultSet??? (count="+count+")");
}
else
{
if (count > 0)
{
if (sql.toUpperCase().startsWith("INSERT")) result.setNrLinesOutput(count);
if (sql.toUpperCase().startsWith("UPDATE")) result.setNrLinesUpdated(count);
if (sql.toUpperCase().startsWith("DELETE")) result.setNrLinesDeleted(count);
}
}
// See if a cache needs to be cleared...
if (sql.toUpperCase().startsWith("ALTER TABLE") ||
sql.toUpperCase().startsWith("DROP TABLE") ||
sql.toUpperCase().startsWith("CREATE TABLE")
)
{
DBCache.getInstance().clear(databaseMeta.getName());
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't execute SQL: "+sql+Const.CR, ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Unexpected error executing SQL: "+Const.CR, e);
}
return result;
}
/**
* Execute a series of SQL statements, separated by ;
*
* We are already connected...
* Multiple statements have to be split into parts
* We use the ";" to separate statements...
*
* We keep the results in Result object from Jobs
*
* @param script The SQL script to be execute
* @throws KettleDatabaseException In case an error occurs
* @return A result with counts of the number or records updates, inserted, deleted or read.
*/
public Result execStatements(String script) throws KettleDatabaseException
{
Result result = new Result();
String all = script;
int from=0;
int to=0;
int length = all.length();
int nrstats = 0;
while (to<length)
{
char c = all.charAt(to);
if (c=='"')
{
c=' ';
while (to<length && c!='"') { to++; c=all.charAt(to); }
}
else
if (c=='\'') // skip until next '
{
c=' ';
while (to<length && c!='\'') { to++; c=all.charAt(to); }
}
else
if (all.substring(to).startsWith("--")) // -- means: ignore comment until end of line...
{
while (to<length && c!='\n' && c!='\r') { to++; c=all.charAt(to); }
}
if (c==';' || to>=length-1) // end of statement
{
if (to>=length-1) to++; // grab last char also!
String stat;
if (to<=length) stat = all.substring(from, to);
else stat = all.substring(from);
// If it ends with a ; remove that ;
// Oracle for example can't stand it when this happens...
if (stat.length()>0 && stat.charAt(stat.length()-1)==';')
{
stat = stat.substring(0,stat.length()-1);
}
if (!Const.onlySpaces(stat))
{
String sql=Const.trim(stat);
if (sql.toUpperCase().startsWith("SELECT"))
{
// A Query
if(log.isDetailed()) log.logDetailed("launch SELECT statement: "+Const.CR+sql);
nrstats++;
ResultSet rs = null;
try
{
rs = openQuery(sql);
if (rs!=null)
{
Object[] row = getRow(rs);
while (row!=null)
{
result.setNrLinesRead(result.getNrLinesRead()+1);
if (log.isDetailed()) log.logDetailed(rowMeta.getString(row));
row = getRow(rs);
}
}
else
{
if (log.isDebug()) log.logDebug("Error executing query: "+Const.CR+sql);
}
} catch (KettleValueException e) {
throw new KettleDatabaseException(e); // just pass the error upwards.
}
finally
{
try
{
if ( rs != null ) rs.close();
}
catch (SQLException ex )
{
if (log.isDebug()) log.logDebug("Error closing query: "+Const.CR+sql);
}
}
}
else // any kind of statement
{
if(log.isDetailed()) log.logDetailed("launch DDL statement: "+Const.CR+sql);
// A DDL statement
nrstats++;
Result res = execStatement(sql);
result.add(res);
}
}
to++;
from=to;
}
else
{
to++;
}
}
if(log.isDetailed()) log.logDetailed(nrstats+" statement"+(nrstats==1?"":"s")+" executed");
return result;
}
public ResultSet openQuery(String sql) throws KettleDatabaseException
{
return openQuery(sql, null, null);
}
/**
* Open a query on the database with a set of parameters stored in a Kettle Row
* @param sql The SQL to launch with question marks (?) as placeholders for the parameters
* @param params The parameters or null if no parameters are used.
* @data the parameter data to open the query with
* @return A JDBC ResultSet
* @throws KettleDatabaseException when something goes wrong with the query.
*/
public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data) throws KettleDatabaseException
{
return openQuery(sql, params, data, ResultSet.FETCH_FORWARD);
}
public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data, int fetch_mode) throws KettleDatabaseException
{
return openQuery(sql, params, data, fetch_mode, false);
}
public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data, int fetch_mode, boolean lazyConversion) throws KettleDatabaseException
{
ResultSet res;
String debug = "Start";
// Create a Statement
try
{
if (params!=null)
{
debug = "P create prepared statement (con==null? "+(connection==null)+")";
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
debug = "P Set values";
setValues(params, data); // set the dates etc!
if (canWeSetFetchSize(pstmt) )
{
debug = "P Set fetchsize";
int fs = Const.FETCH_SIZE<=pstmt.getMaxRows()?pstmt.getMaxRows():Const.FETCH_SIZE;
// System.out.println("Setting pstmt fetchsize to : "+fs);
{
if (databaseMeta.getDatabaseInterface() instanceof MySQLDatabaseMeta && databaseMeta.isStreamingResults())
{
pstmt.setFetchSize(Integer.MIN_VALUE);
}
else
pstmt.setFetchSize(fs);
}
debug = "P Set fetch direction";
pstmt.setFetchDirection(fetch_mode);
}
debug = "P Set max rows";
if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) pstmt.setMaxRows(rowlimit);
debug = "exec query";
res = pstmt.executeQuery();
}
else
{
debug = "create statement";
sel_stmt = connection.createStatement();
if (canWeSetFetchSize(sel_stmt))
{
debug = "Set fetchsize";
int fs = Const.FETCH_SIZE<=sel_stmt.getMaxRows()?sel_stmt.getMaxRows():Const.FETCH_SIZE;
if (databaseMeta.getDatabaseInterface() instanceof MySQLDatabaseMeta && databaseMeta.isStreamingResults())
{
sel_stmt.setFetchSize(Integer.MIN_VALUE);
}
else
{
sel_stmt.setFetchSize(fs);
}
debug = "Set fetch direction";
sel_stmt.setFetchDirection(fetch_mode);
}
debug = "Set max rows";
if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) sel_stmt.setMaxRows(rowlimit);
debug = "exec query";
res=sel_stmt.executeQuery(databaseMeta.stripCR(sql));
}
debug = "openQuery : get rowinfo";
// MySQL Hack only. It seems too much for the cursor type of operation on MySQL, to have another cursor opened
// to get the length of a String field. So, on MySQL, we ingore the length of Strings in result rows.
rowMeta = getRowInfo(res.getMetaData(), databaseMeta.getDatabaseInterface() instanceof MySQLDatabaseMeta, lazyConversion);
}
catch(SQLException ex)
{
// log.logError("ERROR executing ["+sql+"]");
// log.logError("ERROR in part: ["+debug+"]");
// printSQLException(ex);
throw new KettleDatabaseException("An error occurred executing SQL: "+Const.CR+sql, ex);
}
catch(Exception e)
{
log.logError("ERROR executing query: "+e.toString());
log.logError("ERROR in part: "+debug);
throw new KettleDatabaseException("An error occurred executing SQL in part ["+debug+"]:"+Const.CR+sql, e);
}
return res;
}
private boolean canWeSetFetchSize(Statement statement) throws SQLException
{
return databaseMeta.isFetchSizeSupported() &&
( statement.getMaxRows()>0 ||
databaseMeta.getDatabaseInterface() instanceof PostgreSQLDatabaseMeta ||
( databaseMeta.getDatabaseInterface() instanceof MySQLDatabaseMeta && databaseMeta.isStreamingResults() )
);
}
public ResultSet openQuery(PreparedStatement ps, RowMetaInterface params, Object[] data) throws KettleDatabaseException
{
ResultSet res;
String debug = "Start";
// Create a Statement
try
{
debug = "OQ Set values";
setValues(params, data, ps); // set the parameters!
if (canWeSetFetchSize(ps))
{
debug = "OQ Set fetchsize";
int fs = Const.FETCH_SIZE<=ps.getMaxRows()?ps.getMaxRows():Const.FETCH_SIZE;
if (databaseMeta.getDatabaseInterface() instanceof MySQLDatabaseMeta && databaseMeta.isStreamingResults())
{
ps.setFetchSize(Integer.MIN_VALUE);
}
else
{
ps.setFetchSize(fs);
}
debug = "OQ Set fetch direction";
ps.setFetchDirection(ResultSet.FETCH_FORWARD);
}
debug = "OQ Set max rows";
if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) ps.setMaxRows(rowlimit);
debug = "OQ exec query";
res = ps.executeQuery();
debug = "OQ getRowInfo()";
// rowinfo = getRowInfo(res.getMetaData());
// MySQL Hack only. It seems too much for the cursor type of operation on MySQL, to have another cursor opened
// to get the length of a String field. So, on MySQL, we ignore the length of Strings in result rows.
rowMeta = getRowInfo(res.getMetaData(), databaseMeta.getDatabaseInterface() instanceof MySQLDatabaseMeta, false);
}
catch(SQLException ex)
{
throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", e);
}
return res;
}
public RowMetaInterface getTableFields(String tablename) throws KettleDatabaseException
{
return getQueryFields(databaseMeta.getSQLQueryFields(tablename), false);
}
public RowMetaInterface getQueryFields(String sql, boolean param) throws KettleDatabaseException
{
return getQueryFields(sql, param, null, null);
}
/**
* See if the table specified exists by reading
* @param tablename The name of the table to check.<br>
* This is supposed to be the properly quoted name of the table or the complete schema-table name combination.
* @return true if the table exists, false if it doesn't.
*/
public boolean checkTableExists(String tablename) throws KettleDatabaseException
{
try
{
if(log.isDebug()) log.logDebug("Checking if table ["+tablename+"] exists!");
// Just try to read from the table.
String sql = databaseMeta.getSQLTableExists(tablename);
try
{
getOneRow(sql);
return true;
}
catch(KettleDatabaseException e)
{
return false;
}
/*
if (getDatabaseMetaData()!=null)
{
ResultSet alltables = getDatabaseMetaData().getTables(null, null, "%" , new String[] { "TABLE", "VIEW", "SYNONYM" } );
boolean found = false;
if (alltables!=null)
{
while (alltables.next() && !found)
{
String schemaName = alltables.getString("TABLE_SCHEM");
String name = alltables.getString("TABLE_NAME");
if ( tablename.equalsIgnoreCase(name) ||
( schemaName!=null && tablename.equalsIgnoreCase( databaseMeta.getSchemaTableCombination(schemaName, name)) )
)
{
log.logDebug("table ["+tablename+"] was found!");
found=true;
}
}
alltables.close();
return found;
}
else
{
throw new KettleDatabaseException("Unable to read table-names from the database meta-data.");
}
}
else
{
throw new KettleDatabaseException("Unable to get database meta-data from the database.");
}
*/
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to check if table ["+tablename+"] exists on connection ["+databaseMeta.getName()+"]", e);
}
}
/**
* See if the column specified exists by reading
* @param columnname The name of the column to check.
* @param tablename The name of the table to check.<br>
* This is supposed to be the properly quoted name of the table or the complete schema-table name combination.
* @return true if the table exists, false if it doesn't.
*/
public boolean checkColumnExists(String columnname, String tablename) throws KettleDatabaseException
{
try
{
if(log.isDebug()) log.logDebug("Checking if column [" + columnname + "] exists in table ["+tablename+"] !");
// Just try to read from the table.
String sql = databaseMeta.getSQLColumnExists(columnname,tablename);
try
{
getOneRow(sql);
return true;
}
catch(KettleDatabaseException e)
{
return false;
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to check if column [" + columnname + "] exists in table ["+tablename+"] on connection ["+databaseMeta.getName()+"]", e);
}
}
/**
* Check whether the sequence exists, Oracle only!
* @param sequenceName The name of the sequence
* @return true if the sequence exists.
*/
public boolean checkSequenceExists(String sequenceName) throws KettleDatabaseException
{
return checkSequenceExists(null, sequenceName);
}
/**
* Check whether the sequence exists, Oracle only!
* @param sequenceName The name of the sequence
* @return true if the sequence exists.
*/
public boolean checkSequenceExists(String schemaName, String sequenceName) throws KettleDatabaseException
{
boolean retval=false;
if (!databaseMeta.supportsSequences()) return retval;
String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName);
try
{
// Get the info from the data dictionary...
String sql = databaseMeta.getSQLSequenceExists(schemaSequence);
ResultSet res = openQuery(sql);
if (res!=null)
{
Object[] row = getRow(res);
if (row!=null)
{
retval=true;
}
closeQuery(res);
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Unexpected error checking whether or not sequence ["+schemaSequence+"] exists", e);
}
return retval;
}
/**
* Check if an index on certain fields in a table exists.
* @param tableName The table on which the index is checked
* @param idx_fields The fields on which the indexe is checked
* @return True if the index exists
*/
public boolean checkIndexExists(String tableName, String idx_fields[]) throws KettleDatabaseException
{
return checkIndexExists(null, tableName, idx_fields);
}
/**
* Check if an index on certain fields in a table exists.
* @param tablename The table on which the index is checked
* @param idx_fields The fields on which the indexe is checked
* @return True if the index exists
*/
public boolean checkIndexExists(String schemaName, String tableName, String idx_fields[]) throws KettleDatabaseException
{
String tablename = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
if (!checkTableExists(tablename)) return false;
if(log.isDebug()) log.logDebug("CheckIndexExists() tablename = "+tablename+" type = "+databaseMeta.getPluginId());
return databaseMeta.getDatabaseInterface().checkIndexExists(this, schemaName, tableName, idx_fields);
}
public String getCreateIndexStatement(String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon)
{
return getCreateIndexStatement(null, tablename, indexname, idx_fields, tk, unique, bitmap, semi_colon);
}
public String getCreateIndexStatement(String schemaname, String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon)
{
String cr_index="";
cr_index += "CREATE ";
if (unique || ( tk && databaseMeta.getDatabaseInterface() instanceof SybaseDatabaseMeta))
cr_index += "UNIQUE ";
if (bitmap && databaseMeta.supportsBitmapIndex())
cr_index += "BITMAP ";
cr_index += "INDEX "+databaseMeta.quoteField(indexname)+Const.CR+" ";
cr_index += "ON ";
// assume table has already been quoted (and possibly includes schema)
cr_index += tablename;
cr_index += Const.CR + "( "+Const.CR;
for (int i=0;i<idx_fields.length;i++)
{
if (i>0) cr_index+=", "; else cr_index+=" ";
cr_index += databaseMeta.quoteField(idx_fields[i])+Const.CR;
}
cr_index+=")"+Const.CR;
if (databaseMeta.getDatabaseInterface() instanceof OracleDatabaseMeta &&
databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0)
{
cr_index+="TABLESPACE "+databaseMeta.quoteField(databaseMeta.getIndexTablespace());
}
if (semi_colon)
{
cr_index+=";"+Const.CR;
}
return cr_index;
}
public String getCreateSequenceStatement(String sequence, long start_at, long increment_by, long max_value, boolean semi_colon)
{
return getCreateSequenceStatement(null, sequence, Long.toString(start_at), Long.toString(increment_by), Long.toString(max_value), semi_colon);
}
public String getCreateSequenceStatement(String sequence, String start_at, String increment_by, String max_value, boolean semi_colon)
{
return getCreateSequenceStatement(null, sequence, start_at, increment_by, max_value, semi_colon);
}
public String getCreateSequenceStatement(String schemaName, String sequence, long start_at, long increment_by, long max_value, boolean semi_colon)
{
return getCreateSequenceStatement(schemaName, sequence, Long.toString(start_at), Long.toString(increment_by), Long.toString(max_value), semi_colon);
}
public String getCreateSequenceStatement(String schemaName, String sequenceName, String start_at, String increment_by, String max_value, boolean semi_colon)
{
String cr_seq="";
if (Const.isEmpty(sequenceName)) return cr_seq;
if (databaseMeta.supportsSequences())
{
String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName);
cr_seq += "CREATE SEQUENCE "+schemaSequence+" "+Const.CR; // Works for both Oracle and PostgreSQL :-)
cr_seq += "START WITH "+start_at+" "+Const.CR;
cr_seq += "INCREMENT BY "+increment_by+" "+Const.CR;
if (max_value != null) {
// "-1" means there is no maxvalue, must be handles different by DB2 / AS400
if (databaseMeta.supportsSequenceNoMaxValueOption() && max_value.trim().equals("-1")) {
cr_seq += "NOMAXVALUE"+Const.CR;
} else {
// set the max value
cr_seq += "MAXVALUE "+max_value+Const.CR;
}
}
if (semi_colon) cr_seq+=";"+Const.CR;
}
return cr_seq;
}
public RowMetaInterface getQueryFields(String sql, boolean param, RowMetaInterface inform, Object[] data) throws KettleDatabaseException
{
RowMetaInterface fields;
DBCache dbcache = DBCache.getInstance();
DBCacheEntry entry=null;
// Check the cache first!
if (dbcache!=null)
{
entry = new DBCacheEntry(databaseMeta.getName(), sql);
fields = dbcache.get(entry);
if (fields!=null)
{
return fields;
}
}
if (connection==null) return null; // Cache test without connect.
// No cache entry found
// The new method of retrieving the query fields fails on Oracle because
// they failed to implement the getMetaData method on a prepared statement. (!!!)
// Even recent drivers like 10.2 fail because of it.
// There might be other databases that don't support it (we have no knowledge of this at the time of writing).
// If we discover other RDBMSs, we will create an interface for it.
// For now, we just try to get the field layout on the re-bound in the exception block below.
if (databaseMeta.supportsPreparedStatementMetadataRetrieval()) {
// On with the regular program.
PreparedStatement preparedStatement = null;
try
{
preparedStatement = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
ResultSetMetaData rsmd = preparedStatement.getMetaData();
fields = getRowInfo(rsmd, false, false);
}
catch(Exception e)
{
fields = getQueryFieldsFallback(sql, param, inform, data);
}
finally
{
if (preparedStatement!=null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
throw new KettleDatabaseException("Unable to close prepared statement after determining SQL layout", e);
}
}
}
} else {
/*
databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_SYBASEIQ
)
{
*/
fields=getQueryFieldsFallback(sql, param, inform, data);
}
// Store in cache!!
if (dbcache!=null && entry!=null)
{
if (fields!=null)
{
dbcache.put(entry, fields);
}
}
return fields;
}
private RowMetaInterface getQueryFieldsFallback(String sql, boolean param, RowMetaInterface inform, Object[] data) throws KettleDatabaseException
{
RowMetaInterface fields;
try
{
if (inform==null
// Hack for MSSQL jtds 1.2 when using xxx NOT IN yyy we have to use a prepared statement (see BugID 3214)
&& databaseMeta.getDatabaseInterface() instanceof MSSQLServerDatabaseMeta )
{
sel_stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
if (databaseMeta.isFetchSizeSupported() && sel_stmt.getMaxRows()>=1)
{
if (databaseMeta.getDatabaseInterface() instanceof MySQLDatabaseMeta) {
sel_stmt.setFetchSize(Integer.MIN_VALUE);
} else {
sel_stmt.setFetchSize(1);
}
}
if (databaseMeta.supportsSetMaxRows()) sel_stmt.setMaxRows(1);
ResultSet r=sel_stmt.executeQuery(databaseMeta.stripCR(sql));
fields = getRowInfo(r.getMetaData(), false, false);
r.close();
sel_stmt.close();
sel_stmt=null;
}
else
{
PreparedStatement ps = connection.prepareStatement(databaseMeta.stripCR(sql));
if (param)
{
RowMetaInterface par = inform;
if (par==null || par.isEmpty()) par = getParameterMetaData(ps);
if (par==null || par.isEmpty()) par = getParameterMetaData(sql, inform, data);
setValues(par, data, ps);
}
ResultSet r = ps.executeQuery();
fields=getRowInfo(ps.getMetaData(), false, false);
r.close();
ps.close();
}
}
catch(Exception ex)
{
throw new KettleDatabaseException("Couldn't get field info from ["+sql+"]"+Const.CR, ex);
}
return fields;
}
public void closeQuery(ResultSet res) throws KettleDatabaseException
{
// close everything involved in the query!
try
{
if (res!=null) res.close();
if (sel_stmt!=null) { sel_stmt.close(); sel_stmt=null; }
if (pstmt!=null) { pstmt.close(); pstmt=null;}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't close query: resultset or prepared statements", ex);
}
}
/**
* Build the row using ResultSetMetaData rsmd
* @param rm The resultset metadata to inquire
* @param ignoreLength true if you want to ignore the length (workaround for MySQL bug/problem)
* @param lazyConversion true if lazy conversion needs to be enabled where possible
*/
private RowMetaInterface getRowInfo(ResultSetMetaData rm, boolean ignoreLength, boolean lazyConversion) throws KettleDatabaseException
{
if (rm==null) {
throw new KettleDatabaseException("No result set metadata available to retrieve row metadata!");
}
rowMeta = new RowMeta();
try
{
// TODO If we do lazy conversion, we need to find out about the encoding
int fieldNr = 1;
int nrcols=rm.getColumnCount();
for (int i=1;i<=nrcols;i++)
{
String name=new String(rm.getColumnName(i));
// Check the name, sometimes it's empty.
if (Const.isEmpty(name) || Const.onlySpaces(name))
{
name = "Field"+fieldNr;
fieldNr++;
}
ValueMetaInterface v = getValueFromSQLType(name, rm, i, ignoreLength, lazyConversion);
rowMeta.addValueMeta(v);
}
return rowMeta;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error getting row information from database: ", ex);
}
}
private ValueMetaInterface getValueFromSQLType(String name, ResultSetMetaData rm, int index, boolean ignoreLength, boolean lazyConversion) throws SQLException
{
int length=-1;
int precision=-1;
int valtype=ValueMetaInterface.TYPE_NONE;
boolean isClob = false;
int type = rm.getColumnType(index);
boolean signed = rm.isSigned(index);
switch(type)
{
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.LONGVARCHAR: // Character Large Object
valtype=ValueMetaInterface.TYPE_STRING;
if (!ignoreLength) length=rm.getColumnDisplaySize(index);
break;
case java.sql.Types.CLOB:
valtype=ValueMetaInterface.TYPE_STRING;
length=DatabaseMeta.CLOB_LENGTH;
isClob=true;
break;
case java.sql.Types.BIGINT:
// verify Unsigned BIGINT overflow!
if (signed)
{
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 9.223.372.036.854.775.807
length=15;
}
else
{
valtype=ValueMetaInterface.TYPE_BIGNUMBER;
precision=0; // Max 18.446.744.073.709.551.615
length=16;
}
break;
case java.sql.Types.INTEGER:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 2.147.483.647
length=9;
break;
case java.sql.Types.SMALLINT:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 32.767
length=4;
break;
case java.sql.Types.TINYINT:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 127
length=2;
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.REAL:
case java.sql.Types.NUMERIC:
valtype=ValueMetaInterface.TYPE_NUMBER;
length=rm.getPrecision(index);
precision=rm.getScale(index);
if (length >=126) length=-1;
if (precision >=126) precision=-1;
if (type==java.sql.Types.DOUBLE || type==java.sql.Types.FLOAT || type==java.sql.Types.REAL)
{
if (precision==0)
{
precision=-1; // precision is obviously incorrect if the type if Double/Float/Real
}
// If we're dealing with PostgreSQL and double precision types
if (databaseMeta.getDatabaseInterface() instanceof PostgreSQLDatabaseMeta && type==java.sql.Types.DOUBLE && precision==16 && length==16)
{
precision=-1;
length=-1;
}
// MySQL: max resolution is double precision floating point (double)
// The (12,31) that is given back is not correct
if (databaseMeta.getDatabaseInterface() instanceof MySQLDatabaseMeta)
{
if (precision >= length) {
precision=-1;
length=-1;
}
}
// if the length or precision needs a BIGNUMBER
if (length>15 || precision>15) valtype=ValueMetaInterface.TYPE_BIGNUMBER;
}
else
{
if (precision==0) {
if (length<=18 && length>0) { // Among others Oracle is affected here.
valtype=ValueMetaInterface.TYPE_INTEGER; // Long can hold up to 18 significant digits
} else if (length>18) {
valtype=ValueMetaInterface.TYPE_BIGNUMBER;
}
} else { // we have a precision: keep NUMBER or change to BIGNUMBER?
if (length>15 || precision>15) valtype=ValueMetaInterface.TYPE_BIGNUMBER;
}
}
if (databaseMeta.getDatabaseInterface() instanceof PostgreSQLDatabaseMeta || databaseMeta.getDatabaseInterface() instanceof GreenplumDatabaseMeta)
{
// undefined size => arbitrary precision
if (type == java.sql.Types.NUMERIC && length == 0 && precision == 0)
{
valtype = ValueMetaInterface.TYPE_BIGNUMBER;
length = -1;
precision = -1;
}
}
if (databaseMeta.getDatabaseInterface() instanceof OracleDatabaseMeta)
{
if (precision == 0 && length == 38 )
{
valtype=ValueMetaInterface.TYPE_INTEGER;
}
if (precision<=0 && length<=0) // undefined size: BIGNUMBER, precision on Oracle can be 38, too big for a Number type
{
valtype=ValueMetaInterface.TYPE_BIGNUMBER;
length=-1;
precision=-1;
}
}
break;
case java.sql.Types.DATE:
if (databaseMeta.getDatabaseInterface() instanceof TeradataDatabaseMeta) {
precision = 1;
}
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
valtype=ValueMetaInterface.TYPE_DATE;
if (databaseMeta.getDatabaseInterface() instanceof MySQLDatabaseMeta) {
String property = databaseMeta.getConnectionProperties().getProperty("yearIsDateType");
if (property != null && property.equalsIgnoreCase("false")
&& rm.getColumnTypeName(index).equalsIgnoreCase("YEAR")) {
valtype = ValueMetaInterface.TYPE_INTEGER;
precision = 0;
length = 4;
break;
}
}
break;
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
valtype=ValueMetaInterface.TYPE_BOOLEAN;
break;
case java.sql.Types.BINARY:
case java.sql.Types.BLOB:
case java.sql.Types.VARBINARY:
case java.sql.Types.LONGVARBINARY:
valtype=ValueMetaInterface.TYPE_BINARY;
if (databaseMeta.isDisplaySizeTwiceThePrecision() && (2 * rm.getPrecision(index)) == rm.getColumnDisplaySize(index))
{
// set the length for "CHAR(X) FOR BIT DATA"
length = rm.getPrecision(index);
}
else
if (databaseMeta.getDatabaseInterface() instanceof OracleDatabaseMeta &&
( type==java.sql.Types.VARBINARY || type==java.sql.Types.LONGVARBINARY )
)
{
// set the length for Oracle "RAW" or "LONGRAW" data types
valtype = ValueMetaInterface.TYPE_STRING;
length = rm.getColumnDisplaySize(index);
}
else
{
length=-1;
}
precision=-1;
break;
default:
valtype=ValueMetaInterface.TYPE_STRING;
precision=rm.getScale(index);
break;
}
// Grab the comment as a description to the field as well.
String comments=rm.getColumnLabel(index);
// get & store more result set meta data for later use
int originalColumnType=rm.getColumnType(index);
String originalColumnTypeName=rm.getColumnTypeName(index);
int originalPrecision=-1;
if (!ignoreLength) rm.getPrecision(index); // Throws exception on MySQL
int originalScale=rm.getScale(index);
// boolean originalAutoIncrement=rm.isAutoIncrement(index); DISABLED FOR PERFORMANCE REASONS : PDI-1788
// int originalNullable=rm.isNullable(index); DISABLED FOR PERFORMANCE REASONS : PDI-1788
boolean originalSigned=rm.isSigned(index);
ValueMetaInterface v=new ValueMeta(name, valtype);
v.setLength(length);
v.setPrecision(precision);
v.setComments(comments);
v.setLargeTextField(isClob);
v.setOriginalColumnType(originalColumnType);
v.setOriginalColumnTypeName(originalColumnTypeName);
v.setOriginalPrecision(originalPrecision);
v.setOriginalScale(originalScale);
// v.setOriginalAutoIncrement(originalAutoIncrement); DISABLED FOR PERFORMANCE REASONS : PDI-1788
// v.setOriginalNullable(originalNullable); DISABLED FOR PERFORMANCE REASONS : PDI-1788
v.setOriginalSigned(originalSigned);
// See if we need to enable lazy conversion...
if (lazyConversion && valtype==ValueMetaInterface.TYPE_STRING) {
v.setStorageType(ValueMetaInterface.STORAGE_TYPE_BINARY_STRING);
// TODO set some encoding to go with this.
// Also set the storage metadata. a copy of the parent, set to String too.
ValueMetaInterface storageMetaData = v.clone();
storageMetaData.setType(ValueMetaInterface.TYPE_STRING);
storageMetaData.setStorageType(ValueMetaInterface.STORAGE_TYPE_NORMAL);
v.setStorageMetadata(storageMetaData);
}
return v;
}
public boolean absolute(ResultSet rs, int position) throws KettleDatabaseException
{
try
{
return rs.absolute(position);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to position "+position, e);
}
}
public boolean relative(ResultSet rs, int rows) throws KettleDatabaseException
{
try
{
return rs.relative(rows);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move the resultset forward "+rows+" rows", e);
}
}
public void afterLast(ResultSet rs)
throws KettleDatabaseException
{
try
{
rs.afterLast();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to after the last position", e);
}
}
public void first(ResultSet rs) throws KettleDatabaseException
{
try
{
rs.first();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to the first position", e);
}
}
/**
* Get a row from the resultset. Do not use lazy conversion
* @param rs The resultset to get the row from
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Object[] getRow(ResultSet rs) throws KettleDatabaseException
{
return getRow(rs, false);
}
/**
* Get a row from the resultset.
* @param rs The resultset to get the row from
* @param lazyConversion set to true if strings need to have lazy conversion enabled
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Object[] getRow(ResultSet rs, boolean lazyConversion) throws KettleDatabaseException
{
if (rowMeta==null)
{
ResultSetMetaData rsmd = null;
try
{
rsmd = rs.getMetaData();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to retrieve metadata from resultset", e);
}
rowMeta = getRowInfo(rsmd, false, lazyConversion);
}
return getRow(rs, null, rowMeta);
}
/**
* Get a row from the resultset.
* @param rs The resultset to get the row from
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Object[] getRow(ResultSet rs, ResultSetMetaData dummy, RowMetaInterface rowInfo) throws KettleDatabaseException
{
try
{
int nrcols=rowInfo.size();
Object[] data = RowDataUtil.allocateRowData(nrcols);
if (rs.next())
{
for (int i=0;i<nrcols;i++)
{
ValueMetaInterface val = rowInfo.getValueMeta(i);
switch(val.getType())
{
case ValueMetaInterface.TYPE_BOOLEAN : data[i] = Boolean.valueOf( rs.getBoolean(i+1) ); break;
case ValueMetaInterface.TYPE_NUMBER : data[i] = new Double( rs.getDouble(i+1) ); break;
case ValueMetaInterface.TYPE_BIGNUMBER : data[i] = rs.getBigDecimal(i+1); break;
case ValueMetaInterface.TYPE_INTEGER : data[i] = Long.valueOf( rs.getLong(i+1) ); break;
case ValueMetaInterface.TYPE_STRING :
{
if (val.isStorageBinaryString()) {
data[i] = rs.getBytes(i+1);
}
else {
data[i] = rs.getString(i+1);
}
}
break;
case ValueMetaInterface.TYPE_BINARY :
{
if (databaseMeta.supportsGetBlob())
{
Blob blob = rs.getBlob(i+1);
if (blob!=null)
{
data[i] = blob.getBytes(1L, (int)blob.length());
}
else
{
data[i] = null;
}
}
else
{
data[i] = rs.getBytes(i+1);
}
}
break;
case ValueMetaInterface.TYPE_DATE :
if (databaseMeta.getDatabaseInterface() instanceof NeoviewDatabaseMeta && val.getOriginalColumnType()==java.sql.Types.TIME)
{
// Neoview can not handle getDate / getTimestamp for a Time column
data[i] = rs.getTime(i+1); break; // Time is a subclass of java.util.Date, the default date will be 1970-01-01
}
else if (val.getPrecision()!=1 && databaseMeta.supportsTimeStampToDateConversion())
{
data[i] = rs.getTimestamp(i+1); break; // Timestamp extends java.util.Date
}
else
{
data[i] = rs.getDate(i+1); break;
}
default: break;
}
if (rs.wasNull()) data[i] = null; // null value, it's the default but we want it just to make sure we handle this case too.
}
}
else
{
data=null;
}
return data;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't get row from result set", ex);
}
}
public void printSQLException(SQLException ex)
{
log.logError("==> SQLException: ");
while (ex != null)
{
log.logError("Message: " + ex.getMessage ());
log.logError("SQLState: " + ex.getSQLState ());
log.logError("ErrorCode: " + ex.getErrorCode ());
ex = ex.getNextException();
log.logError("");
}
}
public void setLookup(String table, String codes[], String condition[],
String gets[], String rename[], String orderby
) throws KettleDatabaseException
{
setLookup(table, codes, condition, gets, rename, orderby, false);
}
public void setLookup(String schema, String table, String codes[], String condition[],
String gets[], String rename[], String orderby
) throws KettleDatabaseException
{
setLookup(schema, table, codes, condition, gets, rename, orderby, false);
}
public void setLookup(String tableName, String codes[], String condition[],
String gets[], String rename[], String orderby,
boolean checkForMultipleResults) throws KettleDatabaseException
{
setLookup(null, tableName, codes, condition, gets, rename, orderby, checkForMultipleResults);
}
// Lookup certain fields in a table
public void setLookup(String schemaName, String tableName, String codes[], String condition[],
String gets[], String rename[], String orderby,
boolean checkForMultipleResults) throws KettleDatabaseException
{
String table = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
String sql = "SELECT ";
for (int i=0;i<gets.length;i++)
{
if (i!=0) sql += ", ";
sql += databaseMeta.quoteField(gets[i]);
if (rename!=null && rename[i]!=null && !gets[i].equalsIgnoreCase(rename[i]))
{
sql+=" AS "+databaseMeta.quoteField(rename[i]);
}
}
sql += " FROM "+table+" WHERE ";
for (int i=0;i<codes.length;i++)
{
if (i!=0) sql += " AND ";
sql += databaseMeta.quoteField(codes[i]);
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql+=" BETWEEN ? AND ? ";
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql+=" "+condition[i]+" ";
}
else
{
sql+=" "+condition[i]+" ? ";
}
}
if (orderby!=null && orderby.length()!=0)
{
sql += " ORDER BY "+orderby;
}
try
{
if(log.isDetailed()) log.logDetailed("Setting preparedStatement to ["+sql+"]");
prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql));
if (!checkForMultipleResults && databaseMeta.supportsSetMaxRows())
{
prepStatementLookup.setMaxRows(1); // alywas get only 1 line back!
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare statement for update ["+sql+"]", ex);
}
}
public boolean prepareUpdate(String table, String codes[], String condition[], String sets[])
{
return prepareUpdate(null, table, codes, condition, sets);
}
// Lookup certain fields in a table
public boolean prepareUpdate(String schemaName, String tableName, String codes[], String condition[], String sets[])
{
StringBuffer sql = new StringBuffer(128);
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
sql.append("UPDATE ").append(schemaTable).append(Const.CR).append("SET ");
for (int i=0;i<sets.length;i++)
{
if (i!=0) sql.append(", ");
sql.append(databaseMeta.quoteField(sets[i]));
sql.append(" = ?").append(Const.CR);
}
sql.append("WHERE ");
for (int i=0;i<codes.length;i++)
{
if (i!=0) sql.append("AND ");
sql.append(databaseMeta.quoteField(codes[i]));
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql.append(" BETWEEN ? AND ? ");
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql.append(' ').append(condition[i]).append(' ');
}
else
{
sql.append(' ').append(condition[i]).append(" ? ");
}
}
try
{
String s = sql.toString();
if(log.isDetailed()) log.logDetailed("Setting update preparedStatement to ["+s+"]");
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(s));
}
catch(SQLException ex)
{
printSQLException(ex);
return false;
}
return true;
}
/**
* Prepare a delete statement by giving it the tablename, fields and conditions to work with.
* @param table The table-name to delete in
* @param codes
* @param condition
* @return true when everything went OK, false when something went wrong.
*/
public boolean prepareDelete(String table, String codes[], String condition[])
{
return prepareDelete(null, table, codes, condition);
}
/**
* Prepare a delete statement by giving it the tablename, fields and conditions to work with.
* @param schemaName the schema-name to delete in
* @param tableName The table-name to delete in
* @param codes
* @param condition
* @return true when everything went OK, false when something went wrong.
*/
public boolean prepareDelete(String schemaName, String tableName, String codes[], String condition[])
{
String sql;
String table = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
sql = "DELETE FROM "+table+Const.CR;
sql+= "WHERE ";
for (int i=0;i<codes.length;i++)
{
if (i!=0) sql += "AND ";
sql += codes[i];
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql+=" BETWEEN ? AND ? ";
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql+=" "+condition[i]+" ";
}
else
{
sql+=" "+condition[i]+" ? ";
}
}
try
{
if(log.isDetailed()) log.logDetailed("Setting update preparedStatement to ["+sql+"]");
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(sql));
}
catch(SQLException ex)
{
printSQLException(ex);
return false;
}
return true;
}
public void setProcLookup(String proc, String arg[], String argdir[], int argtype[], String returnvalue, int returntype)
throws KettleDatabaseException
{
String sql;
int pos=0;
sql = "{ ";
if (returnvalue!=null && returnvalue.length()!=0)
{
sql+="? = ";
}
sql+="call "+proc+" ";
if (arg.length>0) sql+="(";
for (int i=0;i<arg.length;i++)
{
if (i!=0) sql += ", ";
sql += " ?";
}
if (arg.length>0) sql+=")";
sql+="}";
try
{
if(log.isDetailed()) log.logDetailed("DBA setting callableStatement to ["+sql+"]");
cstmt=connection.prepareCall(sql);
pos=1;
if (!Const.isEmpty(returnvalue))
{
switch(returntype)
{
case ValueMetaInterface.TYPE_NUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DOUBLE); break;
case ValueMetaInterface.TYPE_BIGNUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DECIMAL); break;
case ValueMetaInterface.TYPE_INTEGER : cstmt.registerOutParameter(pos, java.sql.Types.BIGINT); break;
case ValueMetaInterface.TYPE_STRING : cstmt.registerOutParameter(pos, java.sql.Types.VARCHAR); break;
case ValueMetaInterface.TYPE_DATE : cstmt.registerOutParameter(pos, java.sql.Types.TIMESTAMP); break;
case ValueMetaInterface.TYPE_BOOLEAN : cstmt.registerOutParameter(pos, java.sql.Types.BOOLEAN); break;
default: break;
}
pos++;
}
for (int i=0;i<arg.length;i++)
{
if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT"))
{
switch(argtype[i])
{
case ValueMetaInterface.TYPE_NUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DOUBLE); break;
case ValueMetaInterface.TYPE_BIGNUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DECIMAL); break;
case ValueMetaInterface.TYPE_INTEGER : cstmt.registerOutParameter(i+pos, java.sql.Types.BIGINT); break;
case ValueMetaInterface.TYPE_STRING : cstmt.registerOutParameter(i+pos, java.sql.Types.VARCHAR); break;
case ValueMetaInterface.TYPE_DATE : cstmt.registerOutParameter(i+pos, java.sql.Types.TIMESTAMP); break;
case ValueMetaInterface.TYPE_BOOLEAN : cstmt.registerOutParameter(i+pos, java.sql.Types.BOOLEAN); break;
default: break;
}
}
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare database procedure call", ex);
}
}
public Object[] getLookup() throws KettleDatabaseException
{
return getLookup(prepStatementLookup);
}
public Object[] getLookup(boolean failOnMultipleResults) throws KettleDatabaseException
{
return getLookup(prepStatementLookup, failOnMultipleResults);
}
public Object[] getLookup(PreparedStatement ps) throws KettleDatabaseException
{
return getLookup(ps, false);
}
public Object[] getLookup(PreparedStatement ps, boolean failOnMultipleResults) throws KettleDatabaseException
{
ResultSet res = null;
try
{
res = ps.executeQuery();
rowMeta = getRowInfo(res.getMetaData(), false, false);
Object[] ret = getRow(res);
if (failOnMultipleResults)
{
if (ret != null && res.next())
{
// if the previous row was null, there's no reason to try res.next() again.
// on DB2 this will even cause an exception (because of the buggy DB2 JDBC driver).
throw new KettleDatabaseException("Only 1 row was expected as a result of a lookup, and at least 2 were found!");
}
}
return ret;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error looking up row in database", ex);
}
finally
{
try
{
if (res!=null) res.close(); // close resultset!
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to close resultset after looking up data", e);
}
}
}
public DatabaseMetaData getDatabaseMetaData() throws KettleDatabaseException
{
try
{
if (dbmd==null) dbmd = connection.getMetaData(); // Only get the metadata once!
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get database metadata from this database connection", e);
}
return dbmd;
}
public String getDDL(String tablename, RowMetaInterface fields) throws KettleDatabaseException
{
return getDDL(tablename, fields, null, false, null, true);
}
public String getDDL(String tablename, RowMetaInterface fields, String tk, boolean use_autoinc, String pk) throws KettleDatabaseException
{
return getDDL(tablename, fields, tk, use_autoinc, pk, true);
}
public String getDDL(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon) throws KettleDatabaseException
{
String retval;
// First, check for reserved SQL in the input row r...
databaseMeta.quoteReservedWords(fields);
String quotedTk = tk != null ? databaseMeta.quoteField(tk) : null;
if (checkTableExists(tableName))
{
retval=getAlterTableStatement(tableName, fields, quotedTk, use_autoinc, pk, semicolon);
}
else
{
retval=getCreateTableStatement(tableName, fields, quotedTk, use_autoinc, pk, semicolon);
}
return retval;
}
/**
* Generates SQL
* @param tableName the table name or schema/table combination: this needs to be quoted properly in advance.
* @param fields the fields
* @param tk the name of the technical key field
* @param use_autoinc true if we need to use auto-increment fields for a primary key
* @param pk the name of the primary/technical key field
* @param semicolon append semicolon to the statement
* @param pkc primary key composite ( name of the key fields)
* @return the SQL needed to create the specified table and fields.
*/
public String getCreateTableStatement(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
StringBuilder retval = new StringBuilder("CREATE TABLE ");
retval.append(tableName+Const.CR);
retval.append("(").append(Const.CR);
for (int i=0;i<fields.size();i++)
{
if (i>0) retval.append(", "); else retval.append(" ");
ValueMetaInterface v=fields.getValueMeta(i);
retval.append(databaseMeta.getFieldDefinition(v, tk, pk, use_autoinc));
}
// At the end, before the closing of the statement, we might need to add some constraints...
// Technical keys
if (tk!=null)
{
if (databaseMeta.requiresCreateTablePrimaryKeyAppend())
{
retval.append(", PRIMARY KEY (").append(tk).append(")").append(Const.CR);
}
}
// Primary keys
if (pk!=null)
{
if (databaseMeta.requiresCreateTablePrimaryKeyAppend())
{
retval.append(", PRIMARY KEY (").append(pk).append(")").append(Const.CR);
}
}
retval.append(")").append(Const.CR);
if (databaseMeta.getDatabaseInterface() instanceof OracleDatabaseMeta &&
databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0)
{
retval.append("TABLESPACE ").append(databaseMeta.getDataTablespace());
}
if (pk==null && tk==null && databaseMeta.getDatabaseInterface() instanceof NeoviewDatabaseMeta)
{
retval.append("NO PARTITION"); // use this as a default when no pk/tk is there, otherwise you get an error
}
if (semicolon) retval.append(";");
// TODO: All this custom database code shouldn't really be in Database.java. It should be in the DB implementations.
if (databaseMeta.getDatabaseInterface() instanceof VerticaDatabaseMeta)
{
retval.append(Const.CR).append("CREATE PROJECTION ").append(tableName).append("_unseg_super").append(Const.CR);
retval.append("(").append(Const.CR);
for (int i=0;i<fields.size();i++)
{
if (i>0) retval.append(", "); else retval.append(" ");
retval.append(fields.getValueMeta(i).getName()).append(Const.CR);
}
retval.append(")").append(Const.CR);
retval.append("AS SELECT").append(Const.CR);
for (int i=0;i<fields.size();i++)
{
if (i>0) retval.append(", "); else retval.append(" ");
retval.append(fields.getValueMeta(i).getName()).append(Const.CR);
}
retval.append("FROM ").append(tableName).append(Const.CR);
retval.append("-- Replace UNSEGMENTED with a hash segmentation for optimum performance").append(Const.CR);
retval.append("--SEGMENTED BY HASH(X,Y,Z)").append(Const.CR);
retval.append("UNSEGMENTED ALL NODES").append(Const.CR);
retval.append(";");
}
return retval.toString();
}
public String getAlterTableStatement(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon) throws KettleDatabaseException
{
String retval="";
// Get the fields that are in the table now:
RowMetaInterface tabFields = getTableFields(tableName);
// Don't forget to quote these as well...
databaseMeta.quoteReservedWords(tabFields);
// Find the missing fields
RowMetaInterface missing = new RowMeta();
for (int i=0;i<fields.size();i++)
{
ValueMetaInterface v = fields.getValueMeta(i);
// Not found?
if (tabFields.searchValueMeta( v.getName() )==null )
{
missing.addValueMeta(v); // nope --> Missing!
}
}
if (missing.size()!=0)
{
for (int i=0;i<missing.size();i++)
{
ValueMetaInterface v=missing.getValueMeta(i);
retval+=databaseMeta.getAddColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
// Find the surplus fields
RowMetaInterface surplus = new RowMeta();
for (int i=0;i<tabFields.size();i++)
{
ValueMetaInterface v = tabFields.getValueMeta(i);
// Found in table, not in input ?
if (fields.searchValueMeta( v.getName() )==null )
{
surplus.addValueMeta(v); // yes --> surplus!
}
}
if (surplus.size()!=0)
{
for (int i=0;i<surplus.size();i++)
{
ValueMetaInterface v=surplus.getValueMeta(i);
retval+=databaseMeta.getDropColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
// OK, see if there are fields for which we need to modify the type... (length, precision)
RowMetaInterface modify = new RowMeta();
for (int i=0;i<fields.size();i++)
{
ValueMetaInterface desiredField = fields.getValueMeta(i);
ValueMetaInterface currentField = tabFields.searchValueMeta( desiredField.getName());
if (desiredField!=null && currentField!=null)
{
String desiredDDL = databaseMeta.getFieldDefinition(desiredField, tk, pk, use_autoinc);
String currentDDL = databaseMeta.getFieldDefinition(currentField, tk, pk, use_autoinc);
boolean mod = !desiredDDL.equalsIgnoreCase(currentDDL);
if (mod)
{
// System.out.println("Desired field: ["+desiredField.toStringMeta()+"], current field: ["+currentField.toStringMeta()+"]");
modify.addValueMeta(desiredField);
}
}
}
if (modify.size()>0)
{
for (int i=0;i<modify.size();i++)
{
ValueMetaInterface v=modify.getValueMeta(i);
retval+=databaseMeta.getModifyColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
return retval;
}
public void truncateTable(String tablename) throws KettleDatabaseException
{
if (Const.isEmpty(connectionGroup))
{
execStatement(databaseMeta.getTruncateTableStatement(null, tablename));
}
else
{
execStatement("DELETE FROM "+databaseMeta.quoteField(tablename));
}
}
public void truncateTable(String schema, String tablename) throws KettleDatabaseException
{
if (Const.isEmpty(connectionGroup))
{
execStatement(databaseMeta.getTruncateTableStatement(schema, tablename));
}
else
{
execStatement("DELETE FROM "+databaseMeta.getQuotedSchemaTableCombination(schema, tablename));
}
}
/**
* Execute a query and return at most one row from the resultset
* @param sql The SQL for the query
* @return one Row with data or null if nothing was found.
*/
public RowMetaAndData getOneRow(String sql) throws KettleDatabaseException
{
ResultSet rs = openQuery(sql);
if (rs!=null)
{
Object[] row = getRow(rs); // One row only;
try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); }
if (pstmt!=null)
{
try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); }
pstmt=null;
}
if (sel_stmt!=null)
{
try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); }
sel_stmt=null;
}
return new RowMetaAndData(rowMeta, row);
}
else
{
throw new KettleDatabaseException("error opening resultset for query: "+sql);
}
}
public RowMeta getMetaFromRow( Object[] row, ResultSetMetaData md ) throws SQLException {
RowMeta meta = new RowMeta();
for( int i=0; i<md.getColumnCount(); i++ ) {
String name = md.getColumnName(i+1);
ValueMetaInterface valueMeta = getValueFromSQLType( name, md, i+1, true, false );
meta.addValueMeta( valueMeta );
}
return meta;
}
public RowMetaAndData getOneRow(String sql, RowMetaInterface param, Object[] data) throws KettleDatabaseException
{
ResultSet rs = openQuery(sql, param, data);
if (rs!=null)
{
Object[] row = getRow(rs); // One value: a number;
rowMeta=null;
RowMeta tmpMeta = null;
try {
ResultSetMetaData md = rs.getMetaData();
tmpMeta = getMetaFromRow( row, md );
} catch (Exception e) {
e.printStackTrace();
} finally {
try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); }
if (pstmt!=null)
{
try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); }
pstmt=null;
}
if (sel_stmt!=null)
{
try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); }
sel_stmt=null;
}
}
return new RowMetaAndData(tmpMeta, row);
}
else
{
return null;
}
}
public RowMetaInterface getParameterMetaData(PreparedStatement ps)
{
RowMetaInterface par = new RowMeta();
try
{
ParameterMetaData pmd = ps.getParameterMetaData();
for (int i=1;i<=pmd.getParameterCount();i++)
{
String name = "par"+i;
int sqltype = pmd.getParameterType(i);
int length = pmd.getPrecision(i);
int precision = pmd.getScale(i);
ValueMeta val;
switch(sqltype)
{
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
val=new ValueMeta(name, ValueMetaInterface.TYPE_STRING);
break;
case java.sql.Types.BIGINT:
case java.sql.Types.INTEGER:
case java.sql.Types.NUMERIC:
case java.sql.Types.SMALLINT:
case java.sql.Types.TINYINT:
val=new ValueMeta(name, ValueMetaInterface.TYPE_INTEGER);
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.REAL:
val=new ValueMeta(name, ValueMetaInterface.TYPE_NUMBER);
break;
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
val=new ValueMeta(name, ValueMetaInterface.TYPE_DATE);
break;
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
val=new ValueMeta(name, ValueMetaInterface.TYPE_BOOLEAN);
break;
default:
val=new ValueMeta(name, ValueMetaInterface.TYPE_NONE);
break;
}
if (val.isNumeric() && ( length>18 || precision>18) )
{
val = new ValueMeta(name, ValueMetaInterface.TYPE_BIGNUMBER);
}
par.addValueMeta(val);
}
}
// Oops: probably the database or JDBC doesn't support it.
catch(AbstractMethodError e) { return null; }
catch(SQLException e) { return null; }
catch(Exception e) { return null; }
return par;
}
public int countParameters(String sql)
{
int q=0;
boolean quote_opened=false;
boolean dquote_opened=false;
for (int x=0;x<sql.length();x++)
{
char c = sql.charAt(x);
switch(c)
{
case '\'': quote_opened= !quote_opened; break;
case '"' : dquote_opened=!dquote_opened; break;
case '?' : if (!quote_opened && !dquote_opened) q++; break;
}
}
return q;
}
// Get the fields back from an SQL query
public RowMetaInterface getParameterMetaData(String sql, RowMetaInterface inform, Object[] data)
{
// The database couldn't handle it: try manually!
int q=countParameters(sql);
RowMetaInterface par=new RowMeta();
if (inform!=null && q==inform.size())
{
for (int i=0;i<q;i++)
{
ValueMetaInterface inf=inform.getValueMeta(i);
ValueMetaInterface v = inf.clone();
par.addValueMeta(v);
}
}
else
{
for (int i=0;i<q;i++)
{
ValueMetaInterface v = new ValueMeta("name"+i, ValueMetaInterface.TYPE_NUMBER);
par.addValueMeta(v);
}
}
return par;
}
public void writeLogRecord(LogTableInterface logTable, LogStatus status, Object subject, Object parent) throws KettleException {
try {
RowMetaAndData logRecord = logTable.getLogRecord(status, subject, parent);
if (logRecord==null) return;
boolean update = (logTable.getKeyField()!=null) && !status.equals(LogStatus.START);
String schemaTable = databaseMeta.getSchemaTableCombination(logTable.getSchemaName(), logTable.getTableName());
RowMetaInterface rowMeta = logRecord.getRowMeta();
Object[] rowData = logRecord.getData();
if (update) {
RowMetaInterface updateRowMeta = new RowMeta();
Object[] updateRowData = new Object[rowMeta.size()];
ValueMetaInterface keyValueMeta = rowMeta.getValueMeta(0);
String sql = "UPDATE " + schemaTable + " SET ";
for (int i = 1; i < rowMeta.size() ; i++) // Without ID_JOB or ID_BATCH
{
ValueMetaInterface valueMeta = rowMeta.getValueMeta(i);
if (i > 1) {
sql += ", ";
}
sql += databaseMeta.quoteField(valueMeta.getName()) + "=? ";
updateRowMeta.addValueMeta(valueMeta);
updateRowData[i-1] = rowData[i];
}
sql += "WHERE ";
sql += databaseMeta.quoteField(keyValueMeta.getName()) + "=? ";
updateRowMeta.addValueMeta(keyValueMeta);
updateRowData[rowMeta.size()-1] = rowData[0];
execStatement(sql, updateRowMeta, updateRowData);
} else {
insertRow(logTable.getSchemaName(), logTable.getTableName(), logRecord.getRowMeta(), logRecord.getData());
}
} catch(Exception e) {
throw new KettleDatabaseException("Unable to write log record to log table " + logTable.getTableName(), e);
}
}
public void cleanupLogRecords(LogTableInterface logTable) throws KettleException {
try {
double timeout = Const.toDouble( Const.trim( environmentSubstitute( logTable.getTimeoutInDays())), 0.0 );
if (timeout>0.000001) {
// The timeout has to be at least a few seconds, otherwise we don't bother
String schemaTable = databaseMeta.getSchemaTableCombination(logTable.getSchemaName(), logTable.getTableName());
// The log date field
LogTableField logField = logTable.getLogDateField();
if (logField!=null) {
String sql = "DELETE FROM "+schemaTable+" WHERE "+databaseMeta.quoteField(logField.getFieldName())+" < ?"; // $NON-NLS$1
// Now calculate the date...
long now = System.currentTimeMillis();
long limit = now - Math.round(timeout*24*60*60*1000);
RowMetaAndData row = new RowMetaAndData();
row.addValue(logField.getFieldName(), ValueMetaInterface.TYPE_DATE, new Date(limit));
execStatement(sql, row.getRowMeta(), row.getData());
} else {
throw new KettleException(BaseMessages.getString(PKG, "Database.Exception.LogTimeoutDefinedOnTableWithoutLogField", logTable.getTableName()));
}
}
} catch(Exception e) {
throw new KettleDatabaseException(BaseMessages.getString(PKG, "Database.Exception.UnableToCleanUpOlderRecordsFromLogTable", logTable.getTableName()), e);
}
}
public Object[] getLastLogDate( String logtable, String name, boolean job, LogStatus status ) throws KettleDatabaseException
{
Object[] row = null;
String jobtrans = job?databaseMeta.quoteField("JOBNAME"):databaseMeta.quoteField("TRANSNAME");
String sql = "";
sql+=" SELECT "+databaseMeta.quoteField("ENDDATE")+", "+databaseMeta.quoteField("DEPDATE")+", "+databaseMeta.quoteField("STARTDATE");
sql+=" FROM "+logtable;
sql+=" WHERE "+databaseMeta.quoteField("ERRORS")+" = 0";
sql+=" AND "+databaseMeta.quoteField("STATUS")+" = 'end'";
sql+=" AND "+jobtrans+" = ?";
sql+=" ORDER BY "+databaseMeta.quoteField("LOGDATE")+" DESC, "+databaseMeta.quoteField("ENDDATE")+" DESC";
try
{
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql));
RowMetaInterface r = new RowMeta();
r.addValueMeta( new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING));
setValues(r, new Object[] { name });
ResultSet res = pstmt.executeQuery();
if (res!=null)
{
rowMeta = getRowInfo(res.getMetaData(), false, false);
row = getRow(res);
res.close();
}
pstmt.close(); pstmt=null;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to obtain last logdate from table "+logtable, ex);
}
return row;
}
public synchronized Long getNextValue(Hashtable<String,Counter> counters, String tableName, String val_key) throws KettleDatabaseException
{
return getNextValue(counters, null, tableName, val_key);
}
public synchronized Long getNextValue(Hashtable<String,Counter> counters, String schemaName, String tableName, String val_key) throws KettleDatabaseException
{
Long nextValue = null;
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
String lookup = schemaTable+"."+databaseMeta.quoteField(val_key);
// Try to find the previous sequence value...
Counter counter = null;
if (counters!=null) counter=counters.get(lookup);
if (counter==null)
{
RowMetaAndData rmad = getOneRow("SELECT MAX("+databaseMeta.quoteField(val_key)+") FROM "+schemaTable);
if (rmad!=null)
{
long previous;
try
{
Long tmp = rmad.getRowMeta().getInteger(rmad.getData(), 0);
// A "select max(x)" on a table with no matching rows will return null.
if ( tmp != null )
previous = tmp.longValue();
else
previous = 0L;
}
catch (KettleValueException e)
{
throw new KettleDatabaseException("Error getting the first long value from the max value returned from table : "+schemaTable);
}
counter = new Counter(previous+1, 1);
nextValue = Long.valueOf( counter.next() );
if (counters!=null) counters.put(lookup, counter);
}
else
{
throw new KettleDatabaseException("Couldn't find maximum key value from table "+schemaTable);
}
}
else
{
nextValue = Long.valueOf( counter.next() );
}
return nextValue;
}
public String toString()
{
if (databaseMeta!=null) return databaseMeta.getName();
else return "-";
}
public boolean isSystemTable(String table_name)
{
return databaseMeta.isSystemTable(table_name);
}
/** Reads the result of an SQL query into an ArrayList
*
* @param sql The SQL to launch
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public List<Object[]> getRows(String sql, int limit) throws KettleDatabaseException
{
return getRows(sql, limit, null);
}
/** Reads the result of an SQL query into an ArrayList
*
* @param sql The SQL to launch
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public List<Object[]> getRows(String sql, int limit, ProgressMonitorListener monitor) throws KettleDatabaseException
{
if (monitor!=null) monitor.setTaskName("Opening query...");
ResultSet rset = openQuery(sql);
return getRows(rset, limit, monitor);
}
/** Reads the result of a ResultSet into an ArrayList
*
* @param rset the ResultSet to read out
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public List<Object[]> getRows(ResultSet rset, int limit, ProgressMonitorListener monitor) throws KettleDatabaseException
{
try
{
List<Object[]> result = new ArrayList<Object[]>();
boolean stop=false;
int i=0;
if (rset!=null)
{
if (monitor!=null && limit>0) monitor.beginTask("Reading rows...", limit);
while ((limit<=0 || i<limit) && !stop)
{
Object[] row = getRow(rset);
if (row!=null)
{
result.add(row);
i++;
}
else
{
stop=true;
}
if (monitor!=null && limit>0) monitor.worked(1);
}
closeQuery(rset);
if (monitor!=null) monitor.done();
}
return result;
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get list of rows from ResultSet : ", e);
}
}
public List<Object[]> getFirstRows(String table_name, int limit) throws KettleDatabaseException
{
return getFirstRows(table_name, limit, null);
}
/**
* Get the first rows from a table (for preview)
* @param table_name The table name (or schema/table combination): this needs to be quoted properly
* @param limit limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException in case something goes wrong
*/
public List<Object[]> getFirstRows(String table_name, int limit, ProgressMonitorListener monitor) throws KettleDatabaseException
{
String sql = "SELECT";
if (databaseMeta.getDatabaseInterface() instanceof NeoviewDatabaseMeta)
{
sql+=" [FIRST " + limit +"]";
}
else if (databaseMeta.getDatabaseInterface() instanceof SybaseIQDatabaseMeta) // improve support Sybase IQ
{
sql+=" TOP " + limit +" ";
}
sql += " * FROM "+table_name;
if (limit>0)
{
sql+=databaseMeta.getLimitClause(limit);
}
return getRows(sql, limit, monitor);
}
public RowMetaInterface getReturnRowMeta()
{
return rowMeta;
}
public String[] getTableTypes() throws KettleDatabaseException
{
try
{
ArrayList<String> types = new ArrayList<String>();
ResultSet rstt = getDatabaseMetaData().getTableTypes();
while(rstt.next())
{
String ttype = rstt.getString("TABLE_TYPE");
types.add(ttype);
}
return types.toArray(new String[types.size()]);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to get table types from database!", e);
}
}
public String[] getTablenames() throws KettleDatabaseException
{
return getTablenames(false);
}
public String[] getTablenames(boolean includeSchema) throws KettleDatabaseException
{
return getTablenames(null, includeSchema);
}
public String[] getTablenames(String schemanamein, boolean includeSchema) throws KettleDatabaseException
{
String schemaname=schemanamein;
if(schemaname==null) {
if (databaseMeta.useSchemaNameForTableList()) schemaname = environmentSubstitute(databaseMeta.getUsername()).toUpperCase();
}
List<String> names = new ArrayList<String>();
ResultSet alltables=null;
try
{
alltables = getDatabaseMetaData().getTables(null, schemaname, null, databaseMeta.getTableTypes() );
while (alltables.next())
{
// due to PDI-743 with ODBC and MS SQL Server the order is changed and try/catch included for safety
String cat = "";
try {
cat = alltables.getString("TABLE_CAT");
} catch (Exception e) {
// ignore
if(log.isDebug()) log.logDebug("Error getting tables for field TABLE_CAT (ignored): "+e.toString());
}
String schema = "";
try {
schema = alltables.getString("TABLE_SCHEM");
} catch (Exception e) {
// ignore
if(log.isDebug()) log.logDebug("Error getting tables for field TABLE_SCHEM (ignored): "+e.toString());
}
if (Const.isEmpty(schema)) schema = cat;
String table = alltables.getString("TABLE_NAME");
String schemaTable;
if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table);
else schemaTable = table;
if (log.isRowLevel()) log.logRowlevel(toString(), "got table from meta-data: "+schemaTable);
names.add(schemaTable);
}
}
catch(SQLException e)
{
log.logError("Error getting tablenames from schema ["+schemaname+"]");
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e);
}
}
if(log.isDetailed()) log.logDetailed("read :"+names.size()+" table names from db meta-data.");
return names.toArray(new String[names.size()]);
}
public String[] getViews() throws KettleDatabaseException
{
return getViews(false);
}
public String[] getViews(boolean includeSchema) throws KettleDatabaseException
{
return getViews(null, includeSchema);
}
public String[] getViews(String schemanamein, boolean includeSchema) throws KettleDatabaseException
{
if (!databaseMeta.supportsViews()) return new String[] {};
String schemaname = schemanamein;
if(schemaname==null) {
if (databaseMeta.useSchemaNameForTableList()) schemaname = environmentSubstitute(databaseMeta.getUsername()).toUpperCase();
}
ArrayList<String> names = new ArrayList<String>();
ResultSet alltables=null;
try
{
alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getViewTypes() );
while (alltables.next())
{
// due to PDI-743 with ODBC and MS SQL Server the order is changed and try/catch included for safety
String cat = "";
try {
cat = alltables.getString("TABLE_CAT");
} catch (Exception e) {
// ignore
if(log.isDebug()) log.logDebug("Error getting views for field TABLE_CAT (ignored): "+e.toString());
}
String schema = "";
try {
schema = alltables.getString("TABLE_SCHEM");
} catch (Exception e) {
// ignore
if(log.isDebug()) log.logDebug("Error getting views for field TABLE_SCHEM (ignored): "+e.toString());
}
if (Const.isEmpty(schema)) schema = cat;
String table = alltables.getString("TABLE_NAME");
String schemaTable;
if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table);
else schemaTable = table;
if (log.isRowLevel()) log.logRowlevel(toString(), "got view from meta-data: "+schemaTable);
names.add(schemaTable);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting views from schema ["+schemaname+"]", e);
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e);
}
}
if(log.isDetailed()) log.logDetailed("read :"+names.size()+" views from db meta-data.");
return names.toArray(new String[names.size()]);
}
public String[] getSynonyms() throws KettleDatabaseException
{
return getSynonyms(false);
}
public String[] getSynonyms(boolean includeSchema) throws KettleDatabaseException
{
return getSynonyms(null,includeSchema);
}
public String[] getSynonyms(String schemanamein, boolean includeSchema) throws KettleDatabaseException
{
if (!databaseMeta.supportsSynonyms()) return new String[] {};
String schemaname = schemanamein;
if(schemaname==null) {
if (databaseMeta.useSchemaNameForTableList()) schemaname = environmentSubstitute(databaseMeta.getUsername()).toUpperCase();
}
ArrayList<String> names = new ArrayList<String>();
ResultSet alltables=null;
try
{
alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getSynonymTypes() );
while (alltables.next())
{
// due to PDI-743 with ODBC and MS SQL Server the order is changed and try/catch included for safety
String cat = "";
try {
cat = alltables.getString("TABLE_CAT");
} catch (Exception e) {
// ignore
if(log.isDebug()) log.logDebug("Error getting synonyms for field TABLE_CAT (ignored): "+e.toString());
}
String schema = "";
try {
schema = alltables.getString("TABLE_SCHEM");
} catch (Exception e) {
// ignore
if(log.isDebug()) log.logDebug("Error getting synonyms for field TABLE_SCHEM (ignored): "+e.toString());
}
if (Const.isEmpty(schema)) schema = cat;
String table = alltables.getString("TABLE_NAME");
String schemaTable;
if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table);
else schemaTable = table;
if (log.isRowLevel()) log.logRowlevel(toString(), "got view from meta-data: "+schemaTable);
names.add(schemaTable);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting synonyms from schema ["+schemaname+"]", e);
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting synonyms from schema ["+schemaname+"]", e);
}
}
if(log.isDetailed()) log.logDetailed("read :"+names.size()+" views from db meta-data.");
return names.toArray(new String[names.size()]);
}
public String[] getSchemas() throws KettleDatabaseException
{
ArrayList<String> catalogList = new ArrayList<String>();
ResultSet catalogResultSet=null;
try
{
catalogResultSet =getDatabaseMetaData().getSchemas();
// Grab all the catalog names and put them in an array list
while (catalogResultSet!=null && catalogResultSet.next())
{
catalogList.add(catalogResultSet.getString(1));
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting schemas!", e);
}
finally
{
try
{
if (catalogResultSet!=null) catalogResultSet.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting schemas!", e);
}
}
if(log.isDetailed()) log.logDetailed("read :"+catalogList.size()+" schemas from db meta-data.");
return catalogList.toArray(new String[catalogList.size()]);
}
public String[] getCatalogs() throws KettleDatabaseException
{
ArrayList<String> catalogList = new ArrayList<String>();
ResultSet catalogResultSet=null;
try
{
catalogResultSet =getDatabaseMetaData().getCatalogs();
// Grab all the catalog names and put them in an array list
while (catalogResultSet!=null && catalogResultSet.next())
{
catalogList.add(catalogResultSet.getString(1));
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting catalogs!", e);
}
finally
{
try
{
if (catalogResultSet!=null) catalogResultSet.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting catalogs!", e);
}
}
if(log.isDetailed()) log.logDetailed( "read :"+catalogList.size()+" catalogs from db meta-data.");
return catalogList.toArray(new String[catalogList.size()]);
}
public String[] getProcedures() throws KettleDatabaseException
{
String sql = databaseMeta.getSQLListOfProcedures();
if (sql!=null)
{
//System.out.println("SQL= "+sql);
List<Object[]> procs = getRows(sql, 1000);
//System.out.println("Found "+procs.size()+" rows");
String[] str = new String[procs.size()];
for (int i=0;i<procs.size();i++)
{
str[i] = ((Object[])procs.get(i))[0].toString();
}
return str;
}
else
{
ResultSet rs = null;
try
{
DatabaseMetaData dbmd = getDatabaseMetaData();
rs = dbmd.getProcedures(null, null, null);
List<Object[]> rows = getRows(rs, 0, null);
String result[] = new String[rows.size()];
for (int i=0;i<rows.size();i++)
{
Object[] row = (Object[])rows.get(i);
String procCatalog = rowMeta.getString(row, "PROCEDURE_CAT", null);
String procSchema = rowMeta.getString(row, "PROCEDURE_SCHEMA", null);
String procName = rowMeta.getString(row, "PROCEDURE_NAME", "");
String name = "";
if (procCatalog!=null) name+=procCatalog+".";
else if (procSchema!=null) name+=procSchema+".";
name+=procName;
result[i] = name;
}
return result;
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get list of procedures from database meta-data: ", e);
}
finally
{
if (rs!=null) try { rs.close(); } catch(Exception e) {}
}
}
}
public boolean isAutoCommit()
{
return commitsize<=0;
}
/**
* @return Returns the databaseMeta.
*/
public DatabaseMeta getDatabaseMeta()
{
return databaseMeta;
}
/**
* Lock a tables in the database for write operations
* @param tableNames The tables to lock
* @throws KettleDatabaseException
*/
public void lockTables(String tableNames[]) throws KettleDatabaseException
{
if (Const.isEmpty(tableNames)) return;
// Quote table names too...
String[] quotedTableNames = new String[tableNames.length];
for (int i=0;i<tableNames.length;i++) quotedTableNames[i] = databaseMeta.getQuotedSchemaTableCombination(null, tableNames[i]);
// Get the SQL to lock the (quoted) tables
String sql = databaseMeta.getSQLLockTables(quotedTableNames);
if (sql!=null)
{
execStatements(sql);
}
}
/**
* Unlock certain tables in the database for write operations
* @param tableNames The tables to unlock
* @throws KettleDatabaseException
*/
public void unlockTables(String tableNames[]) throws KettleDatabaseException
{
if (Const.isEmpty(tableNames)) return;
// Quote table names too...
String[] quotedTableNames = new String[tableNames.length];
for (int i=0;i<tableNames.length;i++) quotedTableNames[i] = databaseMeta.getQuotedSchemaTableCombination(null, tableNames[i]);
// Get the SQL to unlock the (quoted) tables
String sql = databaseMeta.getSQLUnlockTables(quotedTableNames);
if (sql!=null)
{
execStatement(sql);
}
}
/**
* @return the opened
*/
public int getOpened()
{
return opened;
}
/**
* @param opened the opened to set
*/
public void setOpened(int opened)
{
this.opened = opened;
}
/**
* @return the connectionGroup
*/
public String getConnectionGroup()
{
return connectionGroup;
}
/**
* @param connectionGroup the connectionGroup to set
*/
public void setConnectionGroup(String connectionGroup)
{
this.connectionGroup = connectionGroup;
}
/**
* @return the partitionId
*/
public String getPartitionId()
{
return partitionId;
}
/**
* @param partitionId the partitionId to set
*/
public void setPartitionId(String partitionId)
{
this.partitionId = partitionId;
}
/**
* @return the copy
*/
public int getCopy()
{
return copy;
}
/**
* @param copy the copy to set
*/
public void setCopy(int copy)
{
this.copy = copy;
}
public void copyVariablesFrom(VariableSpace space)
{
variables.copyVariablesFrom(space);
}
public String environmentSubstitute(String aString)
{
return variables.environmentSubstitute(aString);
}
public String[] environmentSubstitute(String aString[])
{
return variables.environmentSubstitute(aString);
}
public VariableSpace getParentVariableSpace()
{
return variables.getParentVariableSpace();
}
public void setParentVariableSpace(VariableSpace parent)
{
variables.setParentVariableSpace(parent);
}
public String getVariable(String variableName, String defaultValue)
{
return variables.getVariable(variableName, defaultValue);
}
public String getVariable(String variableName)
{
return variables.getVariable(variableName);
}
public boolean getBooleanValueOfVariable(String variableName, boolean defaultValue) {
if (!Const.isEmpty(variableName))
{
String value = environmentSubstitute(variableName);
if (!Const.isEmpty(value))
{
return ValueMeta.convertStringToBoolean(value);
}
}
return defaultValue;
}
public void initializeVariablesFrom(VariableSpace parent)
{
variables.initializeVariablesFrom(parent);
}
public String[] listVariables()
{
return variables.listVariables();
}
public void setVariable(String variableName, String variableValue)
{
variables.setVariable(variableName, variableValue);
}
public void shareVariablesWith(VariableSpace space)
{
variables = space;
// Also share the variables with the meta data object
// Make sure it's not the databaseMeta object itself. We would get an infinite loop in that case.
if (space!=databaseMeta) databaseMeta.shareVariablesWith(space);
}
public void injectVariables(Map<String,String> prop)
{
variables.injectVariables(prop);
}
public RowMetaAndData callProcedure(String arg[], String argdir[], int argtype[],
String resultname, int resulttype) throws KettleDatabaseException {
RowMetaAndData ret;
try {
cstmt.execute();
ret = new RowMetaAndData();
int pos = 1;
if (resultname != null && resultname.length() != 0) {
ValueMeta vMeta = new ValueMeta(resultname, resulttype);
Object v =null;
switch (resulttype) {
case ValueMetaInterface.TYPE_BOOLEAN:
v=Boolean.valueOf(cstmt.getBoolean(pos));
break;
case ValueMetaInterface.TYPE_NUMBER:
v=new Double(cstmt.getDouble(pos));
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
v=cstmt.getBigDecimal(pos);
break;
case ValueMetaInterface.TYPE_INTEGER:
v=Long.valueOf(cstmt.getLong(pos));
break;
case ValueMetaInterface.TYPE_STRING:
v=cstmt.getString(pos);
break;
case ValueMetaInterface.TYPE_BINARY:
if (databaseMeta.supportsGetBlob())
{
Blob blob = cstmt.getBlob(pos);
if (blob!=null)
{
v = blob.getBytes(1L, (int)blob.length());
}
else
{
v = null;
}
}
else
{
v = cstmt.getBytes(pos);
}
break;
case ValueMetaInterface.TYPE_DATE:
if (databaseMeta.supportsTimeStampToDateConversion())
{
v=cstmt.getTimestamp(pos);
}
else
{
v=cstmt.getDate(pos);
}
break;
}
ret.addValue(vMeta, v);
pos++;
}
for (int i = 0; i < arg.length; i++) {
if (argdir[i].equalsIgnoreCase("OUT")
|| argdir[i].equalsIgnoreCase("INOUT")) {
ValueMeta vMeta = new ValueMeta(arg[i], argtype[i]);
Object v=null;
switch (argtype[i]) {
case ValueMetaInterface.TYPE_BOOLEAN:
v=Boolean.valueOf(cstmt.getBoolean(pos + i));
break;
case ValueMetaInterface.TYPE_NUMBER:
v=new Double(cstmt.getDouble(pos + i));
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
v=cstmt.getBigDecimal(pos + i);
break;
case ValueMetaInterface.TYPE_INTEGER:
v=Long.valueOf(cstmt.getLong(pos + i));
break;
case ValueMetaInterface.TYPE_STRING:
v=cstmt.getString(pos + i);
break;
case ValueMetaInterface.TYPE_BINARY:
if (databaseMeta.supportsGetBlob())
{
Blob blob = cstmt.getBlob(pos + i);
if (blob!=null)
{
v = blob.getBytes(1L, (int)blob.length());
}
else
{
v = null;
}
}
else
{
v = cstmt.getBytes(pos + i);
}
break;
case ValueMetaInterface.TYPE_DATE:
if (databaseMeta.supportsTimeStampToDateConversion())
{
v=cstmt.getTimestamp(pos + i);
}
else
{
v=cstmt.getDate(pos + i);
}
break;
}
ret.addValue(vMeta, v);
}
}
return ret;
} catch (SQLException ex) {
throw new KettleDatabaseException("Unable to call procedure", ex);
}
}
/**
* Return SQL CREATION statement for a Table
* @param tableName The table to create
* @throws KettleDatabaseException
*/
public String getDDLCreationTable(String tableName, RowMetaInterface fields) throws KettleDatabaseException
{
String retval;
// First, check for reserved SQL in the input row r...
databaseMeta.quoteReservedWords(fields);
String quotedTk=databaseMeta.quoteField(null);
retval=getCreateTableStatement(tableName, fields, quotedTk, false, null, true);
return retval;
}
/**
* Return SQL TRUNCATE statement for a Table
* @param schema The schema
* @param tableNameWithSchema The table to create
* @throws KettleDatabaseException
*/
public String getDDLTruncateTable(String schema, String tablename) throws KettleDatabaseException
{
if (Const.isEmpty(connectionGroup))
{
return(databaseMeta.getTruncateTableStatement(schema, tablename));
}
else
{
return("DELETE FROM "+databaseMeta.getQuotedSchemaTableCombination(schema, tablename));
}
}
/**
* Return SQL statement (INSERT INTO TableName ...
* @param schemaName tableName The schema
* @param tableName
* @param fields
* @param dateFormat date format of field
* @throws KettleDatabaseException
*/
public String getSQLOutput(String schemaName, String tableName, RowMetaInterface fields, Object[] r,String dateFormat) throws KettleDatabaseException
{
StringBuffer ins=new StringBuffer(128);
try{
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
ins.append("INSERT INTO ").append(schemaTable).append('(');
// now add the names in the row:
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(", ");
String name = fields.getValueMeta(i).getName();
ins.append(databaseMeta.quoteField(name));
}
ins.append(") VALUES (");
java.text.SimpleDateFormat[] fieldDateFormatters = new java.text.SimpleDateFormat[fields.size()];
// new add values ...
for (int i=0;i<fields.size();i++)
{
ValueMetaInterface valueMeta = fields.getValueMeta(i);
Object valueData = r[i];
if (i>0) ins.append(",");
// Check for null values...
if (valueMeta.isNull(valueData)) {
ins.append("null");
} else {
// Normal cases...
switch(valueMeta.getType()) {
case ValueMetaInterface.TYPE_BOOLEAN:
case ValueMetaInterface.TYPE_STRING:
String string = valueMeta.getString(valueData);
// Have the database dialect do the quoting.
// This also adds the single quotes around the string (thanks to PostgreSQL)
string = databaseMeta.quoteSQLString(string);
ins.append(string) ;
break;
case ValueMetaInterface.TYPE_DATE:
Date date = fields.getDate(r,i);
if (Const.isEmpty(dateFormat))
if (databaseMeta.getDatabaseInterface() instanceof OracleDatabaseMeta) {
if (fieldDateFormatters[i]==null) {
fieldDateFormatters[i]=new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
}
ins.append("TO_DATE('").append(fieldDateFormatters[i].format(date)).append("', 'YYYY/MM/DD HH24:MI:SS')");
} else {
ins.append("'" + fields.getString(r,i)+ "'") ;
}
else
{
try
{
java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(dateFormat);
ins.append("'" + formatter.format(fields.getDate(r,i))+ "'") ;
}
catch(Exception e)
{
throw new KettleDatabaseException("Error : ", e);
}
}
break;
default:
ins.append( fields.getString(r,i)) ;
break;
}
}
}
ins.append(')');
}catch (Exception e)
{
throw new KettleDatabaseException(e);
}
return ins.toString();
}
public Savepoint setSavepoint() throws KettleDatabaseException {
try {
return connection.setSavepoint();
} catch (SQLException e) {
throw new KettleDatabaseException(BaseMessages.getString(PKG, "Database.Exception.UnableToSetSavepoint"), e);
}
}
public Savepoint setSavepoint(String savePointName) throws KettleDatabaseException {
try {
return connection.setSavepoint(savePointName);
} catch (SQLException e) {
throw new KettleDatabaseException(BaseMessages.getString(PKG, "Database.Exception.UnableToSetSavepointName", savePointName), e);
}
}
public void releaseSavepoint(Savepoint savepoint) throws KettleDatabaseException {
try {
connection.releaseSavepoint(savepoint);
} catch (SQLException e) {
throw new KettleDatabaseException(BaseMessages.getString(PKG, "Database.Exception.UnableToReleaseSavepoint"), e);
}
}
public void rollback(Savepoint savepoint) throws KettleDatabaseException {
try {
connection.rollback(savepoint);
} catch (SQLException e) {
throw new KettleDatabaseException(BaseMessages.getString(PKG, "Database.Exception.UnableToRollbackToSavepoint"), e);
}
}
public Object getParentObject() {
return parentLoggingObject;
}
/**
* Return primary key column names ...
* @param tablename
* @throws KettleDatabaseException
*/
public String[] getPrimaryKeyColumnNames(String tablename) throws KettleDatabaseException {
List<String> names = new ArrayList<String>();
ResultSet allkeys=null;
try {
allkeys=getDatabaseMetaData().getPrimaryKeys(null, null, tablename);
while (allkeys.next()) {
String keyname=allkeys.getString("PK_NAME");
String col_name=allkeys.getString("COLUMN_NAME");
if(!names.contains(col_name)) names.add(col_name);
if (log.isRowLevel()) log.logRowlevel(toString(), "getting key : "+keyname + " on column "+col_name);
}
}
catch(SQLException e) {
log.logError(toString(), "Error getting primary keys columns from table ["+tablename+"]");
}
finally {
try {
if (allkeys!=null) allkeys.close();
} catch(SQLException e) {
throw new KettleDatabaseException("Error closing connection while searching primary keys in table ["+tablename+"]", e);
}
}
return names.toArray(new String[names.size()]);
}
/**
* Return all sequence names from connection
* @return The sequences name list.
* @throws KettleDatabaseException
*/
public String[] getSequences() throws KettleDatabaseException
{
if(databaseMeta.supportsSequences()) {
String sql = databaseMeta.getSQLListOfSequences();
if (sql!=null)
{
List<Object[]> seqs = getRows(sql, 0);
String[] str = new String[seqs.size()];
for (int i=0;i<seqs.size();i++)
{
str[i] = ((Object[])seqs.get(i))[0].toString();
}
return str;
}
}else {
throw new KettleDatabaseException("Sequences are only available for Oracle databases.");
}
return null;
}
public String getFilename() {
return null;
}
public String getLogChannelId() {
return log.getLogChannelId();
}
public String getObjectName() {
return databaseMeta.getName();
}
public String getObjectCopy() {
return null;
}
public ObjectId getObjectId() {
return databaseMeta.getObjectId();
}
public ObjectRevision getObjectRevision() {
return databaseMeta.getObjectRevision();
}
public LoggingObjectType getObjectType() {
return LoggingObjectType.DATABASE;
}
public LoggingObjectInterface getParent() {
return parentLoggingObject;
}
public RepositoryDirectory getRepositoryDirectory() {
return null;
}
public LogLevel getLogLevel() {
return logLevel;
}
public void setLogLevel(LogLevel logLevel) {
this.logLevel = logLevel;
log.setLogLevel(logLevel);
}
/**
* @return the carteObjectId
*/
public String getContainerObjectId() {
return containerObjectId;
}
/**
* @param containerObjectId the execution container Object id to set
*/
public void setContainerObjectId(String containerObjectId) {
this.containerObjectId = containerObjectId;
}
}
|
package Application;
import Domain.Models.Permission;
import Persistence.Entities.AccountEntity;
import Persistence.Entities.MusicianPartEntity;
import Persistence.Entities.PartEntity;
import Persistence.PersistanceFacade;
import Utils.Enum.AccountRole;
import Utils.Enum.SectionType;
import java.util.Collection;
public class AccountAdministrationManager {
private static AccountAdministrationManager instance = null;
private static PersistanceFacade<AccountEntity> persistanceFacade = new PersistanceFacade<>(AccountEntity.class);
private AccountRole accountRole = null;
private AccountEntity userAccount = null;
private Permission permission = null;
private SectionType sectionType;
private AccountAdministrationManager() {}
public static AccountAdministrationManager getInstance() {
if(instance == null) {
instance = new AccountAdministrationManager();
}
return instance;
}
public void setAccount(String username, String password) {
AccountEntity accountEntity = persistanceFacade.get(p -> p.getUsername().equals(username) && p.getPassword().equals(password));
if(accountEntity != null) {
setLoggedInUser(accountEntity);
}
}
private void setLoggedInUser(AccountEntity account) {
resetUser();
userAccount = account;
accountRole = AccountRole.valueOf(userAccount.getAccountRole());
// get section type
if(account.getPersonAccountId().getMusicianPartsByPersonId() != null) {
Collection<MusicianPartEntity> parts = account.getPersonAccountId().getMusicianPartsByPersonId();
for(MusicianPartEntity musicianPartEntity : parts) {
sectionType = SectionType.valueOf(musicianPartEntity.getPartByPart().getSectionType());
return;
}
}
permission = new Permission(accountRole);
}
public void resetUser() {
accountRole = null;
userAccount = null;
permission = null;
sectionType = null;
}
public SectionType getSectionType() { return sectionType; }
public AccountEntity getLoggedInAccount(){
return userAccount;
}
public Permission getUserPermissions(){
return permission;
}
public AccountRole getAccountRole() {
return accountRole;
}
}
|
/** The functionality for printing the sets of cards.
* @author funkydelpueblo
* @version 0.1
*/
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
public class PrintUtility {
// Card Text Printing
public static void printCards(boolean areWhite){
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(new CardsPrintable(areWhite));
boolean doPrint = job.printDialog();
if (doPrint) {
try {
job.print();
} catch (PrinterException e) {
//pass
}
}
}
public static class CardsPrintable implements Printable{
private Color foreground;
private Color background;
private boolean white;
public CardsPrintable(boolean areWhite){
if(areWhite){
foreground = Color.BLACK;
background = Color.WHITE;
}else{
foreground = Color.WHITE;
background = Color.BLACK;
}
this.white = areWhite;
}
@Override
public int print(Graphics g, PageFormat pf, int page)
throws PrinterException {
java.util.ArrayList<String> data = new java.util.ArrayList<String>();
java.util.ArrayList<Card> cards;
if(this.white){
cards = Model.getInstance().getAllWhite();
}else{
cards = Model.getInstance().getAllBlack();
}
if(page > Math.ceil(cards.size() / 9.0) - 1){
return NO_SUCH_PAGE;
}
for(Card c : cards){
data.add(c.text);
}
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
System.out.println(pf.getImageableX() + pf.getImageableWidth());
g2d.setRenderingHint(
java.awt.RenderingHints.KEY_TEXT_ANTIALIASING,
java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
final int TOP = 2;
final int WIDTH = 175;
final double ratio = 1.4; //This is true.
final int HEIGHT = (int)(WIDTH * ratio);
int y = TOP;
int x = TOP;
Font helvetica = new Font("Helvetica", Font.BOLD, 14);
g2d.setFont(helvetica);
//Draw all card text
for(int i = page * 9; i < (page + 1) * 9 && i < cards.size(); i++ ){
String s = cards.get(i).text;
//Background
g2d.setColor(this.background);
g2d.fillRect(x, y, WIDTH, HEIGHT);
//Draw text
g2d.setColor(this.foreground);
PrintUtility.drawString(g2d, s, x + 15, y + 25, WIDTH - 30, 2);
//Bound card
g2d.drawLine(x, y, x + WIDTH, y);
g2d.drawLine(x, y, x, y + HEIGHT);
g2d.drawLine(x + WIDTH, y, x + WIDTH, y + HEIGHT);
g2d.drawLine(x, y + HEIGHT, x + WIDTH, y + HEIGHT);
x += WIDTH;
if(x > 400){
x = TOP;
y += HEIGHT;
}
}
// tell the caller that this page is part
// of the printed document
return PAGE_EXISTS;
}
}
// Card Back Printing
public static void printCardBacks(boolean areWhite){
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(new CardBacksPrintable(areWhite));
boolean doPrint = job.printDialog();
if (doPrint) {
try {
job.print();
} catch (PrinterException e) {
//pass
}
}
}
public static class CardBacksPrintable implements Printable{
private Color foreground;
private Color background;
private boolean white;
public CardBacksPrintable(boolean areWhite){
if(areWhite){
foreground = Color.BLACK;
background = Color.WHITE;
}else{
foreground = Color.WHITE;
background = Color.BLACK;
}
this.white = areWhite;
}
@Override
public int print(Graphics g, PageFormat pf, int page)
throws PrinterException {
int numCards;
if(this.white){
numCards = Model.getInstance().getAllWhite().size();
}else{
numCards = Model.getInstance().getAllBlack().size();
}
if(page > Math.ceil(numCards / 9.0) - 1){
return NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
g2d.setRenderingHint(
java.awt.RenderingHints.KEY_TEXT_ANTIALIASING,
java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
final int TOP = 2;
final int LEFT = 49;
final int WIDTH = 175;
final double ratio = 1.4; //This is true.
final int HEIGHT = (int)(WIDTH * ratio);
int y = TOP;
int x = LEFT;
Font helvetica = new Font("Helvetica", Font.BOLD, 30);
g2d.setFont(helvetica);
//Draw all card text
for(int i = page * 9; i < (page + 1) * 9; i++ ){
//Background
g2d.setColor(this.background);
g2d.fillRect(x, y, WIDTH, HEIGHT);
//Draw text
g2d.setColor(this.foreground);
PrintUtility.drawString(g2d, "Calls About Hermajesty", x + 15, y + 35, WIDTH - 30, 2);
//Bound card
/*g2d.drawLine(x, y, x + WIDTH, y);
g2d.drawLine(x, y, x, y + HEIGHT);
g2d.drawLine(x + WIDTH, y, x + WIDTH, y + HEIGHT);
g2d.drawLine(x, y + HEIGHT, x + WIDTH, y + HEIGHT);*/
//We don't draw the lines on the back, because it leads to issues with printer accuracy
x += WIDTH;
if(x > 534){
x = LEFT;
y += HEIGHT;
}
}
return PAGE_EXISTS;
}
}
private static void drawString(Graphics g, String s, int x, int y, int width, int extraHeight)
{
// FontMetrics gives us information about the width,
// height, etc. of the current Graphics object's Font.
java.awt.FontMetrics fm = g.getFontMetrics();
int lineHeight = fm.getHeight() + extraHeight;
int curX = x;
int curY = y;
String[] words = s.split(" ");
for (String word : words)
{
// Find out thw width of the word.
int wordWidth = fm.stringWidth(word + " ");
// If text exceeds the width, then move to next line.
if (curX + wordWidth >= x + width)
{
curY += lineHeight;
curX = x;
}
g.drawString(word, curX, curY);
// Move over to the right for next word.
curX += wordWidth;
}
}
}
|
import java.time.LocalDate;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Hail Eris! A Class to work with discordian dates
*
* @author 0xflotus
* @version 0.9.4 06/03/2017
* @since 06/02/2017
*
*/
public class DiscordianDate {
private int _year, _season, _yearDay, _seasonDay, _weekDay;
private static boolean _isLeap;
private static String[] _seasonNames = { "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath" };
private static String[] _dayNames = { "Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange" };
private static String[] _holidays = { "Mungday", "Chaoflux", "St. Tib's Day", "Mojoday", "Discoflux", "Syaday",
"Confuflux", "Zaraday", "Bureflux", "Maladay", "Afflux" };
private static LocalDate _localDate;
public static final int MAX_DAY_OF_SEASON = 73;
public static final int YEAR_DIFFERENCE = 1166;
public static final int COUNT_SEASONS = _seasonNames.length;
public static final int COUNT_DAYS = _dayNames.length;
public static final DiscordianDate MAX_VALUE = new DiscordianDate(LocalDate.MAX);
private DiscordianDate(LocalDate ld) {
_year = ld.getYear() + YEAR_DIFFERENCE;
_yearDay = ld.getDayOfYear();
_isLeap = ld.isLeapYear();
int yd = _yearDay - 1;
if (_isLeap && yd > 59)
yd
_season = (yd / MAX_DAY_OF_SEASON) + 1;
_weekDay = (yd % COUNT_DAYS) + 1;
_seasonDay = (yd % MAX_DAY_OF_SEASON) + 1;
}
private static Optional<String> whichHoliday(DiscordianDate ddate) {
return getHolyday(ddate).equals(DiscordianHoliday.NO_HOLIDAY) ? Optional.empty()
: Optional.of(getHolyday(ddate));
}
private static class DiscordianHoliday {
int day;
boolean leap;
Map<Integer, String> map;
private static final String NO_HOLIDAY = "No Holiday";
DiscordianHoliday(int day, boolean leap) {
this.day = day;
this.leap = leap;
populate();
}
public String getHoliday() {
return map.getOrDefault(this.day, NO_HOLIDAY);
}
private void populate() {
map = new HashMap<>();
map.put(5, _holidays[0]);
map.put(50, _holidays[1]);
map.put(60, leap ? _holidays[2] : NO_HOLIDAY);
map.put(leap ? 79 : 78, _holidays[3]);
map.put(leap ? 124 : 123, _holidays[4]);
map.put(leap ? 152 : 151, _holidays[5]);
map.put(leap ? 197 : 196, _holidays[6]);
map.put(leap ? 225 : 224, _holidays[7]);
map.put(leap ? 270 : 269, _holidays[8]);
map.put(leap ? 298 : 297, _holidays[9]);
map.put(leap ? 343 : 342, _holidays[10]);
}
}
/**
* @param ddate
* the discordian date
* @return the Holiday or "No Holiday"
*/
public static String getHolyday(DiscordianDate ddate) {
return new DiscordianHoliday(ddate._yearDay, DiscordianDate._isLeap).getHoliday();
}
/**
* @param ddate
* the discordian date
* @return true, if the date is a holyday
*/
public static boolean isHoliday(DiscordianDate ddate) {
return DiscordianDate.whichHoliday(ddate).isPresent();
}
/**
* Object method to check for holyday
*
* @return true, if the object is a holyday
*/
public boolean isHoliday() {
return DiscordianDate.isHoliday(this);
}
/**
* @param days
* to add
* @return a new DiscordianDate with added days
*/
public DiscordianDate addDaysFromNow(int days) {
_localDate = LocalDate.now().plusDays(days);
return new DiscordianDate(_localDate);
}
/**
* @param weeks
* to add
* @return a new DiscordianDate with added weeks
*/
public DiscordianDate addWeeksFromNow(int weeks) {
_localDate = LocalDate.now().plusWeeks(weeks);
return new DiscordianDate(_localDate);
}
/**
* @param months
* to add
* @return a new DiscordianDate with added months
*/
public DiscordianDate addMonthsFromNow(int months) {
_localDate = LocalDate.now().plusMonths(months);
return new DiscordianDate(_localDate);
}
/**
* @param years
* to add
* @return a new DiscordianDate with added years
*/
public DiscordianDate addYearsFromNow(int years) {
_localDate = LocalDate.now().plusYears(years);
return new DiscordianDate(_localDate);
}
/**
* @return a new DiscordianDate with current value
*/
public static DiscordianDate now() {
_localDate = LocalDate.now();
return new DiscordianDate(_localDate);
}
/**
* @param localdate
* @return a new DiscordianDate with specified LocalDate
*/
public static DiscordianDate of(LocalDate ld) {
_localDate = ld;
return new DiscordianDate(_localDate);
}
/**
* @param dayOfMonth
* @return a new DiscordianDate with current year, month and specified
* dayOfMonth
*/
public static DiscordianDate of(int dayOfMonth) {
_localDate = LocalDate.of(LocalDate.now().getYear(), LocalDate.now().getMonth(), dayOfMonth);
return new DiscordianDate(_localDate);
}
/**
* @param month
* @param dayOfMonth
* @return a new DiscordianDate with current year and specified month and
* dayOfMonth
*/
public static DiscordianDate of(int month, int dayOfMonth) {
_localDate = LocalDate.of(LocalDate.now().getYear(), month, dayOfMonth);
return new DiscordianDate(_localDate);
}
/**
* @param year
* @param month
* @param dayOfMonth
* @return a new DiscordianDate with specified year, month and dayOfMonth
*/
public static DiscordianDate of(int year, int month, int dayOfMonth) {
_localDate = LocalDate.of(year, month, dayOfMonth);
return new DiscordianDate(_localDate);
}
/**
* @return the discordian year
*/
public int getYear() {
return _year;
}
/**
* @return the number of season
*/
public int getSeason() {
return _season;
}
/**
* @return the number of the day of the year
*/
public int getYearDay() {
return _yearDay;
}
/**
* @return the day of the season
*/
public int getSeasonDay() {
return _seasonDay;
}
/**
* @return the name of this date's season
*/
public String getSeasonName() {
return _seasonNames[_season - 1];
}
/**
* @return the name of the date's day
*/
public String getDayName() {
return _dayNames[_weekDay - 1];
}
/**
* @return the LocalDate-Representation of the discordian date
*/
public LocalDate getTime() {
return _localDate;
}
/**
* @return a List of Holiday Names
*/
public static List<String> getHolidayNames() {
return Arrays.asList(_holidays);
}
/**
* @return a List of possible DayNames
*/
public static List<String> getPossibleDayNames() {
return Arrays.asList(_dayNames);
}
/**
* @return a List of possible SeasonNames
*/
public static List<String> getPossibleSeasonNames() {
return Arrays.asList(_seasonNames);
}
/**
* A String representation of the discordian date
*/
@Override
public String toString() {
return _isLeap && _yearDay == 59 ? _holidays[2] + ", " + Integer.toString(_year)
: _dayNames[_weekDay - 1] + ", " + _seasonNames[_season - 1] + " " + Integer.toString(_seasonDay) + ", "
+ Integer.toString(_year);
}
}
|
package dc;
import java.util.Arrays;
import java.util.HashMap;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import com.neilalexander.jnacl.crypto.salsa20;
import com.neilalexander.jnacl.crypto.salsa20;
import dc.DCPackage;
import cli.Debugger;
public class KeyHandler {
private static MessageDigest md;
private static final String HASH_ALG = "SHA-256";
public static final int KEY_SIZE = 32;
// Nonce size must not be larger than key size.
public static final int NONCE_SIZE = 8;
private HashMap<String, KeyNoncePair> keychain;
private final String alias;
private int numKeys;
static {
try {
md = MessageDigest.getInstance(HASH_ALG);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
System.err.println("[KeyHandler] Severe: The algorithm "+HASH_ALG+" is not available. Make sure that your JRE provides an implementation of " + HASH_ALG);
e.printStackTrace();
System.exit(1);
}
}
public KeyHandler(String alias) {
this.alias = alias;
keychain = new HashMap<String, KeyNoncePair>();
}
public void addKey(String foreignAlias) {
String baseString = symmetricConcat(alias, foreignAlias);
md.update(baseString.getBytes());
byte[] hash = md.digest();
addKey(foreignAlias, hash);
}
public void addKey(String c, byte[] key) {
if(key.length != KEY_SIZE) {
System.err.println("[KeyHandler] Severe: The provided key has length " + key.length + " but it has to be of length " + KEY_SIZE + ".");
} else {
Debugger.println(2, "[KeyHandler] Adding key " + Arrays.toString(key) + " for station " + c + " to keychain.");
synchronized(keychain) {
KeyNoncePair knp = new KeyNoncePair(key);
keychain.put(c, knp);
numKeys++;
}
}
}
public void removeKey(String c) {
synchronized(keychain) {
keychain.remove(c);
numKeys
}
}
public byte[] getOutput(int length) {
return nextKeyMix(length);
}
public byte[] getOutput(byte[] message) {
byte[] output = new byte[message.length];
byte[] currentKeyMix = nextKeyMix(message.length);
for(int i = 0; i < message.length; i++) {
output[i] = (byte) (message[i] ^ currentKeyMix[i % currentKeyMix.length]);
}
return output;
}
private byte[] nextKeyMix(int length) {
byte[] keyMix = new byte[length];
synchronized(keychain) {
for(KeyNoncePair knp: keychain.values()) {
knp.encrypt(keyMix);
}
}
Debugger.println(2, "[KeyHandler] Station "+ alias+ " has keyMix: " + Arrays.toString(keyMix));
return keyMix;
}
public boolean approved() {
synchronized(keychain) {
return numKeys >= DCConfig.MIN_NUM_KEYS;
}
}
private String symmetricConcat(String a1, String a2) {
String s1, s2;
if(a1.length() <= a2.length()) {
s1 = a1;
s2 = a2;
} else {
s1 = a2;
s2 = a1;
}
for(int i = 0; i < s1.length(); i++) {
if(s1.charAt(i) < s2.charAt(i)) {
return s1+s2;
} else if(s1.charAt(i) > s2.charAt(i)) {
return s2 + s1;
}
}
return s1 + s2;
}
private class KeyNoncePair {
private final byte[] key;
private final byte[] nonce;
public KeyNoncePair(byte[] key) {
byte[] nonce = new byte[NONCE_SIZE];
for(int i = 0; i < NONCE_SIZE; i++) {
nonce[i] = key[i];
}
this.key = key;
this.nonce = nonce;
}
public byte[] encrypt(byte[] input) {
int kl = key.length, il = input.length;
int iterations = il / kl;
if(il % kl > 0) iterations++;
for(int i = 0; i < iterations; i++) {
byte[] keystream = new byte[kl];
salsa20.crypto_stream(keystream, kl, nonce, 0, key);
int lim = (i+1) * kl;
// In the last iteration, the input length is our limit
if(lim > il) lim = il;
for(int n = i * kl; n < lim; n++) {
input[n] ^= keystream[n % kl];
}
nextNonce();
}
return input;
}
private void nextNonce() {
for(int i = 0; i < NONCE_SIZE; i++) {
byte b = nonce[i];
if(b == Byte.MAX_VALUE) {
nonce[i] = Byte.MIN_VALUE;
} else {
nonce[i] = ++b;
return;
}
}
}
}
}
|
package extension;
import framework.IMoniteur;;
public class Moniteur implements IMoniteur {
@Override
public void notifier(String s) {
System.out.println("Le plugin "+s+" a été chargé.");
}
@Override
public void notifierAutorun(String s) {
System.out.println("Le plugin "+s+" (autorun) a été lancé.");
}
}
|
package ibis.frontend.ibis;
import ibis.frontend.generic.RunJavac;
import ibis.util.ClassLister;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipOutputStream;
/**
* The main class of the Ibisc frontend.
* Loads all Ibisc components that are found on the classpath, and runs them
* all on the specified arguments.
*/
public class Ibisc {
/** Contains the (classname, <code>IbiscEntry</code>) pairs. */
public static HashMap allClasses = new HashMap();
/** The list of jarfiles. */
private static ArrayList jarFiles = new ArrayList();
/** Verbose flag. */
private static boolean verbose = false;
/** Set when jar files must be compressed. */
private static boolean compress = false;
private static ByteCodeWrapper w;
private static void getClassesFromDirectory(File f, String prefix) {
File[] list = f.listFiles();
if (! prefix.equals("")) {
prefix = prefix + f.getName() + File.separator;
} else {
prefix = f.getName() + File.separator;
}
for (int i = 0; i < list.length; i++) {
String fname = list[i].getName();
if (list[i].isDirectory()) {
getClassesFromDirectory(list[i], prefix);
} else if (fname.endsWith(".class")) {
getClassFromClassFile(prefix + fname);
} else if (prefix.equals("") && fname.endsWith(".jar")) {
getClassesFromJarFile(list[i], prefix + fname);
}
}
}
private static void getClassFromClassFile(String fileName) {
ClassInfo cl = null;
try {
cl = w.parseClassFile(fileName);
} catch(IOException e) {
System.err.println("Ibisc: warning: could not read class "
+ fileName);
}
if (cl != null) {
allClasses.put(cl.getClassName(), new IbiscEntry(cl, fileName));
}
}
private static void getClassesFromJarFile(File f, String fileName) {
JarFile jf = null;
JarInfo jarInfo = null;
try {
jf = new JarFile(f, true);
jarInfo = new JarInfo(jf);
} catch(IOException e) {
System.err.println("Ibisc: warning: could not read jarfile "
+ fileName);
return;
}
jarFiles.add(jarInfo);
jarInfo.modified = true; // for testing ...
for (Enumeration iitems = jarInfo.entries(); iitems.hasMoreElements();) {
JarEntryInfo ient = (JarEntryInfo) iitems.nextElement();
String iname = ient.jarEntry.getName();
if (iname.endsWith(".class")) {
try {
ClassInfo cl = w.parseInputStream(ient.getInputStream(),
iname);
IbiscEntry entry = new IbiscEntry(cl, iname);
allClasses.put(cl.getClassName(), entry);
entry.jarInfo = jarInfo;
ient.ibiscEntry = entry;
} catch(IOException e) {
System.err.println("Ibisc: warning: could not read "
+ "class " + iname + " from jar file "
+ fileName);
}
}
}
}
/**
* Verifies all modified classes.
* @param ic the <code>IbiscComponent</code> after which this
* verification is run.
*/
private static void verifyClasses(IbiscComponent ic) {
for (Iterator i = allClasses.values().iterator(); i.hasNext();) {
IbiscEntry e = (IbiscEntry) i.next();
if (e.modified) {
if (! e.cl.doVerify()) {
System.out.println("Ibisc: verification failed after "
+ "component " + ic.getClass().getName());
System.exit(1);
}
}
}
}
/**
* Writes all modified classes that are not part of a jar.
*/
private static void writeClasses() {
for (Iterator i = allClasses.values().iterator(); i.hasNext();) {
IbiscEntry e = (IbiscEntry) i.next();
if (e.modified && e.jarInfo == null) {
File temp = null;
try {
File canonicalDir = new File(e.fileName).getCanonicalFile().getParentFile();
temp = File.createTempFile("Ibisc_", null, canonicalDir);
e.cl.dump(temp.getCanonicalPath());
if (! temp.renameTo(new File(e.fileName))) {
throw new Exception("Could not write " + e.fileName);
}
} catch (Exception ex) {
System.err.println("Ibisc: got exception while writing "
+ e.fileName + ": " + ex);
if (temp != null) {
temp.delete();
}
System.exit(1);
}
e.modified = false;
}
}
}
/**
* Writes all jars that have a modified (or added) entry.
*/
private static void writeJars() {
// First, determine which jars have actually changed.
for (Iterator i = allClasses.values().iterator(); i.hasNext();) {
IbiscEntry e = (IbiscEntry) i.next();
if (e.modified && e.jarInfo != null) {
e.jarInfo.modified = true;
}
}
// Then, write ...
for (int i = 0; i < jarFiles.size(); i++) {
JarInfo ji = (JarInfo) jarFiles.get(i);
if (ji.modified) {
String name = ji.jarFile.getName();
File temp = null;
try {
File canonicalDir = new File(name).getCanonicalFile().getParentFile();
temp = File.createTempFile("Ibisc_", null, canonicalDir);
FileOutputStream out = new FileOutputStream(temp);
BufferedOutputStream bo = new BufferedOutputStream(out, 16384);
ZipOutputStream zo = new ZipOutputStream(bo);
zo.setMethod(ZipOutputStream.DEFLATED);
if (! compress) {
zo.setLevel(0);
}
for (Enumeration iitems = ji.entries(); iitems.hasMoreElements();) {
JarEntryInfo ient = (JarEntryInfo) iitems.nextElement();
ient.write(zo);
}
zo.close();
if (! temp.renameTo(new File(name))) {
throw new Exception("Could not write " + name);
}
} catch(Exception e) {
System.err.println("Ibisc: got exception while writing "
+ name + ": " + e);
e.printStackTrace();
if (temp != null) {
temp.delete();
}
System.exit(1);
}
ji.modified = false;
}
}
}
/**
* Writes all classes and jars that have been modified.
*/
static void writeAll() {
writeClasses();
writeJars();
}
/**
* Reads all classes and jars from the specified arguments.
* @param leftArgs the arguments.
*/
static void readAll(ArrayList leftArgs) {
// Convert the rest of the arguments to classes
for (int i = 0; i < leftArgs.size(); i++) {
String arg = (String) leftArgs.get(i);
File f = new File(arg);
if (f.isDirectory()) {
getClassesFromDirectory(f, "");
} else if (arg.endsWith(".class")) {
getClassFromClassFile(arg);
} else if (arg.endsWith(".jar")) {
getClassesFromJarFile(f, arg);
} else {
System.err.println("Ibisc: illegal argument: " + arg
+ " is not a jar or class file.");
System.exit(1);
}
}
}
public static void main(String[] args) {
boolean keep = false;
boolean verify = false;
ArrayList leftArgs = new ArrayList();
// Process own arguments.
for (int i = 0; i < args.length; i++) {
if (false) {
} else if (args[i].equals("-v")) {
verbose = true;
} else if (args[i].equals("-verify")) {
verify = true;
} else if (args[i].equals("-keep")) {
keep = true;
} else if (args[i].equals("-compress")) {
compress = true;
} else {
leftArgs.add(args[i]);
}
}
// Obtain a list of Ibisc components.
ClassLister clstr = ClassLister.getClassLister(null);
List clcomponents = clstr.getClassList("Ibisc-Component", IbiscComponent.class);
ArrayList components = new ArrayList();
// If no classes found, at least add IOGenerator.
if (clcomponents.size() == 0) {
try {
Class cl = Class.forName("ibis.frontend.io.IOGenerator");
clcomponents.add(cl);
} catch(Exception e) {
// Ignore
}
}
// Instantiate Ibisc components.
for (Iterator iter = clcomponents.iterator(); iter.hasNext();) {
Class cl = (Class) iter.next();
IbiscComponent ic = null;
try {
ic = (IbiscComponent) cl.newInstance();
ic.setVerbose(verbose);
ic.fromIbisc = true;
ic.setKeep(keep);
if (ic.processArgs(leftArgs)) {
components.add(ic);
}
} catch(Exception e) {
System.err.println("Ibisc: warning: could not instantiate "
+ cl.getName());
}
}
// Check for unrecognized arguments.
for (int i = 0; i < leftArgs.size(); i++) {
String arg = (String) leftArgs.get(i);
if (arg.startsWith("-")) {
System.err.println("Ibisc: unrecognized argument: " + arg);
System.exit(1);
}
}
// IOGenerator should be last
int szm1 = components.size() - 1;
for (int i = 0; i < szm1; i++) {
IbiscComponent ic = (IbiscComponent) components.get(i);
if (ic instanceof ibis.frontend.io.IOGenerator) {
components.set(i, components.get(szm1));
components.set(szm1, ic);
break;
}
}
if (components.size() == 0) {
System.err.println("Ibisc: warning: no components found!");
}
String wrapperKind = null;
// Make all components process all classes.
for (int i = 0; i < components.size(); i++) {
IbiscComponent ic = (IbiscComponent) components.get(i);
String knd = ic.rewriterImpl();
if (wrapperKind == null || ! knd.equals(wrapperKind)) {
if (wrapperKind != null) {
writeAll();
}
allClasses.clear();
wrapperKind = knd;
if (knd.equals("BCEL")) {
w = new BCELWrapper();
} else {
System.err.println("Ibisc: component "
+ ic.getClass().getName()
+ ": unsupported bytecode rewriter: " + knd);
}
readAll(leftArgs);
}
ic.setWrapper(w);
ic.processClasses(allClasses);
if (verify) {
// Verify after each component.
verifyClasses(ic);
}
}
// Now, write out all modified stuff.
writeAll();
}
}
|
package tree;
import java.util.Set;
/**
* @author Alexis Giraudet
*/
public interface Tree<K extends Comparable<K>> extends Set<K> {
public int height();
}
|
package ui;
import java.util.function.BiFunction;
import java.util.function.Predicate;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import model.Model;
import model.TurboIssue;
import command.CommandType;
import command.TurboCommandExecutor;
import filter.FilterExpression;
import filter.ParseException;
import filter.Parser;
import filter.PredicateApplicationException;
public abstract class Column extends VBox {
// A Column is a JavaFX node that is contained by a ColumnControl.
// It is in charge of displaying a list of issues and providing functions
// to filter it. It does not, however, specify how the list is to be
// displayed -- that is the job of its subclasses.
public static final String NO_FILTER = "No Filter";
public static final filter.Predicate EMPTY_PREDICATE = new filter.Predicate();
private final Stage mainStage;
private final Model model;
private final ColumnControl parentColumnControl;
private int columnIndex;
private final SidePanel sidePanel;
private Predicate<TurboIssue> predicate = p -> true;
private String filterInput = "";
private FilterExpression currentFilterExpression = EMPTY_PREDICATE;
private ObservableList<TurboIssue> issues = FXCollections.observableArrayList();
private FilteredList<TurboIssue> filteredList = null;
private TurboCommandExecutor dragAndDropExecutor;
private Label filterLabel;
public Column(Stage mainStage, Model model, ColumnControl parentColumnControl, SidePanel sidePanel, int columnIndex, TurboCommandExecutor dragAndDropExecutor) {
this.mainStage = mainStage;
this.model = model;
this.parentColumnControl = parentColumnControl;
this.columnIndex = columnIndex;
this.sidePanel = sidePanel;
this.dragAndDropExecutor = dragAndDropExecutor;
getChildren().add(createFilterBox());
setup();
}
private void setup() {
setPrefWidth(380);
setMaxWidth(380);
getStyleClass().add("borders");
setOnDragOver(e -> {
if (e.getGestureSource() != this && e.getDragboard().hasString()) {
DragData dd = DragData.deserialise(e.getDragboard().getString());
if (dd.getSource() == DragData.Source.ISSUE_CARD) {
e.acceptTransferModes(TransferMode.MOVE);
}
}
});
setOnDragEntered(e -> {
if (e.getDragboard().hasString()) {
DragData dd = DragData.deserialise(e.getDragboard().getString());
if (dd.getColumnIndex() != columnIndex) {
getStyleClass().add("dragged-over");
}
}
e.consume();
});
setOnDragExited(e -> {
getStyleClass().remove("dragged-over");
e.consume();
});
setOnDragDropped(e -> {
Dragboard db = e.getDragboard();
boolean success = false;
if (db.hasString()) {
success = true;
DragData dd = DragData.deserialise(db.getString());
TurboIssue rightIssue = model.getIssueWithId(dd.getIssueIndex());
applyCurrentFilterExpressionToIssue(rightIssue, true);
}
e.setDropCompleted(success);
e.consume();
});
}
private Node createFilterBox() {
HBox filterBox = new HBox();
filterLabel = new Label(NO_FILTER);
filterLabel.setPadding(new Insets(3));
filterBox.setOnMouseClicked(e -> onFilterBoxClick());
filterBox.setAlignment(Pos.TOP_LEFT);
HBox.setHgrow(filterBox, Priority.ALWAYS);
filterBox.getChildren().add(filterLabel);
setupIssueDragEvents(filterBox);
HBox rightAlignBox = new HBox();
Label addIssue = new Label("\u271A");
addIssue.setStyle("-fx-font-size: 16pt;");
addIssue.setOnMouseClicked((e) -> {
TurboIssue issue = new TurboIssue("New issue", "", model);
applyCurrentFilterExpressionToIssue(issue, false);
sidePanel.displayIssue(issue).thenApply(r -> {
if (r.equals("done")) {
model.createIssue(issue);
}
parentColumnControl.refresh();
sidePanel.displayTabs();
return true;
}).exceptionally(ex -> {
ex.printStackTrace();
return false;
});
});
Label closeList = new Label("\u2716");
closeList.setStyle("-fx-font-size: 16pt;");
closeList.setOnMouseClicked((e) -> {
parentColumnControl.closeColumn(columnIndex);
});
Label toggleHierarchyMode = new Label("\u27A5");
toggleHierarchyMode.setStyle("-fx-font-size: 16pt;");
toggleHierarchyMode.setOnMouseClicked((e) -> {
parentColumnControl.toggleColumn(columnIndex);
});
HBox.setMargin(rightAlignBox, new Insets(0,5,0,0));
rightAlignBox.setSpacing(5);
rightAlignBox.setAlignment(Pos.TOP_RIGHT);
HBox.setHgrow(rightAlignBox, Priority.ALWAYS);
rightAlignBox.getChildren().addAll(toggleHierarchyMode, addIssue, closeList);
HBox topBox = new HBox();
topBox.setSpacing(5);
topBox.getChildren().addAll(filterBox, rightAlignBox);
return topBox;
}
private void setupIssueDragEvents(HBox filterBox) {
filterBox.setOnDragOver(e -> {
if (e.getGestureSource() != this && e.getDragboard().hasString()) {
DragData dd = DragData.deserialise(e.getDragboard().getString());
if (dd.getSource() == DragData.Source.ISSUE_CARD) {
e.acceptTransferModes(TransferMode.MOVE);
}
}
});
filterBox.setOnDragEntered(e -> {
if (e.getDragboard().hasString()) {
filterBox.getStyleClass().add("dragged-over");
}
e.consume();
});
filterBox.setOnDragExited(e -> {
filterBox.getStyleClass().remove("dragged-over");
e.consume();
});
filterBox.setOnDragDropped(e -> {
Dragboard db = e.getDragboard();
boolean success = false;
if (db.hasString()) {
success = true;
DragData dd = DragData.deserialise(db.getString());
TurboIssue rightIssue = model.getIssueWithId(dd.getIssueIndex());
filterByString("parent(" + rightIssue.getTitle() + ")");
}
e.setDropCompleted(success);
e.consume();
});
}
private void onFilterBoxClick() {
(new FilterDialog(mainStage, filterInput))
.show()
.thenApply(filterString -> {
filterByString(filterString);
return true;
}).exceptionally(ex -> {
ex.printStackTrace();
return false;
});
}
public void filterByString(String filterString) {
filterInput = filterString;
if (filterString.isEmpty()) {
filterLabel.setText(NO_FILTER);
this.filter(EMPTY_PREDICATE);
} else {
try {
FilterExpression filter = Parser.parse(filterString);
if (filter != null) {
filterLabel.setText(filter.toString());
this.filter(filter);
} else {
filterLabel.setText(NO_FILTER);
this.filter(EMPTY_PREDICATE);
}
} catch (ParseException ex) {
filterLabel.setText("Parse error in filter: " + ex);
this.filter(EMPTY_PREDICATE);
}
}
}
public void filter(FilterExpression filter) {
currentFilterExpression = filter;
// This cast utilises a functional interface
final BiFunction<TurboIssue, Model, Boolean> temp = filter::isSatisfiedBy;
predicate = i -> temp.apply(i, model);
refreshItems();
}
public FilteredList<TurboIssue> getFilteredList() {
return filteredList;
}
public void setItems(ObservableList<TurboIssue> items) {
this.issues = items;
refreshItems();
}
public void refreshItems() {
filteredList = new FilteredList<TurboIssue>(issues, predicate);
}
public abstract void deselect();
private void applyCurrentFilterExpressionToIssue(TurboIssue issue, boolean updateModel) {
if (currentFilterExpression != EMPTY_PREDICATE) {
try {
if (currentFilterExpression.canBeAppliedToIssue()) {
TurboIssue clone = new TurboIssue(issue);
currentFilterExpression.applyTo(issue, model);
if (updateModel){
dragAndDropExecutor.executeCommand(CommandType.EDIT_ISSUE, model, clone, issue);
}
parentColumnControl.refresh();
} else {
throw new PredicateApplicationException("Could not apply predicate " + currentFilterExpression + ".");
}
} catch (PredicateApplicationException ex) {
parentColumnControl.displayMessage(ex.getMessage());
}
}
}
public void updateIndex(int updated) {
columnIndex = updated;
}
}
|
package org.dspace.search;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import org.apache.log4j.Logger;
import org.dspace.content.Collection;
import org.dspace.content.Item;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.handle.HandleManager;
import org.dspace.storage.rdbms.DatabaseManager;
import org.dspace.storage.rdbms.TableRow;
import org.dspace.storage.rdbms.TableRowIterator;
/**
* Utility class for extracting information about items, possibly just within a
* certain community or collection, that have been created, modified or
* withdrawn within a particular range of dates.
*
* @author Robert Tansley
* @version $Revision$
*/
public class Harvest
{
/** log4j logger */
private static Logger log = Logger.getLogger(Harvest.class);
/**
* Obtain information about items that have been created, modified or
* withdrawn within a given date range. You can also specify 'offset'
* and 'limit' so that a big harvest can be split up into smaller sections.
* <P>
* Note that dates are passed in the standard ISO8601 format used by
* DSpace (and OAI-PMH).<P>
* FIXME: Assumes all in_archive items have public metadata
*
* @param context DSpace context
* @param scope a Collection, or <code>null</code>
* indicating the scope is all of DSpace
* @param startDate start of date range, or <code>null</code>
* @param endDate end of date range, or <code>null</code>
* @param offset for a partial harvest, the point in the overall list
* of matching items to start at. 0 means just start
* at the beginning.
* @param limit the number of matching items to return in a partial
* harvest. Specify 0 to return the whole list
* (or the rest of the list if an offset was specified.)
* @param items if <code>true</code> the <code>item</code> field of
* each <code>HarvestedItemInfo</code> object is
* filled out
* @param collections if <code>true</code> the <code>collectionHandles</code>
* field of each <code>HarvestedItemInfo</code> object
* is filled out
* @param withdrawn If <code>true</code>, information about withdrawn
* items is included
* @return List of <code>HarvestedItemInfo</code> objects
*/
public static List harvest(Context context,
Collection scope,
String startDate,
String endDate,
int offset,
int limit,
boolean items,
boolean collections,
boolean withdrawn)
throws SQLException
{
// SQL to add to the list of tables after the SELECT
String scopeTableSQL = "";
// SQL to add to the WHERE clause of the query
String scopeWhereSQL = "";
if (scope != null)
{
scopeTableSQL = ", collection2item";
scopeWhereSQL = " AND collection2item.collection_id=" +
scope.getID() +
" AND collection2item.item_id=handle.resource_id";
}
// Put together our query. Note there is no need for an
// "in_archive=true" condition, we are using the existence of
// Handles as our 'existence criterion'.
String query =
"SELECT handle.handle, handle.resource_id, item.withdrawn, item.last_modified FROM handle, item" +
scopeTableSQL + " WHERE handle.resource_type_id=" + Constants.ITEM +
" AND handle.resource_id=item.item_id" + scopeWhereSQL;
if (startDate != null)
{
query = query + " AND item.last_modified >= '" + startDate + "'";
}
if (endDate != null)
{
/* If the end date has seconds precision, e.g.:
*
* 2004-04-29T13:45:43Z
*
* we need to add 999 milliseconds to this. This is because
* SQL TIMESTAMPs have millisecond precision, and so might
* have a value:
*
* 2004-04-29T13:45:43.952Z
*
* and so <= '2004-04-29T13:45:43Z' would not pick this up.
* Reading things out of the database, TIMESTAMPs are rounded
* down, so the above value would be read as
* '2004-04-29T13:45:43Z', and therefore a caller would expect
* <= '2004-04-29T13:45:43Z' to include that value.
*
* Got that? ;-)
*/
if (endDate.length() == 20)
{
endDate = endDate.substring(0, 19) + ".999Z";
}
query = query + " AND item.last_modified <= '" + endDate + "'";
}
if (withdrawn = false)
{
// Exclude withdrawn items
query = query + " AND withdrawn=false";
}
// Order by item ID, so that for a given harvest the order will be
// consistent. This is so that big harvests can be broken up into
// several smaller operations (e.g. for OAI resumption tokens.)
query = query + " ORDER BY handle.resource_id";
log.debug(LogManager.getHeader(context,
"harvest SQL",
query));
// Execute
TableRowIterator tri = DatabaseManager.query(context, query);
List infoObjects = new LinkedList();
int index = 0;
// Process results of query into HarvestedItemInfo objects
while (tri.hasNext())
{
TableRow row = tri.next();
/*
* This conditional ensures that we only process items within
* any constraints specified by 'offset' and 'limit' parameters.
*/
if (index >= offset &&
(limit == 0 || index < offset + limit))
{
HarvestedItemInfo itemInfo = new HarvestedItemInfo();
itemInfo.handle = row.getStringColumn("handle");
itemInfo.itemID = row.getIntColumn("resource_id");
// Put datestamp in ISO8601
itemInfo.datestamp = row.getDateColumn("last_modified");
itemInfo.withdrawn = row.getBooleanColumn("withdrawn");
if (collections)
{
fillCollections(context, itemInfo);
}
if (items)
{
// Get the item
itemInfo.item = Item.find(context, itemInfo.itemID);
}
infoObjects.add(itemInfo);
}
index++;
}
return infoObjects;
}
/**
* Get harvested item info for a single item. <code>item</code> field in
* returned <code>HarvestedItemInfo</code> object is always filled out.
*
* @param context DSpace context
* @param handle Prefix-less Handle of item
* @param collections if <code>true</code> the <code>collectionHandles</code>
* field of the <code>HarvestedItemInfo</code> object
* is filled out
*
* @return <code>HarvestedItemInfo</code> object for the single item, or
* <code>null</code>
*/
public static HarvestedItemInfo getSingle(Context context,
String handle,
boolean collections)
throws SQLException
{
// FIXME: Assume Handle is item
Item i = (Item) HandleManager.resolveToObject(context, handle);
if (i == null)
{
return null;
}
// Fill out OAI info item object
HarvestedItemInfo itemInfo = new HarvestedItemInfo();
itemInfo.item = i;
itemInfo.handle = handle;
itemInfo.withdrawn = i.isWithdrawn();
itemInfo.datestamp = i.getLastModified();
itemInfo.itemID = i.getID();
// Get the sets
if (collections)
{
fillCollections(context, itemInfo);
}
return itemInfo;
}
/**
* Fill out the containers field of the HarvestedItemInfo object
*
* @param context DSpace context
* @param itemInfo HarvestedItemInfo object to fill out
*/
private static void fillCollections(Context context,
HarvestedItemInfo itemInfo)
throws SQLException
{
// Get the collection Handles from DB
TableRowIterator colRows = DatabaseManager.query(
context,
"SELECT handle.handle FROM handle, collection2item WHERE handle.resource_type_id=" +
Constants.COLLECTION + " AND collection2item.collection_id=handle.resource_id AND collection2item.item_id = " +
itemInfo.itemID);
// Chuck 'em in the itemInfo object
itemInfo.collectionHandles = new LinkedList();
while (colRows.hasNext())
{
TableRow r = colRows.next();
itemInfo.collectionHandles.add(r.getStringColumn("handle"));
}
}
}
|
package com.bbn.kbp.events2014.bin;
import com.bbn.bue.common.diff.SummaryConfusionMatrix;
import com.bbn.bue.common.evaluation.FMeasureInfo;
import com.bbn.bue.common.files.FileUtils;
import com.bbn.bue.common.parameters.Parameters;
import com.bbn.bue.common.primitives.DoubleUtils;
import com.bbn.bue.common.symbols.Symbol;
import com.bbn.kbp.events2014.AnswerKey;
import com.bbn.kbp.events2014.AssessedResponse;
import com.bbn.kbp.events2014.CorefAnnotation;
import com.bbn.kbp.events2014.FieldAssessment;
import com.bbn.kbp.events2014.KBPString;
import com.bbn.kbp.events2014.Response;
import com.bbn.kbp.events2014.ResponseAssessment;
import com.bbn.kbp.events2014.io.AnnotationStore;
import com.bbn.kbp.events2014.io.AssessmentSpecFormats;
import com.bbn.nlp.coreference.measures.B3Scorer;
import com.bbn.nlp.coreference.measures.BLANCScorer;
import com.bbn.nlp.coreference.measures.BLANCScorers;
import com.bbn.nlp.coreference.measures.MUCScorer;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
/**
* Assesses the agreement for dual annotation on the same files. Parameters:
* dualAnnotation.docIDsToCompare: a file listing documents to compare annotation for, one doc ID
* per line dualAnnotation.{left|right}.name: a name to attach to each annotation store, for more
* readable output dualAnnotation.{left|right}.path: the paths to the left and right annotation
* stores
*/
public final class DualAnnotationAgreement {
private static final Logger log = LoggerFactory.getLogger(DualAnnotationAgreement.class);
private DualAnnotationAgreement() {
throw new UnsupportedOperationException();
}
/**
* Represents the degree of agreement of an assessment between the two stores.
*/
private enum AgreementState {
/**
* the assessments match
*/
AGREE,
/**
* the assessments disagree
*/
DISAGREE,
/**
* the assessment was not applicable for the left annotator only
*/
NA_LEFT,
/**
* the assessment was not applicable for the right annotator only
*/
NA_RIGHT,
/**
* the assessment was not applicale for both annotation
*/
NA_BOTH;
public static final ImmutableSet<AgreementState> NON_APPLICABLE_STATES =
ImmutableSet.of(NA_LEFT, NA_RIGHT, NA_BOTH);
}
;
private static void trueMain(String[] argv) throws IOException {
final Parameters dualAnnotationParams = Parameters.loadSerifStyle(new File(argv[0]))
.copyNamespace("dualAnnotation");
// determine which documents to compare
final File docIDsToCompareFile = dualAnnotationParams.getExistingFile("docIDsToCompare");
log.info("Comparing docIDs from {}", docIDsToCompareFile);
final List<Symbol> docIDsToCompare = FileUtils.loadSymbolList(docIDsToCompareFile);
log.info("Loaded {} docIDs", docIDsToCompare.size());
final AssessmentSpecFormats.Format fileFormat =
dualAnnotationParams.getEnum("fileFormat", AssessmentSpecFormats.Format.class);
final Parameters leftParams = dualAnnotationParams.copyNamespace("left");
final String leftStoreName = leftParams.getString("name");
final File leftStorePath = leftParams.getExistingDirectory("path");
final AnnotationStore leftAnnStore =
AssessmentSpecFormats.openAnnotationStore(leftStorePath, fileFormat);
log.info("Loading left annotation store {} from {}", leftStoreName, leftStorePath);
final Parameters rightParams = dualAnnotationParams.copyNamespace("right");
final String rightStoreName = rightParams.getString("name");
final File rightStorePath = rightParams.getExistingDirectory("path");
final AnnotationStore rightAnnStore =
AssessmentSpecFormats.openAnnotationStore(rightStorePath, fileFormat);
log.info("Loading right annotation store {} from {}", rightStoreName, rightStorePath);
final Optional<AnnotationStore> excludeStore =
getExcludeStore(dualAnnotationParams, fileFormat);
final Optional<CorefRecorder> corefRecorder;
if (dualAnnotationParams.getBoolean("doCorefAgreement")) {
checkState(!excludeStore.isPresent(), "Coref agreement analysis is incompatible with specifying an exclude store");
corefRecorder = Optional.of(new CorefRecorder());
} else {
corefRecorder = Optional.absent();
}
final AgreementRecorder agreementRecorder = new AgreementRecorder();
for (final Symbol docID : docIDsToCompare) {
final AnswerKey leftAnnotation = leftAnnStore.read(docID);
final AnswerKey rightAnnotation = rightAnnStore.read(docID);
final AnswerKey excludeAnnotation = excludeStore.isPresent()?excludeStore.get().read(
docID):AnswerKey.createEmpty(docID);
final Map<Response, AssessedResponse> leftAnnotationsIndexed = Maps.uniqueIndex(
leftAnnotation.annotatedResponses(), AssessedResponse.Response);
final Map<Response, AssessedResponse> rightAnnotationsIndexed = Maps.uniqueIndex(
rightAnnotation.annotatedResponses(), AssessedResponse.Response);
if (!leftAnnotationsIndexed.keySet().equals(rightAnnotationsIndexed.keySet())) {
reportResponseMismatch(docID, leftAnnotationsIndexed.keySet(),
rightAnnotationsIndexed.keySet());
}
final ImmutableSet<Response> responsesInBoth = Sets.intersection(leftAnnotationsIndexed.keySet(),
rightAnnotationsIndexed.keySet()).immutableCopy();
final Set<Response> excludedResponses = FluentIterable.from(excludeAnnotation.annotatedResponses())
.transform(AssessedResponse.Response).toSet();
final ImmutableSet<Response> nonExcludedInBoth = Sets.difference(responsesInBoth,
excludedResponses).immutableCopy();
log.info("For {}, left had {}, right had {}, {} in common, {} not excluded", docID,
leftAnnotation.annotatedResponses().size(), rightAnnotation.annotatedResponses().size(),
responsesInBoth.size(), nonExcludedInBoth.size());
for (final Response response : nonExcludedInBoth) {
// get will succeed by above checks
agreementRecorder.recordAgreement(leftAnnotation.assessment(response).get(),
rightAnnotation.assessment(response).get());
}
if (corefRecorder.isPresent()) {
corefRecorder.get().observe(leftAnnotation.corefAnnotation(), rightAnnotation.corefAnnotation());
}
}
agreementRecorder.dumpResults();
System.out.println();
System.out.println();
if (corefRecorder.isPresent()) {
corefRecorder.get().dumpResults();
}
}
private static Optional<AnnotationStore> getExcludeStore(final Parameters dualAnnotationParams,
final AssessmentSpecFormats.Format fileFormat) throws IOException {
final Optional<File> excludeStorePath = dualAnnotationParams.getOptionalExistingDirectory("exclude");
final Optional<AnnotationStore> excludeStore;
if (excludeStorePath.isPresent()) {
excludeStore = Optional.of(
AssessmentSpecFormats.openAnnotationStore(excludeStorePath.get(), fileFormat));
log.info("All responses found in {} will be excluded from analysis (this is probably a shared ancestor store)",
excludeStorePath.get());
} else {
excludeStore = Optional.absent();
}
return excludeStore;
}
private static class CorefRecorder {
private final B3Scorer b3Scorer = B3Scorer.createByElementScorer();
private final BLANCScorer blancScorer = BLANCScorers.getStandardBLANCScorer();
private final MUCScorer mucScorer = MUCScorer.create();
private final List<Float> b3Scores = Lists.newArrayList();
private final List<Double> blancScores = Lists.newArrayList();
private final List<Float> mucScores = Lists.newArrayList();
public void observe(CorefAnnotation left, CorefAnnotation right) {
checkArgument(left.docId().equals(right.docId()));
checkArgument(left.annotatedCASes().equals(right.annotatedCASes()));
final Collection<Collection<KBPString>> leftAsClusters = asCollectionOfCollections(left);
final Collection<Collection<KBPString>> rightAsClusters = asCollectionOfCollections(right);
b3Scores.add(b3Scorer.score(rightAsClusters, leftAsClusters).F1());
blancScores.add(blancScorer.score(rightAsClusters, leftAsClusters).blancScore());
final Optional<FMeasureInfo> mucScore = mucScorer.score(rightAsClusters, leftAsClusters);
if (mucScore.isPresent()) {
mucScores.add(mucScore.get().F1());
} else {
log.warn(
"No valid MUC score can be computer for {}; it will not be included in the MUC score average",
left.docId());
}
}
public void dumpResults() {
System.out.format("Mean coref score by B^3: %.2f\n", 100.0 * floatMean(b3Scores));
System.out.format("Mean coref score by BLANC: %.2f\n", 100.0 * doubleMean(blancScores));
System.out.format("Mean coref score by MUC: %.2f\n", 100.0 * floatMean(mucScores));
}
public double doubleMean(Collection<Double> vals) {
return DoubleUtils.sum(vals) / vals.size();
}
public float floatMean(Collection<Float> vals) {
float sum = 0.0f;
for (float x : vals) {
sum += x;
}
return sum / vals.size();
}
private Collection<Collection<KBPString>> asCollectionOfCollections(CorefAnnotation coref) {
final Multimap<Integer, KBPString> corefIdToResponse = HashMultimap.create();
for (final KBPString cas : coref.annotatedCASes()) {
corefIdToResponse.put(coref.corefId(cas).get(), cas);
}
return corefIdToResponse.asMap().values();
}
}
private static class AgreementRecorder {
final Map<String, SummaryConfusionMatrix.Builder> assessmentNameToConfusionMatrix =
ImmutableMap.<String, SummaryConfusionMatrix.Builder>builder()
.put("AET", SummaryConfusionMatrix.builder())
.put("AER", SummaryConfusionMatrix.builder())
.put("BF", SummaryConfusionMatrix.builder())
.put("CAS", SummaryConfusionMatrix.builder())
.put("CAS type", SummaryConfusionMatrix.builder())
.put("Realis", SummaryConfusionMatrix.builder()).build();
final ImmutableSet<String> USES_CORRECT_INEXACT = ImmutableSet.of("AET", "AER", "BF", "CAS");
public void recordAgreement(ResponseAssessment leftAssessment,
ResponseAssessment rightAssessment) {
recordAssessment(assessmentNameToConfusionMatrix.get("AET"),
leftAssessment.justificationSupportsEventType(),
rightAssessment.justificationSupportsEventType());
recordAssessment(assessmentNameToConfusionMatrix.get("AER"),
leftAssessment.justificationSupportsRole(), rightAssessment.justificationSupportsRole());
recordAssessment(assessmentNameToConfusionMatrix.get("BF"),
leftAssessment.baseFillerCorrect(), rightAssessment.baseFillerCorrect());
recordAssessment(assessmentNameToConfusionMatrix.get("CAS"),
leftAssessment.entityCorrectFiller(), rightAssessment.entityCorrectFiller());
recordAssessment(assessmentNameToConfusionMatrix.get("Realis"),
leftAssessment.realis(), rightAssessment.realis());
recordAssessment(assessmentNameToConfusionMatrix.get("CAS type"),
leftAssessment.mentionTypeOfCAS(), rightAssessment.mentionTypeOfCAS());
}
private static <T> void recordAssessment(SummaryConfusionMatrix.Builder confusionMatrixBuilder,
Optional<T> leftAssessment, Optional<T> rightAssessment) {
confusionMatrixBuilder.accumulate(asSymbol(leftAssessment), asSymbol(rightAssessment), 1.0);
}
private static final Symbol NA = Symbol.from("n/a");
private static final Symbol PRESENT = Symbol.from("Present");
private static <T> Symbol asSymbol(Optional<T> assessment) {
if (assessment.isPresent()) {
return Symbol.from(assessment.get().toString());
} else {
return NA;
}
}
private static SummaryConfusionMatrix.CellFilter NEITHER_IS_NA =
new SummaryConfusionMatrix.CellFilter() {
@Override
public boolean keepCell(Symbol row, Symbol column) {
return !row.equals(NA) && !column.equals(NA);
}
};
private static final Function<Symbol, Symbol> ASSESSMENT_IS_PRESENT =
new Function<Symbol, Symbol>() {
@Override
public Symbol apply(Symbol x) {
if (NA.equals(x)) {
return NA;
} else {
return PRESENT;
}
}
};
private static final Function<Symbol, Symbol> COUNT_CORRECT_AND_INEXACT_AS_THE_SAME =
new Function<Symbol, Symbol>() {
private final ImmutableSet<Symbol> IS_CORRECT_OR_INEXACT = ImmutableSet.of(
Symbol.from(FieldAssessment.CORRECT.toString()),
Symbol.from(FieldAssessment.INEXACT.toString()));
private final Symbol NOT_INCORRECT = Symbol.from("NotIncorrect");
@Override
public Symbol apply(Symbol x) {
if (IS_CORRECT_OR_INEXACT.contains(x)) {
return NOT_INCORRECT;
} else {
return x;
}
}
};
private static final KappaCalculator kappaCalculator = KappaCalculator.create();
public void dumpResults() {
for (final Map.Entry<String, SummaryConfusionMatrix.Builder> assessmentResults
: assessmentNameToConfusionMatrix.entrySet()) {
final String assessmentName = assessmentResults.getKey();
final SummaryConfusionMatrix confusionMatrix = assessmentResults.getValue().build();
System.out.println(" ============== " + assessmentName + " ==============\n\n");
final SummaryConfusionMatrix filteredConfusionMatrix =
confusionMatrix.filteredCopy(NEITHER_IS_NA);
System.out.println("Confusion matrix when both assessments are present:\n");
System.out.println(filteredConfusionMatrix.prettyPrint());
System.out.format("Agreement: %.2f%%\n", 100.0 * filteredConfusionMatrix.accuracy());
System.out.format("Agreement kappa: %.2f\n\n",
100.0 * kappaCalculator.computeKappa(filteredConfusionMatrix));
if (USES_CORRECT_INEXACT.contains(assessmentName)) {
final SummaryConfusionMatrix lenientConfusionMatrix =
filteredConfusionMatrix
.copyWithTransformedLabels(COUNT_CORRECT_AND_INEXACT_AS_THE_SAME);
System.out.println(
"Confusion matrix when both assessments are present, collapsing CORRECT and INEXACT:\n");
System.out.println(lenientConfusionMatrix.prettyPrint());
System.out.format("Agreement: %.2f%%\n", 100.0 * lenientConfusionMatrix.accuracy());
System.out.format("Agreement kappa: %.2f\n\n",
100.0 * kappaCalculator.computeKappa(lenientConfusionMatrix));
}
}
System.out.println(
"\n\n\nBelow are the 'presence agreement' numbers indicating how often both annotators made "
+ " a certain assessment at all, regardless of how they assessed. A difference on assessment presence "
+ " generally indicates a difference on some prior assessment this assessment depends on.");
for (final Map.Entry<String, SummaryConfusionMatrix.Builder> assessmentResults
: assessmentNameToConfusionMatrix.entrySet()) {
final String assessmentName = assessmentResults.getKey();
final SummaryConfusionMatrix confusionMatrix = assessmentResults.getValue().build();
System.out.println(" ============== " + assessmentName + " ==============\n\n");
System.out.println("Agreement concerning assessment presence");
final SummaryConfusionMatrix presenceConfusionMatrix =
confusionMatrix.copyWithTransformedLabels(ASSESSMENT_IS_PRESENT);
System.out.println(presenceConfusionMatrix.prettyPrint());
System.out
.format("Presence agreement: %.2f%%\n", 100.0 * presenceConfusionMatrix.accuracy());
System.out.format("Presence kappa: %.2f\n\n",
100.0 * kappaCalculator.computeKappa(presenceConfusionMatrix));
}
}
}
private static void reportResponseMismatch(Symbol docID, Set<Response> leftAnnotationsIndexed,
Set<Response> rightAnnotationsIndexed) {
final Set<String> leftOnly =
FluentIterable.from(Sets.difference(leftAnnotationsIndexed, rightAnnotationsIndexed))
.transform(Response.uniqueIdFunction()).toSet();
final Set<String> rightOnly =
FluentIterable.from(Sets.difference(rightAnnotationsIndexed, leftAnnotationsIndexed))
.transform(Response.uniqueIdFunction()).toSet();
log.warn("For document " + docID + ", sets of assessed responses do not match. "
+ "In left only: " + leftOnly + "; in right only: " + rightOnly + ". If this is just due to "
+ "realis expansion this is OK; otherwise not.");
}
public static void main(String[] argv) {
// we wrap the main method in this way to
// ensure a non-zero return value on failure
try {
trueMain(argv);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
package com.yahoo.jdisc.application;
import com.google.inject.Inject;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import static java.util.Collections.singletonList;
/**
* <p>This is a utility class to help with installing, starting, stopping and uninstalling OSGi Bundles. You can choose
* to inject an instance of this class, or it can be created explicitly by reference to a {@link OsgiFramework}.</p>
*
* <p>Please see commentary on {@link OsgiFramework#installBundle(String)} for a description of exception-safety issues
* to consider when installing bundles that use the {@link OsgiHeader#PREINSTALL_BUNDLE} manifest instruction.</p>
*
* @author Simon Thoresen Hult
*/
public final class BundleInstaller {
private final OsgiFramework osgiFramework;
@Inject
public BundleInstaller(OsgiFramework osgiFramework) {
this.osgiFramework = osgiFramework;
}
public List<Bundle> installAndStart(String... locations) throws BundleException {
return installAndStart(Arrays.asList(locations));
}
public List<Bundle> installAndStart(Iterable<String> locations) throws BundleException {
List<Bundle> bundles = new LinkedList<>();
try {
for (String location : locations) {
bundles.addAll(osgiFramework.installBundle(location));
}
} catch (BundleInstallationException e) {
bundles.addAll(e.installedBundles());
throw new BundleInstallationException(bundles, e);
} catch (Exception e) {
throw new BundleInstallationException(bundles, e);
}
try {
for (Bundle bundle : bundles) {
start(bundle);
}
} catch (Exception e) {
throw new BundleInstallationException(bundles, e);
}
return bundles;
}
public void stopAndUninstall(Bundle... bundles) throws BundleException {
stopAndUninstall(Arrays.asList(bundles));
}
public void stopAndUninstall(Iterable<Bundle> bundles) throws BundleException {
for (Bundle bundle : bundles) {
stop(bundle);
}
for (Bundle bundle : bundles) {
bundle.uninstall();
}
}
private void start(Bundle bundle) throws BundleException {
if (bundle.getState() == Bundle.ACTIVE) {
throw new BundleException("OSGi bundle " + bundle.getSymbolicName() + " already started.");
}
if (!OsgiHeader.asList(bundle, OsgiHeader.APPLICATION).isEmpty()) {
throw new BundleException("OSGi header '" + OsgiHeader.APPLICATION + "' not allowed for " +
"non-application bundle " + bundle.getSymbolicName() + ".");
}
osgiFramework.startBundles(singletonList(bundle), false);
}
private void stop(Bundle bundle) throws BundleException {
if (bundle.getState() != Bundle.ACTIVE) {
throw new BundleException("OSGi bundle " + bundle.getSymbolicName() + " not started.");
}
bundle.stop();
}
}
|
package org.languagetool.rules.patterns;
import org.jetbrains.annotations.Nullable;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.rules.RuleMatch;
import java.util.*;
/**
* Evaluates a {@link RuleFilter}.
* @since 2.7
*/
class RuleFilterEvaluator {
private final RuleFilter filter;
RuleFilterEvaluator(RuleFilter filter) {
this.filter = filter;
}
@Nullable
RuleMatch runFilter(String filterArgs, RuleMatch ruleMatch, AnalyzedTokenReadings[] patternTokens, List<Integer> tokenPositions) {
Map<String,String> args = getResolvedArguments(filterArgs, patternTokens, tokenPositions);
return filter.acceptRuleMatch(ruleMatch, args, patternTokens);
}
/**
* Resolves the backref arguments, e.g. replaces {@code \1} by the value of the first token in the pattern.
*/
Map<String,String> getResolvedArguments(String filterArgs, AnalyzedTokenReadings[] patternTokens, List<Integer> tokenPositions) {
Map<String,String> result = new HashMap<>();
String[] arguments = filterArgs.split("\\s+");
for (String arg : arguments) {
int delimPos = arg.indexOf(':');
if (delimPos == -1) {
throw new RuntimeException("Invalid syntax for key/value, expected 'key:value', got: '" + arg + "'");
}
String key = arg.substring(0, delimPos);
String val = arg.substring(delimPos + 1);
if (val.startsWith("\\")) {
int refNumber = Integer.parseInt(val.replace("\\", ""));
if (refNumber > tokenPositions.size()) {
throw new RuntimeException("Your reference number " + refNumber + " is bigger than the number of tokens: " + tokenPositions.size());
}
int correctedRef = getSkipCorrectedReference(tokenPositions, refNumber);
if (correctedRef >= patternTokens.length) {
throw new RuntimeException("Your reference number " + refNumber +
" is bigger than number of matching tokens: " + patternTokens.length);
}
if (result.containsKey(key)) {
throw new RuntimeException("Duplicate key '" + key + "'");
}
result.put(key, patternTokens[correctedRef].getToken());
} else {
result.put(key, val);
}
}
return result;
}
// when there's a 'skip', we need to adapt the reference number
private int getSkipCorrectedReference(List<Integer> tokenPositions, int refNumber) {
int correctedRef = 0;
int i = 0;
for (int tokenPosition : tokenPositions) {
if (i++ >= refNumber) {
break;
}
correctedRef += tokenPosition;
}
return correctedRef - 1;
}
}
|
package org.languagetool.gui;
import java.awt.Component;
import java.util.ResourceBundle;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import org.languagetool.JLanguageTool;
import org.languagetool.Language;
import org.languagetool.databroker.ResourceDataBroker;
/**
* A ComboBox Renderer that can display a flag icon along with the language
*
* @author Panagiotis Minos
*/
class LanguageComboBoxRenderer extends JLabel implements ListCellRenderer<LanguageAdapter> {
private static final Border BORDER = new EmptyBorder(1, 3, 1, 1);
private final ResourceBundle messages;
private final String extLangSuffix;
LanguageComboBoxRenderer(ResourceBundle messages, String extLangSuffix) {
super();
setOpaque(true);
setBorder(BORDER);
this.messages = messages;
this.extLangSuffix = extLangSuffix;
}
private String getTranslatedName(Language language) {
String name = language.getTranslatedName(messages);
if (language.isExternal()) {
name += extLangSuffix;
}
return name;
}
@Override
public Component getListCellRendererComponent(JList list, LanguageAdapter adapter, int index, boolean isSelected, boolean cellHasFocus) {
setComponentOrientation(list.getComponentOrientation());
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
if (adapter != null) {
Language lang = adapter.getLanguage();
if (lang != null) {
setText(getTranslatedName(lang));
String langTag = lang.getLocaleWithCountryAndVariant().toLanguageTag();
String country = lang.getLocaleWithCountryAndVariant().getCountry().toLowerCase();
ResourceDataBroker dataBroker = JLanguageTool.getDataBroker();
String filename = "flags/bytag/" + langTag + ".png";
if (!dataBroker.resourceExists(filename)) {
filename = "flags/" + country + ".png";
}
if (!dataBroker.resourceExists(filename)) {
filename = "flags/empty.png";
}
ImageIcon icon = new ImageIcon(dataBroker.getFromResourceDirAsUrl(filename));
setIcon(icon);
} else {
setText(adapter.getValue());
setIcon(null);
}
}
setEnabled(list.isEnabled());
setFont(list.getFont());
setBorder(BORDER);
return this;
}
}
|
package it.geosolutions.jaiext.nullop;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.image.RenderedImage;
import java.awt.image.renderable.ParameterBlock;
import java.awt.image.renderable.RenderableImage;
import java.util.Vector;
import javax.media.jai.JAI;
import javax.media.jai.OperationDescriptorImpl;
import javax.media.jai.OperationNode;
import javax.media.jai.ParameterBlockJAI;
import javax.media.jai.RenderableOp;
import javax.media.jai.RenderedOp;
import javax.media.jai.registry.RenderableRegistryMode;
import javax.media.jai.registry.RenderedRegistryMode;
public class NullDescriptor extends OperationDescriptorImpl {
/**
* The resource strings that provide the general documentation
* and specify the parameter list for this operation.
*/
private static final String[][] resources = {
{"GlobalName", "NullOp"},
{"LocalName", "NullOp"},
{"Vendor", "it.geosolutions.jaiext.roiaware"},
{"Description", "Operation used for wrapping other images"},
{"DocURL", "http://java.sun.com/products/java-media/jai/forDevelopers/jai-apidocs/javax/media/jai/operator/NullDescriptor.html"},
{"Version", "1.0"},
};
private static final String[] supportedModes = {
"rendered",
"renderable"
};
/** Constructor. */
public NullDescriptor() {
super(resources, supportedModes, 1, null, null, null, null);
}
/**
* If the PB has more than one source, replace it with a new PB which
* has only one source equal to the first source of the input.
* We want to support an arbitrary number of sources but only care that
* there is at least one of the appropriate class.
*/
private static ParameterBlock foolSourceValidation(ParameterBlock args) {
if(args.getNumSources() > 1) {
Vector singleSource = new Vector();
singleSource.add(args.getSource(0));
args = new ParameterBlock(singleSource, args.getParameters());
}
return args;
}
protected boolean validateSources(String modeName,
ParameterBlock args,
StringBuffer msg) {
if ( args == null || msg == null ) {
throw new IllegalArgumentException("No parameterBlock or StringBuffer present");
}
return super.validateSources(modeName, foolSourceValidation(args), msg);
}
public Object getInvalidRegion(String modeName,
ParameterBlock oldParamBlock,
RenderingHints oldHints,
ParameterBlock newParamBlock,
RenderingHints newHints,
OperationNode node) {
if (modeName == null || oldParamBlock == null || newParamBlock == null) {
throw new IllegalArgumentException("Some parameters are not defined");
}
if (oldParamBlock.getNumSources() < 1 ||
newParamBlock.getNumSources() < 1) {
throw new IllegalArgumentException("No sources provided");
}
return oldParamBlock.getSource(0).equals(newParamBlock.getSource(0)) ?
new Rectangle() : null;
}
public static RenderedOp create(RenderedImage source0,
RenderingHints hints) {
ParameterBlockJAI pb =
new ParameterBlockJAI("NullOp",
RenderedRegistryMode.MODE_NAME);
pb.setSource("source0", source0);
return JAI.create("NullOp", pb, hints);
}
public static RenderableOp createRenderable(RenderableImage source0,
RenderingHints hints) {
ParameterBlockJAI pb =
new ParameterBlockJAI("NullOp",
RenderableRegistryMode.MODE_NAME);
pb.setSource("source0", source0);
return JAI.createRenderable("NullOp", pb, hints);
}
}
|
package de.learnlib.api;
import java.util.Collection;
import net.automatalib.words.Word;
/**
* This interface specifies components that analize counterexamples
* and generate a collection of suffixes which can be used by
* learning algorithms to produce a refined hypothesis. Some analysis
* strategies will produce additional membership queries to yield a result.
*
* @author Maik Merten <maikmerten@googlemail.com>
*
* @param <I> input symbol class
*
*/
public interface CEXHandlerSuffixes<I, O> {
/**
* Analize a counterexample and generate a set of counterexamples
* that effect refinement of the current hypothesis constructed by
* a learning algorithm.
*
* @param ceQuery A Query that produces diverging output between the current hypothesis and the system under learning
* @param suffixes A collection that shall be filled with the suffixes created during analysis
*/
public void createSuffixes(Query<I, O> ceQuery, Collection<Word<I>> suffixes);
}
|
package org.eclipse.birt.report.designer.internal.ui.views;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter;
import org.eclipse.birt.report.designer.core.model.views.outline.ReportElementModel;
import org.eclipse.birt.report.designer.internal.ui.dialogs.DeleteWarningDialog;
import org.eclipse.birt.report.designer.internal.ui.dialogs.ImageBuilderDialog;
import org.eclipse.birt.report.designer.internal.ui.dialogs.NewSectionDialog;
import org.eclipse.birt.report.designer.internal.ui.palette.BasePaletteFactory;
import org.eclipse.birt.report.designer.internal.ui.views.actions.CopyAction;
import org.eclipse.birt.report.designer.internal.ui.views.actions.CutAction;
import org.eclipse.birt.report.designer.internal.ui.views.actions.DeleteAction;
import org.eclipse.birt.report.designer.internal.ui.views.actions.InsertAction;
import org.eclipse.birt.report.designer.internal.ui.views.actions.PasteAction;
import org.eclipse.birt.report.designer.internal.ui.views.actions.RenameAction;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.ReportPlatformUIImages;
import org.eclipse.birt.report.designer.ui.actions.PageSetAction.CodePageAction;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.model.activity.SemanticException;
import org.eclipse.birt.report.model.api.CellHandle;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.ElementFactory;
import org.eclipse.birt.report.model.api.GridHandle;
import org.eclipse.birt.report.model.api.ParameterGroupHandle;
import org.eclipse.birt.report.model.api.ReportElementHandle;
import org.eclipse.birt.report.model.api.RowHandle;
import org.eclipse.birt.report.model.api.SlotHandle;
import org.eclipse.birt.report.model.api.TableHandle;
import org.eclipse.birt.report.model.elements.ReportDesignConstants;
import org.eclipse.birt.report.model.metadata.ElementDefn;
import org.eclipse.gef.Request;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PlatformUI;
/**
* Default node provider. This class is the base class for other providers
*
*
*/
public class DefaultNodeProvider implements INodeProvider
{
private static final String DLG_CONFIRM_MSG = Messages.getString( "DefaultNodeProvider.Dlg.Confirm" ); //$NON-NLS-1$
private static final String DLG_HAS_FOLLOWING_CLIENTS_MSG = Messages.getString( "DefaultNodeProvider.Tree.Clients" ); //$NON-NLS-1$
private static final String DLG_REFERENCE_FOUND_TITLE = Messages.getString( "DefaultNodeProvider.Tree.Reference" ); //$NON-NLS-1$
public static final String BODY = Messages.getString( "DefaultNodeProvider.Tree.Body" ); //$NON-NLS-1$
public static final String PAGESETUP = Messages.getString( "DefaultNodeProvider.Tree.PageSetup" ); //$NON-NLS-1$
public static final String DATASOURCES = Messages.getString( "DefaultNodeProvider.Tree.DataSources" ); //$NON-NLS-1$
public static final String DATASETS = Messages.getString( "DefaultNodeProvider.Tree.DataSets" ); //$NON-NLS-1$
public static final String STYLES = Messages.getString( "DefaultNodeProvider.Tree.Styles" ); //$NON-NLS-1$
public static final String PARAMETERS = Messages.getString( "DefaultNodeProvider.Tree.Parameters" ); //$NON-NLS-1$
public static final String SCRATCHPAD = Messages.getString( "DefaultNodeProvider.Tree.Scratch" ); //$NON-NLS-1$
public static final String MASTERPAGE = Messages.getString( "DefaultNodeProvider.Tree.MasterPages" ); //$NON-NLS-1$
public static final String COLUMNHEADING_DISPALYNAME = Messages.getString( "DefaultNodeProvider.Tree.ColumnHedings" ); //$NON-NLS-1$
public static final String DETAIL_DISPALYNAME = Messages.getString( "DefaultNodeProvider.Tree.Detail" ); //$NON-NLS-1$
public static final String HEADER_DISPALYNAME = Messages.getString( "DefaultNodeProvider.Tree.Header" ); //$NON-NLS-1$
public static final String FOOTER_DISPALYNAME = Messages.getString( "DefaultNodeProvider.Tree.Footer" ); //$NON-NLS-1$
public static final String GROUPS_DISPALYNAME = Messages.getString( "DefaultNodeProvider.Tree.Groups" ); //$NON-NLS-1$
public static final String MISSINGNAME = Messages.getString( "DefaultNodeProvider.Tree.Invalid" ); //$NON-NLS-1$
public static final String CONFIRM_PARAM_DELETE_TITLE = Messages.getString( "DefaultNodeProvider.ParameterGroup.ConfirmTitle" ); //$NON-NLS-1$
public static final String CONFIRM_PARAM_DELETE_MESSAGE = Messages.getString( "DefaultNodeProvider.ParameterGroup.ConfirmMessage" ); //$NON-NLS-1$
/**
* Creates the context menu
*
* @param sourceViewer
* TODO
* @param object
* the object
* @param menu
* the menu
*/
public void createContextMenu( TreeViewer sourceViewer, Object object,
IMenuManager menu )
{
menu.add( new Separator( IWorkbenchActionConstants.MB_ADDITIONS ) );
// Rename action
RenameAction renameAction = new RenameAction( sourceViewer );
if ( renameAction.isEnabled( ) )
{//if can rename,add to menu
menu.add( renameAction );
}
// Delete action
DeleteAction deleteAction = deleteAction = new DeleteAction( object );
if ( deleteAction.isEnabled( ) )
{//if can delete,add to menu
menu.add( deleteAction );
}
CutAction cutAction = new CutAction( object );
if ( cutAction.isEnabled( ) )
menu.add( cutAction );
CopyAction copyAction = new CopyAction( object );
if ( copyAction.isEnabled( ) )
menu.add( copyAction );
menu.add( new PasteAction( object ) );
menu.add( new Separator( ) );
Action pageAction = new CodePageAction( object );
if ( pageAction.isEnabled( ) )
menu.add( pageAction );
menu.add( new Separator( IWorkbenchActionConstants.MB_ADDITIONS
+ "-end" ) );//$NON-NLS-1$
}
/**
* Gets the display name of the node.
*
* @param model
* the object
*/
public String getNodeDisplayName( Object model )
{
return DEUtil.getDisplayLabel( model );
}
/**
* Gets the children element of the given model using visitor.
*
* @param model
* the model
*/
public Object[] getChildren( Object model )
{
if ( model instanceof ReportElementModel )
{
if ( ( (ReportElementModel) model ).getSlotHandle( ) != null )
{
return this.getChildrenBySlotHandle( ( (ReportElementModel) model ).getSlotHandle( ) );
}
}
return new Object[]{};
}
public Object getParent( Object model )
{
if ( model instanceof ReportElementModel )
{
return ( (ReportElementModel) model ).getElementHandle( );
}
else if ( model instanceof ReportElementHandle )
{
ReportElementHandle handle = (ReportElementHandle) model;
if ( handle instanceof CellHandle
|| handle.getContainer( ) instanceof CellHandle
|| handle.getContainer( ) instanceof ParameterGroupHandle
|| ( handle instanceof RowHandle && handle.getContainer( ) instanceof GridHandle ) )
{
return handle.getContainer( );
}
if ( handle.getContainerSlotHandle( ) != null )
{
return new ReportElementModel( handle.getContainerSlotHandle( ) );
}
}
return null;
}
/**
* Gets the icon image for the given model.
*
* @param model
* the model of the node
*
* @return Returns the icon name for the model,or null if no proper one
* available for the given model
*/
public Image getNodeIcon( Object model )
{
Image icon = null;
String iconName = getIconName( model );
if ( iconName != null )
{//if the getIconName is defined
icon = ReportPlatformUIImages.getImage( iconName );
}
if ( icon == null )
{
if ( model instanceof DesignElementHandle )
{
icon = ReportPlatformUIImages.getImage( model );
}
}
return icon;
}
/**
* Gets the icon name for the given model. The default implementation does
* nothing.The subclasses may override it if necessary
*
* @param model
* the model of the node
*
* @return Returns the icon name for the model,or null if no proper one
* available for the given model
*/
public String getIconName( Object model )
{//Do nothing
return null;
}
protected Object[] getChildrenBySlotHandle( SlotHandle slotHandle )
{
ArrayList list = new ArrayList( );
Iterator itor = slotHandle.iterator( );
while ( itor.hasNext( ) )
{
Object obj = itor.next( );
if ( obj instanceof DesignElementHandle )
{
DesignElementHandle eleHandle = (DesignElementHandle) obj;
list.add( eleHandle );
}
}
return list.toArray( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.internal.ui.views.INodeProvider#getCommand(org.eclipse.gef.Request)
*/
public boolean performRequest( Object model, Request request )
throws Exception
{
if ( request.getType( ).equals( IRequestConstants.REQUEST_TYPE_INSERT ) )
{
Map extendsData = request.getExtendedData( );
SlotHandle slotHandle = (SlotHandle) extendsData.get( IRequestConstants.REQUEST_KEY_INSERT_SLOT );
String type = (String) extendsData.get( IRequestConstants.REQUEST_KEY_INSERT_TYPE );
String position = (String) extendsData.get( IRequestConstants.REQUEST_KEY_INSERT_POSITION );
return performInsert( model,
slotHandle,
type,
position,
extendsData );
}
if ( request.getType( ).equals( IRequestConstants.REQUEST_TYPE_EDIT ) )
{
return performEdit( (ReportElementHandle) model );
}
if ( request.getType( ).equals( IRequestConstants.REQUEST_TYPE_DELETE ) )
{
if ( model instanceof IStructuredSelection )
{
boolean retValue = false;
for ( Iterator itor = ( (IStructuredSelection) model ).iterator( ); itor.hasNext( ); )
{
Object obj = itor.next( );
retValue |= ProviderFactory.createProvider( obj )
.performRequest( obj, request );
}
return retValue;
}
DesignElementHandle handle = (DesignElementHandle) model;
if ( handle.getContainer( ) == null )
{//has been deleted
return false;
}
return performDelete( handle );
}
return false;
}
protected DesignElementHandle createElement( String type ) throws Exception
{
ElementFactory factory = SessionHandleAdapter.getInstance( )
.getReportDesignHandle( )
.getElementFactory( );
if ( ReportDesignConstants.TABLE_ITEM.equals( type ) )
{
TableHandle table = factory.newTableItem( null, 3 );
BasePaletteFactory.setInitWidth( table );
return table;
}
else if ( ReportDesignConstants.GRID_ITEM.equals( type ) )
{
GridHandle grid = factory.newGridItem( null, 3, 3 );
BasePaletteFactory.setInitWidth( grid );
return grid;
}
else if ( ReportDesignConstants.IMAGE_ITEM.equals( type ) )
{
ImageBuilderDialog dialog = new ImageBuilderDialog( PlatformUI.getWorkbench( )
.getDisplay( )
.getActiveShell( ) );
if ( dialog.open( ) == Dialog.OK )
{
return (DesignElementHandle) dialog.getResult( );
}
return null;
}
return factory.newElement( type, null );
}
protected DesignElementHandle createElement( SlotHandle slotHandle,
String type ) throws Exception
{
if ( type == null )
{
List supportList = DEUtil.getElementSupportList( slotHandle );
if ( supportList.size( ) == 1 )
{
type = ( (ElementDefn) supportList.get( 0 ) ).getName( );
}
else
{
NewSectionDialog dialog = new NewSectionDialog( PlatformUI.getWorkbench( )
.getDisplay( )
.getActiveShell( ),
supportList );
if ( dialog.open( ) == Dialog.CANCEL )
{
return null;
}
type = (String) dialog.getResult( )[0];
}
}
return createElement( type );
}
/**
* @param model
* @param slotHandle
* @param type
* @param position
* @return Returns true if performed correctly,otherwise returns false
* @throws SemanticException
*/
protected boolean performInsert( Object model, SlotHandle slotHandle,
String type, String position ) throws Exception
{
return performInsert( model, slotHandle, type, position, null );
}
protected boolean performInsert( Object model, SlotHandle slotHandle,
String type, String position, Map extendData ) throws Exception
{
DesignElementHandle elementHandle = createElement( slotHandle, type );
if ( extendData != null )
{
extendData.put( IRequestConstants.REQUEST_KEY_RESULT, elementHandle );
}
if ( elementHandle == null )
{
return false;
}
if ( position == InsertAction.CURRENT )
{
slotHandle.add( elementHandle );
}
else
{
if ( model instanceof DesignElementHandle )
{
DesignElementHandle handle = (DesignElementHandle) model;
int pos = slotHandle.findPosn( handle.getElement( ) );
if ( position == InsertAction.ABOVE )
{
if ( pos > 0 )
{
pos
}
}
else if ( position == InsertAction.BELOW )
{
if ( pos < slotHandle.getCount( ) )
{
pos++;
}
else
{
pos = -1;
}
}
if ( pos == -1 )
{
slotHandle.add( elementHandle );
}
else
{
slotHandle.add( elementHandle, pos );
}
}
}
return true;
}
protected boolean performEdit( ReportElementHandle handle )
{
return false;
}
protected boolean performDelete( DesignElementHandle handle )
throws SemanticException
{
if ( handle instanceof ParameterGroupHandle )
{
if ( ( (ParameterGroupHandle) handle ).getParameters( ).getCount( ) > 0 )
{
if ( !MessageDialog.openQuestion( PlatformUI.getWorkbench( )
.getDisplay( )
.getActiveShell( ),
CONFIRM_PARAM_DELETE_TITLE,
CONFIRM_PARAM_DELETE_MESSAGE ) )
{
return false;
}
}
}
ArrayList referenceList = new ArrayList( );
for ( Iterator itor = handle.clientsIterator( ); itor.hasNext( ); )
{
referenceList.add( itor.next( ) );
}
if ( !referenceList.isEmpty( ) )
{
DeleteWarningDialog dialog = new DeleteWarningDialog( PlatformUI.getWorkbench( )
.getDisplay( )
.getActiveShell( ),
DLG_REFERENCE_FOUND_TITLE,
referenceList );
dialog.setPreString( DEUtil.getDisplayLabel( handle )
+ DLG_HAS_FOLLOWING_CLIENTS_MSG );
dialog.setSufString( DLG_CONFIRM_MSG );
if ( dialog.open( ) == Dialog.CANCEL )
{
return false;
}
}
handle.drop( );
return true;
}
}
|
/**
* An attachable rank tips view that show 2 lines text containing a tips and a
* number.
*
*/
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
public class RankTipsView extends View {
private int mBackgroundColor;
private int mTextColor;
private int mWidth, mHeight;
private int mHalfWidth,mHalfHeight;
private Paint mPathPaint;
private Paint mTextPaint;
private Path mPath;
private String mTipsText;
private int mRank;
private int mTextSize;
public RankTipsView(Context context) {
this(context, null);
}
public RankTipsView(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.textViewStyle);
}
public RankTipsView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
if (!(getLayoutParams() instanceof FrameLayout.LayoutParams)) {
FrameLayout.LayoutParams layoutParams =
new FrameLayout.LayoutParams(
android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
Gravity.RIGHT | Gravity.TOP);
setLayoutParams(layoutParams);
}
setMargin(0, 0, DensityUtils.dip2px(getContext(),5), 0);
mBackgroundColor =Color.parseColor("#d3321b");
mTextColor = Color.parseColor("#ffffff");
mHalfWidth=DensityUtils.dip2px(getContext(),14);
mHalfHeight=DensityUtils.dip2px(getContext(),24);
mPathPaint = new Paint();
mPathPaint.setColor(mBackgroundColor);
mPathPaint.setStyle(Paint.Style.FILL);
mTextPaint = new Paint();
mTextPaint.setColor(mTextColor);
mTextPaint.setStyle(Paint.Style.FILL);
mTextPaint.setTextAlign(Paint.Align.CENTER);
mTextSize =DensityUtils.sp2px(getContext(),10);
mTextPaint.setTextSize(mTextSize);
mTipsText="TOP";
mRank=1;
mPath = new Path();
mPath.setFillType(Path.FillType.WINDING);
mPath.lineTo(-mHalfWidth,mHalfHeight/2);
mPath.lineTo(-mHalfWidth,-mHalfHeight);
mPath.lineTo(mHalfWidth,-mHalfHeight);
mPath.lineTo(mHalfWidth,mHalfHeight/2);
mPath.lineTo(0,0);
}
public void setWidth(int widthDip){
mHalfWidth=DensityUtils.dip2px(getContext(),widthDip/2);
invalidate();
requestLayout();
}
public void setHeight(int heightDip){
mHalfHeight=DensityUtils.dip2px(getContext(),heightDip*2/3);
invalidate();
requestLayout();
}
public void setTipsText(String text){
mTipsText =text;
invalidate();
requestLayout();
}
public void setNumber(int num){
mRank=num;
invalidate();
requestLayout();
}
public void setTextSize(int sizeSp){
mTextSize =DensityUtils.sp2px(getContext(),sizeSp);
invalidate();
requestLayout();
}
public void setTextColor(int color){
mTextColor=color;
mTextPaint.setColor(mTextColor);
invalidate();
requestLayout();
}
public void setBackgroundColor(int color){
mBackgroundColor =color;
mPathPaint.setColor(mBackgroundColor);
invalidate();
requestLayout();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
double minw = getPaddingLeft() + getPaddingRight() + 2*mHalfWidth;
int w = resolveSizeAndState((int)minw, widthMeasureSpec, 1);
double minh = getPaddingBottom() + getPaddingTop()+2*mHalfHeight;
int h = resolveSizeAndState((int)minh, heightMeasureSpec, 0);
setMeasuredDimension(w, h);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = w;
mHeight = h;
}
@Override
public void onDraw(Canvas canvas){
mPath.reset();
mPath.lineTo(-mHalfWidth,mHalfHeight/2);
mPath.lineTo(-mHalfWidth,-mHalfHeight);
mPath.lineTo(mHalfWidth,-mHalfHeight);
mPath.lineTo(mHalfWidth,mHalfHeight/2);
mPath.lineTo(0,0);
canvas.translate(mWidth / 2, mHeight / 2);
canvas.drawPath(mPath,mPathPaint);
canvas.drawText(mTipsText,0,-mHalfHeight*3/4+mTextSize/2,mTextPaint);
canvas.drawText(String.valueOf(mRank),0,-mHalfHeight/4+mTextSize/2,
mTextPaint);
}
public void setGravity(int gravity) {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) getLayoutParams();
params.gravity = gravity;
setLayoutParams(params);
invalidate();
requestLayout();
}
public int getGravity() {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) getLayoutParams();
return params.gravity;
}
public void setMargin(int dipMargin) {
setMargin(dipMargin, dipMargin, dipMargin, dipMargin);
}
public void setMargin(int leftDipMargin, int topDipMargin, int rightDipMargin, int bottomDipMargin) {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) getLayoutParams();
params.leftMargin = DensityUtils.dip2px(getContext(),leftDipMargin);
params.topMargin = DensityUtils.dip2px(getContext(),topDipMargin);
params.rightMargin = DensityUtils.dip2px(getContext(),rightDipMargin);
params.bottomMargin = DensityUtils.dip2px(getContext(),bottomDipMargin);
setLayoutParams(params);
invalidate();
requestLayout();
}
public int[] getMargin() {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) getLayoutParams();
return new int[] { params.leftMargin, params.topMargin, params.rightMargin, params.bottomMargin };
}
/**
* Attach the RankTipsView to the target view
*
* @param target the view to attach the RankTipsView
*/
public void setTargetView(View target) {
if (getParent() != null) {
((ViewGroup) getParent()).removeView(this);
}
if (target == null) {
return;
}
if (target.getParent() instanceof FrameLayout) {
((FrameLayout) target.getParent()).addView(this);
} else if (target.getParent() instanceof ViewGroup) {
// use a new Framelayout container for adding
ViewGroup parentContainer = (ViewGroup) target.getParent();
int groupIndex = parentContainer.indexOfChild(target);
parentContainer.removeView(target);
FrameLayout badgeContainer = new FrameLayout(getContext());
ViewGroup.LayoutParams parentLayoutParams = target.getLayoutParams();
badgeContainer.setLayoutParams(parentLayoutParams);
target.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
parentContainer.addView(badgeContainer, groupIndex, parentLayoutParams);
badgeContainer.addView(target);
badgeContainer.addView(this);
} else if (target.getParent() == null) {
Log.e(getClass().getSimpleName(), "ParentView is needed");
}
}
}
class DensityUtils {
public DensityUtils() {
}
/**
* convert the dp to px depend on the device density.
*
* @param context the context
* @param dpValue a value of dp
* @return the result of px
*/
public static int dip2px(Context context, float dpValue) {
return (int) (dpValue * getDensity(context) + 0.5f);
}
/**
* convert the px to dp depend on the device density.
*
* @param context the context
* @param pxValue a value of px
* @return the result of dp
*/
public static int px2dip(Context context, float pxValue) {
return (int) (pxValue / getDensity(context) + 0.5f);
}
/**
* convert the sp to px depend on the device scaledDensity.
*
* @param context the context
* @param spValue a value of sp
* @return the result of px
*/
public static int sp2px(Context context, float spValue) {
return (int) (spValue * getFontDensity(context) + 0.5);
}
/**
* convert the px to sp depend on the device scaledDensity.
*
* @param context the context
* @param pxValue a value of px
* @return the result of sp
*/
public static int px2sp(Context context, float pxValue) {
return (int) (pxValue / getFontDensity(context) + 0.5);
}
/**
* get the density of device screen.
*
* @param context the context
* @return the screen density
*/
public static float getDensity(Context context) {
return context.getResources().getDisplayMetrics().density;
}
/**
* get the scale density of device screen.
* usually this value is the same as density.
* but it can adjust by user.
*
* @param context the context
* @return the screen scale density.
*/
public static float getFontDensity(Context context) {
return context.getResources().getDisplayMetrics().scaledDensity;
}
}
|
package com.intuit.karate.netty;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileChangedWatcher {
private static final Logger logger = LoggerFactory.getLogger(FileChangedWatcher.class);
private File file;
private FeatureServer server;
private Integer port;
private boolean ssl;
private File cert;
private File key;
public FileChangedWatcher(File mock, FeatureServer server, Integer port, boolean ssl, File cert, File key) {
this.file = mock;
this.server = server;
this.port = port;
this.ssl = ssl;
this.cert = cert;
this.key = key;
}
public void watch() throws InterruptedException, IOException {
try {
final Path directoryPath = file.toPath().getParent();
final WatchService watchService = FileSystems.getDefault().newWatchService();
directoryPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
while (true) {
final WatchKey wk = watchService.take();
for (WatchEvent<?> event : wk.pollEvents()) {
final Path fileChangedPath = (Path) event.context();
if (fileChangedPath.endsWith(file.getName())) {
onModified();
}
}
wk.reset();
}
} catch (Exception exception) {
logger.error("exception when handling change of mock file");
}
}
public void onModified() {
if (server != null) {
server.stop();
server = FeatureServer.start(file, port, ssl, cert, key, null);
}
}
}
|
package com.mikepenz.crossfadedrawerlayout.view;
import android.content.Context;
import android.support.v4.widget.DrawerLayout;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.mikepenz.crossfadedrawerlayout.ApplyTransformationListener;
import com.mikepenz.crossfadedrawerlayout.animation.ResizeWidthAnimation;
public class CrossfadeDrawerLayout extends DrawerLayout {
private static final int DEFAULT_ANIMATION = 200;
private boolean mDrawerOpened = false;
private float mTouchDown = -1;
private float mPrevTouch = -1;
private DrawerListener mDrawerListener;
private CrossfadeListener mCrossfadeListener;
private int mMinWidth = 0;
private int mMaxWidth = 0;
private RelativeLayout mContainer;
private ViewGroup mSmallView;
private ViewGroup mLargeView;
private boolean mIsCrossfaded = false;
public CrossfadeDrawerLayout(Context context) {
super(context);
init(context);
}
public CrossfadeDrawerLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public CrossfadeDrawerLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
public void init(Context ctx) {
super.setDrawerListener(drawerListener);
//define default valuse for min and max
mMinWidth = (int) UIUtils.convertDpToPixel(72, ctx);
mMaxWidth = (int) UIUtils.convertDpToPixel(200, ctx);
}
public void setMinWidthPx(int minWidth) {
this.mMinWidth = minWidth;
}
public void setMaxWidthPx(int maxWidth) {
this.mMaxWidth = maxWidth;
}
public ViewGroup getSmallView() {
return mSmallView;
}
public ViewGroup getLargeView() {
return mLargeView;
}
public boolean isCrossfaded() {
return mIsCrossfaded;
}
/**
* defines a CrossfadeListener which is called when you slide the crossfader
*
* @param crossfadeListener
* @return
*/
public CrossfadeDrawerLayout withCrossfadeListener(CrossfadeListener crossfadeListener) {
this.mCrossfadeListener = crossfadeListener;
return this;
}
@Override
public void addView(View child, int index) {
child = wrapSliderContent(child, index);
super.addView(child, index);
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
child = wrapSliderContent(child, index);
super.addView(child, index, params);
}
/**
* this will wrap the view which is added to the slider into another layout so we can then overlap the small and large view
*
* @param child
* @param index
* @return
*/
private View wrapSliderContent(View child, int index) {
//TODO !!
if (index == 1 && child.getId() != -1) {
mLargeView = (ViewGroup) child;
mContainer = new RelativeLayout(getContext());
mContainer.setGravity(Gravity.START);
mContainer.setLayoutParams(child.getLayoutParams());
mContainer.addView(mLargeView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
mSmallView = new LinearLayout(getContext());
mContainer.addView(mSmallView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
UIUtils.setAlpha(mLargeView, 0);
mLargeView.setVisibility(View.GONE);
return mContainer;
}
return child;
}
@Override
public void setDrawerListener(DrawerListener listener) {
this.mDrawerListener = listener;
}
public DrawerListener drawerListener = new DrawerListener() {
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
mDrawerOpened = slideOffset == 1;
if (mDrawerListener != null) {
mDrawerListener.onDrawerSlide(drawerView, slideOffset);
}
}
@Override
public void onDrawerOpened(View drawerView) {
if (mDrawerListener != null) {
mDrawerListener.onDrawerOpened(drawerView);
}
}
@Override
public void onDrawerClosed(View drawerView) {
MarginLayoutParams lp = (MarginLayoutParams) drawerView.getLayoutParams();
lp.width = mMinWidth;
drawerView.setLayoutParams(lp);
//revert alpha :D
UIUtils.setAlpha(mSmallView, 1);
mSmallView.bringToFront();
UIUtils.setAlpha(mLargeView, 0);
if (mDrawerListener != null) {
mDrawerListener.onDrawerClosed(drawerView);
}
}
@Override
public void onDrawerStateChanged(int newState) {
if (mDrawerListener != null) {
mDrawerListener.onDrawerStateChanged(newState);
}
}
};
@Override
public boolean dispatchTouchEvent(MotionEvent motionEvent) {
if (mDrawerOpened) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
mTouchDown = motionEvent.getX();
mPrevTouch = motionEvent.getX();
return super.dispatchTouchEvent(motionEvent);
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
boolean click = mTouchDown == mPrevTouch;
mTouchDown = -1;
mPrevTouch = -1;
MarginLayoutParams lp = (MarginLayoutParams) mContainer.getLayoutParams();
float percentage = calculatePercentage(lp.width);
if (percentage > 50) {
fadeUp(DEFAULT_ANIMATION);
} else {
fadeDown(DEFAULT_ANIMATION);
}
if (click) {
return super.dispatchTouchEvent(motionEvent);
} else {
return true;
}
} else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE && mTouchDown != -1) {
MarginLayoutParams lp = (MarginLayoutParams) mContainer.getLayoutParams();
//the current drawer width
float diff = motionEvent.getX() - mTouchDown;
if (diff == 0) {
//no difference nothing to do
return super.dispatchTouchEvent(motionEvent);
} else if (diff > 0 && lp.width <= mMaxWidth && (lp.width + diff) < mMaxWidth && lp.width >= mMinWidth) {
lp.width = (int) (lp.width + diff);
mContainer.setLayoutParams(lp);
mTouchDown = motionEvent.getX();
overlapViews(lp.width);
} else if (diff < 0 && lp.width >= mMinWidth && (lp.width + diff) > mMinWidth) {
lp.width = (int) (lp.width + diff);
mContainer.setLayoutParams(lp);
mTouchDown = motionEvent.getX();
overlapViews(lp.width);
} else if (lp.width < mMinWidth) {
lp.width = mMinWidth;
mContainer.setLayoutParams(lp);
mDrawerOpened = false;
mTouchDown = -1;
overlapViews(mMinWidth);
}
return true;
}
}
return super.dispatchTouchEvent(motionEvent);
}
@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
try {
return super.onTouchEvent(motionEvent);
} catch (RuntimeException ex) {
ex.printStackTrace();
}
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
try {
return super.onInterceptTouchEvent(ev);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
}
return false;
}
/**
* crossfade the small to the large view (with default animation time)
*/
public void crossfade() {
crossfade(DEFAULT_ANIMATION);
}
/**
* crossfade the small to the large view
*
* @param duration
*/
public void crossfade(int duration) {
if (isCrossfaded()) {
fadeDown(duration);
} else {
fadeUp(duration);
}
}
/**
* animate to the large view
*
* @param duration
*/
public void fadeUp(int duration) {
//animate up
mContainer.clearAnimation();
ResizeWidthAnimation anim = new ResizeWidthAnimation(mContainer, mMaxWidth, new ApplyTransformationListener() {
@Override
public void applyTransformation(int width) {
overlapViews(width);
}
});
anim.setDuration(duration);
mContainer.startAnimation(anim);
}
/**
* animate to the small view
*
* @param duration
*/
public void fadeDown(int duration) {
//fade down
mContainer.clearAnimation();
ResizeWidthAnimation anim = new ResizeWidthAnimation(mContainer, mMinWidth, new ApplyTransformationListener() {
@Override
public void applyTransformation(int width) {
overlapViews(width);
}
});
anim.setDuration(duration);
mContainer.startAnimation(anim);
}
/**
* calculate the percentage to how many percent the slide is already visible
*
* @param width
* @return
*/
private float calculatePercentage(int width) {
int absolute = mMaxWidth - mMinWidth;
int current = width - mMinWidth;
float percentage = 100.0f * current / absolute;
//we can assume that we are crossfaded if the percentage is > 90
mIsCrossfaded = percentage > 90;
return percentage;
}
//remember the previous width to optimize performance
private int mWidth = -1;
/**
* overlap the views and provide the crossfade effect
*
* @param width
*/
private void overlapViews(int width) {
if (width == mWidth) {
return;
}
//remember this width so it is't processed twice
mWidth = width;
float percentage = calculatePercentage(width);
float alpha = percentage / 100;
UIUtils.setAlpha(mSmallView, 1);
mSmallView.setClickable(false);
mLargeView.bringToFront();
UIUtils.setAlpha(mLargeView, alpha);
mLargeView.setClickable(true);
mLargeView.setVisibility(alpha > 0.01f ? View.VISIBLE : View.GONE);
//notify the crossfadeListener
if (mCrossfadeListener != null) {
mCrossfadeListener.onCrossfade(mContainer, calculatePercentage(width), width);
}
}
public interface CrossfadeListener {
void onCrossfade(View containerView, float currentSlidePercentage, int slideOffset);
}
}
|
package org.opendaylight.ovsdb.lib.notation.json;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.jsontype.TypeIdResolver;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.opendaylight.ovsdb.lib.notation.OvsdbSet;
import org.opendaylight.ovsdb.lib.notation.UUID;
public class OvsdbTypesIdResolver implements TypeIdResolver {
private JavaType baseType;
@Override
public void init(JavaType bt) {
this.baseType = bt;
}
@Override
public String idFromValue(Object value) {
throw new UnsupportedOperationException("not yet done");
}
@Override
public String idFromValueAndType(Object value, Class<?> suggestedType) {
throw new UnsupportedOperationException("not yet done");
}
@Override
public String idFromBaseType() {
throw new UnsupportedOperationException("not yet done");
}
@Override
public JavaType typeFromId(String id) {
if ("set".equals(id)) {
return TypeFactory.defaultInstance().constructCollectionType(OvsdbSet.class, Object.class);
} else if ("uuid".equals(id) || "named-uuid".equals(id)) {
return TypeFactory.defaultInstance().constructType(UUID.class);
}
return null;
}
@Override
public JsonTypeInfo.Id getMechanism() {
throw new UnsupportedOperationException("not yet done");
}
}
|
package edu.ucsf.lava.crms.importer.model;
import edu.ucsf.lava.core.importer.model.ImportDefinition;
import edu.ucsf.lava.core.model.EntityBase;
import edu.ucsf.lava.core.model.EntityManager;
public class CrmsImportDefinition extends ImportDefinition {
public static EntityManager MANAGER = new EntityBase.Manager(CrmsImportDefinition.class);
// if does not exist, will be created. support re-runnable imports. note that for instruments,
// additional requirement is that if it does exist it must not have data entered, as do not
// want to overwrite data
public static Short MAY_OR_MAY_NOT_EXIST = 1;
// ensure that a duplicate record is not created. supports import updates.
public static Short MUST_EXIST = 2;
// entity will be created. does not support re-runnable in that entity will exist for all
// subsequent imports so just create a warning instead of an error for this (in other words,
// this flag means entity must not exist prior to the first import which creates the entity)
public static Short MUST_NOT_EXIST = 3;
//TODO:
// for visit and time format fields (birthDateFormat, visitDateFormat, visitTimeFormat) have dropdown list with
// common formats but make it a suggest field. Info text regarding default values
// same with dcStatus but not sure about the suggest bc do not have suggest on regular dcStatus ??
// within the context of REDCap?? pretty sure Songster does updates in Excel
private Short patientExistRule;
// currently this flag is not used unless it is determined that import files should be able to overwrite
// existing Patient data
private Boolean allowPatientUpdate;
//?? need flags for Caregiver, Contact Info, etc.. or just handle that with property names in mapping file?
// note that pediLAVA new patient history could have multiple caregivers, also caregivers may have contact info
// this is used both for importing data in the context of a specific project, and to provide context for
// lists for other property values that are dependent on projName (visitType, visitWith, visitLocation)
private String projName;
// Enrollment Status
private Short esExistRule;
// currently this flag is not used unless it is determined that import files should be able to overwrite
// existing EnrollmentStatus data
private Boolean allowEsUpdate;
private String esStatus;
// VIsit
private Short visitExistRule;
// currently this flag is not used unless it is determined that import files should be able to overwrite
// existing Visit data
private Boolean allowVisitUpdate;
// if import will create new Visits, account for all Visit required fields
// visitDate (and optionally visitTime) must be present in the data file (mapped to either visitDate or
// dcDate). the rest of the required fields may not be in the data file so need to be supplied as part of
// the definition
private String visitType;
private String visitWith;
private String visitLoc;
private String visitStatus;
// Instrument
private Short instrExistRule;
// note that this flag applies to instruments that have already been data entered. if an instrument exists
// but has not been data entered then this flag need not be considered as no data will be overwritten by import
private Boolean allowInstrUpdate;
private String instrType;
private String instrVer;
private String instrDcStatus;
public CrmsImportDefinition(){
super();
this.setAuditEntityType("CrmsImportDefinition");
}
public Short getPatientExistRule() {
return patientExistRule;
}
public void setPatientExistRule(Short patientExistRule) {
this.patientExistRule = patientExistRule;
}
public Boolean getAllowPatientUpdate() {
return allowPatientUpdate;
}
public void setAllowPatientUpdate(Boolean allowPatientUpdate) {
this.allowPatientUpdate = allowPatientUpdate;
}
public String getProjName() {
return projName;
}
public void setProjName(String projName) {
this.projName = projName;
}
public Short getEsExistRule() {
return esExistRule;
}
public void setEsExistRule(Short esExistRule) {
this.esExistRule = esExistRule;
}
public Boolean getAllowEsUpdate() {
return allowEsUpdate;
}
public void setAllowEsUpdate(Boolean allowEsUpdate) {
this.allowEsUpdate = allowEsUpdate;
}
public String getEsStatus() {
return esStatus;
}
public void setEsStatus(String esStatus) {
this.esStatus = esStatus;
}
public Short getVisitExistRule() {
return visitExistRule;
}
public void setVisitExistRule(Short visitExistRule) {
this.visitExistRule = visitExistRule;
}
public Boolean getAllowVisitUpdate() {
return allowVisitUpdate;
}
public void setAllowVisitUpdate(Boolean allowVisitUpdate) {
this.allowVisitUpdate = allowVisitUpdate;
}
public String getVisitType() {
return visitType;
}
public void setVisitType(String visitType) {
this.visitType = visitType;
}
public String getVisitWith() {
return visitWith;
}
public void setVisitWith(String visitWith) {
this.visitWith = visitWith;
}
public String getVisitLoc() {
return visitLoc;
}
public void setVisitLoc(String visitLoc) {
this.visitLoc = visitLoc;
}
public String getVisitStatus() {
return visitStatus;
}
public void setVisitStatus(String visitStatus) {
this.visitStatus = visitStatus;
}
public Short getInstrExistRule() {
return instrExistRule;
}
public void setInstrExistRule(Short instrExistRule) {
this.instrExistRule = instrExistRule;
}
public Boolean getAllowInstrUpdate() {
return allowInstrUpdate;
}
public void setAllowInstrUpdate(Boolean allowInstrUpdate) {
this.allowInstrUpdate = allowInstrUpdate;
}
public String getInstrType() {
return instrType;
}
public void setInstrType(String instrType) {
this.instrType = instrType;
}
public String getInstrVer() {
return instrVer;
}
public void setInstrVer(String instrVer) {
this.instrVer = instrVer;
}
public String getInstrDcStatus() {
return instrDcStatus;
}
public void setInstrDcStatus(String instrDcStatus) {
this.instrDcStatus = instrDcStatus;
}
}
|
package engine;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
class Search {
private Search() {
// This class should not be instantiated
throw new IllegalStateException();
}
/**
* A BFS Implementation to find the shortest path from src to tgt. Since
* this is BFS, the shortest path is in terms of length, not weights.
*
* @param g the Graph
* @param src the node to start BFS from
* @param tgt the node to end BFS at
* @param flow whether or not this is BFS on a flow graph
* @return the shortest path from src to tgt.
*/
static List<Node> bfs(Graph g, Node src, Node tgt, boolean flow) {
if (g == null || src == null) {
throw new IllegalArgumentException();
}
if (src == tgt) {
LinkedList<Node> output = new LinkedList<>();
output.add(tgt);
return output;
}
// The nodes we've explored
HashSet<Node> explored = new HashSet<>();
explored.add(src);
// Keeps track of the parents of each node
Map<Node, Node> parents = new HashMap<>();
parents.put(src, null);
// Keep track of nodes to be visited
Queue<Node> q = new LinkedList<>();
q.add(src);
while (!q.isEmpty()) {
Node user = q.poll();
Set<Edge> following = user.getEdges();
for (Edge e : following) {
Node n = e.getTgt();
if (n == tgt) {
parents.put(n, user);
// We found the target node
Node i = n;
LinkedList<Node> output = new LinkedList<>();
output.addFirst(i);
while (parents.get(i) != null) {
output.addFirst(parents.get(i));
i = parents.get(i);
}
return output;
}
if ((flow && e.getWeight() - e.getFlow() > 0) || !flow) {
if (!explored.contains(n)) {
explored.add(n);
q.add(n);
parents.put(n, user);
}
}
}
}
// If there is no path
return new LinkedList<>();
}
/**
* function performs DFS on given graph and returns
* a map of Nodes in graph to a list of integers.
* The list contains a start time and a finish time
* for each Node.
*
* @param g the Graph
* @param src the Node to start DFS
* @return a mapping of start and finish times for
* each node
*/
static Map<Node, List<Integer>> dfs(Graph g, Node src) {
if (g == null || src == null) {
throw new IllegalArgumentException();
}
Set<Node> nodes = g.getAllNodes();
//A mapping of a Node to its corresponding finish time
Map<Node, List<Integer>> timeStamps =
new HashMap<Node, List<Integer>>();
//Set keeping track gray nodes
Set<Node> visited = new HashSet<Node>();
//stack to perform depth first search
Stack<Node> stack = new Stack<Node>();
stack.push(src);
//counter to record finish times
int counter = 1;
while (!stack.empty()) {
Node a = stack.peek();
//If node has not been visited yet
if (!visited.contains(a)) {
visited.add(a);
stamp(timeStamps, a, counter);
Set<Node> neighbors = a.getNeighbors();
for (Node n : neighbors) {
if (!visited.contains(n))
stack.add(n);
}
}
/*If node has already been visited then stamp finish time and
pop from stack. If stack is empty then search the graph for
unvisited nodes. */
else {
stamp(timeStamps, a, counter);
stack.pop();
if (stack.isEmpty() &&
getUnvisited(nodes, visited) != null) {
stack.push(getUnvisited(nodes, visited));
}
}
counter++;
}
return timeStamps;
}
/**
* Function performs a topological sort on the vertices
* of a given graph by performing DFS and arrange
* vertices by descending finish times.
*
* @param g the Graph
* @return a topological sort of the vertices in the
* graph.
*/
static List<Node> topSort(Graph g) {
if (!detectCycle(g)) {
TreeMap<Node, Integer> map = new TreeMap<Node, Integer>();
Set<Node> nodes = g.getAllNodes();
Set<Node> visited = new HashSet<Node>();
Node src = getUnvisited(nodes, visited);
Map<Node, List<Integer>> timeStamps = dfs(g, src);
for (Node n : nodes) {
int finishTime = timeStamps.get(n).get(1);
map.put(n, finishTime);
}
Set<Node> keys = map.keySet();
Stack<Node> sort = new Stack<Node>();
for (Node n : keys) {
sort.push(n);
}
return sort;
} else {
throw new IllegalArgumentException();
}
}
static Map<Node, Integer> singleSourceShortestPath(Graph g, Node src) {
// TODO: Implement
// Also return something
// Implement Dijkstra's algorithm for SSSP
return null;
}
/**
* Check if n has in degree
*
* @param n the node to check
* @param graph the graph containing the node
* @return true if in degree == 0, false otherwise
*/
private static boolean checkInDegree(Node n, Set<Node> graph) {
for (Node k : graph) {
if (k.getNeighbors().contains(n)) {
return false;
}
}
return true;
}
/**
* Given a set of nodes in a graph and a set of visited nodes, function returns
an unvisited node of zero In degree. If there are no nodes of zero
in degree in remaining connected component, returns arbitrary unvisited node
*
* @param graph the set of nodes of a Graph
* @param visited a set of discovered nodes
* @return a node with zero in degree. If such a node
* does not exist then return the first unvisited node
* encountered.
*/
private static Node getUnvisited(Set<Node> graph, Set<Node> visited) {
for (Node n : graph) {
if (!visited.contains(n) && checkInDegree(n, graph)) {
return n;
}
}
for (Node n : graph) {
if (!visited.contains(n)) {
return n;
}
}
return null;
}
/**
* Given a map, a node, and an int, function adds int to the set of
integers mapped by the given node. Helper function for dfs and
cycle detection.
*
* @param map current time stamp maps
* @param n Node to be stamped
* @param i integer to stamp node with
* @return a map time stamps with given
* node stamped with given integer.
*/
private static Map<Node, List<Integer>> stamp(Map<Node,
List<Integer>> map, Node n, int i) {
if (map.containsKey(n)) {
List<Integer> set = map.get(n);
if (set.size() > 2) {
return map;
} else {
set.add(i);
map.put(n, set);
return map;
}
} else {
List<Integer> set = new LinkedList<Integer>();
map.put(n, set);
return map;
}
}
/**
* function returns a boolean checking if given graph contains a cycle.
Returns true if there exists a cycle.
*
* @param g the Graph
* @return true if there is a cycle and false otherwise
*/
private static boolean detectCycle(Graph g) {
if (g == null) {
throw new IllegalArgumentException();
}
Set<Node> nodes = g.getAllNodes();
Node src = g.getNodeByID(0);
//Set keeping track gray nodes
Set<Node> visited = new HashSet<Node>();
//stack to perform depth first search
Stack<Node> stack = new Stack<Node>();
stack.add(src);
while (!stack.empty()) {
Node a = stack.peek();
if (!visited.contains(a)) {
visited.add(a);
Set<Node> neighbors = a.getNeighbors();
for (Node n : neighbors) {
if (!visited.contains(n))
stack.add(n);
}
}
//if node is in the stack more than once,
//then a cycle exists in given graph
else {
int count = 0;
for (Node k : stack) {
if (k.equals(a)) {
count++;
}
}
if (count >= 2) {
return true;
}
stack.pop();
if (stack.isEmpty() && getUnvisited(nodes, visited) != null) {
stack.push(getUnvisited(nodes, visited));
}
}
}
return false;
}
}
|
package org.wildfly.extension.messaging.activemq;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PATH;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.ADDRESS_SETTING;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.BINDINGS_DIRECTORY;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.BROADCAST_GROUP;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.DISCOVERY_GROUP;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.HTTP_ACCEPTOR;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.INCOMING_INTERCEPTORS;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.JGROUPS_CHANNEL;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.JGROUPS_STACK;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.JOURNAL_DIRECTORY;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.LARGE_MESSAGES_DIRECTORY;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.MODULE;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.NAME;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.OUTGOING_INTERCEPTORS;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.PAGING_DIRECTORY;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.SECURITY_SETTING;
import static org.wildfly.extension.messaging.activemq.PathDefinition.PATHS;
import static org.wildfly.extension.messaging.activemq.PathDefinition.RELATIVE_TO;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.ACTIVEMQ_SERVER_CAPABILITY;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.ASYNC_CONNECTION_EXECUTION_ENABLED;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.CLUSTER_PASSWORD;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.CLUSTER_USER;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.CONNECTION_TTL_OVERRIDE;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.CREATE_BINDINGS_DIR;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.CREATE_JOURNAL_DIR;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.ID_CACHE_SIZE;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.JMX_CAPABILITY;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.JMX_DOMAIN;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.JMX_MANAGEMENT_ENABLED;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.JOURNAL_BUFFER_SIZE;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.JOURNAL_BUFFER_TIMEOUT;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.JOURNAL_COMPACT_MIN_FILES;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.JOURNAL_COMPACT_PERCENTAGE;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.JOURNAL_FILE_SIZE;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.JOURNAL_MAX_IO;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.JOURNAL_MIN_FILES;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.JOURNAL_SYNC_NON_TRANSACTIONAL;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.JOURNAL_SYNC_TRANSACTIONAL;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.JOURNAL_TYPE;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.LOG_JOURNAL_WRITE_RATE;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.MANAGEMENT_ADDRESS;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.MANAGEMENT_NOTIFICATION_ADDRESS;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.MEMORY_MEASURE_INTERVAL;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.MEMORY_WARNING_THRESHOLD;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.MESSAGE_COUNTER_MAX_DAY_HISTORY;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.MESSAGE_COUNTER_SAMPLE_PERIOD;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.MESSAGE_EXPIRY_SCAN_PERIOD;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.MESSAGE_EXPIRY_THREAD_PRIORITY;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.OVERRIDE_IN_VM_SECURITY;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.PAGE_MAX_CONCURRENT_IO;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.PERF_BLAST_PAGES;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.PERSISTENCE_ENABLED;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.PERSIST_DELIVERY_COUNT_BEFORE_DELIVERY;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.PERSIST_ID_CACHE;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.RUN_SYNC_SPEED_TEST;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.SCHEDULED_THREAD_POOL_MAX_SIZE;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.SECURITY_DOMAIN;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.SECURITY_ENABLED;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.SECURITY_INVALIDATION_INTERVAL;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.SERVER_DUMP_INTERVAL;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.STATISTICS_ENABLED;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.THREAD_POOL_MAX_SIZE;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.TRANSACTION_TIMEOUT;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.TRANSACTION_TIMEOUT_SCAN_PERIOD;
import static org.wildfly.extension.messaging.activemq.ServerDefinition.WILD_CARD_ROUTING_ENABLED;
import static org.wildfly.extension.messaging.activemq.ha.HAPolicyConfigurationBuilder.addHAPolicyConfiguration;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.management.MBeanServer;
import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration;
import org.apache.activemq.artemis.api.core.BroadcastGroupConfiguration;
import org.apache.activemq.artemis.api.core.DiscoveryGroupConfiguration;
import org.apache.activemq.artemis.api.core.Interceptor;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.config.Configuration;
import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl;
import org.apache.activemq.artemis.core.security.Role;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.JournalType;
import org.apache.activemq.artemis.core.settings.impl.AddressSettings;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.controller.services.path.PathManager;
import org.jboss.as.controller.services.path.PathManagerService;
import org.jboss.as.network.OutboundSocketBinding;
import org.jboss.as.network.SocketBinding;
import org.jboss.as.security.plugins.SecurityDomainContext;
import org.jboss.as.security.service.SecurityDomainService;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceBuilder.DependencyType;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.wildfly.clustering.jgroups.spi.ChannelFactory;
import org.wildfly.clustering.jgroups.spi.service.ProtocolStackServiceName;
import org.wildfly.extension.messaging.activemq.jms.JMSService;
import org.wildfly.extension.messaging.activemq.logging.MessagingLogger;
class ServerAdd extends AbstractAddStepHandler {
static final String PATH_BASE = "paths";
public static final ServerAdd INSTANCE = new ServerAdd();
private ServerAdd() {
super(ACTIVEMQ_SERVER_CAPABILITY, ServerDefinition.ATTRIBUTES);
}
@Override
protected Resource createResource(OperationContext context) {
ActiveMQServerResource resource = new ActiveMQServerResource();
context.addResource(PathAddress.EMPTY_ADDRESS, resource);
return resource;
}
@Override
protected void populateModel(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {
super.populateModel(context, operation, resource);
if (context.isNormalServer()) {
// add an operation to create all the messaging paths resources that have not been already been created
// prior to adding the ActiveMQ server
context.addStep(new OperationStepHandler() {
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
final ModelNode model = Resource.Tools.readModel(resource);
for (String path : PathDefinition.PATHS.keySet()) {
if (!model.get(ModelDescriptionConstants.PATH).hasDefined(path)) {
PathAddress pathAddress = PathAddress.pathAddress(PathElement.pathElement(ModelDescriptionConstants.PATH, path));
context.createResource(pathAddress);
}
}
}
}, OperationContext.Stage.MODEL);
}
}
@Override
protected void performRuntime(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {
// Add a RUNTIME step to actually install the ActiveMQ Service. This will execute after the runtime step
// added by any child resources whose ADD handler executes after this one in the model stage.
context.addStep(new OperationStepHandler() {
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
final ServiceTarget serviceTarget = context.getServiceTarget();
final String serverName = context.getCurrentAddressValue();
// Transform the configuration based on the recursive model
final ModelNode model = Resource.Tools.readModel(resource);
final Configuration configuration = transformConfig(context, serverName, model);
// Create path services
String bindingsPath = PATHS.get(BINDINGS_DIRECTORY).resolveModelAttribute(context, model.get(PATH, BINDINGS_DIRECTORY)).asString();
String bindingsRelativeToPath = RELATIVE_TO.resolveModelAttribute(context, model.get(PATH, BINDINGS_DIRECTORY)).asString();
String journalPath = PATHS.get(JOURNAL_DIRECTORY).resolveModelAttribute(context, model.get(PATH, JOURNAL_DIRECTORY)).asString();
String journalRelativeToPath = RELATIVE_TO.resolveModelAttribute(context, model.get(PATH, JOURNAL_DIRECTORY)).asString();
String largeMessagePath = PATHS.get(LARGE_MESSAGES_DIRECTORY).resolveModelAttribute(context, model.get(PATH, LARGE_MESSAGES_DIRECTORY)).asString();
String largeMessageRelativeToPath = RELATIVE_TO.resolveModelAttribute(context, model.get(PATH, LARGE_MESSAGES_DIRECTORY)).asString();
String pagingPath = PATHS.get(PAGING_DIRECTORY).resolveModelAttribute(context, model.get(PATH, PAGING_DIRECTORY)).asString();
String pagingRelativeToPath = RELATIVE_TO.resolveModelAttribute(context, model.get(PATH, PAGING_DIRECTORY)).asString();
// Create the ActiveMQ Service
final ActiveMQServerService serverService = new ActiveMQServerService(
configuration, new ActiveMQServerService.PathConfig(bindingsPath, bindingsRelativeToPath, journalPath, journalRelativeToPath, largeMessagePath, largeMessageRelativeToPath, pagingPath, pagingRelativeToPath));
processIncomingInterceptors(INCOMING_INTERCEPTORS.resolveModelAttribute(context, operation), serverService);
processOutgoingInterceptors(OUTGOING_INTERCEPTORS.resolveModelAttribute(context, operation), serverService);
// Add the ActiveMQ Service
ServiceName activeMQServiceName = MessagingServices.getActiveMQServiceName(serverName);
final ServiceBuilder<ActiveMQServer> serviceBuilder = serviceTarget.addService(activeMQServiceName, serverService);
if (context.hasOptionalCapability(JMX_CAPABILITY, ACTIVEMQ_SERVER_CAPABILITY.getDynamicName(serverName), null)) {
ServiceName jmxCapability = context.getCapabilityServiceName(JMX_CAPABILITY, MBeanServer.class);
serviceBuilder.addDependency(jmxCapability, MBeanServer.class, serverService.getMBeanServer());
}
serviceBuilder.addDependency(PathManagerService.SERVICE_NAME, PathManager.class, serverService.getPathManagerInjector());
// Add security
String domain = SECURITY_DOMAIN.resolveModelAttribute(context, model).asString();
serviceBuilder.addDependency(DependencyType.REQUIRED,
SecurityDomainService.SERVICE_NAME.append(domain),
SecurityDomainContext.class,
serverService.getSecurityDomainContextInjector());
// Process acceptors and connectors
final Set<String> socketBindings = new HashSet<String>();
TransportConfigOperationHandlers.processAcceptors(context, configuration, model, socketBindings);
// if there is any HTTP acceptor, add a dependency on the http-upgrade-registry service to
// make sure that ActiveMQ server will be stopped *after* the registry (and its underlying XNIO thread)
// is stopped.
if (model.hasDefined(HTTP_ACCEPTOR)) {
for (final Property property : model.get(HTTP_ACCEPTOR).asPropertyList()) {
String httpListener = HTTPAcceptorDefinition.HTTP_LISTENER.resolveModelAttribute(context, property.getValue()).asString();
serviceBuilder.addDependency(HTTPUpgradeService.HTTP_UPGRADE_REGISTRY.append(httpListener));
}
}
for (final String socketBinding : socketBindings) {
final ServiceName socketName = SocketBinding.JBOSS_BINDING_NAME.append(socketBinding);
serviceBuilder.addDependency(socketName, SocketBinding.class, serverService.getSocketBindingInjector(socketBinding));
}
final Set<String> outboundSocketBindings = new HashSet<String>();
TransportConfigOperationHandlers.processConnectors(context, configuration, model, outboundSocketBindings);
for (final String outboundSocketBinding : outboundSocketBindings) {
final ServiceName outboundSocketName = OutboundSocketBinding.OUTBOUND_SOCKET_BINDING_BASE_SERVICE_NAME.append(outboundSocketBinding);
// Optional dependency so it won't fail if the user used a ref to socket-binding instead of
// outgoing-socket-binding
serviceBuilder.addDependency(DependencyType.OPTIONAL, outboundSocketName, OutboundSocketBinding.class, serverService.getOutboundSocketBindingInjector(outboundSocketBinding));
if (!socketBindings.contains(outboundSocketBinding)) {
// Add a dependency on the regular socket binding as well so users don't have to use
// outgoing-socket-binding to configure a ref to the local server socket
final ServiceName socketName = SocketBinding.JBOSS_BINDING_NAME.append(outboundSocketBinding);
serviceBuilder.addDependency(DependencyType.OPTIONAL, socketName, SocketBinding.class, serverService.getSocketBindingInjector(outboundSocketBinding));
}
}
//this requires connectors
BroadcastGroupAdd.addBroadcastGroupConfigs(context, configuration, model);
final List<BroadcastGroupConfiguration> broadcastGroupConfigurations = configuration.getBroadcastGroupConfigurations();
final Map<String, DiscoveryGroupConfiguration> discoveryGroupConfigurations = configuration.getDiscoveryGroupConfigurations();
if(broadcastGroupConfigurations != null) {
for(final BroadcastGroupConfiguration config : broadcastGroupConfigurations) {
final String name = config.getName();
final String key = "broadcast" + name;
ModelNode broadcastGroupModel = model.get(BROADCAST_GROUP, name);
if (broadcastGroupModel.hasDefined(JGROUPS_CHANNEL.getName())) {
ModelNode channelFactory = JGROUPS_STACK.resolveModelAttribute(context, broadcastGroupModel);
ServiceName channelFactoryServiceName = channelFactory.isDefined() ? ProtocolStackServiceName.CHANNEL_FACTORY.getServiceName(channelFactory.asString()) : ProtocolStackServiceName.CHANNEL_FACTORY.getServiceName();
String channelName = JGROUPS_CHANNEL.resolveModelAttribute(context, broadcastGroupModel).asString();
serviceBuilder.addDependency(channelFactoryServiceName, ChannelFactory.class, serverService.getJGroupsInjector(key));
serverService.getJGroupsChannels().put(key, channelName);
} else {
final ServiceName groupBinding = GroupBindingService.getBroadcastBaseServiceName(activeMQServiceName).append(name);
serviceBuilder.addDependency(groupBinding, SocketBinding.class, serverService.getGroupBindingInjector(key));
}
}
}
if(discoveryGroupConfigurations != null) {
for(final DiscoveryGroupConfiguration config : discoveryGroupConfigurations.values()) {
final String name = config.getName();
final String key = "discovery" + name;
ModelNode discoveryGroupModel = model.get(DISCOVERY_GROUP, name);
if (discoveryGroupModel.hasDefined(JGROUPS_CHANNEL.getName())) {
ModelNode channelFactory = JGROUPS_STACK.resolveModelAttribute(context, discoveryGroupModel);
ServiceName channelFactoryServiceName = channelFactory.isDefined() ? ProtocolStackServiceName.CHANNEL_FACTORY.getServiceName(channelFactory.asString()) : ProtocolStackServiceName.CHANNEL_FACTORY.getServiceName();
String channelName = JGROUPS_CHANNEL.resolveModelAttribute(context, discoveryGroupModel).asString();
serviceBuilder.addDependency(channelFactoryServiceName, ChannelFactory.class, serverService.getJGroupsInjector(key));
serverService.getJGroupsChannels().put(key, channelName);
} else {
final ServiceName groupBinding = GroupBindingService.getDiscoveryBaseServiceName(activeMQServiceName).append(name);
serviceBuilder.addDependency(groupBinding, SocketBinding.class, serverService.getGroupBindingInjector(key));
}
}
}
// Install the ActiveMQ Service
ServiceController<ActiveMQServer> activeMQServerServiceController = serviceBuilder.install();
// Provide our custom Resource impl a ref to the ActiveMQ server so it can create child runtime resources
((ActiveMQServerResource)resource).setActiveMQServerServiceController(activeMQServerServiceController);
// Install the JMSService
boolean overrideInVMSecurity = OVERRIDE_IN_VM_SECURITY.resolveModelAttribute(context, operation).asBoolean();
JMSService.addService(serviceTarget, activeMQServiceName, overrideInVMSecurity);
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
}, OperationContext.Stage.RUNTIME);
}
/**
* Transform the detyped operation parameters into the ActiveMQ configuration.
*
* @param context the operation context
* @param serverName the name of the ActiveMQ instance
* @param model the subsystem root resource model
* @return the ActiveMQ configuration
*/
private Configuration transformConfig(final OperationContext context, String serverName, final ModelNode model) throws OperationFailedException {
Configuration configuration = new ConfigurationImpl();
configuration.setName(serverName);
configuration.setEnabledAsyncConnectionExecution(ASYNC_CONNECTION_EXECUTION_ENABLED.resolveModelAttribute(context, model).asBoolean());
configuration.setClusterPassword(CLUSTER_PASSWORD.resolveModelAttribute(context, model).asString());
configuration.setClusterUser(CLUSTER_USER.resolveModelAttribute(context, model).asString());
configuration.setConnectionTTLOverride(CONNECTION_TTL_OVERRIDE.resolveModelAttribute(context, model).asInt());
configuration.setCreateBindingsDir(CREATE_BINDINGS_DIR.resolveModelAttribute(context, model).asBoolean());
configuration.setCreateJournalDir(CREATE_JOURNAL_DIR.resolveModelAttribute(context, model).asBoolean());
configuration.setIDCacheSize(ID_CACHE_SIZE.resolveModelAttribute(context, model).asInt());
// TODO do we want to allow the jmx configuration ?
configuration.setJMXDomain(JMX_DOMAIN.resolveModelAttribute(context, model).asString());
configuration.setJMXManagementEnabled(JMX_MANAGEMENT_ENABLED.resolveModelAttribute(context, model).asBoolean());
// Journal
final JournalType journalType = JournalType.valueOf(JOURNAL_TYPE.resolveModelAttribute(context, model).asString());
configuration.setJournalType(journalType);
// AIO Journal
configuration.setJournalBufferSize_AIO(JOURNAL_BUFFER_SIZE.resolveModelAttribute(context, model).asInt(ActiveMQDefaultConfiguration.getDefaultJournalBufferSizeAio()));
configuration.setJournalBufferTimeout_AIO(JOURNAL_BUFFER_TIMEOUT.resolveModelAttribute(context, model).asInt(ActiveMQDefaultConfiguration.getDefaultJournalBufferTimeoutAio()));
configuration.setJournalMaxIO_AIO(JOURNAL_MAX_IO.resolveModelAttribute(context, model).asInt(ActiveMQDefaultConfiguration.getDefaultJournalMaxIoAio()));
// NIO Journal
configuration.setJournalBufferSize_NIO(JOURNAL_BUFFER_SIZE.resolveModelAttribute(context, model).asInt(ActiveMQDefaultConfiguration.getDefaultJournalBufferSizeNio()));
configuration.setJournalBufferTimeout_NIO(JOURNAL_BUFFER_TIMEOUT.resolveModelAttribute(context, model).asInt(ActiveMQDefaultConfiguration.getDefaultJournalBufferTimeoutNio()));
configuration.setJournalMaxIO_NIO(JOURNAL_MAX_IO.resolveModelAttribute(context, model).asInt(ActiveMQDefaultConfiguration.getDefaultJournalMaxIoNio()));
configuration.setJournalCompactMinFiles(JOURNAL_COMPACT_MIN_FILES.resolveModelAttribute(context, model).asInt());
configuration.setJournalCompactPercentage(JOURNAL_COMPACT_PERCENTAGE.resolveModelAttribute(context, model).asInt());
configuration.setJournalFileSize(JOURNAL_FILE_SIZE.resolveModelAttribute(context, model).asInt());
configuration.setJournalMinFiles(JOURNAL_MIN_FILES.resolveModelAttribute(context, model).asInt());
configuration.setJournalSyncNonTransactional(JOURNAL_SYNC_NON_TRANSACTIONAL.resolveModelAttribute(context, model).asBoolean());
configuration.setJournalSyncTransactional(JOURNAL_SYNC_TRANSACTIONAL.resolveModelAttribute(context, model).asBoolean());
configuration.setLogJournalWriteRate(LOG_JOURNAL_WRITE_RATE.resolveModelAttribute(context, model).asBoolean());
configuration.setManagementAddress(SimpleString.toSimpleString(MANAGEMENT_ADDRESS.resolveModelAttribute(context, model).asString()));
configuration.setManagementNotificationAddress(SimpleString.toSimpleString(MANAGEMENT_NOTIFICATION_ADDRESS.resolveModelAttribute(context, model).asString()));
configuration.setMemoryMeasureInterval(MEMORY_MEASURE_INTERVAL.resolveModelAttribute(context, model).asLong());
configuration.setMemoryWarningThreshold(MEMORY_WARNING_THRESHOLD.resolveModelAttribute(context, model).asInt());
configuration.setMessageCounterEnabled(STATISTICS_ENABLED.resolveModelAttribute(context, model).asBoolean());
configuration.setMessageCounterSamplePeriod(MESSAGE_COUNTER_SAMPLE_PERIOD.resolveModelAttribute(context, model).asInt());
configuration.setMessageCounterMaxDayHistory(MESSAGE_COUNTER_MAX_DAY_HISTORY.resolveModelAttribute(context, model).asInt());
configuration.setMessageExpiryScanPeriod(MESSAGE_EXPIRY_SCAN_PERIOD.resolveModelAttribute(context, model).asLong());
configuration.setMessageExpiryThreadPriority(MESSAGE_EXPIRY_THREAD_PRIORITY.resolveModelAttribute(context, model).asInt());
configuration.setJournalPerfBlastPages(PERF_BLAST_PAGES.resolveModelAttribute(context, model).asInt());
configuration.setPersistDeliveryCountBeforeDelivery(PERSIST_DELIVERY_COUNT_BEFORE_DELIVERY.resolveModelAttribute(context, model).asBoolean());
configuration.setPageMaxConcurrentIO(PAGE_MAX_CONCURRENT_IO.resolveModelAttribute(context, model).asInt());
configuration.setPersistenceEnabled(PERSISTENCE_ENABLED.resolveModelAttribute(context, model).asBoolean());
configuration.setPersistIDCache(PERSIST_ID_CACHE.resolveModelAttribute(context, model).asBoolean());
configuration.setRunSyncSpeedTest(RUN_SYNC_SPEED_TEST.resolveModelAttribute(context, model).asBoolean());
configuration.setScheduledThreadPoolMaxSize(SCHEDULED_THREAD_POOL_MAX_SIZE.resolveModelAttribute(context, model).asInt());
configuration.setSecurityEnabled(SECURITY_ENABLED.resolveModelAttribute(context, model).asBoolean());
configuration.setSecurityInvalidationInterval(SECURITY_INVALIDATION_INTERVAL.resolveModelAttribute(context, model).asLong());
configuration.setServerDumpInterval(SERVER_DUMP_INTERVAL.resolveModelAttribute(context, model).asLong());
configuration.setThreadPoolMaxSize(THREAD_POOL_MAX_SIZE.resolveModelAttribute(context, model).asInt());
configuration.setTransactionTimeout(TRANSACTION_TIMEOUT.resolveModelAttribute(context, model).asLong());
configuration.setTransactionTimeoutScanPeriod(TRANSACTION_TIMEOUT_SCAN_PERIOD.resolveModelAttribute(context, model).asLong());
configuration.setWildcardRoutingEnabled(WILD_CARD_ROUTING_ENABLED.resolveModelAttribute(context, model).asBoolean());
addHAPolicyConfiguration(context, configuration, model);
processAddressSettings(context, configuration, model);
processSecuritySettings(context, configuration, model);
// Add in items from child resources
GroupingHandlerAdd.addGroupingHandlerConfig(context,configuration, model);
DiscoveryGroupAdd.addDiscoveryGroupConfigs(context, configuration, model);
DivertAdd.addDivertConfigs(context, configuration, model);
QueueAdd.addQueueConfigs(context, configuration, model);
BridgeAdd.addBridgeConfigs(context, configuration, model);
ClusterConnectionAdd.addClusterConnectionConfigs(context, configuration, model);
ConnectorServiceDefinition.addConnectorServiceConfigs(context, configuration, model);
return configuration;
}
/**
* Process the address settings.
*
* @param configuration the ActiveMQ configuration
* @param params the detyped operation parameters
*/
/**
* Process the address settings.
*
* @param configuration the ActiveMQ configuration
* @param params the detyped operation parameters
* @throws org.jboss.as.controller.OperationFailedException
*/
static void processAddressSettings(final OperationContext context, final Configuration configuration, final ModelNode params) throws OperationFailedException {
if (params.hasDefined(ADDRESS_SETTING)) {
for (final Property property : params.get(ADDRESS_SETTING).asPropertyList()) {
final String match = property.getName();
final ModelNode config = property.getValue();
final AddressSettings settings = AddressSettingAdd.createSettings(context, config);
configuration.getAddressesSettings().put(match, settings);
}
}
}
private List<Class> unwrapClasses(List<ModelNode> classesModel) throws OperationFailedException {
List<Class> classes = new ArrayList<>();
for (ModelNode classModel : classesModel) {
String className = classModel.get(NAME).asString();
String moduleName = classModel.get(MODULE).asString();
try {
ModuleIdentifier moduleID = ModuleIdentifier.create(moduleName);
Module module = Module.getCallerModuleLoader().loadModule(moduleID);
Class<?> clazz = module.getClassLoader().loadClass(className);
classes.add(clazz);
} catch (Exception e) {
throw MessagingLogger.ROOT_LOGGER.unableToLoadClassFromModule(className, moduleName);
}
}
return classes;
}
private void processIncomingInterceptors(ModelNode model, ActiveMQServerService serverService) throws OperationFailedException {
if (!model.isDefined()) {
return;
}
List<ModelNode> interceptors = model.asList();
for (Class clazz : unwrapClasses(interceptors)) {
try {
Interceptor interceptor = Interceptor.class.cast(clazz.newInstance());
serverService.getIncomingInterceptors().add(interceptor);
} catch (Exception e) {
throw new OperationFailedException(e);
}
}
}
private void processOutgoingInterceptors(ModelNode model, ActiveMQServerService serverService) throws OperationFailedException {
if (!model.isDefined()) {
return;
}
List<ModelNode> interceptors = model.asList();
for (Class clazz : unwrapClasses(interceptors)) {
try {
Interceptor interceptor = Interceptor.class.cast(clazz.newInstance());
serverService.getOutgoingInterceptors().add(interceptor);
} catch (Exception e) {
throw new OperationFailedException(e);
}
}
}
/**
* Process the security settings.
*
* @param configuration the ActiveMQ configuration
* @param params the detyped operation parameters
*/
static void processSecuritySettings(final OperationContext context, final Configuration configuration, final ModelNode params) throws OperationFailedException {
if (params.get(SECURITY_SETTING).isDefined()) {
for (final Property property : params.get(SECURITY_SETTING).asPropertyList()) {
final String match = property.getName();
final ModelNode config = property.getValue();
if(config.hasDefined(CommonAttributes.ROLE)) {
final Set<Role> roles = new HashSet<Role>();
for (final Property role : config.get(CommonAttributes.ROLE).asPropertyList()) {
roles.add(SecurityRoleDefinition.transform(context, role.getName(), role.getValue()));
}
configuration.getSecurityRoles().put(match, roles);
}
}
}
}
}
|
package net.sf.mmm.util.nls;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.Reader;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
import net.sf.mmm.util.io.StreamUtil;
import net.sf.mmm.util.nls.api.NlsMessage;
import net.sf.mmm.util.nls.api.NlsTemplateResolver;
import net.sf.mmm.util.nls.base.NlsBundleSynchronizer;
import net.sf.mmm.util.nls.impl.NlsTemplateResolverImpl;
/**
* This class can be used to create and update the localized bundles
* (properties) from an {@link AbstractResourceBundle}.<br>
* <b>ATTENTION:</b><br>
* This class only works with java 6 or above.
*
* @author Joerg Hohwiller (hohwille at users.sourceforge.net)
*/
public class ResourceBundleSynchronizer {
/** @see #getBasePath() */
private static final String DEFAULT_BASE_PATH = "src/main/resources";
/** @see #getEncoding() */
private static final String DEFAULT_ENCODING = "UTF-8";
/** @see #getEncoding() */
private static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss Z";
/** @see #getLocales() */
private String[] locales;
/** @see #getBasePath() */
private String basePath;
/** @see #getEncoding() */
private String encoding;
/** @see #getNewline() */
private String newline;
/** @see #getDatePattern() */
private String datePattern;
/** @see #getStreamUtil() */
private StreamUtil streamUtil;
/** @see #getOut() */
private PrintStream out;
/**
* The constructor.
*/
public ResourceBundleSynchronizer() {
super();
this.basePath = DEFAULT_BASE_PATH;
this.datePattern = DEFAULT_DATE_PATTERN;
this.encoding = DEFAULT_ENCODING;
this.newline = "\n";
this.locales = new String[] { "" };
this.out = System.out;
}
/**
* @return the out-stream where to print information to.
*/
public PrintStream getOut() {
return this.out;
}
/**
* This method gets the pattern used to format the date comment.
*
* @see SimpleDateFormat
*
* @return the date pattern.
*/
public String getDatePattern() {
return this.datePattern;
}
/**
* @param datePattern the datePattern to set
*/
public void setDatePattern(String datePattern) {
this.datePattern = datePattern;
}
/**
* This method gets the locales of the bundles that should be
* {@link #synchronize(ResourceBundle) synchronized}. Examples for locales
* (entries of the returned array) are <code>""</code>, <code></code>
*
* @return the locales to create/update.
*/
public String[] getLocales() {
return this.locales;
}
/**
* This method sets the {@link #getLocales() locales}.
*
* @param locales are the locales to set
*/
public void setLocales(String[] locales) {
this.locales = locales;
}
/**
* This method sets the {@link #getLocales() locales}.
*
* @param locales are the locales to set
*/
public void setLocales(Locale[] locales) {
this.locales = new String[locales.length];
for (int i = 0; i < locales.length; i++) {
this.locales[i] = locales[i].toString();
}
}
/**
* This method gets the base-path where the bundles are written to. They will
* appear there under their appropriate classpath. The default is
* {@link #DEFAULT_BASE_PATH}.
*
* @return the basePath is the base path where the resource bundles are
* written to.
*/
public String getBasePath() {
return this.basePath;
}
/**
* This method sets the {@link #getBasePath() base-path}.
*
* @param basePath the basePath to set
*/
public void setBasePath(String basePath) {
this.basePath = basePath;
}
/**
* This method gets the encoding used to read and write the bundles. The
* default is <code>UTF-8</code>.
*
* @return the encoding.
*/
public String getEncoding() {
return this.encoding;
}
/**
* This method sets the {@link #getEncoding() encoding}.
*
* @param encoding the encoding to set
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}
/**
* This method sets the newline string used to terminate a line in the
* resource bundle. The default is LF (<code>\n</code>).
*
* @return the newline
*/
public String getNewline() {
return this.newline;
}
/**
* @param newline the newline to set
*/
public void setNewline(String newline) {
this.newline = newline;
}
/**
* This method gets the {@link StreamUtil} instance to use.
*
* @return the {@link StreamUtil}.
*/
public StreamUtil getStreamUtil() {
if (this.streamUtil == null) {
this.streamUtil = StreamUtil.getInstance();
}
return this.streamUtil;
}
/**
* This method sets the {@link #getStreamUtil() StreamUtil}.
*
* @param streamUtil is the {@link StreamUtil} instance to use.
*/
public void setStreamUtil(StreamUtil streamUtil) {
this.streamUtil = streamUtil;
}
/**
* This method synchronizes (creates or updates) the localized bundles
* (properties). If a bundle already exists, it will NOT just be overwritten
* but the missing keys are appended to the end of the file. If no keys are
* missing, the existing file remains untouched.
*
* @param bundle is the bundle instance as java object.
* @throws IOException if the operation failed with an input/output error.
*/
public void synchronize(ResourceBundle bundle) throws IOException {
if (bundle.keySet().isEmpty()) {
this.out.println(bundle.getClass().getName() + " is empty - noting to do!");
return;
}
SimpleDateFormat sdf = new SimpleDateFormat(this.datePattern);
String date = sdf.format(new Date());
String path = this.basePath + File.separatorChar
+ bundle.getClass().getName().replace('.', File.separatorChar);
new File(path).getParentFile().mkdirs();
for (String locale : this.locales) {
StringBuffer pathBuffer = new StringBuffer(path);
if (locale.length() > 0) {
pathBuffer.append('_');
pathBuffer.append(locale);
}
pathBuffer.append(".properties");
File file = new File(pathBuffer.toString());
Properties existingBundle;
boolean update = file.exists();
if (update) {
this.out.println("Updating " + file.getPath());
FileInputStream in = new FileInputStream(file);
Reader reader = new InputStreamReader(in, this.encoding);
existingBundle = getStreamUtil().loadProperties(reader);
} else {
this.out.println("Creating " + file.getPath());
existingBundle = new Properties();
}
StringBuffer buffer = new StringBuffer();
for (String key : bundle.keySet()) {
if (!existingBundle.containsKey(key)) {
String value = bundle.getString(key);
buffer.append(key);
buffer.append(" = ");
if (locale.length() > 0) {
buffer.append("TODO(");
buffer.append(locale);
buffer.append("):");
}
value = value.replace("\r", "");
value = value.replace("\n", "\\n");
buffer.append(value);
buffer.append(this.newline);
}
}
if (buffer.length() > 0) {
OutputStream outStream = new FileOutputStream(file, update);
try {
Writer writer = new OutputStreamWriter(outStream, this.encoding);
if (update) {
writer.append("# Updated ");
} else {
writer.append("# Generated ");
}
writer.append(date);
writer.append(this.newline);
writer.write(buffer.toString());
writer.flush();
writer.close();
outStream = null;
} finally {
if (outStream != null) {
outStream.close();
}
}
}
}
}
/**
* This method prints the usage of this class.
*/
public void usage() {
NlsMessage message = NlsAccess.getFactory().create(
NlsBundleSynchronizer.MSG_SYNCHRONIZER_USAGE, ResourceBundleSynchronizer.class.getName(),
DEFAULT_ENCODING, DEFAULT_BASE_PATH, DEFAULT_DATE_PATTERN,
NlsBundleSynchronizer.class.getName());
NlsTemplateResolver nationalizer = new NlsTemplateResolverImpl(new NlsBundleSynchronizer());
this.out.println(message.getLocalizedMessage(Locale.getDefault(), nationalizer));
}
/**
* The non-static version of the {@link #main(String[]) main-method}.
*
* @param arguments are the commandline arguments.
* @return the exit-code. <code>0</code> for success, anything else if
* something went wrong.
* @throws Exception if the operation failed.
*/
public int run(String[] arguments) throws Exception {
String bundleClassName = null;
List<String> currentLocales = new ArrayList<String>();
currentLocales.add("");
for (int argIndex = 0; argIndex < arguments.length; argIndex++) {
String arg = arguments[argIndex];
if ((arg.length() > 0) && (arg.charAt(0) == '-')) {
if ("--help".equals(arg)) {
usage();
return 0;
}
argIndex++;
if ((bundleClassName != null) || (argIndex < arguments.length)) {
usage();
return -1;
}
String value = arguments[argIndex];
if ("--encoding".equals(arg)) {
setEncoding(value);
} else if ("--path".equals(arg)) {
setBasePath(value);
} else if ("--date-pattern".equals(arg)) {
setDatePattern(value);
} else {
this.out.println("Error: unknown option '" + arg + "'!");
usage();
return -1;
}
} else if (bundleClassName == null) {
bundleClassName = arg;
} else {
currentLocales.add(arg);
}
}
if (bundleClassName == null) {
this.out.println("Error: <bundle-class> not specified!");
usage();
return -1;
}
String[] localeArray = currentLocales.toArray(new String[currentLocales.size()]);
setLocales(localeArray);
Class<?> bundleClass = Class.forName(bundleClassName);
if (!ResourceBundle.class.isAssignableFrom(bundleClass)) {
throw new IllegalArgumentException("Given class '" + bundleClassName + "' does NOT extend '"
+ ResourceBundle.class.getName() + "'!");
}
ResourceBundle bundle = (ResourceBundle) bundleClass.newInstance();
synchronize(bundle);
return 0;
}
/**
* This is the main method used to run this class as application.
*
* @param arguments are the commandline arguments.
*/
public static void main(String[] arguments) {
ResourceBundleSynchronizer synchronizer = new ResourceBundleSynchronizer();
int exitCode;
try {
exitCode = synchronizer.run(arguments);
System.exit(exitCode);
} catch (Exception e) {
e.printStackTrace(System.out);
System.exit(-1);
}
}
}
|
package com.intellij.psi.tree;
import com.intellij.lang.Language;
import com.intellij.lang.LanguageExtensionPoint;
import com.intellij.lang.ParserDefinition;
import com.intellij.lang.PsiParser;
import com.intellij.lexer.Lexer;
import com.intellij.mock.MockPsiFile;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase;
import gnu.trove.THashMap;
import gnu.trove.TObjectIntHashMap;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
* @author gregsh
*/
public abstract class IElementTypeTest extends LightPlatformCodeInsightFixtureTestCase {
// load all parser definitions, instantiate all lexers & parsers to initialize all IElementType constants
@SuppressWarnings("UnusedDeclaration")
public void testCount() throws Exception {
int count = IElementType.getAllocatedTypesCount();
System.out.println("Preloaded: " + count +" element types");
List<LanguageExtensionPoint> extensions = ExtensionPointName.<LanguageExtensionPoint>create("com.intellij.lang.parserDefinition").getExtensionList();
System.out.println("ParserDefinitions: " + extensions.size());
THashMap<Language, String> languageMap = new THashMap<Language, String>();
languageMap.put(Language.ANY, "platform");
final TObjectIntHashMap<String> map = new TObjectIntHashMap<String>();
for (LanguageExtensionPoint e : extensions) {
String key = e.getPluginDescriptor().getPluginId().getIdString();
int curCount = IElementType.getAllocatedTypesCount();
ParserDefinition definition = (ParserDefinition)e.getInstance();
IFileElementType type = definition.getFileNodeType();
Language language = type.getLanguage();
languageMap.put(language, key);
if (language.getBaseLanguage() != null && !languageMap.containsKey(language.getBaseLanguage())) {
languageMap.put(language.getBaseLanguage(), key);
}
try {
Lexer lexer = definition.createLexer(MockPsiFile.DUMMY_LANG_VERSION);
PsiParser parser = definition.createParser(MockPsiFile.DUMMY_LANG_VERSION);
}
catch (UnsupportedOperationException e1) {
}
// language-based calculation: per-class-loading stuff commented
//int diff = IElementType.getAllocatedTypesCount() - curCount;
//map.put(key, map.get(key) + diff);
}
// language-based calculation
count = IElementType.getAllocatedTypesCount();
for (short i = 0; i < count; i ++ ) {
IElementType type = IElementType.find(i);
Language language = type.getLanguage();
String key = null;
for (Language cur = language; cur != null && key == null; cur = cur.getBaseLanguage()) {
key = languageMap.get(cur);
}
key = StringUtil.notNullize(key, "unknown");
map.put(key, map.get(key) + 1);
//if (key.equals("unknown")) System.out.println(type +" " + language);
}
System.out.println("Total: " + IElementType.getAllocatedTypesCount() +" element types");
// Show per-plugin statistics
Object[] keys = map.keys();
Arrays.sort(keys, new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
return map.get((String)o2) - map.get((String)o1);
}
});
int sum = 0;
for (Object key : keys) {
int value = map.get((String)key);
if (value == 0) continue;
sum += value;
System.out.println(" " + key + ": " + value);
}
// leave some index-space for plugin developers
assertTrue(IElementType.getAllocatedTypesCount() < 10000);
assertEquals(IElementType.getAllocatedTypesCount(), sum);
// output on 11.05.2012
// Preloaded: 3485 types
// 95 definitions
// Total: 7694 types
}
}
|
package org.openlmis.report.builder;
import java.util.Map;
public class StockImbalanceQueryBuilder {
public static String getQuery(Map params){
String query = "SELECT distinct\n" +
" facilities.name AS Facility,\n" +
"facilities.name AS SupplyingFacility,\n" +
" requisition_line_items.product AS Product,\n" +
" requisition_line_items.stockinhand physicalCount,\n" +
" requisition_line_items.amc,\n" +
" CASE WHEN coalesce(requisition_line_items.AMC,0) = 0 THEN 0 ELSE round(requisition_line_items.stockinhand/requisition_line_items.AMC,1) END AS months,\n" +
" coalesce(CASE WHEN (requisition_line_items.stockinhand - coalesce(amc,0) * fn_get_max_mos (programs.id, facilities.id, products.code)) < 0 THEN 0 ELSE (requisition_line_items.stockinhand - coalesce(amc,0) * fn_get_max_mos (programs.id, facilities.id, products.code)) END ,0) AS orderQuantity,\n" +
" CASE WHEN requisition_line_items.stockinhand = 0 THEN 'Stockedout' ELSE\n" +
" CASE WHEN requisition_line_items.stockinhand > 0 AND requisition_line_items.stockinhand < coalesce(amc,0) * fn_get_max_mos (programs.id, facilities.id, products.code) THEN 'Understocked' ELSE\n" +
"\t\tCASE WHEN requisition_line_items.stockinhand > coalesce(amc,0) * fn_get_max_mos (programs.id, facilities.id, products.code) THEN 'Understocked' ELSE '' END\n" +
" END\n" +
" END AS Status\n" +
"\n" +
"\n" +
"FROM\n" +
" facilities\n" +
"INNER JOIN facility_types ON facilities.typeid = facility_types.id\n" +
"INNER JOIN requisitions ON requisitions.facilityid = facilities.id\n" +
"INNER JOIN requisition_line_items ON requisition_line_items.rnrid = requisitions.id\n" +
"INNER JOIN products ON products.code = requisition_line_items.productcode\n" +
"INNER JOIN program_products ON program_products.productid = products.id\n" +
"INNER JOIN programs ON program_products.programid = programs.id AND programs.id = requisitions.programid\n" +
"INNER JOIN programs_supported ON programs.id = programs_supported.programid AND facilities.id = programs_supported.facilityid\n" +
"INNER JOIN requisition_group_members ON facilities.id = requisition_group_members.facilityid\n" +
"INNER JOIN requisition_groups ON requisition_groups.id = requisition_group_members.requisitiongroupid\n" +
"INNER JOIN requisition_group_program_schedules ON requisition_group_program_schedules.programid = programs.id AND requisition_group_program_schedules.requisitiongroupid = requisition_groups.id\n" +
"INNER JOIN processing_schedules ON processing_schedules.id = requisition_group_program_schedules.programid\n" +
"INNER JOIN processing_periods ON processing_periods.scheduleid = processing_schedules.id\n" +
"where requisition_line_items.stockinhand is not null" +"\n";
// writePredicates(params)+ "\n";
// "group by facilities.name,li.productcode, li.product, li.productcategory ,requisition_groups.id \n" +
// " order by " + QueryHelpers.getSortOrder(params, "facilities.name asc,li.productcode asc, li.product asc, li.productcategory asc , requisition_groups.id asc");
return query;
}
private static String writePredicates(Map params){
String predicate = "WHERE r.status = 'RELEASED' ";
String facilityTypeId = params.get("facilityTypeId") == null ? null :((String[])params.get("facilityTypeId"))[0];
String facilityName = params.get("facilityName") == null ? null : ((String[])params.get("facilityName"))[0];
String period = params.get("periodId") == null ? null : ((String[])params.get("periodId"))[0];
String program = params.get("programId") == null ? null : ((String[])params.get("programId"))[0];
String product = params.get("productId") == null ? null : ((String[])params.get("productId"))[0];
String zone = params.get("zoneId") == null ? null : ((String[])params.get("zoneId"))[0];
String rgroup = params.get("rgroupId") == null ? null : ((String[])params.get("rgroupId"))[0];
String schedule = params.get("scheduleId") == null ? null : ((String[])params.get("scheduleId"))[0];
predicate += " and processing_periods.id = "+ period;
predicate += " and programs.id = "+ program;
predicate += " and processing_schedules.id = "+ schedule;
if (zone != null && !zone.equals("undefined") && !zone.isEmpty() && !zone.equals("0") && !zone.equals("-1")) {
predicate += " and facilities.geographiczoneid = "+ zone;
}
if (product != null && !product.equals("undefined") && !product.isEmpty() && !product.equals("0") && !product.equals("-1")) {
predicate += " and program_products.productid = "+ product;
}
if (rgroup != null && !rgroup.equals("undefined") && !rgroup.isEmpty() && !rgroup.equals("0") && !rgroup.equals("-1")) {
predicate += " and requisition_groups.id = "+ rgroup;
}
if (facilityTypeId != null && !facilityTypeId.equals("undefined") && !facilityTypeId.isEmpty() && !facilityTypeId.equals("0") && !facilityTypeId.equals("-1")) {
predicate += " and facility_types.id = "+ facilityTypeId;
}
if (facilityName != null && !facilityName.equals("undefined") && !facilityName.isEmpty() ) {
predicate += " and facilities.name = '"+ facilityName +"'";
}
return predicate;
}
}
|
package net.anotheria.moskito.web.filters;
import net.anotheria.moskito.core.config.MoskitoConfiguration;
import net.anotheria.moskito.core.config.MoskitoConfigurationHolder;
import net.anotheria.moskito.core.context.CurrentMeasurement;
import net.anotheria.moskito.core.context.MoSKitoContext;
import net.anotheria.moskito.core.dynamic.EntryCountLimitedOnDemandStatsProducer;
import net.anotheria.moskito.core.dynamic.OnDemandStatsProducer;
import net.anotheria.moskito.core.dynamic.OnDemandStatsProducerException;
import net.anotheria.moskito.core.predefined.Constants;
import net.anotheria.moskito.core.predefined.FilterStats;
import net.anotheria.moskito.core.predefined.FilterStatsFactory;
import net.anotheria.moskito.core.producers.IStatsProducer;
import net.anotheria.moskito.core.registry.ProducerRegistryFactory;
import net.anotheria.moskito.core.stats.Interval;
import net.anotheria.moskito.web.filters.caseextractor.FilterCaseExtractor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A generic filter that supports multiple tag extractors. This filter replaced the single-use filters like RefererFilter, RequestURIFilter etc. Main purpose was to reduce code as well as get shorter stack traces.
* The filter is implementing IStatsProducer interface but only to be able to 'mark' itself in the path, it doesn't actually collect own stats.
*
* @author lrosenberg
* @since 26.04.16 19:04
*/
public class GenericMonitoringFilter implements Filter, IStatsProducer {
/**
* Logger instance, available for all subclasses.
*/
protected Logger log = LoggerFactory.getLogger(getClass());
/**
* Parameter name for the init parameter for the limit of dynamic case names (number of names) in the filter config. If the number of cases will exceed this limit,
* the new cases will be ignored (to prevent memory leakage).
*/
public static final String INIT_PARAM_LIMIT = "limit";
/**
* Constant for use-cases which are over limit. In case we gather all request urls and we set a limit of 1000 it may well happen, that we actually have more than the set limit.
* In this case it is good to know how many requests those, 'other' urls produce.
*/
public static final String OTHER = "-other-";
/**
* Case extractors. Each extractor can extract the monitoring cases by some parameter, for example URI, Referer, User-Agent etc.
*/
private Map<FilterCaseExtractor, OnDemandStatsProducer<FilterStats>> extractorMap = new HashMap<>();
private void beforeExecution(HttpServletRequest req, HttpServletResponse res){
for (Map.Entry<FilterCaseExtractor, OnDemandStatsProducer<FilterStats>> extractorEntry : extractorMap.entrySet()) {
OnDemandStatsProducer<FilterStats> producer = extractorEntry.getValue();
FilterStats defaultStats = producer.getDefaultStats();
String caseName = extractorEntry.getKey().extractCaseName(req);
FilterStats caseStats = getCaseStats(caseName, producer);
defaultStats.addRequest();
if (caseStats != null) {
caseStats.addRequest();
}
}
}
private FilterStats getCaseStats(String caseName, OnDemandStatsProducer<FilterStats> producer){
if (caseName == null)
return null;
try {
return producer.getStats(caseName);
} catch (OnDemandStatsProducerException e) {
log.debug("Couldn't get stats for case : " + caseName + ", probably limit reached");
try {
return producer.getStats(OTHER);
} catch (OnDemandStatsProducerException e1) {
log.error("This can't happen, 'OtherStats' aka " + OTHER + " doesn't exists in producer for case " + caseName);
}
}
return null;
}
private void afterExecution(HttpServletRequest req, HttpServletResponse res, long executionTime, Throwable t){
double executionTimeInMicroseconds = ((double)executionTime)/1000;
//TODO removed ServerTiming header, because it is yet too later (after the execution)
for (Map.Entry<FilterCaseExtractor, OnDemandStatsProducer<FilterStats>> extractorEntry : extractorMap.entrySet()){
OnDemandStatsProducer<FilterStats> producer = extractorEntry.getValue();
FilterStats defaultStats = producer.getDefaultStats();
String caseName = extractorEntry.getKey().extractCaseName(req);
FilterStats caseStats = getCaseStats(caseName, producer);
defaultStats.addExecutionTime(executionTime);
defaultStats.notifyRequestFinished();
if (caseStats!=null) {
caseStats.addExecutionTime(executionTime);
caseStats.notifyRequestFinished();
}
if (t!=null){
if (t instanceof ServletException){
defaultStats.notifyServletException(t);
if (caseStats!=null)
caseStats.notifyServletException(t);
}else if(t instanceof IOException){
defaultStats.notifyIOException(t);
if (caseStats!=null)
caseStats.notifyIOException(t);
}else if(t instanceof RuntimeException){
defaultStats.notifyRuntimeException(t);
if (caseStats!=null)
caseStats.notifyRuntimeException(t);
}else{
defaultStats.notifyError(t);
if (caseStats!=null)
caseStats.notifyError();
}
}
}
}
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
if (! (req instanceof HttpServletRequest)){
chain.doFilter(req, res);
return;
}
beforeExecution((HttpServletRequest)req, (HttpServletResponse)res);
CurrentMeasurement measurement = MoSKitoContext.get().notifyProducerEntry(this);
if (measurement.isFirst()){
System.out.println("I am first!!!");
}
long startTime = System.nanoTime();
Throwable t = null;
try{
chain.doFilter(req, res);
}catch(ServletException e){
t = e;
}catch(IOException e){
t = e;
}catch(RuntimeException e){
t = e;
}catch(Error e){
t = e;
}finally{
long exTime = System.nanoTime() - startTime;
afterExecution( (HttpServletRequest)req, (HttpServletResponse) res, exTime, t);
if (measurement.isFirst()){
measurement.notifyProducerFinished();
}
}
}
@Override public void init(FilterConfig config) throws ServletException {
int limit = -1;
String pLimit = config.getInitParameter(INIT_PARAM_LIMIT);
if (pLimit!=null) {
try {
limit = Integer.parseInt(pLimit);
} catch (NumberFormatException ignored) {
log.warn("couldn't parse limit \"" + pLimit + "\", assume -1 aka no limit.");
}
}
MoskitoConfiguration configuration = MoskitoConfigurationHolder.getConfiguration();
net.anotheria.moskito.core.config.filter.FilterConfig filterConfig = configuration.getFilterConfig();
String[] extractorNames = filterConfig.getCaseExtractors();
if (extractorNames != null && extractorNames.length>0){
for (String extractorName : extractorNames){
try {
FilterCaseExtractor extractor = (FilterCaseExtractor)Class.forName(extractorName).newInstance();
OnDemandStatsProducer<FilterStats> onDemandProducer = limit == -1 ?
new OnDemandStatsProducer<FilterStats>(extractor.getProducerId(), extractor.getCategory(), extractor.getSubsystem(), new FilterStatsFactory(getMonitoringIntervals())) :
new EntryCountLimitedOnDemandStatsProducer<FilterStats>(extractor.getProducerId(), extractor.getCategory(), extractor.getSubsystem(), new FilterStatsFactory(getMonitoringIntervals()), limit);
ProducerRegistryFactory.getProducerRegistryInstance().registerProducer(onDemandProducer);
extractorMap.put(extractor, onDemandProducer);
//force request uri filter to create 'other' stats.
try{
//force creation of 'other' stats.
if (limit!=-1)
onDemandProducer.getStats(OTHER);
}catch(OnDemandStatsProducerException e){
log.error("Can't create 'other' stats for limit excess", e);
}
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
log.error("Can't load filter case extractor "+extractorName, e);
}
}
}
}
@Override public void destroy(){
}
protected Interval[] getMonitoringIntervals(){
return Constants.getDefaultIntervals();
}
@Override
public List getStats() {
return Collections.emptyList();
}
@Override
public String getProducerId() {
return getClass().getSimpleName();
}
@Override
public String getCategory() {
return "filter";
}
@Override
public String getSubsystem() {
return "web";
}
}
|
package org.navalplanner.business.planner.entities;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.Validate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.validator.AssertTrue;
import org.hibernate.validator.Valid;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.navalplanner.business.orders.entities.AggregatedHoursGroup;
import org.navalplanner.business.orders.entities.HoursGroup;
import org.navalplanner.business.orders.entities.OrderElement;
import org.navalplanner.business.orders.entities.TaskSource;
import org.navalplanner.business.planner.entities.DerivedAllocationGenerator.IWorkerFinder;
import org.navalplanner.business.planner.entities.allocationalgorithms.HoursModification;
import org.navalplanner.business.planner.entities.allocationalgorithms.ResourcesPerDayModification;
import org.navalplanner.business.planner.entities.consolidations.Consolidation;
import org.navalplanner.business.planner.limiting.entities.LimitingResourceQueueElement;
import org.navalplanner.business.resources.daos.IResourceDAO;
import org.navalplanner.business.resources.entities.Criterion;
import org.navalplanner.business.resources.entities.Resource;
import org.navalplanner.business.resources.entities.Worker;
import org.navalplanner.business.scenarios.entities.Scenario;
import org.navalplanner.business.util.deepcopy.AfterCopy;
public class Task extends TaskElement {
private static final Log LOG = LogFactory.getLog(Task.class);
public static Task createTask(TaskSource taskSource) {
Task task = new Task();
OrderElement orderElement = taskSource.getOrderElement();
orderElement.applyStartConstraintIfNeededTo(task);
Task result = create(task, taskSource);
result.initializeEndDate();
return result;
}
@Override
protected void initializeEndDate() {
Integer workHours = getWorkHours();
long endDateTime = getStartDate().getTime()
+ timeElapsedMillisWorkingOneResourceEightHoursPerDay(workHours);
setEndDate(new Date(endDateTime));
}
private long timeElapsedMillisWorkingOneResourceEightHoursPerDay(
Integer workHours) {
final long millisecondsPerDay = 24 * 3600l * 1000;
return workHours * millisecondsPerDay / 8;
}
private CalculatedValue calculatedValue = CalculatedValue.END_DATE;
private Set<ResourceAllocation<?>> resourceAllocations = new HashSet<ResourceAllocation<?>>();
@Valid
private Set<ResourceAllocation<?>> getResourceAlloations() {
return new HashSet<ResourceAllocation<?>>(resourceAllocations);
}
@AfterCopy
private void ifLimitingAllocationRemove() {
if (isLimiting()) {
resourceAllocations.clear();
}
}
private TaskStartConstraint startConstraint = new TaskStartConstraint();
private SubcontractedTaskData subcontractedTaskData;
private Integer priority;
private Consolidation consolidation;
/**
* Constructor for hibernate. Do not use!
*/
public Task() {
}
@SuppressWarnings("unused")
@AssertTrue(message = "order element associated to a task must be not null")
private boolean theOrderElementMustBeNotNull() {
return getOrderElement() != null;
}
public HoursGroup getHoursGroup() {
return getTaskSource().getHoursGroups().iterator().next();
}
public Set<Criterion> getCriterions() {
return Collections
.unmodifiableSet(getHoursGroup().getValidCriterions());
}
public Integer getHoursSpecifiedAtOrder() {
return getWorkHours();
}
public int getAssignedHours() {
return new AggregateOfResourceAllocations(resourceAllocations)
.getTotalHours();
}
public int getTotalHours() {
return (getTaskSource() != null) ? getTaskSource().getTotalHours() : 0;
}
@Override
public boolean isLeaf() {
return true;
}
@Override
public List<TaskElement> getChildren() {
throw new UnsupportedOperationException();
}
public Set<ResourceAllocation<?>> getSatisfiedResourceAllocations() {
Set<ResourceAllocation<?>> result = new HashSet<ResourceAllocation<?>>();
if (isLimiting()) {
result.addAll(getLimitingResourceAllocations());
} else {
result.addAll(ResourceAllocation
.getSatisfied(resourceAllocations));
}
return Collections.unmodifiableSet(result);
}
@Override
public Set<ResourceAllocation<?>> getAllResourceAllocations() {
return Collections.unmodifiableSet(resourceAllocations);
}
public Set<ResourceAllocation<?>> getLimitingResourceAllocations() {
Set<ResourceAllocation<?>> result = new HashSet<ResourceAllocation<?>>();
for (ResourceAllocation<?> each: resourceAllocations) {
if (each.isLimiting()) {
result.add(each);
}
}
return Collections.unmodifiableSet(result);
}
public Set<ResourceAllocation<?>> getNonLimitingResourceAllocations() {
Set<ResourceAllocation<?>> result = new HashSet<ResourceAllocation<?>>();
for (ResourceAllocation<?> each: resourceAllocations) {
if (!each.isLimiting()) {
result.add(each);
}
}
return Collections.unmodifiableSet(result);
}
public boolean isLimiting() {
return !(getLimitingResourceAllocations().isEmpty());
}
private ResourceAllocation<?> getAssociatedLimitingResourceAllocation() {
Set<ResourceAllocation<?>> resourceAllocations = getLimitingResourceAllocations();
return (resourceAllocations.size() > 0) ? resourceAllocations.iterator().next() : null;
}
public LimitingResourceQueueElement getAssociatedLimitingResourceQueueElementIfAny() {
if (!isLimiting()) {
throw new IllegalStateException("this is not a limiting task");
}
return getAssociatedLimitingResourceAllocation()
.getLimitingResourceQueueElement();
}
public boolean isLimitingAndHasDayAssignments() {
ResourceAllocation<?> resourceAllocation = getAssociatedLimitingResourceAllocation();
return (resourceAllocation != null) ? resourceAllocation.isLimitingAndHasDayAssignments() : false;
}
public void addResourceAllocation(ResourceAllocation<?> resourceAllocation) {
addResourceAllocation(resourceAllocation, true);
}
public void addResourceAllocation(ResourceAllocation<?> resourceAllocation,
boolean generateDayAssignments) {
if (!resourceAllocation.getTask().equals(this)) {
throw new IllegalArgumentException(
"the resourceAllocation's task must be this task");
}
resourceAllocations.add(resourceAllocation);
if (generateDayAssignments) {
resourceAllocation.associateAssignmentsToResource();
}
}
public void removeResourceAllocation(
ResourceAllocation<?> resourceAllocation) {
resourceAllocation.detach();
resourceAllocations.remove(resourceAllocation);
}
public CalculatedValue getCalculatedValue() {
if (calculatedValue == null) {
return CalculatedValue.END_DATE;
}
return calculatedValue;
}
public void setCalculatedValue(CalculatedValue calculatedValue) {
Validate.notNull(calculatedValue);
this.calculatedValue = calculatedValue;
}
public void setDaysDuration(Integer duration) {
Validate.notNull(duration);
Validate.isTrue(duration >= 0);
DateTime endDate = toDateTime(getStartDate()).plusDays(duration);
setEndDate(endDate.toDate());
}
public Integer getDaysDuration() {
Days daysBetween = Days.daysBetween(new LocalDate(
toDateTime(getStartDate())), new LocalDate(
toDateTime(getEndDate())));
return daysBetween.getDays();
}
private DateTime toDateTime(Date startDate) {
return new DateTime(startDate.getTime());
}
/**
* Checks if there isn't any {@link Worker} repeated in the {@link Set} of
* {@link ResourceAllocation} of this {@link Task}.
* @return <code>true</code> if the {@link Task} is valid, that means there
* isn't any {@link Worker} repeated.
*/
public boolean isValidResourceAllocationWorkers() {
Set<Long> workers = new HashSet<Long>();
for (ResourceAllocation<?> resourceAllocation : resourceAllocations) {
if (resourceAllocation instanceof SpecificResourceAllocation) {
Resource resource = ((SpecificResourceAllocation) resourceAllocation)
.getResource();
if (resource != null) {
if (workers.contains(resource.getId())) {
return false;
} else {
workers.add(resource.getId());
}
}
}
}
return true;
}
public Set<GenericResourceAllocation> getGenericResourceAllocations() {
return new HashSet<GenericResourceAllocation>(ResourceAllocation
.getOfType(GenericResourceAllocation.class,
getSatisfiedResourceAllocations()));
}
public Set<SpecificResourceAllocation> getSpecificResourceAllocations() {
return new HashSet<SpecificResourceAllocation>(ResourceAllocation
.getOfType(SpecificResourceAllocation.class,
getSatisfiedResourceAllocations()));
}
public static class ModifiedAllocation {
public static List<ModifiedAllocation> copy(Scenario onScenario,
Collection<ResourceAllocation<?>> resourceAllocations) {
List<ModifiedAllocation> result = new ArrayList<ModifiedAllocation>();
for (ResourceAllocation<?> resourceAllocation : resourceAllocations) {
result.add(new ModifiedAllocation(resourceAllocation,
resourceAllocation.copy(onScenario)));
}
return result;
}
public static List<ResourceAllocation<?>> modified(
Collection<ModifiedAllocation> collection) {
List<ResourceAllocation<?>> result = new ArrayList<ResourceAllocation<?>>();
for (ModifiedAllocation modifiedAllocation : collection) {
result.add(modifiedAllocation.getModification());
}
return result;
}
private final ResourceAllocation<?> original;
private final ResourceAllocation<?> modification;
public ModifiedAllocation(ResourceAllocation<?> original,
ResourceAllocation<?> modification) {
Validate.notNull(original);
Validate.notNull(modification);
this.original = original;
this.modification = modification;
}
public ResourceAllocation<?> getOriginal() {
return original;
}
public ResourceAllocation<?> getModification() {
return modification;
}
}
public void mergeAllocation(Scenario scenario,
CalculatedValue calculatedValue,
AggregateOfResourceAllocations aggregate,
List<ResourceAllocation<?>> newAllocations,
List<ModifiedAllocation> modifications,
Collection<? extends ResourceAllocation<?>> toRemove) {
if (aggregate.isEmpty()) {
return;
}
final LocalDate start = aggregate.getStart();
final LocalDate end = aggregate.getEnd();
mergeAllocation(scenario, start, end, calculatedValue, newAllocations,
modifications, toRemove);
}
private void mergeAllocation(Scenario scenario, final LocalDate start,
final LocalDate end,
CalculatedValue calculatedValue,
List<ResourceAllocation<?>> newAllocations,
List<ModifiedAllocation> modifications,
Collection<? extends ResourceAllocation<?>> toRemove) {
this.calculatedValue = calculatedValue;
setStartDate(start.toDateTimeAtStartOfDay().toDate());
setDaysDuration(Days.daysBetween(start, end).getDays());
for (ModifiedAllocation pair : modifications) {
Validate.isTrue(resourceAllocations.contains(pair.getOriginal()));
pair.getOriginal().mergeAssignmentsAndResourcesPerDay(scenario,
pair.getModification());
}
remove(toRemove);
addAllocations(scenario, newAllocations);
}
private void remove(Collection<? extends ResourceAllocation<?>> toRemove) {
for (ResourceAllocation<?> resourceAllocation : toRemove) {
removeResourceAllocation(resourceAllocation);
}
}
private void addAllocations(Scenario scenario,
List<ResourceAllocation<?>> newAllocations) {
for (ResourceAllocation<?> resourceAllocation : newAllocations) {
resourceAllocation.switchToScenario(scenario);
addResourceAllocation(resourceAllocation);
}
}
public void explicityMoved(Date date) {
getStartConstraint().explicityMovedTo(date);
}
public TaskStartConstraint getStartConstraint() {
if (startConstraint == null) {
startConstraint = new TaskStartConstraint();
}
return startConstraint;
}
private static abstract class AllocationModificationStrategy {
public abstract List<ResourcesPerDayModification> getResourcesPerDayModified(
List<ResourceAllocation<?>> allocations);
public abstract List<HoursModification> getHoursModified(
List<ResourceAllocation<?>> allocations);
}
private static class WithTheSameHoursAndResourcesPerDay extends
AllocationModificationStrategy {
@Override
public List<HoursModification> getHoursModified(
List<ResourceAllocation<?>> allocations) {
return HoursModification.fromExistent(allocations);
}
@Override
public List<ResourcesPerDayModification> getResourcesPerDayModified(
List<ResourceAllocation<?>> allocations) {
return ResourcesPerDayModification.fromExistent(allocations);
}
}
private static class WithAnotherResources extends
AllocationModificationStrategy {
private final IResourceDAO resourceDAO;
WithAnotherResources(IResourceDAO resourceDAO) {
this.resourceDAO = resourceDAO;
}
@Override
public List<HoursModification> getHoursModified(
List<ResourceAllocation<?>> allocations) {
return HoursModification.withNewResources(allocations, resourceDAO);
}
@Override
public List<ResourcesPerDayModification> getResourcesPerDayModified(
List<ResourceAllocation<?>> allocations) {
return ResourcesPerDayModification.withNewResources(allocations,
resourceDAO);
}
}
public void copyAssignmentsFromOneScenarioToAnother(Scenario from, Scenario to) {
for (ResourceAllocation<?> each : getAllResourceAllocations()) {
each.copyAssignmentsFromOneScenarioToAnother(from, to);
}
}
@Override
protected void moveAllocations(Scenario scenario) {
reassign(scenario, new WithTheSameHoursAndResourcesPerDay());
}
public void reassignAllocationsWithNewResources(Scenario scenario,
IResourceDAO resourceDAO) {
reassign(scenario, new WithAnotherResources(resourceDAO));
}
private void reassign(Scenario onScenario, AllocationModificationStrategy strategy) {
if (isLimiting()) {
return;
}
List<ModifiedAllocation> copied = ModifiedAllocation.copy(onScenario,
getSatisfiedResourceAllocations());
List<ResourceAllocation<?>> toBeModified = ModifiedAllocation
.modified(copied);
List<ResourcesPerDayModification> allocations = strategy
.getResourcesPerDayModified(toBeModified);
if (allocations.isEmpty()) {
return;
}
switch (calculatedValue) {
case NUMBER_OF_HOURS:
ResourceAllocation.allocating(allocations)
.allocateOnTaskLength();
break;
case END_DATE:
LocalDate end = ResourceAllocation
.allocating(allocations)
.untilAllocating(getAssignedHours());
setEndDate(end.toDateTimeAtStartOfDay().toDate());
break;
case RESOURCES_PER_DAY:
List<HoursModification> hoursModified = strategy
.getHoursModified(toBeModified);
ResourceAllocation.allocatingHours(hoursModified)
.allocateUntil(new LocalDate(getEndDate()));
break;
default:
throw new RuntimeException("cant handle: " + calculatedValue);
}
updateDerived(copied);
mergeAllocation(onScenario, asLocalDate(getStartDate()),
asLocalDate(getEndDate()),
calculatedValue, Collections
.<ResourceAllocation<?>> emptyList(), copied,
Collections.<ResourceAllocation<?>> emptyList());
}
private void updateDerived(List<ModifiedAllocation> allocations) {
for (ModifiedAllocation each : allocations) {
ResourceAllocation<?> original = each.getOriginal();
if (!original.getDerivedAllocations().isEmpty()) {
IWorkerFinder workersFinder = createFromExistentDerivedAllocationsFinder(original);
each.getModification().createDerived(workersFinder);
}
}
}
private IWorkerFinder createFromExistentDerivedAllocationsFinder(
ResourceAllocation<?> original) {
Set<DerivedAllocation> derivedAllocations = original
.getDerivedAllocations();
final Set<Worker> allWorkers = new HashSet<Worker>();
for (DerivedAllocation each : derivedAllocations) {
allWorkers.addAll(Resource.workers(each.getResources()));
}
return new IWorkerFinder() {
@Override
public Collection<Worker> findWorkersMatching(
Collection<? extends Criterion> requiredCriterions) {
if (requiredCriterions.isEmpty()) {
return new ArrayList<Worker>();
}
Collection<Worker> result = new ArrayList<Worker>();
for (Worker each : allWorkers) {
if (each.satisfiesCriterions(requiredCriterions)) {
result.add(each);
}
}
return result;
}
};
}
private LocalDate asLocalDate(Date date) {
return new LocalDate(date.getTime());
}
public List<AggregatedHoursGroup> getAggregatedByCriterions() {
return getTaskSource().getAggregatedByCriterions();
}
public void setSubcontractedTaskData(SubcontractedTaskData subcontractedTaskData) {
this.subcontractedTaskData = subcontractedTaskData;
}
@Valid
public SubcontractedTaskData getSubcontractedTaskData() {
return subcontractedTaskData;
}
public void removeAllSatisfiedResourceAllocations() {
Set<ResourceAllocation<?>> resourceAllocations = getSatisfiedResourceAllocations();
for (ResourceAllocation<?> resourceAllocation : resourceAllocations) {
removeResourceAllocation(resourceAllocation);
}
}
public void removeAllResourceAllocations() {
for (Iterator<ResourceAllocation<?>> i = resourceAllocations.iterator(); i
.hasNext();) {
ResourceAllocation<?> each = i.next();
removeResourceAllocation(each);
}
}
public boolean isSubcontracted() {
return (subcontractedTaskData != null);
}
public boolean hasSomeSatisfiedAllocation() {
return !getSatisfiedResourceAllocations().isEmpty();
}
@Override
protected boolean canBeResized() {
return ((calculatedValue != CalculatedValue.END_DATE) || (resourceAllocations
.isEmpty()));
}
@Override
public boolean canBeExplicitlyResized() {
return canBeResized() && !isSubcontracted();
}
@Override
public boolean isMilestone() {
return false;
}
public void removeSubcontractCommunicationDate() {
if (subcontractedTaskData != null) {
subcontractedTaskData.setSubcontractCommunicationDate(null);
}
}
public boolean hasResourceAllocations() {
return !resourceAllocations.isEmpty();
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public void setConsolidation(Consolidation consolidation) {
this.consolidation = consolidation;
}
@Valid
public Consolidation getConsolidation() {
return consolidation;
}
@Override
public boolean hasLimitedResourceAllocation() {
return !getLimitingResourceAllocations().isEmpty();
}
public boolean hasConsolidations() {
return ((consolidation != null) && (!consolidation.isEmpty()));
}
public LocalDate getFirstDayNotConsolidated() {
if (consolidation != null) {
LocalDate until = consolidation.getConsolidatedUntil();
if (until != null) {
return until.plusDays(1);
}
}
return LocalDate.fromDateFields(getStartDate());
}
}
|
package uk.ac.ebi.quickgo.ontology.traversal;
import uk.ac.ebi.quickgo.ontology.model.AncestorGraph;
import uk.ac.ebi.quickgo.ontology.model.OntologyRelationType;
import uk.ac.ebi.quickgo.ontology.model.OntologyRelationship;
import java.util.Deque;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
class SubGraphCalculator {
static Trampoline<AncestorGraph> createTrampoline(Deque<String> targetVertices, Set<String> stopNodes,
OntologyRelationType[] targetRelations, AncestorGraph ancestorGraph, OntologyGraph ontologyGraph) {
String target = targetVertices.pollFirst();
if (Objects.nonNull(target)) {
//Process this node if it hasn't already been considered.
if (!ancestorGraph.vertices.contains(target)) {
ancestorGraph.vertices.add(target);
//if target is not a stop node look for parents
if (!stopNodes.contains(target)) {
try {
Set<OntologyRelationship> parents = ontologyGraph.parents(target, targetRelations);
ancestorGraph.edges.addAll(parents);
addParentsToWorkQueue(targetVertices, parents);
} catch (Exception e) {
//continue processing.
}
}
}
if(!targetVertices.isEmpty()) {
return new Trampoline<AncestorGraph>() {
public Optional<Trampoline<AncestorGraph>> nextTrampoline() {
return Optional.of(createTrampoline(targetVertices,
stopNodes,
targetRelations,
ancestorGraph,
ontologyGraph));
}
};
}
}
return new Trampoline<AncestorGraph>() {
public AncestorGraph getValue() { return ancestorGraph; }
};
}
private static void addParentsToWorkQueue(Deque<String> targetVertices, Set<OntologyRelationship> parents) {
parents.stream()
.map(p -> p.parent)
.forEach(targetVertices::addLast);
}
}
|
package nars.inference;
import java.util.List;
import nars.config.Parameters;
import nars.control.DerivationContext;
import nars.entity.BudgetValue;
import nars.entity.Concept;
import nars.entity.Sentence;
import nars.entity.Stamp;
import nars.entity.Task;
import nars.entity.TruthValue;
import static nars.inference.TemporalRules.ORDER_BACKWARD;
import static nars.inference.TemporalRules.ORDER_FORWARD;
import static nars.inference.TemporalRules.ORDER_INVALID;
import static nars.inference.TemporalRules.ORDER_NONE;
import static nars.inference.TemporalRules.abdIndComOrder;
import static nars.inference.TemporalRules.analogyOrder;
import static nars.inference.TemporalRules.dedExeOrder;
import static nars.inference.TemporalRules.resemblanceOrder;
import static nars.inference.TemporalRules.reverseOrder;
import nars.io.Output;
import nars.io.Symbols;
import nars.io.Symbols.NativeOperator;
import nars.language.CompoundTerm;
import nars.language.Conjunction;
import nars.language.Equivalence;
import nars.language.Implication;
import nars.language.Interval;
import nars.language.Statement;
import nars.language.Term;
import nars.language.Terms;
import static nars.language.Terms.reduceComponents;
import nars.language.Variables;
/**
* Syllogisms: Inference rules based on the transitivity of the relation.
*/
public final class SyllogisticRules {
/**
* <pre>
* {<S ==> M>, <M ==> P>} |- {<S ==> P>, <P ==> S>}
* </pre>
*
* @param term1 Subject of the first new task
* @param term2 Predicate of the first new task
* @param sentence The first premise
* @param belief The second premise
* @param nal Reference to the memory
*/
static void dedExe(Term term1, Term term2, Sentence sentence, Sentence belief, DerivationContext nal) {
if (Statement.invalidStatement(term1, term2)) {
return;
}
int order1 = sentence.term.getTemporalOrder();
int order2 = belief.term.getTemporalOrder();
int order = dedExeOrder(order1, order2);
if (order == ORDER_INVALID) {
return;
}
TruthValue value1 = sentence.truth;
TruthValue value2 = belief.truth;
TruthValue truth1 = null;
TruthValue truth2 = null;
BudgetValue budget1, budget2;
if (sentence.isQuestion()) {
budget1 = BudgetFunctions.backwardWeak(value2, nal);
budget2 = BudgetFunctions.backwardWeak(value2, nal);
} else if (sentence.isQuest()) {
budget1 = BudgetFunctions.backward(value2, nal);
budget2 = BudgetFunctions.backward(value2, nal);
} else {
if (sentence.isGoal()) {
truth1 = TruthFunctions.desireWeak(value1, value2);
truth2 = TruthFunctions.desireWeak(value1, value2);
} else {
// isJudgment
truth1 = TruthFunctions.deduction(value1, value2);
truth2 = TruthFunctions.exemplification(value1, value2);
}
budget1 = BudgetFunctions.forward(truth1, nal);
budget2 = BudgetFunctions.forward(truth2, nal);
}
Statement content = (Statement) sentence.term;
Statement content1 = Statement.make(content, term1, term2, order);
Statement content2 = Statement.make(content, term2, term1, reverseOrder(order));
if ((content1 == null) || (content2 == null))
return;
nal.doublePremiseTask(content1, truth1, budget1,false, false); //(allow overlap) but not needed here, isn't detachment
nal.doublePremiseTask(content2, truth2, budget2,false, false);
}
static void abdIndCom(final Term term1, final Term term2, final Sentence sentence1, final Sentence sentence2, final int figure, final DerivationContext nal) {
if (Statement.invalidStatement(term1, term2) || Statement.invalidPair(term1, term2)) {
return;
}
int order1 = sentence1.term.getTemporalOrder();
int order2 = sentence2.term.getTemporalOrder();
int order = abdIndComOrder(order1, order2);
Statement taskContent = (Statement) sentence1.term;
TruthValue truth1 = null;
TruthValue truth2 = null;
TruthValue truth3 = null;
BudgetValue budget1, budget2, budget3;
TruthValue value1 = sentence1.truth;
TruthValue value2 = sentence2.truth;
if (sentence1.isQuestion()) {
budget1 = BudgetFunctions.backward(value2, nal);
budget2 = BudgetFunctions.backwardWeak(value2, nal);
budget3 = BudgetFunctions.backward(value2, nal);
} else if (sentence1.isQuest()) {
budget1 = BudgetFunctions.backwardWeak(value2, nal);
budget2 = BudgetFunctions.backward(value2, nal);
budget3 = BudgetFunctions.backwardWeak(value2, nal);
} else {
if (sentence1.isGoal()) {
truth1 = TruthFunctions.desireStrong(value1, value2); //P --> S
truth2 = TruthFunctions.desireWeak(value2, value1); //S --> P
truth3 = TruthFunctions.desireStrong(value1, value2); //S <-> P
} else {
// isJudgment
truth1 = TruthFunctions.abduction(value1, value2); //P --> S
truth2 = TruthFunctions.abduction(value2, value1); //S --> P
truth3 = TruthFunctions.comparison(value1, value2); //S <-> P
}
budget1 = BudgetFunctions.forward(truth1, nal);
budget2 = BudgetFunctions.forward(truth2, nal);
budget3 = BudgetFunctions.forward(truth3, nal);
}
if (order != ORDER_INVALID) {
nal.doublePremiseTask(
Statement.make(taskContent, term1, term2, order),
truth1, budget1,false, false);
nal.doublePremiseTask(
Statement.make(taskContent, term2, term1, reverseOrder(order)),
truth2, budget2,false, false);
nal.doublePremiseTask(
Statement.makeSym(taskContent, term1, term2, order),
truth3, budget3,false, false);
}
if(Parameters.BREAK_NAL_HOL_BOUNDARY && order1==order2 && taskContent.isHigherOrderStatement() && sentence2.term.isHigherOrderStatement()) {
/* Bridge to higher order statements:
<a ==> c>.
<b ==> c>.
|-
<a <-> b>. %F_cmp%
<a --> b>. %F_abd%
<b --> a>. %F_abd%
*/
/* if(truth1!=null)
truth1=truth1.clone();
if(truth2!=null)
truth2=truth2.clone();*/
if(truth3!=null)
truth3=truth3.clone();
/* nal.doublePremiseTask(
Statement.make(NativeOperator.INHERITANCE, term1, term2),
truth1, budget1.clone(),false, false);
nal.doublePremiseTask(
Statement.make(NativeOperator.INHERITANCE, term2, term1),
truth2, budget2.clone(),false, false);*/
nal.doublePremiseTask(
Statement.make(NativeOperator.SIMILARITY, term1, term2, TemporalRules.ORDER_NONE),
truth3, budget3.clone(),false, false);
}
}
/**
* {<S ==> P>, <M <=> P>} |- <S ==> P>
*
* @param subj Subject of the new task
* @param pred Predicate of the new task
* @param asym The asymmetric premise
* @param sym The symmetric premise
* @param figure Locations of the shared term in premises
* @param nal Reference to the memory
*/
static void analogy(Term subj, Term pred, Sentence asym, Sentence sym, int figure, DerivationContext nal) {
if (Statement.invalidStatement(subj, pred)) {
return;
}
int order1 = asym.term.getTemporalOrder();
int order2 = sym.term.getTemporalOrder();
int order = analogyOrder(order1, order2, figure);
if (order == ORDER_INVALID) {
return;
}
Statement st = (Statement) asym.term;
TruthValue truth = null;
BudgetValue budget;
Sentence sentence = nal.getCurrentTask().sentence;
CompoundTerm taskTerm = (CompoundTerm) sentence.term;
if (sentence.isQuestion() || sentence.isQuest()) {
if (taskTerm.isCommutative()) {
if(asym.truth==null) { //a question for example
return;
}
budget = BudgetFunctions.backwardWeak(asym.truth, nal);
} else {
if(sym.truth==null) { //a question for example
return;
}
budget = BudgetFunctions.backward(sym.truth, nal);
}
} else {
if (sentence.isGoal()) {
if (taskTerm.isCommutative()) {
truth = TruthFunctions.desireWeak(asym.truth, sym.truth);
} else {
truth = TruthFunctions.desireStrong(asym.truth, sym.truth);
}
} else {
truth = TruthFunctions.analogy(asym.truth, sym.truth);
}
budget = BudgetFunctions.forward(truth, nal);
}
//nal.mem().logic.ANALOGY.commit();
nal.doublePremiseTask( Statement.make(st, subj, pred, order), truth, budget,false, false); //(allow overlap) but not needed here, isn't detachment
}
/**
* {<S <=> M>, <M <=> P>} |- <S <=> P>
*
* @param term1 Subject of the new task
* @param term2 Predicate of the new task
* @param belief The first premise
* @param sentence The second premise
* @param figure Locations of the shared term in premises
* @param nal Reference to the memory
*/
static void resemblance(Term term1, Term term2, Sentence belief, Sentence sentence, int figure, DerivationContext nal) {
if (Statement.invalidStatement(term1, term2)) {
return;
}
int order1 = belief.term.getTemporalOrder();
int order2 = sentence.term.getTemporalOrder();
int order = resemblanceOrder(order1, order2, figure);
if (order == ORDER_INVALID) {
return;
}
Statement st = (Statement) belief.term;
TruthValue truth = null;
BudgetValue budget;
if (sentence.isQuestion() || sentence.isQuest()) {
budget = BudgetFunctions.backward(belief.truth, nal);
} else {
if (sentence.isGoal()) {
truth = TruthFunctions.desireStrong(sentence.truth, belief.truth);
} else {
truth = TruthFunctions.resemblance(belief.truth, sentence.truth);
}
budget = BudgetFunctions.forward(truth, nal);
}
boolean higherOrder=(belief.term.isHigherOrderStatement() || sentence.term.isHigherOrderStatement());
boolean bothHigherOrder=(belief.term.isHigherOrderStatement() && sentence.term.isHigherOrderStatement());
if(!bothHigherOrder && higherOrder) {
if(belief.term.isHigherOrderStatement()) {
order=belief.term.getTemporalOrder();
}
else
if(sentence.term.isHigherOrderStatement()) {
order=sentence.term.getTemporalOrder();
}
}
Statement s=Statement.make(higherOrder ? NativeOperator.EQUIVALENCE : NativeOperator.SIMILARITY, term1, term2, order);
//if(!Terms.equalSubTermsInRespectToImageAndProduct(term2, term2))
nal.doublePremiseTask( s, truth, budget,false, false); //(allow overlap) but not needed here, isn't detachment
// nal.doublePremiseTask( Statement.make(st, term1, term2, order), truth, budget,false, true );
if(Parameters.BREAK_NAL_HOL_BOUNDARY && !sentence.term.hasVarIndep() && (st instanceof Equivalence) && order1==order2 && belief.term.isHigherOrderStatement() && sentence.term.isHigherOrderStatement()) {
BudgetValue budget1=null, budget2=null, budget3=null;
TruthValue truth1=null, truth2=null, truth3=null;
TruthValue value1 = sentence.truth;
TruthValue value2 = belief.truth;
if (sentence.isQuestion()) {
/* budget1 = BudgetFunctions.backward(value2, nal);
budget2 = BudgetFunctions.backwardWeak(value2, nal);*/
budget3 = BudgetFunctions.backward(value2, nal);
} else if (sentence.isQuest()) {
/* budget1 = BudgetFunctions.backwardWeak(value2, nal);
budget2 = BudgetFunctions.backward(value2, nal);*/
budget3 = BudgetFunctions.backwardWeak(value2, nal);
} else {
if (sentence.isGoal()) {
/* truth1 = TruthFunctions.desireStrong(value1, value2);
truth2 = TruthFunctions.desireWeak(value2, value1);*/
truth3 = TruthFunctions.desireStrong(value1, value2);
} else {
// isJudgment
/* truth1 = TruthFunctions.abduction(value1, value2);
truth2 = TruthFunctions.abduction(value2, value1);*/
truth3 = TruthFunctions.comparison(value1, value2);
}
/*budget1 = BudgetFunctions.forward(truth1, nal);
budget2 = BudgetFunctions.forward(truth2, nal);*/
budget3 = BudgetFunctions.forward(truth3, nal);
}
/* Bridge to higher order statements:
<b <=> k>.
<b <=> c>.
|-
<k <-> c>. %F_cmp%
*/
/* nal.doublePremiseTask(
Statement.make(NativeOperator.INHERITANCE, term1, term2),
truth1, budget1.clone(),false, false);
nal.doublePremiseTask(
Statement.make(NativeOperator.INHERITANCE, term2, term1),
truth2, budget2.clone(),false, false);*/
nal.doublePremiseTask(
Statement.make(NativeOperator.SIMILARITY, term1, term2, TemporalRules.ORDER_NONE),
truth3, budget3.clone(),false, false);
}
}
/**
* {<<M --> S> ==> <M --> P>>, <M --> S>} |- <M --> P> {<<M --> S> ==> <M
* --> P>>, <M --> P>} |- <M --> S> {<<M --> S> <=> <M --> P>>, <M --> S>}
* |- <M --> P> {<<M --> S> <=> <M --> P>>, <M --> P>} |- <M --> S>
*
* @param mainSentence The implication/equivalence premise
* @param subSentence The premise on part of s1
* @param side The location of s2 in s1
* @param nal Reference to the memory
*/
static void detachment(Sentence mainSentence, Sentence subSentence, int side, DerivationContext nal) {
Statement statement = (Statement) mainSentence.term;
if (!(statement instanceof Implication) && !(statement instanceof Equivalence)) {
return;
}
Term subject = statement.getSubject();
Term predicate = statement.getPredicate();
Term content;
Term term = subSentence.term;
if ((side == 0) && term.equals(subject)) {
content = predicate;
} else if ((side == 1) && term.equals(predicate)) {
content = subject;
} else {
return;
}
if ((content instanceof Statement) && ((Statement) content).invalid()) {
return;
}
Sentence taskSentence = nal.getCurrentTask().sentence;
Sentence beliefSentence = nal.getCurrentBelief();
if (beliefSentence == null)
return;
int order = statement.getTemporalOrder();
boolean shiftedTimeForward = false;
if ((order != ORDER_NONE) && (order!=ORDER_INVALID) && (!taskSentence.isGoal()) && (!taskSentence.isQuest())) {
long baseTime = subSentence.getOccurenceTime();
if (baseTime == Stamp.ETERNAL) {
baseTime = nal.getTime();
}
long inc = order * nal.mem().param.duration.get();
long time = (side == 0) ? baseTime+inc : baseTime-inc;
shiftedTimeForward = (side == 0);
nal.getTheNewStamp().setOccurrenceTime(time);
}
TruthValue beliefTruth = beliefSentence.truth;
TruthValue truth1 = mainSentence.truth;
TruthValue truth2 = subSentence.truth;
TruthValue truth = null;
boolean strong = false;
BudgetValue budget;
if (taskSentence.isQuestion()) {
if (statement instanceof Equivalence) {
budget = BudgetFunctions.backward(beliefTruth, nal);
} else if (side == 0) {
budget = BudgetFunctions.backwardWeak(beliefTruth, nal);
} else {
budget = BudgetFunctions.backward(beliefTruth, nal);
}
} else if (taskSentence.isQuest()) {
if (statement instanceof Equivalence) {
budget = BudgetFunctions.backwardWeak(beliefTruth, nal);
} else if (side == 0) {
budget = BudgetFunctions.backward(beliefTruth, nal);
} else {
budget = BudgetFunctions.backwardWeak(beliefTruth, nal);
}
} else {
if (taskSentence.isGoal()) {
if (statement instanceof Equivalence) {
truth = TruthFunctions.desireStrong(truth1, truth2);
strong = true; //not for goals anymore
} else if (side == 0) {
truth = TruthFunctions.desireInd(truth1, truth2);
} else {
truth = TruthFunctions.desireDed(truth1, truth2);
strong = true; //not for goals anymore
}
} else { // isJudgment
if (statement instanceof Equivalence) {
truth = TruthFunctions.analogy(truth2, truth1);
strong = true;
} else if (side == 0) {
truth = TruthFunctions.deduction(truth1, truth2);
strong = true;
} else {
truth = TruthFunctions.abduction(truth2, truth1);
}
}
budget = BudgetFunctions.forward(truth, nal);
}
if(!Variables.indepVarUsedInvalid(content)) {
boolean allowOverlap = taskSentence.isJudgment() && strong;
List<Task> ret = nal.doublePremiseTask(content, truth, budget, false, allowOverlap); //(strong) when strong on judgement
if(shiftedTimeForward && ret != null && ret.size() > 0 && mainSentence.isEternal() && taskSentence.isJudgment() && mainSentence.isJudgment() && shiftedTimeForward) {
//discountPredictiveHypothesis(nal, mainSentence, budget);
// SyllogisticRules.generatePotentialNegConfirmation(nal, mainSentence, budget, mintime, maxtime, 1);
}
}
}
public static void generatePotentialNegConfirmation(DerivationContext nal, Sentence mainSentence, BudgetValue budget, long mintime, long maxtime, float priority) {
//derivation was successful and it was a judgment event
try { //that was predicted by an eternal belief that shifted time
float immediateDisappointmentConfidence = 0.1f;
Stamp stamp = new Stamp(nal.memory);
stamp.setOccurrenceTime(Stamp.ETERNAL);
//long serial = stamp.evidentialBase[0];
Sentence s = new Sentence(mainSentence.term, mainSentence.punctuation, new TruthValue(0.0f, immediateDisappointmentConfidence), stamp);
//s.producedByTemporalInduction = true; //also here to not go into sequence buffer
Task t = new Task(s, new BudgetValue(0.99f,0.1f,0.1f)); //Budget for one-time processing
Concept c = nal.memory.concept(((Statement) mainSentence.term).getPredicate()); //put into consequence concept
if(c != null /*&& mintime > nal.memory.time()*/ && c.observable && mainSentence.getTerm() instanceof Statement && ((Statement)mainSentence.getTerm()).getTemporalOrder() == TemporalRules.ORDER_FORWARD) {
if(c.negConfirmation == null || priority > c.negConfirmationPriority /*|| t.getPriority() > c.negConfirmation.getPriority() */) {
c.negConfirmation = t;
c.negConfirmationPriority = priority;
c.negConfirm_abort_maxtime = maxtime;
c.negConfirm_abort_mintime = mintime;
nal.memory.emit(Output.ANTICIPATE.class,((Statement) c.negConfirmation.sentence.term).getPredicate()); //disappoint/confirm printed anyway
}
}
}catch(Exception ex) {
System.out.println("problem in anticipation handling");
}
}
/**
* {<(&&, S1, S2, S3) ==> P>, S1} |- <(&&, S2, S3) ==> P> {<(&&, S2, S3) ==>
* P>, <S1 ==> S2>} |- <(&&, S1, S3) ==> P> {<(&&, S1, S3) ==> P>, <S1 ==>
* S2>} |- <(&&, S2, S3) ==> P>
*
* @param premise1 The conditional premise
* @param index The location of the shared term in the condition of premise1
* @param premise2 The premise which, or part of which, appears in the
* condition of premise1
* @param side The location of the shared term in premise2: 0 for subject, 1
* for predicate, -1 for the whole term
* @param nal Reference to the memory
*/
static void conditionalDedInd(Sentence premise1Sentence, Implication premise1, short index, Term premise2, int side, DerivationContext nal) {
Task task = nal.getCurrentTask();
Sentence taskSentence = task.sentence;
Sentence belief = nal.getCurrentBelief();
boolean deduction = (side != 0);
boolean conditionalTask = Variables.hasSubstitute(Symbols.VAR_INDEPENDENT, premise2, belief.term);
Term commonComponent;
Term newComponent = null;
if (side == 0) {
commonComponent = ((Statement) premise2).getSubject();
newComponent = ((Statement) premise2).getPredicate();
} else if (side == 1) {
commonComponent = ((Statement) premise2).getPredicate();
newComponent = ((Statement) premise2).getSubject();
} else {
commonComponent = premise2;
}
Term subj = premise1.getSubject();
if (!(subj instanceof Conjunction)) {
return;
}
Conjunction oldCondition = (Conjunction) subj;
int index2 = Terms.indexOf(oldCondition.term,commonComponent);
if (index2 >= 0) {
index = (short) index2;
} else {
Term[] u = new Term[] { premise1, premise2 };
boolean match = Variables.unify(Symbols.VAR_INDEPENDENT, oldCondition.term[index], commonComponent, u);
premise1 = (Implication) u[0]; premise2 = u[1];
if (!match && (commonComponent.getClass() == oldCondition.getClass())) {
CompoundTerm compoundCommonComponent = ((CompoundTerm) commonComponent);
if ((oldCondition.term.length > index) && (compoundCommonComponent.term.length > index)) { // assumption: { was missing
u = new Term[] { premise1, premise2 };
match = Variables.unify(Symbols.VAR_INDEPENDENT,
oldCondition.term[index],
compoundCommonComponent.term[index],
u);
premise1 = (Implication) u[0]; premise2 = u[1];
}
}
if (!match) {
return;
}
}
int conjunctionOrder = subj.getTemporalOrder();
if (conjunctionOrder == ORDER_FORWARD) {
if (index > 0) {
return;
}
if ((side == 0) && (premise2.getTemporalOrder() == ORDER_FORWARD)) {
return;
}
if ((side == 1) && (premise2.getTemporalOrder() == ORDER_BACKWARD)) {
return;
}
}
Term newCondition;
if (oldCondition.equals(commonComponent)) {
newCondition = null;
} else {
newCondition = oldCondition.setComponent(index, newComponent, nal.mem());
}
Term content;
long delta = 0;
long mintime = 0;
long maxtime = 0;
boolean predictedEvent = false;
final Interval.AtomicDuration duration = nal.mem().param.duration;
if (newCondition != null) {
if (newCondition instanceof Interval) {
content = premise1.getPredicate();
delta = ((Interval) newCondition).getTime(duration);
if(taskSentence.getOccurenceTime() != Stamp.ETERNAL) {
mintime = taskSentence.getOccurenceTime() + Interval.magnitudeToTime(((Interval) newCondition).magnitude - 1, duration);
maxtime = taskSentence.getOccurenceTime() + Interval.magnitudeToTime(((Interval) newCondition).magnitude + 2, duration);
predictedEvent = true;
}
} else if ((newCondition instanceof Conjunction) && (((CompoundTerm) newCondition).term[0] instanceof Interval)) {
Interval interval = (Interval) ((CompoundTerm) newCondition).term[0];
delta = interval.getTime(duration);
newCondition = ((CompoundTerm)newCondition).setComponent(0, null, nal.mem());
content = Statement.make(premise1, newCondition, premise1.getPredicate(), premise1.getTemporalOrder());
} else {
content = Statement.make(premise1, newCondition, premise1.getPredicate(), premise1.getTemporalOrder());
}
} else {
content = premise1.getPredicate();
}
if (content == null)
return;
if(!predictedEvent && ((Conjunction) subj).getTemporalOrder() == TemporalRules.ORDER_FORWARD) { //do not allow sequences
boolean last_ival = false; //which have two intervals as result of this, makes sure we only detach (&/ from left side
for(Term t: ((Conjunction) subj).term) {
boolean ival = t instanceof Interval;
if(last_ival && ival) {
return;
}
last_ival = ival;
}
}
if (delta != 0) {
long baseTime = (belief.term instanceof Implication) ?
taskSentence.getOccurenceTime() : belief.getOccurenceTime();
if (baseTime == Stamp.ETERNAL) {
baseTime = nal.getTime();
}
if(premise1.getTemporalOrder()==TemporalRules.ORDER_CONCURRENT)
return;
baseTime += delta;
nal.getTheNewStamp().setOccurrenceTime(baseTime);
}
TruthValue truth1 = taskSentence.truth;
TruthValue truth2 = belief.truth;
TruthValue truth = null;
BudgetValue budget;
if (taskSentence.isQuestion() || taskSentence.isQuest()) {
budget = BudgetFunctions.backwardWeak(truth2, nal);
} else {
if (taskSentence.isGoal()) {
if (conditionalTask) {
truth = TruthFunctions.desireWeak(truth1, truth2);
} else if (deduction) {
truth = TruthFunctions.desireInd(truth1, truth2);
} else {
truth = TruthFunctions.desireDed(truth1, truth2);
}
} else {
if (deduction) {
truth = TruthFunctions.deduction(truth1, truth2);
} else if (conditionalTask) {
truth = TruthFunctions.induction(truth2, truth1);
} else {
truth = TruthFunctions.induction(truth1, truth2);
}
}
budget = BudgetFunctions.forward(truth, nal);
}
List<Task> ret = nal.doublePremiseTask(content, truth, budget,false, taskSentence.isJudgment() && deduction); //(allow overlap) when deduction on judgment
if(!nal.evidentalOverlap && ret != null && ret.size() > 0) {
if(predictedEvent && taskSentence.isJudgment() && truth != null && truth.getExpectation() > Parameters.DEFAULT_CONFIRMATION_EXPECTATION &&
!premise1Sentence.stamp.alreadyAnticipatedNegConfirmation) {
premise1Sentence.stamp.alreadyAnticipatedNegConfirmation = true;
SyllogisticRules.generatePotentialNegConfirmation(nal, premise1Sentence, budget, mintime, maxtime, 1);
}
}
}
/**
* {<(&&, S1, S2, S3) <=> P>, S1} |- <(&&, S2, S3) <=> P> {<(&&, S2, S3) <=> P>,
* <S1 ==> S2>} |- <(&&, S1, S3) <=> P> {<(&&, S1, S3) <=> P>, <S1 ==>
*
* @param premise1 The equivalence premise
* @param index The location of the shared term in the condition of premise1
* @param premise2 The premise which, or part of which, appears in the
* condition of premise1
* @param side The location of the shared term in premise2: 0 for subject, 1
* for predicate, -1 for the whole term
* @param nal Reference to the memory
*/
static void conditionalAna(Equivalence premise1, short index, Term premise2, int side, DerivationContext nal) {
Task task = nal.getCurrentTask();
Sentence taskSentence = task.sentence;
Sentence belief = nal.getCurrentBelief();
boolean conditionalTask = Variables.hasSubstitute(Symbols.VAR_INDEPENDENT, premise2, belief.term);
Term commonComponent;
Term newComponent = null;
if (side == 0) {
commonComponent = ((Statement) premise2).getSubject();
newComponent = ((Statement) premise2).getPredicate();
} else if (side == 1) {
commonComponent = ((Statement) premise2).getPredicate();
newComponent = ((Statement) premise2).getSubject();
} else {
commonComponent = premise2;
}
Term tm = premise1.getSubject();
if (!(tm instanceof Conjunction)) {
return;
}
Conjunction oldCondition = (Conjunction) tm;
Term[] u = new Term[] { premise1, premise2 };
boolean match = Variables.unify(Symbols.VAR_DEPENDENT, oldCondition.term[index], commonComponent, u);
premise1 = (Equivalence) u[0]; premise2 = u[1];
if (!match && (commonComponent.getClass() == oldCondition.getClass())) {
u = new Term[] { premise1, premise2 };
match = Variables.unify(Symbols.VAR_DEPENDENT, oldCondition.term[index], ((CompoundTerm) commonComponent).term[index], u);
premise1 = (Equivalence) u[0]; premise2 = u[1];
}
if (!match) {
return;
}
int conjunctionOrder = oldCondition.getTemporalOrder();
if (conjunctionOrder == ORDER_FORWARD) {
if (index > 0) {
return;
}
if ((side == 0) && (premise2.getTemporalOrder() == ORDER_FORWARD)) {
return;
}
if ((side == 1) && (premise2.getTemporalOrder() == ORDER_BACKWARD)) {
return;
}
}
Term newCondition;
if (oldCondition.equals(commonComponent)) {
newCondition = null;
} else {
newCondition = oldCondition.setComponent(index, newComponent, nal.mem());
}
Term content;
if (newCondition != null) {
content = Statement.make(premise1, newCondition, premise1.getPredicate(), premise1.getTemporalOrder());
} else {
content = premise1.getPredicate();
}
if (content == null)
return;
TruthValue truth1 = taskSentence.truth;
TruthValue truth2 = belief.truth;
TruthValue truth = null;
BudgetValue budget;
if (taskSentence.isQuestion() || taskSentence.isQuest()) {
budget = BudgetFunctions.backwardWeak(truth2, nal);
} else {
if (taskSentence.isGoal()) {
if (conditionalTask) {
truth = TruthFunctions.desireWeak(truth1, truth2);
} else {
truth = TruthFunctions.desireDed(truth1, truth2);
}
} else {
if (conditionalTask) {
truth = TruthFunctions.comparison(truth1, truth2);
} else {
truth = TruthFunctions.analogy(truth1, truth2);
}
}
budget = BudgetFunctions.forward(truth, nal);
}
nal.doublePremiseTask(content, truth, budget, false, taskSentence.isJudgment() && !conditionalTask); //(allow overlap) when !conditionalTask on judgment
}
/**
* {<(&&, S2, S3) ==> P>, <(&&, S1, S3) ==> P>} |- <S1 ==> S2>
*
* @param cond1 The condition of the first premise
* @param cond2 The condition of the second premise
* @param taskContent The first premise
* @param st2 The second premise
* @param nal Reference to the memory
* @return Whether there are derived tasks
*/
static boolean conditionalAbd(Term cond1, Term cond2, Statement st1, Statement st2, DerivationContext nal) {
if (!(st1 instanceof Implication) || !(st2 instanceof Implication)) {
return false;
}
if (!(cond1 instanceof Conjunction) && !(cond2 instanceof Conjunction)) {
return false;
}
int order1 = st1.getTemporalOrder();
int order2 = st2.getTemporalOrder();
if (order1 != reverseOrder(order2)) {
return false;
}
Term term1 = null;
Term term2 = null;
// if ((cond1 instanceof Conjunction) && !Variable.containVarDep(cond1.getName())) {
if (cond1 instanceof Conjunction) {
term1 = reduceComponents((CompoundTerm) cond1, cond2, nal.mem());
}
// if ((cond2 instanceof Conjunction) && !Variable.containVarDep(cond2.getName())) {
if (cond2 instanceof Conjunction) {
term2 = reduceComponents((CompoundTerm) cond2, cond1, nal.mem());
}
if ((term1 == null) && (term2 == null)) {
return false;
}
Task task = nal.getCurrentTask();
Sentence sentence = task.sentence;
Sentence belief = nal.getCurrentBelief();
TruthValue value1 = sentence.truth;
TruthValue value2 = belief.truth;
Term content;
boolean keepOrder = Variables.hasSubstitute(Symbols.VAR_INDEPENDENT, st1, task.getTerm());
TruthValue truth = null;
BudgetValue budget;
//is this correct because the second term2!=null condition may overwrite the first
//should the inner if be: if (term2 == null) then it makes sense.
if (term1 != null) {
if (term2 != null) {
content = Statement.make(st2, term2, term1, st2.getTemporalOrder());
} else {
content = term1;
if(content.hasVarIndep()) {
return false;
}
}
if (sentence.isQuestion() || sentence.isQuest()) {
budget = BudgetFunctions.backwardWeak(value2, nal);
} else {
if (sentence.isGoal()) {
if (keepOrder) {
truth = TruthFunctions.desireDed(value1, value2);
} else {
truth = TruthFunctions.desireInd(value1, value2);
}
} else { // isJudgment
truth = TruthFunctions.abduction(value2, value1);
}
budget = BudgetFunctions.forward(truth, nal);
}
nal.doublePremiseTask(content, truth, budget,false, false);
}
if (term2 != null) {
if (term1 != null) {
content = Statement.make(st1, term1, term2, st1.getTemporalOrder());
} else {
content = term2;
if(content.hasVarIndep()) {
return false;
}
}
if (sentence.isQuestion() || sentence.isQuest()) {
budget = BudgetFunctions.backwardWeak(value2, nal);
} else {
if (sentence.isGoal()) {
if (keepOrder) {
truth = TruthFunctions.desireDed(value1, value2);
} else {
truth = TruthFunctions.desireInd(value1, value2);
}
} else { // isJudgment
truth = TruthFunctions.abduction(value1, value2);
}
budget = BudgetFunctions.forward(truth, nal);
}
nal.doublePremiseTask(content, truth, budget,false, false);
}
return true;
}
/**
* {(&&, <#x() --> S>, <#x() --> P>>, <M --> P>} |- <M --> S>
*
* @param compound The compound term to be decomposed
* @param component The part of the compound to be removed
* @param compoundTask Whether the compound comes from the task
* @param nal Reference to the memory
*/
static void elimiVarDep(CompoundTerm compound, Term component, boolean compoundTask, DerivationContext nal) {
Term comp = null;
for(Term t : compound) {
Term[] unify = new Term[] { t, component };
if(Variables.unify(Symbols.VAR_DEPENDENT, unify)) {
comp = t;
break;
}
}
if(comp == null) {
return;
}
Term content = reduceComponents(compound, comp, nal.mem());
if ((content == null) || ((content instanceof Statement) && ((Statement) content).invalid())) {
return;
}
Task task = nal.getCurrentTask();
Sentence sentence = task.sentence;
Sentence belief = nal.getCurrentBelief();
TruthValue v1 = sentence.truth;
TruthValue v2 = belief.truth;
TruthValue truth = null;
BudgetValue budget;
if (sentence.isQuestion() || sentence.isQuest()) {
budget = (compoundTask ? BudgetFunctions.backward(v2, nal) : BudgetFunctions.backwardWeak(v2, nal));
} else {
if (sentence.isGoal()) {
truth = (compoundTask ? TruthFunctions.desireDed(v1, v2) : TruthFunctions.desireInd(v1, v2)); // to check
} else {
truth = (compoundTask ? TruthFunctions.anonymousAnalogy(v1, v2) : TruthFunctions.anonymousAnalogy(v2, v1));
}
budget = BudgetFunctions.compoundForward(truth, content, nal);
}
nal.doublePremiseTask(content, truth, budget,false, false);
}
}
|
package ajb.utils;
import java.awt.Point;
import ajb.domain.Pixel;
public class PixelGridUtils {
/**
* Returns true if the passed in point is within the boundaries of the
* passed in grid i.e. in a grid initialise with 10 rows and 10 columns
* points with x or y above 10 are not within the grid.
*
* @param point {@link Point}
* @param grid {@link Pixel}[][]
* @return {@link boolean}
*/
public static boolean isPointWithinGrid(Point point, Pixel[][] grid) {
try {
@SuppressWarnings("unused")
Pixel pixel = grid[point.x][point.y];
return true;
} catch (IndexOutOfBoundsException ioobe) {
return false;
}
}
/**
* Outputs the passed in grid to the console
*
* @param grid {@link Pixel}[][]
*/
public static void outputGridAsAscii(Pixel[][] grid) {
for (int x = 0; x < grid.length; x++) {
StringBuilder strBld = new StringBuilder();
for (int y = 0; y < grid[0].length; y++) {
if (grid[x][y].value == Pixel.EMPTY) {
strBld.append(" ");
} else if (grid[x][y].value == Pixel.FILLED) {
strBld.append(".");
} else if (grid[x][y].value == Pixel.BORDER) {
strBld.append("x");
}
}
System.out.println(strBld.toString());
}
}
/**
* Simply populates the passed in grid with {@link Pixel} objects
*
* @param grid {@link Pixel}[][]
* @param rows {@link int}
* @param cols {@link int}
*/
public static void initEmptyGrid(Pixel[][] grid, int rows, int cols) {
for (int x = 0; x < rows; x++) {
for (int y = 0; y < cols; y++) {
grid[x][y] = new Pixel();
}
}
}
/**
* Takes the passed in grid and returns a grid that has been floored i.e.
* reduced so that rows and column with no filled pixels on them are removed
*
* @param grid {@link Pixel}[][]
* @return {@link Pixel}[][]
*/
public static Pixel[][] floor(Pixel[][] grid) {
Pixel[][] flooredGrid = null;
int lastFilledRow = 0;
int lastFilledCol = 0;
int firstFilledRow = grid.length;
int firstFilledColumn = grid[0].length;
for (int r = 0; r < grid.length; r++) {
boolean empty = true;
for (int c = 0; c < grid[0].length; c++) {
boolean colEmpty = true;
if (grid[r][c].value != Pixel.EMPTY) {
if (firstFilledRow > r) {
firstFilledRow = r;
}
if (firstFilledColumn > c) {
firstFilledColumn = c;
}
empty = false;
colEmpty = false;
}
if (!colEmpty && c > lastFilledCol) {
lastFilledCol = c;
}
}
if (!empty) {
lastFilledRow = r;
}
}
flooredGrid = new Pixel[lastFilledRow - (firstFilledRow - 1)][lastFilledCol - (firstFilledColumn - 1)];
int newRow = 0;
for (int r = firstFilledRow; r < lastFilledRow + 1; r++) {
int newCol = 0;
for (int c = firstFilledColumn; c < lastFilledCol + 1; c++) {
flooredGrid[newRow][newCol] = grid[r][c];
newCol++;
}
newRow++;
}
return flooredGrid;
}
/**
* Takes the passed in grid and returns a grid that contains the original
* plus a mirrored copy
*
* @param halfGrid {@link Pixel}[][]
* @return {@link Pixel}[][]
*/
public static Pixel[][] mirrorCopyGridHorizontally(Pixel[][] halfGrid) {
int rows = halfGrid.length;
int cols = (halfGrid[0].length * 2);
Pixel[][] fullGrid = new Pixel[rows][cols];
// Copy left to right
for (int r = 0; r < rows; r++) {
for (int c = 0; c < (cols / 2); c++) {
fullGrid[r][c] = halfGrid[r][c];
fullGrid[r][(cols - 1) - c] = halfGrid[r][c];
}
}
return fullGrid;
}
/**
* Takes the passed in grid extends it by 2 then puts a border pixel next to
* every edge pixel i.e. pixels that do not have another filled pixel next
* to them
*
* @param grid {@link Pixel}[][]
* @return {@link Pixel}[][]
*/
public static Pixel[][] addBorders(Pixel[][] grid) {
Pixel[][] gridWithBorders = PixelGridUtils.extendGrid(grid, 2);
for (int r = 0; r < gridWithBorders.length; r++) {
for (int c = 0; c < gridWithBorders[0].length; c++) {
if (gridWithBorders[r][c].value == Pixel.FILLED) {
// Top
if (gridWithBorders[r == 0 ? 0 : r - 1][c].value != Pixel.FILLED) {
gridWithBorders[r == 0 ? 0 : r - 1][c].value = Pixel.BORDER;
}
// Left
if (gridWithBorders[r][c == 0 ? 0 : c - 1].value != Pixel.FILLED) {
gridWithBorders[r][c == 0 ? 0 : c - 1].value = Pixel.BORDER;
}
// Right
if (gridWithBorders[r][c == (gridWithBorders[0].length / 2) - 1 ? (gridWithBorders[0].length / 2) - 1 : c + 1].value != Pixel.FILLED) {
gridWithBorders[r][c == (gridWithBorders[0].length / 2) - 1 ? (gridWithBorders[0].length / 2) - 1 : c + 1].value = Pixel.BORDER;
}
// Bottom
if (gridWithBorders[r == gridWithBorders.length - 1 ? gridWithBorders.length - 1 : r + 1][c].value != Pixel.FILLED) {
gridWithBorders[r == gridWithBorders.length - 1 ? gridWithBorders.length - 1 : r + 1][c].value = Pixel.BORDER;
}
}
}
}
return gridWithBorders;
}
/**
* Takes the passed in grid and extends it by the passed in amount
*
* @param grid {@link Pixel}[][]
* @param extendAmount {@link int}
* @return {@link Pixel}[][]
*/
public static Pixel[][] extendGrid(Pixel[][] grid, int extendAmount) {
Pixel[][] extendedGrid = new Pixel[grid.length + extendAmount][grid[0].length + extendAmount];
initEmptyGrid(extendedGrid, grid.length + extendAmount, grid[0].length + extendAmount);
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
extendedGrid[r + (extendAmount / 2)][c + (extendAmount / 2)] = grid[r][c];
}
}
return extendedGrid;
}
/**
* Loops through each pixel in the grid and works out if they are surrounded
* by other filled pixels i.e. no straight path to the edge of the grid
* without encountering anything but empty pixels.
*
* This does have the effect of leaving some plain areas on the generated
* vessels - effects larger ones more.
*
* @TODO Implement some noise to any pixels set as Pixel.SECONDARY
*
* @param grid {@link Pixel}[][]
*/
public static void fillEmptySurroundedPixelsInGrid(Pixel[][] grid) {
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c].value == Pixel.EMPTY) {
boolean filledPixelAbove = false;
boolean filledPixelBelow = false;
boolean filledPixelOnTheLeft = false;
boolean filledPixelOnTheRight = false;
for (int r1 = r - 1; r1 > 0; r1
if (grid[r1][c].value == Pixel.FILLED) {
filledPixelAbove = true;
break;
}
}
for (int r1 = r + 1; r1 < grid.length; r1++) {
if (grid[r1][c].value == Pixel.FILLED) {
filledPixelBelow = true;
break;
}
}
for (int c1 = c - 1; c1 > 0; c1
if (grid[r][c1].value == Pixel.FILLED) {
filledPixelOnTheLeft = true;
break;
}
}
for (int c1 = c + 1; c1 < grid[0].length; c1++) {
if (grid[r][c1].value == Pixel.FILLED) {
filledPixelOnTheRight = true;
break;
}
}
if (filledPixelAbove && filledPixelBelow && filledPixelOnTheLeft && filledPixelOnTheRight) {
grid[r][c].value = Pixel.SECONDARY;
}
}
}
}
}
}
|
package com.plugin.datepicker;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.Random;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.util.Log;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TimePicker;
@SuppressLint("NewApi")
public class DatePickerPlugin extends CordovaPlugin {
private static final String ACTION_DATE = "date";
private static final String ACTION_TIME = "time";
private static final String RESULT_ERROR = "error";
private static final String RESULT_CANCEL = "cancel";
private final String pluginName = "DatePickerPlugin";
// On some devices, onDateSet or onTimeSet are being called twice
private boolean called = false;
private boolean canceled = false;
@Override
public boolean execute(final String action, final JSONArray data, final CallbackContext callbackContext) {
Log.d(pluginName, "DatePicker called with options: " + data);
called = false;
canceled = false;
boolean result = false;
this.show(data, callbackContext);
result = true;
return result;
}
public synchronized void show(final JSONArray data, final CallbackContext callbackContext) {
DatePickerPlugin datePickerPlugin = this;
Context currentCtx = cordova.getActivity();
Runnable runnable;
JsonDate jsonDate = new JsonDate().fromJson(data);
if (ACTION_TIME.equalsIgnoreCase(jsonDate.action)) {
runnable = runnableTimeDialog(datePickerPlugin, currentCtx,
callbackContext, jsonDate, Calendar.getInstance(TimeZone.getDefault()));
} else {
runnable = runnableDatePicker(datePickerPlugin, currentCtx, callbackContext, jsonDate);
}
cordova.getActivity().runOnUiThread(runnable);
}
private TimePicker timePicker;
private int timePickerHour = 0;
private int timePickerMinute = 0;
private Runnable runnableTimeDialog(final DatePickerPlugin datePickerPlugin,
final Context currentCtx, final CallbackContext callbackContext,
final JsonDate jsonDate, final Calendar calendarDate) {
return new Runnable() {
@Override
public void run() {
final TimeSetListener timeSetListener = new TimeSetListener(datePickerPlugin, callbackContext, calendarDate);
final TimePickerDialog timeDialog = new TimePickerDialog(currentCtx, timeSetListener, jsonDate.hour,
jsonDate.minutes, jsonDate.is24Hour) {
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
timePicker = view;
timePickerHour = hourOfDay;
timePickerMinute = minute;
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
timeDialog.setCancelable(true);
timeDialog.setCanceledOnTouchOutside(false);
if (!jsonDate.nowText.isEmpty()){
timeDialog.setButton(DialogInterface.BUTTON_NEUTRAL, jsonDate.nowText, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (timePicker != null) {
Calendar now = Calendar.getInstance();
timeSetListener.onTimeSet(timePicker, now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE));
}
}
});
}
String labelCancel = jsonDate.cancelText.isEmpty() ? currentCtx.getString(android.R.string.cancel) : jsonDate.cancelText;
timeDialog.setButton(DialogInterface.BUTTON_NEGATIVE, labelCancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
canceled = true;
callbackContext.error(RESULT_CANCEL);
}
});
String labelOk = jsonDate.okText.isEmpty() ? currentCtx.getString(android.R.string.ok) : jsonDate.okText;
timeDialog.setButton(DialogInterface.BUTTON_POSITIVE, labelOk, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (timePicker != null) {
Calendar now = Calendar.getInstance();
timeSetListener.onTimeSet(timePicker, timePickerHour, timePickerMinute);
}
}
});
}
timeDialog.show();
timeDialog.updateTime(new Random().nextInt(23), new Random().nextInt(59));
timeDialog.updateTime(jsonDate.hour, jsonDate.minutes);
}
};
}
private Runnable runnableDatePicker(
final DatePickerPlugin datePickerPlugin, final Context currentCtx,
final CallbackContext callbackContext, final JsonDate jsonDate) {
return new Runnable() {
@Override
public void run() {
final DateSetListener dateSetListener = new DateSetListener(datePickerPlugin, callbackContext, jsonDate);
final DatePickerDialog dateDialog = new DatePickerDialog(currentCtx, dateSetListener, jsonDate.year,
jsonDate.month, jsonDate.day);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
prepareDialog(dateDialog, dateSetListener, callbackContext, currentCtx, jsonDate);
}
else {
prepareDialogPreHoneycomb(dateDialog, callbackContext, currentCtx, jsonDate);
}
dateDialog.show();
}
};
}
private void prepareDialog(final DatePickerDialog dateDialog, final OnDateSetListener dateListener,
final CallbackContext callbackContext, Context currentCtx, JsonDate jsonDate) {
dateDialog.setCancelable(true);
dateDialog.setCanceledOnTouchOutside(false);
if (!jsonDate.todayText.isEmpty()){
dateDialog.setButton(DialogInterface.BUTTON_NEUTRAL, jsonDate.todayText, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Calendar now = Calendar.getInstance();
DatePicker datePicker = dateDialog.getDatePicker();
dateListener.onDateSet(datePicker, now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH));
}
});
}
String labelCancel = jsonDate.cancelText.isEmpty() ? currentCtx.getString(android.R.string.cancel) : jsonDate.cancelText;
dateDialog.setButton(DialogInterface.BUTTON_NEGATIVE, labelCancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
canceled = true;
}
});
String labelOk = jsonDate.okText.isEmpty() ? currentCtx.getString(android.R.string.ok) : jsonDate.okText;
dateDialog.setButton(DialogInterface.BUTTON_POSITIVE, labelOk, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
DatePicker datePicker = dateDialog.getDatePicker();
dateListener.onDateSet(datePicker, datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());
}
});
DatePicker dp = dateDialog.getDatePicker();
if(jsonDate.minDate > 0) {
dp.setMinDate(jsonDate.minDate);
}
if(jsonDate.maxDate > 0 && jsonDate.maxDate > jsonDate.minDate) {
dp.setMaxDate(jsonDate.maxDate);
}
}
private void prepareDialogPreHoneycomb(DatePickerDialog dateDialog,
final CallbackContext callbackContext, Context currentCtx, final JsonDate jsonDate){
java.lang.reflect.Field mDatePickerField = null;
try {
mDatePickerField = dateDialog.getClass().getDeclaredField("mDatePicker");
} catch (NoSuchFieldException e) {
callbackContext.error(RESULT_ERROR);
}
mDatePickerField.setAccessible(true);
DatePicker pickerView = null;
try {
pickerView = (DatePicker) mDatePickerField.get(dateDialog);
} catch (IllegalArgumentException e) {
callbackContext.error(RESULT_ERROR);
} catch (IllegalAccessException e) {
callbackContext.error(RESULT_ERROR);
}
final Calendar startDate = Calendar.getInstance();
startDate.setTimeInMillis(jsonDate.minDate);
final Calendar endDate = Calendar.getInstance();
endDate.setTimeInMillis(jsonDate.maxDate);
final int minYear = startDate.get(Calendar.YEAR);
final int minMonth = startDate.get(Calendar.MONTH);
final int minDay = startDate.get(Calendar.DAY_OF_MONTH);
final int maxYear = endDate.get(Calendar.YEAR);
final int maxMonth = endDate.get(Calendar.MONTH);
final int maxDay = endDate.get(Calendar.DAY_OF_MONTH);
if(startDate !=null || endDate != null) {
pickerView.init(jsonDate.year, jsonDate.month, jsonDate.day, new OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int month, int day) {
if(jsonDate.maxDate > 0 && jsonDate.maxDate > jsonDate.minDate) {
if(year > maxYear || month > maxMonth && year == maxYear || day > maxDay && year == maxYear && month == maxMonth){
view.updateDate(maxYear, maxMonth, maxDay);
}
}
if(jsonDate.minDate > 0) {
if(year < minYear || month < minMonth && year == minYear || day < minDay && year == minYear && month == minMonth) {
view.updateDate(minYear, minMonth, minDay);
}
}
}
});
}
}
private final class DateSetListener implements OnDateSetListener {
private JsonDate jsonDate;
private final DatePickerPlugin datePickerPlugin;
private final CallbackContext callbackContext;
private DateSetListener(DatePickerPlugin datePickerPlugin, CallbackContext callbackContext, JsonDate jsonDate) {
this.datePickerPlugin = datePickerPlugin;
this.callbackContext = callbackContext;
this.jsonDate = jsonDate;
}
/**
* Return a string containing the date in the format YYYY/MM/DD or call TimeDialog if action != date
*/
@Override
public void onDateSet(final DatePicker view, final int year, final int monthOfYear, final int dayOfMonth) {
if (canceled || called) {
return;
}
called = true;
canceled = false;
Log.d("onDateSet", "called: " + called);
Log.d("onDateSet", "canceled: " + canceled);
Log.d("onDateSet", "mode: " + jsonDate.action);
if (ACTION_DATE.equalsIgnoreCase(jsonDate.action)) {
String returnDate = year + "/" + (monthOfYear + 1) + "/" + dayOfMonth;
Log.d("onDateSet", "returnDate: " + returnDate);
callbackContext.success(returnDate);
} else {
// Open time dialog
Calendar selectedDate = Calendar.getInstance();
selectedDate.set(Calendar.YEAR, year);
selectedDate.set(Calendar.MONTH, monthOfYear);
selectedDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
cordova.getActivity().runOnUiThread(runnableTimeDialog(datePickerPlugin, cordova.getActivity(),
callbackContext, jsonDate, selectedDate));
}
}
}
private final class TimeSetListener implements OnTimeSetListener {
private Calendar calendarDate;
private final CallbackContext callbackContext;
private TimeSetListener(DatePickerPlugin datePickerPlugin, CallbackContext callbackContext, Calendar selectedDate) {
this.callbackContext = callbackContext;
this.calendarDate = selectedDate != null ? selectedDate : Calendar.getInstance();
}
/**
* Return the current date with the time modified as it was set in the
* time picker.
*/
@Override
public void onTimeSet(final TimePicker view, final int hourOfDay, final int minute) {
if (canceled) {
return;
}
calendarDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendarDate.set(Calendar.MINUTE, minute);
calendarDate.set(Calendar.SECOND, 0);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String toReturn = sdf.format(calendarDate.getTime());
callbackContext.success(toReturn);
}
}
private final class JsonDate {
private String action = ACTION_DATE;
private String okText = "";
private String cancelText = "";
private String todayText = "";
private String nowText = "";
private long minDate = 0;
private long maxDate = 0;
private int month = 0;
private int day = 0;
private int year = 0;
private int hour = 0;
private int minutes = 0;
private boolean is24Hour = false;
public JsonDate() {
reset(Calendar.getInstance());
}
private void reset(Calendar c) {
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
hour = c.get(Calendar.HOUR_OF_DAY);
minutes = c.get(Calendar.MINUTE);
}
public JsonDate fromJson(JSONArray data) {
try {
JSONObject obj = data.getJSONObject(0);
action = isNotEmpty(obj, "mode") ? obj.getString("mode")
: ACTION_DATE;
minDate = isNotEmpty(obj, "minDate") ? obj.getLong("minDate") : 0l;
maxDate = isNotEmpty(obj, "maxDate") ? obj.getLong("maxDate") : 0l;
okText = isNotEmpty(obj, "okText") ? obj.getString("okText") : "";
cancelText = isNotEmpty(obj, "cancelText") ? obj
.getString("cancelText") : "";
todayText = isNotEmpty(obj, "todayText") ? obj
.getString("todayText") : "";
nowText = isNotEmpty(obj, "nowText") ? obj.getString("nowText")
: "";
is24Hour = isNotEmpty(obj, "is24Hour") ? obj.getBoolean("is24Hour")
: false;
String optionDate = obj.getString("date");
String[] datePart = optionDate.split("/");
month = Integer.parseInt(datePart[0]) - 1;
day = Integer.parseInt(datePart[1]);
year = Integer.parseInt(datePart[2]);
hour = Integer.parseInt(datePart[3]);
minutes = Integer.parseInt(datePart[4]);
} catch (JSONException e) {
reset(Calendar.getInstance());
}
return this;
}
public boolean isNotEmpty(JSONObject object, String key)
throws JSONException {
return object.has(key)
&& !object.isNull(key)
&& object.get(key).toString().length() > 0
&& !JSONObject.NULL.toString().equals(
object.get(key).toString());
}
}
}
|
package re.notifica.cordova;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import com.google.android.gms.common.api.CommonStatusCodes;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import re.notifica.Notificare;
import re.notifica.NotificareCallback;
import re.notifica.NotificareError;
import re.notifica.beacon.BeaconRangingListener;
import re.notifica.billing.BillingManager;
import re.notifica.billing.BillingResult;
import re.notifica.billing.Purchase;
import re.notifica.model.NotificareApplicationInfo;
import re.notifica.model.NotificareAsset;
import re.notifica.model.NotificareBeacon;
import re.notifica.model.NotificareDevice;
import re.notifica.model.NotificareInboxItem;
import re.notifica.model.NotificareNotification;
import re.notifica.model.NotificarePass;
import re.notifica.model.NotificareProduct;
import re.notifica.model.NotificareScannable;
import re.notifica.model.NotificareTimeOfDay;
import re.notifica.model.NotificareTimeOfDayRange;
import re.notifica.model.NotificareUser;
import re.notifica.model.NotificareUserData;
import re.notifica.model.NotificareUserDataField;
import re.notifica.model.NotificareUserPreference;
import re.notifica.model.NotificareUserSegment;
public class NotificarePlugin extends CordovaPlugin implements Observer<SortedSet<NotificareInboxItem>>, Notificare.OnNotificareReadyListener, Notificare.OnServiceErrorListener, Notificare.OnNotificareNotificationListener, BeaconRangingListener, Notificare.OnBillingReadyListener, BillingManager.OnRefreshFinishedListener, BillingManager.OnPurchaseFinishedListener {
private static final String TAG = NotificarePlugin.class.getSimpleName();
private static final int SCANNABLE_REQUEST_CODE = 9004;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
private LiveData<SortedSet<NotificareInboxItem>> mInboxItems;
private boolean mIsBillingReady = false;
private CallbackContext mainCallback;
private List<PluginResult> eventQueue;
/**
* Shared instance
*/
private static NotificarePlugin instance;
private static final Object lock = new Object();
/**
* Constructor
*/
public NotificarePlugin() {
instance = this;
eventQueue = new ArrayList<>();
}
/**
* Singleton method
* @return the shared instance of the plugin
*/
public static NotificarePlugin shared() {
synchronized (lock) {
if (instance == null) {
instance = new NotificarePlugin();
}
return instance;
}
}
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
this.handleIntent(cordova.getActivity().getIntent());
}
@Override
public void onPause(boolean multitasking) {
super.onPause(multitasking);
Notificare.shared().removeServiceErrorListener(this);
Notificare.shared().removeNotificareNotificationListener(this);
if (Notificare.shared().getBeaconClient() != null) {
Notificare.shared().getBeaconClient().removeRangingListener(this);
}
if (mInboxItems != null) {
mInboxItems.removeObserver(this);
}
Notificare.shared().removeBillingReadyListener(this);
}
@Override
public void onResume(boolean multitasking) {
super.onResume(multitasking);
Notificare.shared().addServiceErrorListener(this);
Notificare.shared().addNotificareNotificationListener(this);
if (Notificare.shared().getBeaconClient() != null) {
Notificare.shared().getBeaconClient().addRangingListener(this);
}
if (Notificare.shared().getInboxManager() != null) {
mInboxItems = Notificare.shared().getInboxManager().getObservableItems();
mInboxItems.observeForever(this);
}
Notificare.shared().addBillingReadyListener(this);
}
@Override
public void onDestroy() {
super.onDestroy();
Notificare.shared().removeServiceErrorListener(this);
Notificare.shared().removeNotificareNotificationListener(this);
if (Notificare.shared().getBeaconClient() != null) {
Notificare.shared().getBeaconClient().removeRangingListener(this);
}
if (mInboxItems != null) {
mInboxItems.removeObserver(this);
}
Notificare.shared().removeBillingReadyListener(this);
}
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("launch")) {
this.launch(args, callbackContext);
return true;
} else if (action.equals("unlaunch")) {
this.unlaunch(callbackContext);
return true;
} else if (action.equals("setAuthorizationOptions")) {
callbackContext.success();
return true;
} else if (action.equals("setPresentationOptions")) {
callbackContext.success();
return true;
} else if (action.equals("setCategoryOptions")) {
callbackContext.success();
return true;
} else if (action.equals("registerForNotifications")) {
this.registerForNotifications(args, callbackContext);
return true;
} else if (action.equals("unregisterForNotifications")) {
this.unregisterForNotifications(args, callbackContext);
return true;
} else if (action.equals("isRemoteNotificationsEnabled")) {
this.isRemoteNotificationsEnabled(args, callbackContext);
return true;
} else if (action.equals("isAllowedUIEnabled")) {
this.isAllowedUIEnabled(args, callbackContext);
return true;
} else if (action.equals("isNotificationFromNotificare")) {
callbackContext.success();
return true;
} else if (action.equals("fetchNotificationSettings")) {
callbackContext.success();
return true;
} else if (action.equals("startLocationUpdates")) {
this.startLocationUpdates(args, callbackContext);
return true;
} else if (action.equals("stopLocationUpdates")) {
this.stopLocationUpdates(args, callbackContext);
return true;
} else if (action.equals("clearLocation")) {
this.clearLocation(args, callbackContext);
return true;
} else if (action.equals("isLocationServicesEnabled")) {
this.isLocationServicesEnabled(args, callbackContext);
return true;
} else if (action.equals("enableBeacons")) {
this.enableBeacons(args, callbackContext);
return true;
} else if (action.equals("disableBeacons")) {
this.disableBeacons(args, callbackContext);
return true;
} else if (action.equals("enableBilling")) {
this.enableBilling(args, callbackContext);
return true;
} else if (action.equals("disableBilling")) {
this.disableBilling(args, callbackContext);
return true;
} else if (action.equals("registerDevice")) {
this.registerDevice(args, callbackContext);
return true;
} else if (action.equals("fetchDevice")) {
this.fetchDevice(args, callbackContext);
return true;
} else if (action.equals("fetchPreferredLanguage")) {
this.fetchPreferredLanguage(args, callbackContext);
return true;
} else if (action.equals("updatePreferredLanguage")) {
this.updatePreferredLanguage(args, callbackContext);
return true;
} else if (action.equals("fetchTags")) {
this.fetchTags(args, callbackContext);
return true;
} else if (action.equals("addTag")) {
this.addTag(args, callbackContext);
return true;
} else if (action.equals("addTags")) {
this.addTags(args, callbackContext);
return true;
} else if (action.equals("removeTag")) {
this.removeTag(args, callbackContext);
return true;
} else if (action.equals("removeTags")) {
this.removeTags(args, callbackContext);
return true;
} else if (action.equals("clearTags")) {
this.clearTags(args, callbackContext);
return true;
} else if (action.equals("fetchUserData")) {
this.fetchUserData(args, callbackContext);
return true;
} else if (action.equals("updateUserData")) {
this.updateUserData(args, callbackContext);
return true;
} else if (action.equals("fetchDoNotDisturb")) {
this.fetchDoNotDisturb(args, callbackContext);
return true;
} else if (action.equals("updateDoNotDisturb")) {
this.updateDoNotDisturb(args, callbackContext);
return true;
} else if (action.equals("clearDoNotDisturb")) {
this.clearDoNotDisturb(args, callbackContext);
return true;
} else if (action.equals("fetchNotification")) {
this.fetchNotification(args, callbackContext);
return true;
} else if (action.equals("fetchNotificationForInboxItem")) {
this.fetchNotificationForInboxItem(args, callbackContext);
return true;
} else if (action.equals("presentNotification")) {
this.presentNotification(args, callbackContext);
return true;
} else if (action.equals("fetchInbox")) {
this.fetchInbox(args, callbackContext);
return true;
} else if (action.equals("presentInboxItem")) {
this.presentInboxItem(args, callbackContext);
return true;
} else if (action.equals("removeFromInbox")) {
this.removeFromInbox(args, callbackContext);
return true;
} else if (action.equals("markAsRead")) {
this.markAsRead(args, callbackContext);
return true;
} else if (action.equals("clearInbox")) {
this.clearInbox(args, callbackContext);
return true;
} else if (action.equals("fetchAssets")) {
this.fetchAssets(args, callbackContext);
return true;
} else if (action.equals("fetchPassWithSerial")) {
this.fetchPassWithSerial(args, callbackContext);
return true;
} else if (action.equals("fetchPassWithBarcode")) {
this.fetchPassWithBarcode(args, callbackContext);
return true;
} else if (action.equals("fetchProducts")) {
this.fetchProducts(args, callbackContext);
return true;
} else if (action.equals("fetchPurchasedProducts")) {
this.fetchPurchasedProducts(args, callbackContext);
return true;
} else if (action.equals("fetchProduct")) {
this.fetchProduct(args, callbackContext);
return true;
} else if (action.equals("buyProduct")) {
this.buyProduct(args, callbackContext);
return true;
} else if (action.equals("logCustomEvent")) {
this.logCustomEvent(args, callbackContext);
return true;
} else if (action.equals("logOpenNotification")) {
this.logOpenNotification(args, callbackContext);
return true;
} else if (action.equals("logInfluencedNotification")) {
this.logInfluencedNotification(args, callbackContext);
return true;
} else if (action.equals("doCloudHostOperation")) {
this.doCloudHostOperation(args, callbackContext);
return true;
} else if (action.equals("createAccount")) {
this.createAccount(args, callbackContext);
return true;
} else if (action.equals("validateAccount")) {
this.validateAccount(args, callbackContext);
return true;
} else if (action.equals("resetPassword")) {
this.resetPassword(args, callbackContext);
return true;
} else if (action.equals("sendPassword")) {
this.sendPassword(args, callbackContext);
return true;
} else if (action.equals("login")) {
this.login(args, callbackContext);
return true;
} else if (action.equals("logout")) {
this.logout(args, callbackContext);
return true;
} else if (action.equals("isLoggedIn")) {
this.isLoggedIn(args, callbackContext);
return true;
} else if (action.equals("generateAccessToken")) {
this.generateAccessToken(args, callbackContext);
return true;
} else if (action.equals("changePassword")) {
this.changePassword(args, callbackContext);
return true;
} else if (action.equals("fetchAccountDetails")) {
this.fetchAccountDetails(args, callbackContext);
return true;
} else if (action.equals("fetchUserPreferences")) {
this.fetchUserPreferences(args, callbackContext);
return true;
} else if (action.equals("addSegmentToUserPreference")) {
this.addSegmentToUserPreference(args, callbackContext);
return true;
} else if (action.equals("removeSegmentFromUserPreference")) {
this.removeSegmentFromUserPreference(args, callbackContext);
return true;
} else if (action.equals("startScannableSession")) {
this.startScannableSession(args, callbackContext);
return true;
} else if (action.equals("presentScannable")) {
this.presentScannable(args, callbackContext);
return true;
}
return false;
}
private void launch(JSONArray args, CallbackContext callbackContext) {
mainCallback = callbackContext;
Notificare.shared().addNotificareReadyListener(this);
PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT);
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
}
private void unlaunch(CallbackContext callbackContext) {
Notificare.shared().unlaunch();
callbackContext.success();
}
private void registerForNotifications(JSONArray args, CallbackContext callbackContext) {
Notificare.shared().enableNotifications();
callbackContext.success();
}
private void unregisterForNotifications(JSONArray args, CallbackContext callbackContext) {
Notificare.shared().disableNotifications();
callbackContext.success();
}
private void isRemoteNotificationsEnabled(JSONArray args, CallbackContext callbackContext) {
callbackContext.success((Notificare.shared().isNotificationsEnabled()) ? 1 : 0);
}
private void isAllowedUIEnabled(JSONArray args, CallbackContext callbackContext) {
callbackContext.success((Notificare.shared().checkAllowedUI()) ? 1 : 0);
}
private void startLocationUpdates(JSONArray args, CallbackContext callbackContext) {
if (!Notificare.shared().hasLocationPermissionGranted()) {
cordova.requestPermissions(this, LOCATION_PERMISSION_REQUEST_CODE, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION});
} else {
Notificare.shared().enableLocationUpdates();
}
callbackContext.success();
}
private void stopLocationUpdates(JSONArray args, CallbackContext callbackContext) {
Notificare.shared().disableLocationUpdates();
callbackContext.success();
}
private void clearLocation(JSONArray args, CallbackContext callbackContext) {
Notificare.shared().clearLocation(new NotificareCallback<Boolean>() {
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
@Override
public void onSuccess(Boolean aBoolean) {
callbackContext.success();
}
});
}
private void isLocationServicesEnabled(JSONArray args, CallbackContext callbackContext) {
callbackContext.success((Notificare.shared().isLocationUpdatesEnabled()) ? 1 : 0);
}
private void enableBeacons(JSONArray args, CallbackContext callbackContext) {
Notificare.shared().enableBeacons();
callbackContext.success();
}
private void disableBeacons(JSONArray args, CallbackContext callbackContext) {
Notificare.shared().disableBeacons();
callbackContext.success();
}
private void enableBilling(JSONArray args, CallbackContext callbackContext) {
Notificare.shared().enableBilling();
callbackContext.success();
}
private void disableBilling(JSONArray args, CallbackContext callbackContext) {
Notificare.shared().disableBilling();
callbackContext.success();
}
private void registerDevice(JSONArray args, CallbackContext callbackContext) {
try {
if (args.getString(0) != null) {
Notificare.shared().setUserId(args.getString(0));
}
if (args.getString(0) != null && args.getString(1) != null) {
Notificare.shared().setUserName(args.getString(1));
}
Notificare.shared().registerDevice(new NotificareCallback<String>() {
@Override
public void onSuccess(String s) {
try {
callbackContext.success(NotificareUtils.mapDevice(Notificare.shared().getRegisteredDevice()));
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void fetchDevice(JSONArray args, CallbackContext callbackContext) {
try {
callbackContext.success(NotificareUtils.mapDevice(Notificare.shared().getRegisteredDevice()));
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void fetchPreferredLanguage(JSONArray args, CallbackContext callbackContext) {
callbackContext.success(Notificare.shared().getPreferredLanguage());
}
private void updatePreferredLanguage(JSONArray args, CallbackContext callbackContext) {
try {
if (args.getString(0) != null) {
Notificare.shared().updatePreferredLanguage(args.getString(0), new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
callbackContext.success();
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("invalid parameters");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void fetchTags(JSONArray args, CallbackContext callbackContext) {
Notificare.shared().fetchDeviceTags(new NotificareCallback<List<String>>() {
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
@Override
public void onSuccess(List<String> tags) {
callbackContext.success(new JSONArray(tags));
}
});
}
private void addTag(JSONArray args, CallbackContext callbackContext) {
try {
if (args.getString(0) != null) {
Notificare.shared().addDeviceTag(args.getString(0), new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
callbackContext.success();
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("invalid parameters");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void addTags(JSONArray args, CallbackContext callbackContext) {
try {
if (args.getJSONArray(0) != null) {
List<String> tagsList = new ArrayList<>();
for (int i = 0; i < args.getJSONArray(0).length(); i++) {
tagsList.add(args.getJSONArray(0).optString(i));
}
Notificare.shared().addDeviceTags(tagsList, new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
callbackContext.success();
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("invalid parameters");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void removeTag(JSONArray args, CallbackContext callbackContext) {
try {
if (args.getString(0) != null) {
Notificare.shared().removeDeviceTag(args.getString(0), new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
callbackContext.success();
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("invalid parameters");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void removeTags(JSONArray args, CallbackContext callbackContext) {
try {
if (args.getJSONArray(0) != null) {
List<String> tagsList = new ArrayList<>();
for (int i = 0; i < args.getJSONArray(0).length(); i++) {
tagsList.add(args.getJSONArray(0).optString(i));
}
Notificare.shared().removeDeviceTags(tagsList, new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
callbackContext.success();
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("invalid parameters");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void clearTags(JSONArray args, CallbackContext callbackContext) {
Notificare.shared().clearDeviceTags(new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
callbackContext.success();
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
}
private void fetchUserData(JSONArray args, CallbackContext callbackContext) {
Notificare.shared().fetchUserData(new NotificareCallback<NotificareUserData>() {
@Override
public void onSuccess(NotificareUserData notificareUserData) {
JSONArray userDataFields = new JSONArray();
try {
for (HashMap.Entry<String, NotificareUserDataField> field : Notificare.shared().getApplicationInfo().getUserDataFields().entrySet()) {
JSONObject userDataMap = new JSONObject();
userDataMap.put("key", field.getValue().getKey());
userDataMap.put("label", field.getValue().getLabel());
userDataMap.put("value", notificareUserData.getValue(field.getKey()));
userDataFields.put(userDataMap);
}
} catch (JSONException e) {
// ignore, send list as is
}
callbackContext.success(userDataFields);
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
}
private void updateUserData(JSONArray args, CallbackContext callbackContext) {
try {
JSONObject fields = args.getJSONObject(0);
if (fields != null) {
NotificareUserData data = new NotificareUserData();
while (fields.keys().hasNext()) {
String key = fields.keys().next();
if (fields.optString(key, null) != null) {
data.setValue(key, fields.optString(key));
}
}
Notificare.shared().updateUserData(data, new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
callbackContext.success();
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("invalid user data");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void fetchDoNotDisturb(JSONArray args, CallbackContext callbackContext) {
Notificare.shared().fetchDoNotDisturb(new NotificareCallback<NotificareTimeOfDayRange>() {
@Override
public void onSuccess(NotificareTimeOfDayRange dnd) {
try {
callbackContext.success(NotificareUtils.mapTimeOfDayRange(dnd));
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
}
private void updateDoNotDisturb(JSONArray args, CallbackContext callbackContext) {
try {
JSONObject deviceDnd = args.getJSONObject(0);
if (deviceDnd != null && deviceDnd.optString("start", null) != null && deviceDnd.optString("end", null) != null) {
String[] s = deviceDnd.optString("start").split(":");
String[] e = deviceDnd.optString("end").split(":");
final NotificareTimeOfDayRange range = new NotificareTimeOfDayRange(
new NotificareTimeOfDay(Integer.parseInt(s[0]),Integer.parseInt(s[1])),
new NotificareTimeOfDay(Integer.parseInt(e[0]),Integer.parseInt(e[1])));
Notificare.shared().updateDoNotDisturb(range, new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
try {
callbackContext.success(NotificareUtils.mapTimeOfDayRange(range));
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("invalid device dnd");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void clearDoNotDisturb(JSONArray args, CallbackContext callbackContext) {
Notificare.shared().clearDoNotDisturb(new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
callbackContext.success();
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
}
private void fetchNotification(JSONArray args, CallbackContext callbackContext) {
try {
JSONObject notification = args.getJSONObject(0);
if (notification != null && notification.optString("id", null) != null) {
Notificare.shared().fetchNotification(notification.optString("id"), new NotificareCallback<NotificareNotification>() {
@Override
public void onSuccess(NotificareNotification notificareNotification) {
try {
callbackContext.success(NotificareUtils.mapNotification(notificareNotification));
} catch (JSONException e) {
NotificareError notificareError = new NotificareError("invalid notification item");
callbackContext.error(notificareError.getLocalizedMessage());
}
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("notification not found");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void fetchNotificationForInboxItem(JSONArray args, CallbackContext callbackContext) {
try {
if (Notificare.shared().getInboxManager() != null) {
JSONObject inboxItem = args.getJSONObject(0);
if (inboxItem != null && inboxItem.optString("inboxId", null) != null && Notificare.shared().getInboxManager() != null) {
NotificareInboxItem notificareInboxItem = Notificare.shared().getInboxManager().getItem(inboxItem.optString("inboxId"));
if (notificareInboxItem != null) {
Notificare.shared().fetchInboxItem(notificareInboxItem, new NotificareCallback<NotificareInboxItem>() {
@Override
public void onSuccess(NotificareInboxItem fetchedInboxItem) {
try {
callbackContext.success(NotificareUtils.mapNotification(fetchedInboxItem.getNotification()));
} catch (JSONException e) {
NotificareError notificareError = new NotificareError("invalid inbox item");
callbackContext.error(notificareError.getLocalizedMessage());
}
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("inbox item not found");
callbackContext.error(notificareError.getLocalizedMessage());
}
} else {
NotificareError notificareError = new NotificareError("inbox item not found");
callbackContext.error(notificareError.getLocalizedMessage());
}
} else {
NotificareError notificareError = new NotificareError("inbox not enabled");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void presentNotification(JSONArray args, CallbackContext callbackContext) {
try {
JSONObject notification = args.getJSONObject(0);
handlePresentNotification(notification);
callbackContext.success();
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void fetchInbox(JSONArray args, CallbackContext callbackContext) {
if (Notificare.shared().getInboxManager() != null) {
JSONArray inbox = new JSONArray();
try {
for (NotificareInboxItem item : Notificare.shared().getInboxManager().getItems()) {
inbox.put(NotificareUtils.mapInboxItem(item));
}
} catch (JSONException e) {
// ignore exceptions, just return the list as is
}
callbackContext.success(inbox);
} else {
NotificareError notificareError = new NotificareError("inbox not enabled");
callbackContext.error(notificareError.getLocalizedMessage());
}
}
private void presentInboxItem(JSONArray args, CallbackContext callbackContext) {
try {
if (Notificare.shared().getInboxManager() != null) {
JSONObject inboxItem = args.getJSONObject(0);
if (inboxItem != null && inboxItem.optString("inboxId", null) != null) {
NotificareInboxItem notificareInboxItem = Notificare.shared().getInboxManager().getItem(inboxItem.optString("inboxId"));
if (notificareInboxItem != null) {
Notificare.shared().openInboxItem(cordova.getActivity(), notificareInboxItem);
callbackContext.success();
}
}
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void removeFromInbox(JSONArray args, CallbackContext callbackContext) {
try {
if (Notificare.shared().getInboxManager() != null) {
JSONObject inboxItem = args.getJSONObject(0);
if (inboxItem != null && inboxItem.optString("inboxId", null) != null) {
NotificareInboxItem notificareInboxItem = Notificare.shared().getInboxManager().getItem(inboxItem.optString("inboxId"));
if (notificareInboxItem != null) {
Notificare.shared().getInboxManager().removeItem(notificareInboxItem, new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
try {
callbackContext.success(NotificareUtils.mapInboxItem(notificareInboxItem));
} catch (JSONException e) {
NotificareError notificareError = new NotificareError("invalid response");
callbackContext.error(notificareError.getLocalizedMessage());
}
}
@Override
public void onError(NotificareError error) {
callbackContext.error(error.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("inbox item not found");
callbackContext.error(notificareError.getLocalizedMessage());
}
} else {
NotificareError notificareError = new NotificareError("inbox item not found");
callbackContext.error(notificareError.getLocalizedMessage());
}
} else {
NotificareError notificareError = new NotificareError("inbox not enabled");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void markAsRead(JSONArray args, CallbackContext callbackContext) {
try {
if (Notificare.shared().getInboxManager() != null) {
JSONObject inboxItem = args.getJSONObject(0);
if (inboxItem != null && inboxItem.optString("inboxId", null) != null) {
NotificareInboxItem notificareInboxItem = Notificare.shared().getInboxManager().getItem(inboxItem.optString("inboxId"));
if (notificareInboxItem != null) {
Notificare.shared().getInboxManager().markItem(notificareInboxItem, new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
try {
callbackContext.success(NotificareUtils.mapInboxItem(notificareInboxItem));
} catch (JSONException e) {
NotificareError notificareError = new NotificareError("invalid response");
callbackContext.error(notificareError.getLocalizedMessage());
}
}
@Override
public void onError(NotificareError error) {
callbackContext.error(error.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("inbox item not found");
callbackContext.error(notificareError.getLocalizedMessage());
}
} else {
NotificareError notificareError = new NotificareError("inbox item not found");
callbackContext.error(notificareError.getLocalizedMessage());
}
} else {
NotificareError notificareError = new NotificareError("inbox not enabled");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void clearInbox(JSONArray args, CallbackContext callbackContext) {
if (Notificare.shared().getInboxManager() != null) {
Notificare.shared().getInboxManager().clearInbox(new NotificareCallback<Integer>() {
@Override
public void onSuccess(Integer count) {
callbackContext.success();
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("inbox not enabled");
callbackContext.error(notificareError.getLocalizedMessage());
}
}
private void fetchAssets(JSONArray args, CallbackContext callbackContext) {
try {
if (args.getString(0) != null) {
Notificare.shared().fetchAssets(args.getString(0), new NotificareCallback<List<NotificareAsset>>() {
@Override
public void onSuccess(List<NotificareAsset> notificareAssets) {
JSONArray assetsArray = new JSONArray();
try {
for (NotificareAsset asset : notificareAssets) {
assetsArray.put(NotificareUtils.mapAsset(asset));
}
} catch (JSONException e) {
// ignore, send list of assets as is
}
callbackContext.success(assetsArray);
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("invalid parameters");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void fetchPassWithSerial(JSONArray args, CallbackContext callbackContext) {
try {
if (args.getString(0) != null) {
Notificare.shared().fetchPass(args.getString(0), new NotificareCallback<NotificarePass>() {
@Override
public void onSuccess(NotificarePass notificarePass) {
try {
callbackContext.success(NotificareUtils.mapPass(notificarePass));
} catch (JSONException e) {
NotificareError notificareError = new NotificareError("invalid response");
callbackContext.error(notificareError.getLocalizedMessage());
}
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("invalid parameters");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void fetchPassWithBarcode(JSONArray args, CallbackContext callbackContext) {
try {
if (args.getString(0) != null) {
Notificare.shared().fetchPass(args.getString(0), new NotificareCallback<NotificarePass>() {
@Override
public void onSuccess(NotificarePass notificarePass) {
try {
callbackContext.success(NotificareUtils.mapPass(notificarePass));
} catch (JSONException e) {
NotificareError notificareError = new NotificareError("invalid response");
callbackContext.error(notificareError.getLocalizedMessage());
}
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("invalid parameters");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void fetchProducts(JSONArray args, CallbackContext callbackContext) {
if (Notificare.shared().getBillingManager() != null) {
callbackContext.success(NotificareUtils.mapProducts(Notificare.shared().getBillingManager().getProducts()));
} else {
NotificareError notificareError = new NotificareError("billing not enabled");
callbackContext.error(notificareError.getLocalizedMessage());
}
}
private void fetchPurchasedProducts(JSONArray args, CallbackContext callbackContext) {
if (Notificare.shared().getBillingManager() != null) {
List<Purchase> purchases = Notificare.shared().getBillingManager().getPurchases();
List<NotificareProduct> products = new ArrayList<>();
for (Purchase purchase : purchases) {
NotificareProduct product = Notificare.shared().getBillingManager().getProduct(purchase.getProductId());
if (product != null) {
products.add(product);
}
}
callbackContext.success(NotificareUtils.mapProducts(products));
} else {
NotificareError notificareError = new NotificareError("billing not enabled");
callbackContext.error(notificareError.getLocalizedMessage());
}
}
private void fetchProduct(JSONArray args, CallbackContext callbackContext) {
try {
if (Notificare.shared().getBillingManager() != null) {
JSONObject product = args.getJSONObject(0);
if (product != null && product.optString("productIdentifier", null) != null) {
NotificareProduct theProduct = Notificare.shared().getBillingManager().getProduct(product.optString("productIdentifier"));
if (theProduct != null) {
try {
callbackContext.success(NotificareUtils.mapProduct(theProduct));
} catch (JSONException e) {
NotificareError notificareError = new NotificareError("invalid response");
callbackContext.error(notificareError.getLocalizedMessage());
}
} else {
NotificareError notificareError = new NotificareError("product not found");
callbackContext.error(notificareError.getLocalizedMessage());
}
} else {
NotificareError notificareError = new NotificareError("product not found");
callbackContext.error(notificareError.getLocalizedMessage());
}
} else {
NotificareError notificareError = new NotificareError("billing not enabled");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void buyProduct(JSONArray args, CallbackContext callbackContext) {
try {
if (Notificare.shared().getBillingManager() != null && cordova.getActivity() != null) {
JSONObject product = args.getJSONObject(0);
if (product != null && product.optString("productIdentifier", null) != null) {
NotificareProduct notificareProduct = Notificare.shared().getBillingManager().getProduct(product.optString("identifier"));
final Activity activity = cordova.getActivity();
activity.runOnUiThread(() -> Notificare.shared().getBillingManager().launchPurchaseFlow(activity, notificareProduct, this));
}
}
callbackContext.success();
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void logCustomEvent(JSONArray args, CallbackContext callbackContext) {
try {
JSONObject data = args.getJSONObject(1);
if (args.getString(0) != null) {
Notificare.shared().getEventLogger().logCustomEvent(args.getString(0), data, new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
callbackContext.success();
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("invalid parameters");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void logOpenNotification(JSONArray args, CallbackContext callbackContext) {
try {
JSONObject notification = args.getJSONObject(0);
if (notification != null && notification.optString("id", null) != null) {
Notificare.shared().getEventLogger().logOpenNotification(notification.optString("id"), new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
callbackContext.success();
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("invalid notification");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void logInfluencedNotification(JSONArray args, CallbackContext callbackContext) {
try {
JSONObject notification = args.getJSONObject(0);
if (notification != null && notification.optString("id", null) != null) {
Notificare.shared().getEventLogger().logOpenNotificationInfluenced(notification.optString("id"), new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
callbackContext.success();
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("invalid notification");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void doCloudHostOperation(JSONArray args, CallbackContext callbackContext) {
try {
if (args.getString(0) != null && args.getString(1) != null) {
JSONObject headers = args.get(2) != JSONObject.NULL ? args.getJSONObject(2) : null;
JSONObject params = args.get(3) != JSONObject.NULL ? args.getJSONObject(3) : null;
JSONObject body = args.get(4) != JSONObject.NULL ? args.getJSONObject(4) : null;
Map<String, String> paramsMap = new HashMap<>();
if (params != null) {
while (params.keys().hasNext()) {
String key = params.keys().next();
paramsMap.put(key, params.optString(key, null));
}
}
Map<String, String> headersMap = new HashMap<>();
if (headers != null) {
while (headers.keys().hasNext()) {
String key = headers.keys().next();
headersMap.put(key, headers.optString(key, null));
}
}
Notificare.shared().doCloudRequest(args.getString(0), "/api" + args.getString(1), paramsMap, body, headersMap, new NotificareCallback<JSONObject>() {
@Override
public void onSuccess(JSONObject jsonObject) {
callbackContext.success(jsonObject);
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("invalid parameters");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void createAccount(JSONArray args, CallbackContext callbackContext) {
try {
if (args.getString(0) != null && args.getString(1) != null && args.getString(2) != null) {
String email = args.getString(0);
String name = args.getString(1);
String password = args.getString(2);
Notificare.shared().createAccount(email, password, name, new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
callbackContext.success();
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("invalid parameters");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void validateAccount(JSONArray args, CallbackContext callbackContext) {
try {
if (args.getString(0) != null) {
Notificare.shared().validateUser(args.getString(0), new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
callbackContext.success();
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("invalid parameters");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void resetPassword(JSONArray args, CallbackContext callbackContext) {
try {
if (args.getString(0) != null &&
args.getString(1) != null) {
Notificare.shared().resetPassword(args.getString(0), args.getString(1), new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
callbackContext.success();
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("invalid parameters");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void sendPassword(JSONArray args, CallbackContext callbackContext) {
try {
if (args.getString(0) != null) {
Notificare.shared().sendPassword(args.getString(0), new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
callbackContext.success();
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("invalid parameters");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void login(JSONArray args, CallbackContext callbackContext) {
try {
if (args.getString(0) != null && args.getString(1) != null) {
Notificare.shared().userLogin(args.getString(0), args.getString(1), new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
callbackContext.success();
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("invalid parameters");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void logout(JSONArray args, CallbackContext callbackContext) {
Notificare.shared().userLogout(new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
callbackContext.success();
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
}
private void isLoggedIn(JSONArray args, CallbackContext callbackContext) {
callbackContext.success((Notificare.shared().isLoggedIn()) ? 1 : 0);
}
private void generateAccessToken(JSONArray args, CallbackContext callbackContext) {
Notificare.shared().generateAccessToken(new NotificareCallback<NotificareUser>() {
@Override
public void onSuccess(NotificareUser notificareUser) {
try {
callbackContext.success(NotificareUtils.mapUser(notificareUser));
} catch (JSONException e) {
NotificareError notificareError = new NotificareError("invalid response");
callbackContext.error(notificareError.getLocalizedMessage());
}
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
}
private void changePassword(JSONArray args, CallbackContext callbackContext) {
try {
if (args.getString(0) != null) {
Notificare.shared().changePassword(args.getString(0), new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
callbackContext.success();
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("invalid parameters");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void fetchAccountDetails(JSONArray args, CallbackContext callbackContext) {
Notificare.shared().fetchUserDetails(new NotificareCallback<NotificareUser>() {
@Override
public void onSuccess(NotificareUser notificareUser) {
try {
callbackContext.success(NotificareUtils.mapUser(notificareUser));
} catch (JSONException e) {
NotificareError notificareError = new NotificareError("invalid response");
callbackContext.error(notificareError.getLocalizedMessage());
}
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
}
private void fetchUserPreferences(JSONArray args, CallbackContext callbackContext) {
Notificare.shared().fetchUserPreferences(new NotificareCallback<List<NotificareUserPreference>>() {
@Override
public void onSuccess(List<NotificareUserPreference> notificareUserPreferences) {
JSONArray preferencesArray = new JSONArray();
try {
for (NotificareUserPreference preference : notificareUserPreferences) {
preferencesArray.put(NotificareUtils.mapUserPreference(preference));
}
} catch (JSONException e) {
// ignore, send list as is
}
callbackContext.success(preferencesArray);
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
}
private void addSegmentToUserPreference(JSONArray args, CallbackContext callbackContext) {
try {
JSONObject segment = args.getJSONObject(0);
JSONObject preference = args.getJSONObject(1);
if (segment != null && preference != null) {
NotificareUserSegment userSegment = NotificareUtils.createUserSegment(segment);
NotificareUserPreference userPreference = NotificareUtils.createUserPreference(preference);
if (userSegment != null && userPreference != null) {
Notificare.shared().userSegmentAddToUserPreference(userSegment, userPreference, new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
callbackContext.success();
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("invalid parameters");
callbackContext.error(notificareError.getLocalizedMessage());
}
} else {
NotificareError notificareError = new NotificareError("invalid parameters");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void removeSegmentFromUserPreference(JSONArray args, CallbackContext callbackContext) {
try {
JSONObject segment = args.getJSONObject(0);
JSONObject preference = args.getJSONObject(1);
if (segment != null && preference != null) {
NotificareUserSegment userSegment = NotificareUtils.createUserSegment(segment);
NotificareUserPreference userPreference = NotificareUtils.createUserPreference(preference);
if (userSegment != null && userPreference != null) {
Notificare.shared().userSegmentRemoveFromUserPreference(userSegment, userPreference, new NotificareCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
callbackContext.success();
}
@Override
public void onError(NotificareError notificareError) {
callbackContext.error(notificareError.getLocalizedMessage());
}
});
} else {
NotificareError notificareError = new NotificareError("invalid parameters");
callbackContext.error(notificareError.getLocalizedMessage());
}
} else {
NotificareError notificareError = new NotificareError("invalid parameters");
callbackContext.error(notificareError.getLocalizedMessage());
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
private void startScannableSession(JSONArray args, CallbackContext callbackContext) {
if (cordova.getActivity() != null) {
Notificare.shared().startScannableActivity(cordova.getActivity(), SCANNABLE_REQUEST_CODE);
}
callbackContext.success();
}
private void presentScannable(JSONArray args, CallbackContext callbackContext) {
try {
JSONObject scannable = args.getJSONObject(0);
if (scannable != null && scannable.optJSONObject("notification") != null) {
handlePresentNotification(scannable.optJSONObject("notification"));
}
} catch (JSONException e) {
callbackContext.error(e.getLocalizedMessage());
}
}
@Override
public void onNotificareReady(NotificareApplicationInfo notificareApplicationInfo) {
try {
handleEventPayload(PluginResult.Status.OK, "ready", NotificareUtils.mapApplicationInfo(notificareApplicationInfo));
handleQueue();
} catch (JSONException e) {
// ignore
}
}
/**
* Present Notification helper
* @param notification
*/
private void handlePresentNotification(JSONObject notification) {
if (notification != null && notification.has("id")) {
String notificationId = notification.optString("id");
if (notification.has("inboxItemId") && notification.optString("inboxItemId", null) != null && Notificare.shared().getInboxManager() != null) {
// This is an item opened with inboxItemId, so coming from NotificationManager open
NotificareInboxItem notificareInboxItem = Notificare.shared().getInboxManager().getItem(notification.optString("inboxItemId"));
if (notificareInboxItem != null) {
Notificare.shared().openInboxItem(cordova.getActivity(), notificareInboxItem);
}
} else if (notificationId != null && !notificationId.isEmpty()) {
// We have a notificationId, let's see if we can create a notification from the payload, otherwise fetch from API
NotificareNotification notificareNotification = NotificareUtils.createNotification(notification);
if (notificareNotification != null) {
Notificare.shared().openNotification(cordova.getActivity(), notificareNotification);
} else {
Notificare.shared().fetchNotification(notificationId, new NotificareCallback<NotificareNotification>() {
@Override
public void onSuccess(NotificareNotification notificareNotification) {
Notificare.shared().openNotification(cordova.getActivity(), notificareNotification);
}
@Override
public void onError(NotificareError notificareError) {
Log.e(TAG, "error fetching notification: " + notificareError.getMessage());
}
});
}
}
}
}
public void handleEventPayload(PluginResult.Status status, String type, JSONObject payload) {
JSONObject result = new JSONObject();
try {
result.put("type", type);
result.put("data", payload);
PluginResult pluginResult = new PluginResult(status, result);
handleEvent(pluginResult);
} catch (JSONException e) {
// ignore
}
}
public void handleEventPayload(PluginResult.Status status, String type, JSONArray payload) {
JSONObject result = new JSONObject();
try {
result.put("type", type);
result.put("data", payload);
PluginResult pluginResult = new PluginResult(status, result);
handleEvent(pluginResult);
} catch (JSONException e) {
// ignore
}
}
public void handleEventPayload(PluginResult.Status status, String type, int payload) {
JSONObject result = new JSONObject();
try {
result.put("type", type);
result.put("data", payload);
PluginResult pluginResult = new PluginResult(status, result);
handleEvent(pluginResult);
} catch (JSONException e) {
// ignore
}
}
public void handleEventPayload(PluginResult.Status status, String type, String payload) {
JSONObject result = new JSONObject();
try {
result.put("type", type);
result.put("data", payload);
PluginResult pluginResult = new PluginResult(status, result);
handleEvent(pluginResult);
} catch (JSONException e) {
// ignore
}
}
/**
* Helper Method to send or queue events
* @param pluginResult
*/
public void handleEvent(PluginResult pluginResult) {
pluginResult.setKeepCallback(true);
if (mainCallback != null) {
mainCallback.sendPluginResult(pluginResult);
} else {
eventQueue.add(pluginResult);
}
}
/**
* Helper Method to handle queued events
*/
public void handleQueue() {
for (PluginResult pluginResult : eventQueue) {
mainCallback.sendPluginResult(pluginResult);
}
eventQueue.clear();
}
/**
* Handle initial intent
* @param intent
*/
private void handleIntent(Intent intent) {
JSONObject notificationMap = parseNotificationIntent(intent);
if (notificationMap != null) {
handleEventPayload(PluginResult.Status.OK, "remoteNotificationReceivedInBackground", notificationMap);
} else {
String token = Notificare.shared().parseValidateUserIntent(intent);
if (token != null && !token.isEmpty()) {
sendValidateUserToken(token);
return;
}
token = Notificare.shared().parseResetPasswordIntent(intent);
if (token != null && !token.isEmpty()) {
sendResetPasswordToken(token);
return;
}
if (intent.getData() != null) {
try {
JSONObject payload = new JSONObject();
payload.put("url", intent.getData().toString());
handleEventPayload(PluginResult.Status.OK, "urlOpened", payload);
} catch (JSONException e) {
// ignore
}
}
}
}
/**
* Send a validate user token received event
* @param token
*/
private void sendValidateUserToken(String token) {
if (token != null && !token.isEmpty()) {
JSONObject tokenMap = new JSONObject();
try {
tokenMap.put("token", token);
handleEventPayload(PluginResult.Status.OK, "activationTokenReceived", tokenMap);
} catch (JSONException e) {
// ignore
}
}
}
/**
* Send a password reset token received event
* @param token
*/
private void sendResetPasswordToken(String token) {
if (token != null && !token.isEmpty()) {
JSONObject tokenMap = new JSONObject();
try {
tokenMap.put("token", token);
handleEventPayload(PluginResult.Status.OK, "resetPasswordTokenReceived", tokenMap);
} catch (JSONException e) {
// ignore
}
}
}
public void sendRegistration(NotificareDevice device) {
if (device.getDeviceId() != null) {
try {
handleEventPayload(PluginResult.Status.OK, "deviceRegistered", NotificareUtils.mapDevice(device));
} catch (JSONException e) {
}
}
}
public void sendUrlClicked(Uri urlClicked, NotificareNotification notification) {
if (urlClicked != null && notification != null) {
JSONObject payload = new JSONObject();
try {
payload.put("url", urlClicked.toString());
payload.put("notification", NotificareUtils.mapNotification(notification));
handleEventPayload(PluginResult.Status.OK, "urlClickedInNotification", payload);
} catch (JSONException e) {
}
}
}
private JSONObject parseNotificationIntent(Intent intent) {
NotificareNotification notification = intent.getParcelableExtra(Notificare.INTENT_EXTRA_NOTIFICATION);
if (notification != null) {
try {
JSONObject notificationMap = NotificareUtils.mapNotification(notification);
// Add inbox item id if present
if (intent.hasExtra(Notificare.INTENT_EXTRA_INBOX_ITEM_ID)) {
notificationMap.put("inboxItemId", intent.getStringExtra(Notificare.INTENT_EXTRA_INBOX_ITEM_ID));
}
return notificationMap;
} catch (JSONException e) {
return null;
}
}
return null;
}
@Override
public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException {
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE:
if (Notificare.shared().checkRequestLocationPermissionResult(permissions, grantResults)) {
Notificare.shared().enableLocationUpdates();
Notificare.shared().enableBeacons(30000);
} else if (Notificare.shared().checkRequestForegroundLocationPermissionResult(permissions, grantResults)) {
Notificare.shared().enableLocationUpdates();
Notificare.shared().enableBeacons(30000);
}
break;
}
}
@Override
public void onChanged(@Nullable SortedSet<NotificareInboxItem> notificareInboxItems) {
JSONArray inbox = new JSONArray();
if (notificareInboxItems != null) {
try {
for (NotificareInboxItem item : notificareInboxItems) {
inbox.put(NotificareUtils.mapInboxItem(item));
}
} catch (JSONException e) {
// ignore, send list as is
}
handleEventPayload(PluginResult.Status.OK, "inboxLoaded", inbox);
handleEventPayload(PluginResult.Status.OK, "badgeUpdated", Notificare.shared().getInboxManager().getUnreadCount());
}
}
@Override
public void onBillingReady() {
if (!mIsBillingReady) {
Notificare.shared().getBillingManager().refresh(this);
}
}
@Override
public void onNotificareNotification(NotificareNotification notification, NotificareInboxItem inboxItem, Boolean shouldPresent) {
if (notification != null) {
try {
JSONObject notificationMap = NotificareUtils.mapNotification(notification);
// Add inbox item id if present
if (inboxItem != null) {
notificationMap.put("inboxItemId", inboxItem.getItemId());
}
handleEventPayload(PluginResult.Status.OK, "remoteNotificationReceivedInForeground", notificationMap);
} catch (JSONException e) {
// ignore
}
}
}
@Override
public void onServiceError(int errorCode, int requestCode) {
if (Notificare.isUserRecoverableError(errorCode) && cordova != null && cordova.getActivity() != null) {
final Activity activity = cordova.getActivity();
activity.runOnUiThread(() -> Notificare.getErrorDialog(errorCode, activity, requestCode).show());
}
}
@Override
public void onRangingBeacons(List<NotificareBeacon> beacons) {
try {
JSONObject payload = new JSONObject();
JSONArray beaconsArray = new JSONArray();
for (NotificareBeacon beacon : beacons) {
beaconsArray.put(NotificareUtils.mapBeacon(beacon));
}
payload.put("beacons", beaconsArray);
if (beacons.size() > 0) {
if (beacons.get(0).getRegion() != null) {
payload.put("region", NotificareUtils.mapRegionForBeacon(beacons.get(0)));
}
}
handleEventPayload(PluginResult.Status.OK, "beaconsInRangeForRegion", payload);
} catch (JSONException e) {
// ignore
}
}
@Override
public void onPurchaseFinished(BillingResult billingResult, Purchase purchase) {
mIsBillingReady = false;
JSONObject payload = new JSONObject();
NotificareProduct product = Notificare.shared().getBillingManager().getProduct(purchase.getProductId());
try {
if (product != null) {
payload.put("product", NotificareUtils.mapProduct(product));
}
if (billingResult.isFailure()) {
payload.put("error", billingResult.getMessage());
handleEventPayload(PluginResult.Status.OK, "productTransactionFailed", payload);
} else if (billingResult.isSuccess()) {
handleEventPayload(PluginResult.Status.OK, "productTransactionCompleted", payload);
}
} catch (JSONException e) {
//ignore
}
}
@Override
public void onRefreshFinished() {
handleEventPayload(PluginResult.Status.OK, "storeLoaded", NotificareUtils.mapProducts(Notificare.shared().getBillingManager().getProducts()));
}
@Override
public void onRefreshFailed(NotificareError notificareError) {
handleEventPayload(PluginResult.Status.ERROR, "storeFailedToLoad", "");
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (!Notificare.shared().handleServiceErrorResolution(requestCode, resultCode, data)) {
if (requestCode == SCANNABLE_REQUEST_CODE) {
if (resultCode == CommonStatusCodes.SUCCESS) {
if (data != null) {
NotificareScannable scannable = Notificare.shared().extractScannableFromActivityResult(data);
if (scannable != null) {
try {
handleEventPayload(PluginResult.Status.OK, "scannableDetected", NotificareUtils.mapScannable(scannable));
} catch (JSONException e) {
// ignore
}
} else {
handleEventPayload(PluginResult.Status.ERROR, "scannableSessionInvalidatedWithError", "scannable not found");
}
} else {
handleEventPayload(PluginResult.Status.ERROR, "scannableSessionInvalidatedWithError", "scan did not return any results");
}
} else if (resultCode == CommonStatusCodes.CANCELED) {
handleEventPayload(PluginResult.Status.ERROR, "scannableSessionInvalidatedWithError", "scan was canceled");
} else {
handleEventPayload(PluginResult.Status.ERROR, "scannableSessionInvalidatedWithError", "unknown error");
}
} else if (Notificare.shared().getBillingManager() != null && Notificare.shared().getBillingManager().handleActivityResult(requestCode, resultCode, data)) {
// Billingmanager handled the result
mIsBillingReady = true; // wait for purchase to finish before doing other calls
}
}
}
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
this.handleIntent(intent);
}
}
|
package org.eclipse.scanning.sequencer;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.eclipse.scanning.api.event.scan.DeviceState;
import org.eclipse.scanning.api.points.IPosition;
import org.eclipse.scanning.api.scan.AbstractRunnableDevice;
import org.eclipse.scanning.api.scan.IPositioner;
import org.eclipse.scanning.api.scan.IRunnableDevice;
import org.eclipse.scanning.api.scan.ScanModel;
import org.eclipse.scanning.api.scan.ScanningException;
/**
* This device does a standard GDA scan at each point. If a given point is a
* MalcolmDevice, that device will be configured and run for its given point.
*
* The levels of the scannables at the position will be taken into
* account and the position reached using an IPositioner then the
* scanners run.
*
* @author Matthew Gerring
*
* @param <T>
*/
final class AcquisitionDevice extends AbstractRunnableDevice<ScanModel> {
// Scanning stuff
private ScanModel model;
private DetectorRunner detectors;
private DetectorReader writers;
/*
* Concurrency design recommended by Keith Ralphs after investigating
* how to pause and resume a collection cycle using Reentrant locks.
* Design requires these three fields.
*/
private ReentrantLock lock;
private Condition paused;
private volatile boolean awaitPaused;
AcquisitionDevice() {
super();
this.lock = new ReentrantLock();
this.paused = lock.newCondition();
}
@Override
public void configure(ScanModel model) throws ScanningException {
this.model = model;
detectors = new DetectorRunner(model.getDetectors());
writers = new DetectorReader(model.getDetectors());
setState(DeviceState.READY);
}
@Override
public void run() throws ScanningException, InterruptedException {
if (model.getPositionIterator()==null) throw new ScanningException("The model must contain some points to scan!");
try {
final IPositioner positioner = scanningService.createPositioner(deviceService);
// TODO Should we validate the position iterator that all
// the positions are valid before running the scan?
// It was called limit checking in GDA.
// Sometimes logic is needed to implement collision avoidance.
setState(DeviceState.RUNNING);
for (IPosition pos : model.getPositionIterator()) {
// Check if we are paused, blocks until we are not
checkPaused();
// TODO Some validation on each point
// perhaps replacing atPointStart(..)
// Whether to deal with atLineStart() and atPointStart()
// Run the position
positioner.setPosition(pos); // moveTo
// check that beam is up. In the past this has been done with
// scannables at a given level that block until they are happy.
writers.await(); // Wait for the previous read out to return, if any
detectors.run(pos); // GDA8: collectData() / GDA9: run() for Malcolm
writers.run(pos, false); // Do not block on the readout, move to the next position immediately.
// TODO Event for actual data written, for analysis to listen to.
}
// On the last iteration we must wait for the final readout.
writers.await(); // Wait for the previous read out to return, if any
setState(DeviceState.READY);
} catch (ScanningException s) {
throw s;
} catch (InterruptedException i) {
throw i;
} catch (Exception ne) {
throw new ScanningException(ne);
}
}
private void checkPaused() throws Exception {
// Check the locking using a condition
if(!lock.tryLock(1, TimeUnit.SECONDS)) {
throw new ScanningException(this, "Internal Error - Could not obtain lock to run device!");
}
try {
if (awaitPaused) {
setState(DeviceState.PAUSED);
paused.await();
setState(DeviceState.RUNNING);
}
} finally {
lock.unlock();
}
}
// TODO Abort can be interpreted different ways. As 'skip' for short exposure experiments
// it finishes the current frame, writes file and stops motors. For long exposure it might
// need to stop the detector exposing further.
// TODO Abort can stop everything, including detectors motors and file writing immediately.
// Should the model define the behaviour of abort for a given detector? This would allow
// abort to be configurable for different detectors.
@Override
public void abort() throws ScanningException {
throw new ScanningException("Not implemented!");
}
@Override
public void pause() throws ScanningException {
if (getState() != DeviceState.RUNNING) {
throw new ScanningException(this, getName()+" is not running and cannot be paused!");
}
try {
lock.lockInterruptibly();
} catch (Exception ne) {
throw new ScanningException(ne);
}
setState(DeviceState.PAUSING);
try {
awaitPaused = true;
for (IRunnableDevice<?> device : model.getDetectors()) {
device.pause();
}
} catch (ScanningException s) {
throw s;
} catch (Exception ne) {
throw new ScanningException(ne);
} finally {
lock.unlock();
}
}
@Override
public void resume() throws ScanningException {
if (getState() != DeviceState.PAUSED) {
throw new ScanningException(this, getName()+" is not paused and cannot be resumed!");
}
try {
lock.lockInterruptibly();
} catch (Exception ne) {
throw new ScanningException(ne);
}
try {
awaitPaused = false;
for (IRunnableDevice<?> device : model.getDetectors()) {
device.resume();
}
paused.signalAll();
} catch (ScanningException s) {
throw s;
} finally {
lock.unlock();
}
}
}
|
package sk.henrichg.phoneprofilesplus;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.WallpaperManager;
import android.appwidget.AppWidgetManager;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.location.LocationManager;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.Settings;
import android.provider.Settings.Global;
import android.support.v4.app.NotificationCompat;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.Surface;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.RemoteViews;
import com.stericson.RootShell.execution.Command;
import com.stericson.RootShell.execution.Shell;
import com.stericson.RootTools.RootTools;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Calendar;
public class ActivateProfileHelper {
private DataWrapper dataWrapper;
private Context context;
private NotificationManager notificationManager;
private Handler brightnessHandler;
public static boolean lockRefresh = false;
public static final String ADAPTIVE_BRIGHTNESS_SETTING_NAME = "screen_auto_brightness_adj";
public ActivateProfileHelper()
{
}
public void initialize(DataWrapper dataWrapper, Activity a, Context c)
{
this.dataWrapper = dataWrapper;
initializeNoNotificationManager(c);
notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
}
public void initializeNoNotificationManager(Context c)
{
context = c;
}
public void deinitialize()
{
dataWrapper = null;
context = null;
notificationManager = null;
}
public void setBrightnessHandler(Handler handler)
{
brightnessHandler = handler;
}
@SuppressWarnings("deprecation")
private void doExecuteForRadios(Profile profile, boolean onlyCheckForPPHelper)
{
if (!onlyCheckForPPHelper)
{
try {
Thread.sleep(300);
} catch (InterruptedException e) {
System.out.println(e);
}
}
// nahodenie mobilnych dat
if (!onlyCheckForPPHelper) {
if (GlobalData.hardwareCheck(GlobalData.PREF_PROFILE_DEVICE_MOBILE_DATA, context) == GlobalData.HARDWARE_CHECK_ALLOWED) {
boolean _isMobileData = isMobileData(context);
boolean _setMobileData = false;
switch (profile._deviceMobileData) {
case 1:
if (!_isMobileData) {
_isMobileData = true;
_setMobileData = true;
}
break;
case 2:
if (_isMobileData) {
_isMobileData = false;
_setMobileData = true;
}
break;
case 3:
_isMobileData = !_isMobileData;
_setMobileData = true;
break;
}
if (_setMobileData) {
setMobileData(context, _isMobileData);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
// nahodenie WiFi AP
boolean canChangeWifi = true;
if (!onlyCheckForPPHelper) {
if (GlobalData.hardwareCheck(GlobalData.PREF_PROFILE_DEVICE_WIFI_AP, context) == GlobalData.HARDWARE_CHECK_ALLOWED) {
WifiApManager wifiApManager = null;
try {
wifiApManager = new WifiApManager(context);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
if (wifiApManager != null) {
boolean setWifiAPState = false;
boolean isWifiAPEnabled = wifiApManager.isWifiAPEnabled();
switch (profile._deviceWiFiAP) {
case 1:
if (!isWifiAPEnabled) {
isWifiAPEnabled = true;
setWifiAPState = true;
canChangeWifi = false;
}
break;
case 2:
if (isWifiAPEnabled) {
isWifiAPEnabled = false;
setWifiAPState = true;
canChangeWifi = true;
}
break;
case 3:
isWifiAPEnabled = !isWifiAPEnabled;
setWifiAPState = true;
canChangeWifi = !isWifiAPEnabled;
break;
}
if (setWifiAPState) {
wifiApManager.setWifiApState(isWifiAPEnabled);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
}
if (canChangeWifi) {
// nahodenie WiFi
if (GlobalData.hardwareCheck(GlobalData.PREF_PROFILE_DEVICE_WIFI, context) == GlobalData.HARDWARE_CHECK_ALLOWED) {
boolean isWifiAPEnabled = WifiApManager.isWifiAPEnabled(context);
if (!isWifiAPEnabled) { // only when wifi AP is not enabled, change wifi
GlobalData.logE("$$$ WifiAP", "ActivateProfileHelper.doExecuteForRadios-isWifiAPEnabled=" + isWifiAPEnabled);
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int wifiState = wifiManager.getWifiState();
boolean isWifiEnabled = ((wifiState == WifiManager.WIFI_STATE_ENABLED) || (wifiState == WifiManager.WIFI_STATE_ENABLING));
boolean setWifiState = false;
switch (profile._deviceWiFi) {
case 1:
if (!isWifiEnabled) {
isWifiEnabled = true;
setWifiState = true;
}
break;
case 2:
if (isWifiEnabled) {
isWifiEnabled = false;
setWifiState = true;
}
break;
case 3:
isWifiEnabled = !isWifiEnabled;
setWifiState = true;
break;
}
if (setWifiState) {
if (!onlyCheckForPPHelper) {
try {
wifiManager.setWifiEnabled(isWifiEnabled);
} catch (Exception e) {
wifiManager.setWifiEnabled(isWifiEnabled);
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println(e);
}
}
if (isWifiEnabled)
// when wifi is enabled from profile, no disable wifi after scan
WifiScanAlarmBroadcastReceiver.setWifiEnabledForScan(context, false);
}
}
}
}
// nahodenie bluetooth
if (GlobalData.hardwareCheck(GlobalData.PREF_PROFILE_DEVICE_BLUETOOTH, context) == GlobalData.HARDWARE_CHECK_ALLOWED)
{
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
boolean isBluetoothEnabled = bluetoothAdapter.isEnabled();
boolean setBluetoothState = false;
switch (profile._deviceBluetooth) {
case 1 :
if (!isBluetoothEnabled)
{
isBluetoothEnabled = true;
setBluetoothState = true;
}
break;
case 2 :
if (isBluetoothEnabled)
{
isBluetoothEnabled = false;
setBluetoothState = true;
}
break;
case 3 :
isBluetoothEnabled = ! isBluetoothEnabled;
setBluetoothState = true;
break;
}
if (setBluetoothState)
{
if (!onlyCheckForPPHelper)
{
if (isBluetoothEnabled)
bluetoothAdapter.enable();
else
bluetoothAdapter.disable();
}
if (isBluetoothEnabled)
// when bluetooth is enabled from profile, no disable bluetooth after scan
BluetoothScanAlarmBroadcastReceiver.setBluetoothEnabledForScan(context, false);
}
}
// nahodenie GPS
if (!onlyCheckForPPHelper) {
if (GlobalData.hardwareCheck(GlobalData.PREF_PROFILE_DEVICE_GPS, context) == GlobalData.HARDWARE_CHECK_ALLOWED)
{
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
switch (profile._deviceGPS) {
case 1:
setGPS(context, true);
break;
case 2:
setGPS(context, false);
break;
case 3:
if (!provider.contains("gps")) {
setGPS(context, true);
} else if (provider.contains("gps")) {
setGPS(context, false);
}
break;
}
}
}
// nahodenie NFC - len v PPHelper
}
public void executeForRadios(Profile profile, boolean onlyCheckForPPHelper)
{
boolean _isAirplaneMode = false;
boolean _setAirplaneMode = false;
if (GlobalData.hardwareCheck(GlobalData.PREF_PROFILE_DEVICE_AIRPLANE_MODE, context) == GlobalData.HARDWARE_CHECK_ALLOWED)
{
_isAirplaneMode = isAirplaneMode(context);
switch (profile._deviceAirplaneMode) {
case 1:
if (!_isAirplaneMode)
{
_isAirplaneMode = true;
_setAirplaneMode = true;
}
break;
case 2:
if (_isAirplaneMode)
{
_isAirplaneMode = false;
_setAirplaneMode = true;
}
break;
case 3:
_isAirplaneMode = !_isAirplaneMode;
_setAirplaneMode = true;
break;
}
}
if (_setAirplaneMode && _isAirplaneMode)
// switch ON airplane mode, set it before executeForRadios
setAirplaneMode(context, _isAirplaneMode);
doExecuteForRadios(profile, onlyCheckForPPHelper);
if (_setAirplaneMode && !(_isAirplaneMode))
// switch OFF airplane mode, set if after executeForRadios
setAirplaneMode(context, _isAirplaneMode);
}
private static final int ZENMODE_ALL = 0;
private static final int ZENMODE_PRIORITY = 1;
private static final int ZENMODE_NONE = 2;
private void correctSilentMode(Profile profile, AudioManager audioManager) {
//if (GlobalData.getRingerMode(context) == 4) {
if (profile._volumeRingerMode == 4) {
// last profile ringer mode = Silent
if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) {
// actual system ringer mode = vibrate
// volume changed it to vibrate
audioManager.setStreamVolume(AudioManager.STREAM_RING, 1, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, 1);
}
}
}
@SuppressLint("NewApi")
public void setVolumes(Profile profile, AudioManager audioManager, int linkUnlink)
{
if (profile.getVolumeSystemChange())
{
audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, profile.getVolumeSystemValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_SYSTEM, profile.getVolumeSystemValue());
correctSilentMode(profile, audioManager);
}
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
int callState = telephony.getCallState();
if (profile.getVolumeRingtoneChange() || profile.getVolumeSystemChange()) {
if (profile.getVolumeRingtoneChange())
GlobalData.setRingerVolume(context, profile.getVolumeRingtoneValue());
if (((!GlobalData.applicationUnlinkRingerNotificationVolumes) || (callState != TelephonyManager.CALL_STATE_RINGING))
&& (linkUnlink == PhoneCallBroadcastReceiver.LINKMODE_NONE)) {
int volume = GlobalData.getRingerVolume(context);
if (volume != -999) {
audioManager.setStreamVolume(AudioManager.STREAM_RING, profile.getVolumeRingtoneValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, profile.getVolumeRingtoneValue());
correctSilentMode(profile, audioManager);
}
}
}
if (profile.getVolumeNotificationChange() || profile.getVolumeSystemChange()) {
if (profile.getVolumeNotificationChange())
GlobalData.setNotificationVolume(context, profile.getVolumeNotificationValue());
if (((!GlobalData.applicationUnlinkRingerNotificationVolumes) || (callState != TelephonyManager.CALL_STATE_RINGING))
&& (linkUnlink == PhoneCallBroadcastReceiver.LINKMODE_NONE)) {
int volume = GlobalData.getNotificationVolume(context);
if (volume != -999) {
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, profile.getVolumeNotificationValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, profile.getVolumeNotificationValue());
correctSilentMode(profile, audioManager);
}
}
}
if (GlobalData.applicationUnlinkRingerNotificationVolumes) {
boolean doUnlink = audioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL;
Log.e("ActivateProfileHelper", "setVolumes doUnlink=" + doUnlink);
Log.e("ActivateProfileHelper", "setVolumes ringerMode=" + audioManager.getRingerMode());
if (doUnlink) {
//if (linkUnlink == PhoneCallBroadcastReceiver.LINKMODE_UNLINK) {
if (callState == TelephonyManager.CALL_STATE_RINGING) {
// for separating ringing and notification
// in ringing state ringer volumes must by set
// and notification volumes must not by set
int volume = GlobalData.getRingerVolume(context);
if (volume != -999) {
audioManager.setStreamVolume(AudioManager.STREAM_RING, volume, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, profile.getVolumeRingtoneValue());
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, volume, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, profile.getVolumeNotificationValue());
correctSilentMode(profile, audioManager);
}
}
else
if (linkUnlink == PhoneCallBroadcastReceiver.LINKMODE_LINK) {
// for separating ringing and notification
// in not ringing state ringer and notification volume must by change
Log.e("ActivateProfileHelper","setVolumes get audio mode="+audioManager.getMode());
int volume = GlobalData.getRingerVolume(context);
if (volume != -999) {
Log.e("ActivateProfileHelper","setVolumes set ring volume="+volume);
audioManager.setStreamVolume(AudioManager.STREAM_RING, volume, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, profile.getVolumeRingtoneValue());
}
volume = GlobalData.getNotificationVolume(context);
if (volume != -999) {
Log.e("ActivateProfileHelper","setVolumes set notification volume="+volume);
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, volume, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, profile.getVolumeNotificationValue());
}
correctSilentMode(profile, audioManager);
}
}
}
if (profile.getVolumeMediaChange())
{
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, profile.getVolumeMediaValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_MUSIC, profile.getVolumeMediaValue());
}
if (profile.getVolumeAlarmChange())
{
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, profile.getVolumeAlarmValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_ALARM, profile.getVolumeAlarmValue());
}
if (profile.getVolumeVoiceChange())
audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, profile.getVolumeVoiceValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_VOICE, profile.getVolumeVoiceValue());
}
private void setZenMode(int mode)
{
if (android.os.Build.VERSION.SDK_INT >= 21)
{
if (GlobalData.grantRoot(false) && (GlobalData.settingsBinaryExists()))
{
String command1 = "settings put global zen_mode " + mode;
//if (GlobalData.isSELinuxEnforcing())
// command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setZenMode", e.getMessage());
}
}
}
}
@SuppressWarnings("deprecation")
public void setRingerMode(Profile profile, AudioManager audioManager, boolean forSilent)
{
GlobalData.logE("@@@ ActivateProfileHelper.setRingerMode", "ringerMode="+audioManager.getRingerMode());
int ringerMode = profile._volumeRingerMode;
//if (profile._volumeRingerMode != 0)
// GlobalData.setRingerMode(context, profile._volumeRingerMode);
//int ringerMode = GlobalData.getRingerMode(context);
// for Lollipop 4=priority mode, for pre-lillipop 4=silent ringer mode
// priority mode must by invoked be 2 calls of setRingerMode:
// first call of setRingerMode must set ringer mode to normal (1) (not called for pre-lollipop)
// second call is normal change ringer mode (4)
// this call sequence sets Lollipop priority mode (check ExecuteVolumeProfilePrefsService, how is called setRingerMode)
if (forSilent) {
if (android.os.Build.VERSION.SDK_INT >= 21) {
if (ringerMode != 4) // 4 = silent ringer mode
return;
else
ringerMode = 1;
} else
return;
}
switch (ringerMode) {
case 1: // Ring
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception e) {
e.printStackTrace();
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception e) {
e.printStackTrace();
}
Settings.System.putInt(context.getContentResolver(), "vibrate_when_ringing", 0);
//setZenMode(ZENMODE_ALL);
break;
case 2: // Ring & Vibrate
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception e) {
e.printStackTrace();
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception e) {
e.printStackTrace();
}
Settings.System.putInt(context.getContentResolver(), "vibrate_when_ringing", 1);
//setZenMode(ZENMODE_ALL);
break;
case 3: // Vibrate
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception e) {
e.printStackTrace();
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception e) {
e.printStackTrace();
}
Settings.System.putInt(context.getContentResolver(), "vibrate_when_ringing", 1);
//setZenMode(ZENMODE_ALL);
break;
case 4: // Silent
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception e) {
e.printStackTrace();
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception e) {
e.printStackTrace();
}
Settings.System.putInt(context.getContentResolver(), "vibrate_when_ringing", 0);
//setZenMode(ZENMODE_PRIORITY);
break;
case 5: // Zen mode
switch (profile._volumeZenMode) {
case 1:
setZenMode(ZENMODE_ALL);
break;
case 2:
setZenMode(ZENMODE_PRIORITY);
break;
case 3:
setZenMode(ZENMODE_NONE);
break;
}
break;
}
}
public void executeForWallpaper(Profile profile) {
if (profile._deviceWallpaperChange == 1)
{
DisplayMetrics displayMetrics = new DisplayMetrics();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
display.getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels << 1; // best wallpaper width is twice screen width
Bitmap decodedSampleBitmap = BitmapManipulator.resampleBitmap(profile.getDeviceWallpaperIdentifier(), width, height);
if (decodedSampleBitmap != null)
{
// set wallpaper
WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
try {
wallpaperManager.setBitmap(decodedSampleBitmap);
} catch (IOException e) {
Log.e("ActivateProfileHelper.executeForWallpaper", "Cannot set wallpaper. Image="+profile.getDeviceWallpaperIdentifier());
}
}
}
}
public void execute(Profile _profile, boolean merged, boolean _interactive, String eventNotificationSound)
{
// rozdelit zvonenie a notifikacie - zial je to oznacene ako @Hide :-(
//Settings.System.putInt(context.getContentResolver(), Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 0);
Profile profile = GlobalData.getMappedProfile(_profile, context);
boolean interactive = _interactive;
// nahodenie volume
// run service for execute volumes
Intent volumeServiceIntent = new Intent(context, ExecuteVolumeProfilePrefsService.class);
volumeServiceIntent.putExtra(GlobalData.EXTRA_PROFILE_ID, profile._id);
volumeServiceIntent.putExtra(GlobalData.EXTRA_MERGED_PROFILE, merged);
volumeServiceIntent.putExtra(GlobalData.EXTRA_LINKUNLINK_VOLUMES, PhoneCallBroadcastReceiver.LINKMODE_NONE);
context.startService(volumeServiceIntent);
/*AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
// nahodenie ringer modu - aby sa mohli nastavit hlasitosti
setRingerMode(profile, audioManager);
setVolumes(profile, audioManager);
// nahodenie ringer modu - hlasitosti zmenia silent/vibrate
setRingerMode(profile, audioManager);*/
// set vibration on touch
switch (profile._vibrationOnTouch) {
case 1:
Settings.System.putInt(context.getContentResolver(), Settings.System.HAPTIC_FEEDBACK_ENABLED, 1);
break;
case 2:
Settings.System.putInt(context.getContentResolver(), Settings.System.HAPTIC_FEEDBACK_ENABLED, 0);
break;
}
// nahodenie tonov
if (profile._soundRingtoneChange == 1)
{
if (profile._soundRingtone.isEmpty())
Settings.System.putString(context.getContentResolver(), Settings.System.RINGTONE, null);
else
Settings.System.putString(context.getContentResolver(), Settings.System.RINGTONE, profile._soundRingtone);
}
if (profile._soundNotificationChange == 1)
{
if (profile._soundNotification.isEmpty())
Settings.System.putString(context.getContentResolver(), Settings.System.NOTIFICATION_SOUND, null);
else
Settings.System.putString(context.getContentResolver(), Settings.System.NOTIFICATION_SOUND, profile._soundNotification);
}
if (profile._soundAlarmChange == 1)
{
if (profile._soundAlarm.isEmpty())
Settings.System.putString(context.getContentResolver(), Settings.System.ALARM_ALERT, null);
else
Settings.System.putString(context.getContentResolver(), Settings.System.ALARM_ALERT, profile._soundAlarm);
}
//// nahodenie radio preferences
// run service for execute radios
Intent radioServiceIntent = new Intent(context, ExecuteRadioProfilePrefsService.class);
radioServiceIntent.putExtra(GlobalData.EXTRA_PROFILE_ID, profile._id);
radioServiceIntent.putExtra(GlobalData.EXTRA_MERGED_PROFILE, merged);
context.startService(radioServiceIntent);
// nahodenie auto-sync
boolean _isAutosync = ContentResolver.getMasterSyncAutomatically();
boolean _setAutosync = false;
switch (profile._deviceAutosync) {
case 1:
if (!_isAutosync)
{
_isAutosync = true;
_setAutosync = true;
}
break;
case 2:
if (_isAutosync)
{
_isAutosync = false;
_setAutosync = true;
}
break;
case 3:
_isAutosync = !_isAutosync;
_setAutosync = true;
break;
}
if (_setAutosync)
ContentResolver.setMasterSyncAutomatically(_isAutosync);
// screen timeout
switch (profile._deviceScreenTimeout) {
case 1:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 15000);
break;
case 2:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 30000);
break;
case 3:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 60000);
break;
case 4:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 120000);
break;
case 5:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 600000);
break;
case 6:
screenTimeoutUnlock(context);
if (android.os.Build.VERSION.SDK_INT < 19)
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, -1);
else
screenTimeoutLock(context);
//Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 18000000);
break;
case 7:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 300000);
break;
}
// zapnutie/vypnutie lockscreenu
//GlobalData.logE("$$$ ActivateProfileHelper.execute","keyguard");
boolean setLockscreen = false;
switch (profile._deviceKeyguard) {
case 1:
// enable lockscreen
GlobalData.logE("$$$ ActivateProfileHelper.execute","keyguard=ON");
GlobalData.setLockscreenDisabled(context, false);
setLockscreen = true;
break;
case 2:
// disable lockscreen
GlobalData.logE("$$$ ActivateProfileHelper.execute","keyguard=OFF");
GlobalData.setLockscreenDisabled(context, true);
setLockscreen = true;
break;
}
if (setLockscreen) {
boolean isScreenOn;
//if (android.os.Build.VERSION.SDK_INT >= 20)
// Display display = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
// isScreenOn = display.getState() != Display.STATE_OFF;
//else
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
isScreenOn = pm.isScreenOn();
GlobalData.logE("$$$ ActivateProfileHelper.execute","isScreenOn="+isScreenOn);
boolean keyguardShowing = false;
KeyguardManager kgMgr = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= 16)
keyguardShowing = kgMgr.isKeyguardLocked();
else
keyguardShowing = kgMgr.inKeyguardRestrictedInputMode();
GlobalData.logE("$$$ ActivateProfileHelper.execute","keyguardShowing="+keyguardShowing);
if (isScreenOn && !keyguardShowing) {
Intent keyguardService = new Intent(context.getApplicationContext(), KeyguardService.class);
context.startService(keyguardService);
}
}
// nahodenie podsvietenia
if (profile.getDeviceBrightnessChange())
{
GlobalData.logE("ActivateProfileHelper.execute", "set brightness: profile="+profile._name);
GlobalData.logE("ActivateProfileHelper.execute", "set brightness: _deviceBrightness="+profile._deviceBrightness);
if (profile.getDeviceBrightnessAutomatic())
{
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS,
profile.getDeviceBrightnessManualValue(context));
if (android.os.Build.VERSION.SDK_INT >= 21) // for Android 5.0: adaptive brightness
Settings.System.putFloat(context.getContentResolver(),
ADAPTIVE_BRIGHTNESS_SETTING_NAME,
profile.getDeviceBrightnessAdaptiveValue(context));
}
else
{
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS,
profile.getDeviceBrightnessManualValue(context));
}
if (brightnessHandler != null)
{
final Profile __profile = profile;
final Context __context = context;
brightnessHandler.post(new Runnable() {
public void run() {
createBrightnessView(__profile, __context);
}
});
}
else
createBrightnessView(profile, context);
}
// nahodenie rotate
switch (profile._deviceAutoRotate) {
case 1:
// set autorotate on
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 1);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_0);
break;
case 2:
// set autorotate off
// degree 0
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_0);
break;
case 3:
// set autorotate off
// degree 90
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_90);
break;
case 4:
// set autorotate off
// degree 180
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_180);
break;
case 5:
// set autorotate off
// degree 270
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_270);
break;
}
// nahodenie pozadia
if (profile._deviceWallpaperChange == 1) {
Intent wallpaperServiceIntent = new Intent(context, ExecuteWallpaperProfilePrefsService.class);
wallpaperServiceIntent.putExtra(GlobalData.EXTRA_PROFILE_ID, profile._id);
wallpaperServiceIntent.putExtra(GlobalData.EXTRA_MERGED_PROFILE, merged);
context.startService(wallpaperServiceIntent);
}
if (interactive)
{
// preferences, ktore vyzaduju interakciu uzivatela
if (GlobalData.hardwareCheck(GlobalData.PREF_PROFILE_DEVICE_MOBILE_DATA, context) == GlobalData.HARDWARE_CHECK_ALLOWED)
{
if (profile._deviceMobileDataPrefs == 1)
{
final Intent intent = new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(intent);
} catch (Exception e) {
final ComponentName componentName = new ComponentName("com.android.phone", "com.android.phone.Settings");
//intent.addCategory(Intent.ACTION_MAIN);
intent.setComponent(componentName);
context.startActivity(intent);
}
}
}
//if (GlobalData.hardwareCheck(GlobalData.PREF_PROFILE_DEVICE_GPS, context))
//{ No check only GPS
if (profile._deviceLocationServicePrefs == 1)
{
final Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
if (profile._deviceRunApplicationChange == 1)
{
String[] splits = profile._deviceRunApplicationPackageName.split("\\|");
Intent intent;
PackageManager packageManager = context.getPackageManager();
for (int i = 0; i < splits.length; i++) {
intent = packageManager.getLaunchIntentForPackage(splits[i]);
if (intent != null) {
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
}
}
}
private static void screenTimeoutLock(Context context)
{
WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
if (GUIData.keepScreenOnView != null)
{
windowManager.removeView(GUIData.keepScreenOnView);
GUIData.keepScreenOnView = null;
}
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
1, 1,
WindowManager.LayoutParams.TYPE_TOAST,
//TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
PixelFormat.TRANSLUCENT
);
params.gravity = Gravity.RIGHT | Gravity.TOP;
GUIData.keepScreenOnView = new BrightnessView(context);
windowManager.addView(GUIData.keepScreenOnView, params);
}
public static void screenTimeoutUnlock(Context context)
{
if (GUIData.keepScreenOnView != null)
{
WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
windowManager.removeView(GUIData.keepScreenOnView);
GUIData.keepScreenOnView = null;
}
GlobalData.logE("@@@ screenTimeoutLock.unlock","xxx");
}
@SuppressLint("RtlHardcoded")
private void createBrightnessView(Profile profile, Context context)
{
//if (dataWrapper.context != null)
WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
if (GUIData.brightneesView != null)
{
windowManager.removeView(GUIData.brightneesView);
GUIData.brightneesView = null;
}
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
1, 1,
WindowManager.LayoutParams.TYPE_TOAST,
//TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
PixelFormat.TRANSLUCENT
);
params.gravity = Gravity.RIGHT | Gravity.TOP;
if (profile.getDeviceBrightnessAutomatic())
params.screenBrightness = LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
else
params.screenBrightness = profile.getDeviceBrightnessManualValue(context) / (float) 255;
GUIData.brightneesView = new BrightnessView(context);
windowManager.addView(GUIData.brightneesView, params);
RemoveBrightnessViewBroadcastReceiver.setAlarm(context);
}
public void showNotification(Profile profile, String eventNotificationSound)
{
if (lockRefresh)
// no refres notification
return;
if (GlobalData.notificationStatusBar)
{
// close showed notification
//notificationManager.cancel(GlobalData.NOTIFICATION_ID);
// vytvorenie intentu na aktivitu, ktora sa otvori na kliknutie na notifikaciu
Intent intent = new Intent(context, LauncherActivity.class);
// clear all opened activities
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
// nastavime, ze aktivita sa spusti z notifikacnej listy
intent.putExtra(GlobalData.EXTRA_START_APP_SOURCE, GlobalData.STARTUP_SOURCE_NOTIFICATION);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
// vytvorenie intentu na restart events
Intent intentRE = new Intent(context, RestartEventsFromNotificationActivity.class);
PendingIntent pIntentRE = PendingIntent.getActivity(context, 0, intentRE, PendingIntent.FLAG_CANCEL_CURRENT);
// vytvorenie samotnej notifikacie
NotificationCompat.Builder notificationBuilder;
RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.notification_drawer);
boolean isIconResourceID;
String iconIdentifier;
String profileName;
Bitmap iconBitmap;
Bitmap preferencesIndicator;
if (profile != null)
{
isIconResourceID = profile.getIsIconResourceID();
iconIdentifier = profile.getIconIdentifier();
profileName = dataWrapper.getProfileNameWithManualIndicator(profile, true, false);
iconBitmap = profile._iconBitmap;
preferencesIndicator = profile._preferencesIndicator;
}
else
{
isIconResourceID = true;
iconIdentifier = GlobalData.PROFILE_ICON_DEFAULT;
profileName = context.getResources().getString(R.string.profiles_header_profile_name_no_activated);
iconBitmap = null;
preferencesIndicator = null;
}
notificationBuilder = new NotificationCompat.Builder(context)
.setContentIntent(pIntent);
if (android.os.Build.VERSION.SDK_INT >= 16) {
if (GlobalData.notificationShowInStatusBar)
notificationBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
else
notificationBuilder.setPriority(NotificationCompat.PRIORITY_MIN);
//notificationBuilder.setPriority(Notification.PRIORITY_HIGH); // for heads-up in Android 5.0
}
if (android.os.Build.VERSION.SDK_INT >= 21)
{
notificationBuilder.setCategory(Notification.CATEGORY_STATUS);
notificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
}
notificationBuilder.setTicker(profileName);
if (isIconResourceID)
{
int iconSmallResource;
if (iconBitmap != null) {
iconSmallResource = context.getResources().getIdentifier(iconIdentifier + "_notify", "drawable", context.getPackageName());
notificationBuilder.setSmallIcon(iconSmallResource);
contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, iconBitmap);
}
else {
if (GlobalData.notificationStatusBarStyle.equals("0") && (android.os.Build.VERSION.SDK_INT < 21)) {
//notificationBuilder.setSmallIcon(0);
iconSmallResource = context.getResources().getIdentifier(iconIdentifier + "_notify_color", "drawable", context.getPackageName());
notificationBuilder.setSmallIcon(iconSmallResource);
//contentView.setImageViewResource(R.id.notification_activated_profile_icon, 0);
contentView.setImageViewResource(R.id.notification_activated_profile_icon, iconSmallResource);
} else {
//notificationBuilder.setSmallIcon(0);
//contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, null);
iconSmallResource = context.getResources().getIdentifier(iconIdentifier + "_notify", "drawable", context.getPackageName());
notificationBuilder.setSmallIcon(iconSmallResource);
int iconLargeResource = context.getResources().getIdentifier(iconIdentifier, "drawable", context.getPackageName());
Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(), iconLargeResource);
contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, largeIcon);
}
}
}
else
{
int iconSmallResource;
if (GlobalData.notificationStatusBarStyle.equals("0"))
iconSmallResource = R.drawable.ic_profile_default;
else
iconSmallResource = R.drawable.ic_profile_default_notify;
//notificationBuilder.setSmallIcon(0);
notificationBuilder.setSmallIcon(iconSmallResource);
//contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, null);
contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, iconBitmap);
}
if (!eventNotificationSound.isEmpty())
{
Uri ringtoneUri=Uri.parse(eventNotificationSound);
notificationBuilder.setSound(ringtoneUri);
}
Notification notification = notificationBuilder.build();
contentView.setTextViewText(R.id.notification_activated_profile_name, profileName);
//contentView.setImageViewBitmap(R.id.notification_activated_profile_pref_indicator,
// ProfilePreferencesIndicator.paint(profile, context));
if ((preferencesIndicator != null) && (GlobalData.notificationPrefIndicator))
contentView.setImageViewBitmap(R.id.notification_activated_profile_pref_indicator, preferencesIndicator);
else
contentView.setImageViewResource(R.id.notification_activated_profile_pref_indicator, R.drawable.ic_empty);
if (android.os.Build.VERSION.SDK_INT >= 20)
contentView.setImageViewResource(R.id.notification_activated_profile_restart_events, R.drawable.ic_action_events_restart);
else
contentView.setImageViewResource(R.id.notification_activated_profile_restart_events, R.drawable.ic_action_events_restart_dark);
contentView.setOnClickPendingIntent(R.id.notification_activated_profile_restart_events, pIntentRE);
notification.contentView = contentView;
if (GlobalData.notificationStatusBarPermanent)
{
//notification.flags |= Notification.FLAG_NO_CLEAR;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
}
else
{
setAlarmForNotificationCancel();
}
notificationManager.notify(GlobalData.PROFILE_NOTIFICATION_ID, notification);
}
else
{
notificationManager.cancel(GlobalData.PROFILE_NOTIFICATION_ID);
}
}
public void removeNotification()
{
notificationManager.cancel(GlobalData.PROFILE_NOTIFICATION_ID);
}
private void setAlarmForNotificationCancel()
{
if (GlobalData.notificationStatusBarCancel.isEmpty() || GlobalData.notificationStatusBarCancel.equals("0"))
return;
Intent intent = new Intent(context, NotificationCancelAlarmBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE);
Calendar now = Calendar.getInstance();
long time = now.getTimeInMillis() + Integer.valueOf(GlobalData.notificationStatusBarCancel) * 1000;
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
//alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, alarmTime, 24 * 60 * 60 * 1000 , pendingIntent);
//alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, 24 * 60 * 60 * 1000 , pendingIntent);
}
public void updateWidget()
{
if (lockRefresh)
// no refres widgets
return;
// icon widget
Intent intent = new Intent(context, IconWidgetProvider.class);
intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");
int ids[] = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, IconWidgetProvider.class));
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
context.sendBroadcast(intent);
// one row widget
Intent intent4 = new Intent(context, OneRowWidgetProvider.class);
intent4.setAction("android.appwidget.action.APPWIDGET_UPDATE");
int ids4[] = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, OneRowWidgetProvider.class));
intent4.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids4);
context.sendBroadcast(intent4);
// list widget
Intent intent2 = new Intent(context, ProfileListWidgetProvider.class);
intent2.setAction(ProfileListWidgetProvider.INTENT_REFRESH_LISTWIDGET);
int ids2[] = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, ProfileListWidgetProvider.class));
intent2.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids2);
context.sendBroadcast(intent2);
// dashclock extension
Intent intent3 = new Intent();
intent3.setAction(DashClockBroadcastReceiver.INTENT_REFRESH_DASHCLOCK);
context.sendBroadcast(intent3);
// activities
Intent intent5 = new Intent();
intent5.setAction(RefreshGUIBroadcastReceiver.INTENT_REFRESH_GUI);
context.sendBroadcast(intent5);
}
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private boolean isAirplaneMode(Context context)
{
if (android.os.Build.VERSION.SDK_INT >= 17)
return Settings.Global.getInt(context.getContentResolver(), Global.AIRPLANE_MODE_ON, 0) != 0;
else
return Settings.System.getInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
private void setAirplaneMode(Context context, boolean mode)
{
if (android.os.Build.VERSION.SDK_INT >= 17)
setAirplaneMode_SDK17(context, mode);
else
setAirplaneMode_SDK8(context, mode);
}
private boolean isMobileData(Context context)
{
/*if (android.os.Build.VERSION.SDK_INT >= 21)
{
return Settings.Global.getInt(context.getContentResolver(), "mobile_data", 0) == 1;
}
else
{*/
final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
final Class<?> connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Method getMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("getMobileDataEnabled");
getMobileDataEnabledMethod.setAccessible(true);
return (Boolean)getMobileDataEnabledMethod.invoke(connectivityManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
} catch (NoSuchMethodException e) {
e.printStackTrace();
return false;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return false;
} catch (IllegalAccessException e) {
e.printStackTrace();
return false;
} catch (InvocationTargetException e) {
e.printStackTrace();
return false;
}
/*
final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null)
{
int netvorkType = networkInfo.getType(); // 0 = mobile, 1 = wifi
//String netvorkTypeName = networkInfo.getTypeName(); // "mobile" or "WIFI"
boolean connected = networkInfo.isConnected(); // true = active connection
//if (netvorkType == 0)
//{
// connected into mobile data
return connected;
//}
//else
//{
// conected into Wifi
// return false;
//}
}
else
return false;
*/
}
private void setMobileData(Context context, boolean enable)
{
/*if (android.os.Build.VERSION.SDK_INT >= 21) // NOT WORKING :-/
{
if (GlobalData.grantRoot(false) && (GlobalData.settingsBinaryExists()))
{
String command1;
if (enable)
command1 = "settings put global mobile_data 1";
else
command1 = "settings put global mobile_data 0";
//if (GlobalData.isSELinuxEnforcing())
// command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setMobileData", e.getMessage());
}
}
}
else
{*/
final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean OK = false;
try {
final Class<?> connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Field iConnectivityManagerField = connectivityManagerClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField.get(connectivityManager);
final Class<?> iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enable);
OK = true;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
if (!OK)
{
try {
Method setMobileDataEnabledMethod = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(connectivityManager, enable);
OK = true;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
@SuppressWarnings("deprecation")
private void setGPS(Context context, boolean enable)
{
boolean isEnabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER);
//if(!provider.contains(LocationManager.GPS_PROVIDER) && enable)
if ((!isEnabled) && enable)
{
if (GlobalData.canExploitGPS(context))
{
GlobalData.logE("ActivateProfileHelper.setGPS", "exploit");
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
context.sendBroadcast(poke);
}
else
if ((android.os.Build.VERSION.SDK_INT >= 17) && GlobalData.grantRoot(false))
{
// zariadenie je rootnute
GlobalData.logE("ActivateProfileHelper.setGPS", "rooted");
String command1;
//String command2;
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
String newSet;
if (provider == "")
newSet = LocationManager.GPS_PROVIDER;
else
newSet = String.format("%s,%s", provider, LocationManager.GPS_PROVIDER);
command1 = "settings put secure location_providers_allowed \"" + newSet + "\"";
//if (GlobalData.isSELinuxEnforcing())
// command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
//command2 = "am broadcast -a android.location.GPS_ENABLED_CHANGE --ez state true";
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setGPS", "Error on run su: "+e.toString());
}
}
else
{
/*GlobalData.logE("ActivateProfileHelper.setGPS", "old method");
try {
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", enable);
context.sendBroadcast(intent);
} catch (SecurityException e) {
e.printStackTrace();
}*/
// for normal apps it is only possible to open the system settings dialog
/* Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent); */
}
}
else
//if(provider.contains(LocationManager.GPS_PROVIDER) && (!enable))
if (isEnabled && (!enable))
{
if (GlobalData.canExploitGPS(context))
{
GlobalData.logE("ActivateProfileHelper.setGPS", "exploit");
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
context.sendBroadcast(poke);
}
else
if ((android.os.Build.VERSION.SDK_INT >= 17) && GlobalData.grantRoot(false))
{
// zariadenie je rootnute
GlobalData.logE("ActivateProfileHelper.setGPS", "rooted");
String command1;
//String command2;
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
String[] list = provider.split(",");
String newSet = "";
int j = 0;
for (int i = 0; i < list.length; i++)
{
if (!list[i].equals(LocationManager.GPS_PROVIDER))
{
if (j > 0)
newSet += ",";
newSet += list[i];
j++;
}
}
command1 = "settings put secure location_providers_allowed \"" + newSet + "\"";
//if (GlobalData.isSELinuxEnforcing())
// command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
//command2 = "am broadcast -a android.location.GPS_ENABLED_CHANGE --ez state false";
Command command = new Command(0, false, command1);//, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setGPS", "Error on run su: "+e.toString());
}
}
else
{
//GlobalData.logE("ActivateProfileHelper.setGPS", "old method");
/*try {
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", enable);
context.sendBroadcast(intent);
} catch (SecurityException e) {
e.printStackTrace();
}*/
// for normal apps it is only possible to open the system settings dialog
/* Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent); */
}
}
}
private void setAirplaneMode_SDK17(Context context, boolean mode)
{
if (GlobalData.grantRoot(false))
{
// zariadenie je rootnute
String command1;
String command2;
if (mode)
{
command1 = "settings put global airplane_mode_on 1";
command2 = "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state true";
}
else
{
command1 = "settings put global airplane_mode_on 0";
command2 = "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state false";
}
//if (GlobalData.isSELinuxEnforcing())
// command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
// command2 = GlobalData.getSELinuxEnforceCommand(command2, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("AirPlaneMode_SDK17.setAirplaneMode", "Error on run su");
}
}
else
{
// for normal apps it is only possible to open the system settings dialog
/* Intent intent = new Intent(android.provider.Settings.ACTION_AIRPLANE_MODE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent); */
}
}
@SuppressWarnings("deprecation")
private void setAirplaneMode_SDK8(Context context, boolean mode)
{
Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, mode ? 1 : 0);
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", mode);
context.sendBroadcast(intent);
}
private void commandWait(Command cmd) throws Exception {
int waitTill = 50;
int waitTillMultiplier = 2;
int waitTillLimit = 3200; //7 tries, 6350 msec
while (!cmd.isFinished() && waitTill<=waitTillLimit) {
synchronized (cmd) {
try {
if (!cmd.isFinished()) {
cmd.wait(waitTill);
waitTill *= waitTillMultiplier;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
if (!cmd.isFinished()){
Log.e("ActivateProfileHelper", "Could not finish root command in " + (waitTill/waitTillMultiplier));
}
}
public static int getMinimumScreenBrightnessSetting (Context context)
{
final Resources res = Resources.getSystem();
int id = res.getIdentifier("config_screenBrightnessSettingMinimum", "integer", "android"); // API17+
if (id == 0)
id = res.getIdentifier("config_screenBrightnessDim", "integer", "android"); // lower API levels
if (id != 0)
{
try {
return res.getInteger(id);
}
catch (Resources.NotFoundException e) {
// ignore
}
}
return 0;
}
public static int getMaximumScreenBrightnessSetting (Context context)
{
final Resources res = Resources.getSystem();
final int id = res.getIdentifier("config_screenBrightnessSettingMaximum", "integer", "android"); // API17+
if (id != 0)
{
try {
return res.getInteger(id);
}
catch (Resources.NotFoundException e) {
// ignore
}
}
return 255;
}
}
|
package com.carrotcreative.cream.loaders.retry;
import android.os.Handler;
public abstract class RetryLoader {
protected static final int START_RETRY_SECONDS = 2;
protected static final int MAX_RETRY_SECONDS = 64;
protected static final float RETRY_SECONDS_GROWTH_RATE = 1.5f;
protected int mAttemptNumber = 0;
protected int mRetrySeconds;
public RetryLoader()
{
mRetrySeconds = START_RETRY_SECONDS;
}
public void retry()
{
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
retryLoad();
updateRetrySeconds();
}
}, mRetrySeconds * 1000);
}
private void updateRetrySeconds()
{
mRetrySeconds = Math.min(MAX_RETRY_SECONDS,
(int) (mRetrySeconds * RETRY_SECONDS_GROWTH_RATE));
}
protected abstract void retryLoad();
}
|
package uk.ac.ebi.biosamples.utils;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AdaptiveThreadPoolExecutor extends ThreadPoolExecutor implements AutoCloseable {
private Logger log = LoggerFactory.getLogger(this.getClass());
private AtomicInteger completedJobs = new AtomicInteger(0);
private AdaptiveThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue, RejectedExecutionHandler rejectedExecutionHandler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, rejectedExecutionHandler);
}
protected void afterExecute(Runnable r, Throwable t) {
if (t != null) return;
completedJobs.incrementAndGet();
}
/**
* By default creates a pool with a queue size of 1000 that
* will test to increase/decrease threads every 60 seconds
* and does not guarantee to distribute jobs fairly among threads
* @return
*/
public static AdaptiveThreadPoolExecutor create() {
return create(1000,60000,false);
}
public static AdaptiveThreadPoolExecutor create(int maxQueueSize, int pollInterval, boolean fairness) {
return create(maxQueueSize, pollInterval, fairness, Runtime.getRuntime().availableProcessors(),
Runtime.getRuntime().availableProcessors()*8);
}
public static AdaptiveThreadPoolExecutor create(int maxQueueSize, int pollInterval, boolean fairness, int initialPoolSize, int maxThreads) {
//default to the number of processors
int corePoolSize = initialPoolSize;
int maximumPoolSize = corePoolSize;
//keep alive is not relevant, since core == maximum
long keepAliveTime = 1;
TimeUnit unit = TimeUnit.DAYS;
// a queue constructed with fairness set to true grants threads access
// in FIFO order.
// Fairness generally decreases throughput but reduces variability and
// avoids starvation.
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(maxQueueSize, fairness);
// A handler for rejected tasks that runs the rejected task directly in
// the calling thread of the execute method,
// unless the executor has been shut down, in which case the task is
// discarded.
RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
AdaptiveThreadPoolExecutor threadPool = new AdaptiveThreadPoolExecutor(corePoolSize, maximumPoolSize,
keepAliveTime, unit, workQueue, rejectedExecutionHandler);
Thread monitorThread = new Thread(new PoolMonitor(threadPool, pollInterval, maxThreads));
monitorThread.setDaemon(true);
monitorThread.start();
return threadPool;
}
/**
* This is a separate thread that monitors a thread pool
* and increases or decreases the number of threads within the pool
* in order to try to maximize the throughput.
* @author faulcon
*
*/
private static class PoolMonitor implements Runnable {
private Logger log = LoggerFactory.getLogger(this.getClass());
private final AdaptiveThreadPoolExecutor pool;
private final int pollInterval;
private final Map<Integer, Double> threadsScores = new HashMap<>();
private final Map<Integer, Long> threadsTime = new HashMap<>();
private final double margin = 1.0;
private final int maxThreads;
public PoolMonitor(AdaptiveThreadPoolExecutor pool, int pollInterval, int maxThreads) {
this.pool = pool;
this.pollInterval = pollInterval;
this.maxThreads = maxThreads;
}
@Override
public void run() {
long lastStep = System.nanoTime();
while (!pool.isTerminated()) {
//wait for it to do stuff
try {
Thread.sleep(pollInterval);
} catch (InterruptedException e) {
if (Thread.interrupted()) {// Clears interrupted status!
throw new RuntimeException(e);
}
}
//test the number of jobs done
//get number of threads they were done with
long now = System.nanoTime();
long interval = now-lastStep;
lastStep = now;
int currentThreads = pool.getMaximumPoolSize();
int doneJobs = pool.completedJobs.getAndSet(0);
//number of jobs per sec per thread
//double score = (((double)doneJobs)*1000000000.0d)/(interval*currentThreads);
double score = (((double)doneJobs)*1000000000.0d)/(interval);
log.info("Completed "+doneJobs+" in "+interval+"ns using "+currentThreads+" threads : score = "+score);
//store the result of this score
threadsScores.put(currentThreads, score);
threadsTime.put(currentThreads, now);
//remove any scores that are too old
Iterator<Integer> iterator = threadsTime.keySet().iterator();
while (iterator.hasNext()) {
int testThreads = iterator.next();
long testTime = threadsTime.get(testThreads);
//more than 25 pollings ago?
if (testTime + (pollInterval*1000000l*25) < now) {
//too old score, remove it
log.info("Remove out-of-date score for "+testThreads+" of "+threadsScores.get(testThreads));
iterator.remove();
threadsScores.remove(testThreads);
}
}
//work out what the best number of threads is
double bestScore = score;
int bestThreads = currentThreads;
for (int testThreads : threadsScores.keySet()) {
double testScore = threadsScores.get(testThreads);
if (testScore > bestScore) {
bestScore = testScore;
bestThreads = testThreads;
}
}
log.info("Best scoring number of threads is "+bestThreads+" with "+bestScore);
//if we are more than margin below the best, change to the best
if (bestThreads != currentThreads && margin*score < bestScore) {
log.info("Adjusting to use "+(bestThreads)+" threads");
pool.setCorePoolSize(bestThreads);
pool.setMaximumPoolSize(bestThreads);
} else {
//experiment if we might do better increase or decreasing the threads
if ((!threadsScores.containsKey(currentThreads+1) || threadsScores.get(currentThreads+1) > margin*score)
&& currentThreads < maxThreads ) {
//increase the number of threads
log.info("Adjusting to try "+(currentThreads+1)+" threads");
pool.setCorePoolSize(currentThreads+1);
pool.setMaximumPoolSize(currentThreads+1);
} else if (currentThreads > 1 && (!threadsScores.containsKey(currentThreads-1) || threadsScores.get(currentThreads-1) > margin*score)) {
//decrease the number of threads
//only decrease threads if there are at least 2 (so we don't drop to zero!)
log.info("Adjusting to try "+(currentThreads-1)+" threads");
pool.setCorePoolSize(currentThreads-1);
pool.setMaximumPoolSize(currentThreads-1);
}
}
}
}
}
/**
* This is required to implement the AutoClosable interface. It will stop
* accepting new jobs and wait up to 24h before termination;
*/
@Override
public void close() throws Exception {
shutdown();
awaitTermination(1, TimeUnit.DAYS);
}
}
|
package fape.core.planning.search.strategies.plans;
import fape.core.planning.states.State;
import fape.core.planning.states.SearchNode;
import java.util.LinkedList;
import java.util.List;
/**
* Used to use a sequence of PartialPlanComparator as one.
*
* The basic algorithm for comparing two partial plans is to apply the comparators in sequence until it results in an ordering
* between the two plans. If no comparator is found, the plans are left unordered.
*/
public class SeqPlanComparator extends PartialPlanComparator {
private final List<PartialPlanComparator> comparators;
public SeqPlanComparator(List<PartialPlanComparator> comparators) {
this.comparators = new LinkedList<>(comparators);
}
@Override
public String shortName() {
String ret = "";
for(PartialPlanComparator comp : comparators) {
ret += comp.shortName() + ",";
}
return ret.substring(0, ret.length()-1);
}
@Override
public String reportOnState(State st) {
StringBuilder sb = new StringBuilder();
for (PartialPlanComparator ppc : comparators) {
sb.append(ppc.reportOnState(st));
sb.append("\n");
}
return sb.toString();
}
@Override
public double g(State st) {
double v = 0;
for(PartialPlanComparator pc : comparators)
v = 1000000 * v + pc.g(st);
return v;
}
@Override
public double h(State st) {
double v = 0;
for(PartialPlanComparator pc : comparators)
v = 1000000 * v + pc.h(st);
return v;
}
@Override
public double hc(State st) {
double v = 0;
for(PartialPlanComparator pc : comparators)
v = 1000000 * v + pc.hc(st);
return v;
}
}
|
package com.intellij.psi.codeStyle.statusbar;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.wm.impl.status.TextPanel;
import com.intellij.util.ui.JBFont;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
public class CodeStyleStatusBarPanel extends JPanel {
private final TextPanel myLabel;
private final JLabel myIconLabel;
public CodeStyleStatusBarPanel() {
super();
setOpaque(false);
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
setAlignmentY(Component.CENTER_ALIGNMENT);
myLabel = new TextPanel() {};
myLabel.setFont(SystemInfo.isMac ? JBUI.Fonts.label(11) : JBFont.label());
add(myLabel);
myIconLabel = new JLabel("");
myIconLabel.setBorder(JBUI.Borders.empty(2,2,2,0));
add(myIconLabel);
setBorder(JBUI.Borders.empty(0));
}
public void setText(@NotNull String text) {
myLabel.setText(text);
}
@Nullable
public String getText() {
return myLabel.getText();
}
public void setIcon(@Nullable Icon icon) {
myIconLabel.setIcon(icon);
myIconLabel.setVisible(icon != null);
}
}
|
package com.intellij.openapi.actionSystem.impl;
import com.intellij.AbstractBundle;
import com.intellij.BundleBase;
import com.intellij.DynamicBundle;
import com.intellij.diagnostic.LoadingState;
import com.intellij.diagnostic.PluginException;
import com.intellij.diagnostic.StartUpMeasurer;
import com.intellij.icons.AllIcons;
import com.intellij.ide.ActivityTracker;
import com.intellij.ide.DataManager;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.IdeaPluginDescriptorImpl;
import com.intellij.ide.plugins.PluginDependency;
import com.intellij.ide.plugins.PluginManagerCore;
import com.intellij.ide.ui.customization.ActionUrl;
import com.intellij.ide.ui.customization.CustomActionsSchema;
import com.intellij.idea.IdeaLogger;
import com.intellij.internal.statistic.collectors.fus.actions.persistence.ActionIdProvider;
import com.intellij.internal.statistic.collectors.fus.actions.persistence.ActionsCollectorImpl;
import com.intellij.internal.statistic.collectors.fus.actions.persistence.ActionsEventLogGroup;
import com.intellij.internal.statistic.eventLog.events.EventFields;
import com.intellij.internal.statistic.eventLog.events.EventPair;
import com.intellij.internal.statistic.eventLog.events.ObjectEventData;
import com.intellij.lang.Language;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.actionSystem.ex.ActionPopupMenuListener;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import com.intellij.openapi.actionSystem.ex.AnActionListener;
import com.intellij.openapi.application.*;
import com.intellij.openapi.application.impl.LaterInvocator;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.actionSystem.EditorAction;
import com.intellij.openapi.editor.actionSystem.EditorActionHandlerBean;
import com.intellij.openapi.extensions.ExtensionPointListener;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.PluginDescriptor;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.fileTypes.PlainTextLanguage;
import com.intellij.openapi.keymap.Keymap;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.keymap.ex.KeymapManagerEx;
import com.intellij.openapi.keymap.impl.DefaultKeymap;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectType;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtilRt;
import com.intellij.openapi.util.text.Strings;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.IdeFrame;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.ui.icons.IconLoadMeasurer;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.ReflectionUtil;
import com.intellij.util.containers.CollectionFactory;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.ui.UIUtil;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import org.jdom.Element;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.Timer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.WindowEvent;
import java.lang.reflect.Constructor;
import java.util.List;
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public final class ActionManagerImpl extends ActionManagerEx implements Disposable {
private static final ExtensionPointName<ActionConfigurationCustomizer> EP =
new ExtensionPointName<>("com.intellij.actionConfigurationCustomizer");
private static final ExtensionPointName<DynamicActionConfigurationCustomizer> DYNAMIC_EP_NAME =
new ExtensionPointName<>("com.intellij.dynamicActionConfigurationCustomizer");
private static final ExtensionPointName<EditorActionHandlerBean> EDITOR_ACTION_HANDLER_EP =
new ExtensionPointName<>("com.intellij.editorActionHandler");
private static final String ACTION_ELEMENT_NAME = "action";
private static final String GROUP_ELEMENT_NAME = "group";
private static final String CLASS_ATTR_NAME = "class";
private static final String ID_ATTR_NAME = "id";
private static final String INTERNAL_ATTR_NAME = "internal";
private static final String ICON_ATTR_NAME = "icon";
private static final String ADD_TO_GROUP_ELEMENT_NAME = "add-to-group";
private static final String SHORTCUT_ELEMENT_NAME = "keyboard-shortcut";
private static final String MOUSE_SHORTCUT_ELEMENT_NAME = "mouse-shortcut";
private static final String DESCRIPTION = "description";
private static final String TEXT_ATTR_NAME = "text";
private static final String KEY_ATTR_NAME = "key";
private static final String POPUP_ATTR_NAME = "popup";
private static final String COMPACT_ATTR_NAME = "compact";
private static final String SEARCHABLE_ATTR_NAME = "searchable";
private static final String SEPARATOR_ELEMENT_NAME = "separator";
private static final String REFERENCE_ELEMENT_NAME = "reference";
private static final String ABBREVIATION_ELEMENT_NAME = "abbreviation";
private static final String GROUPID_ATTR_NAME = "group-id";
private static final String ANCHOR_ELEMENT_NAME = "anchor";
private static final String FIRST = "first";
private static final String LAST = "last";
private static final String BEFORE = "before";
private static final String AFTER = "after";
private static final String SECONDARY = "secondary";
private static final String RELATIVE_TO_ACTION_ATTR_NAME = "relative-to-action";
private static final String FIRST_KEYSTROKE_ATTR_NAME = "first-keystroke";
private static final String SECOND_KEYSTROKE_ATTR_NAME = "second-keystroke";
private static final String REMOVE_SHORTCUT_ATTR_NAME = "remove";
private static final String REPLACE_SHORTCUT_ATTR_NAME = "replace-all";
private static final String KEYMAP_ATTR_NAME = "keymap";
private static final String KEYSTROKE_ATTR_NAME = "keystroke";
private static final String REF_ATTR_NAME = "ref";
private static final String VALUE_ATTR_NAME = "value";
private static final String ACTIONS_BUNDLE = "messages.ActionsBundle";
private static final String USE_SHORTCUT_OF_ATTR_NAME = "use-shortcut-of";
private static final String OVERRIDES_ATTR_NAME = "overrides";
private static final String KEEP_CONTENT_ATTR_NAME = "keep-content";
private static final String PROJECT_TYPE = "project-type";
private static final String UNREGISTER_ELEMENT_NAME = "unregister";
private static final String OVERRIDE_TEXT_ELEMENT_NAME = "override-text";
private static final String SYNONYM_ELEMENT_NAME = "synonym";
private static final String PLACE_ATTR_NAME = "place";
private static final String USE_TEXT_OF_PLACE_ATTR_NAME = "use-text-of-place";
private static final String RESOURCE_BUNDLE_ATTR_NAME = "resource-bundle";
private static final Logger LOG = Logger.getInstance(ActionManagerImpl.class);
private static final int DEACTIVATED_TIMER_DELAY = 5000;
private static final int TIMER_DELAY = 500;
private static final int UPDATE_DELAY_AFTER_TYPING = 500;
private final Object myLock = new Object();
private final Map<String, AnAction> idToAction = CollectionFactory.createSmallMemoryFootprintMap();
private final MultiMap<PluginId, String> pluginToId = new MultiMap<>();
private final Object2IntMap<String> idToIndex = new Object2IntOpenHashMap<>();
private final Map<Object, String> actionToId = CollectionFactory.createSmallMemoryFootprintMap();
private final MultiMap<String, String> idToGroupId = new MultiMap<>();
private final List<String> myNotRegisteredInternalActionIds = new ArrayList<>();
private final List<AnActionListener> myActionListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private final List<ActionPopupMenuListener> myActionPopupMenuListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private final List<Object/*ActionPopupMenuImpl|JBPopup*/> myPopups = new ArrayList<>();
private MyTimer myTimer;
private int myRegisteredActionsCount;
private String myLastPreformedActionId;
private String myPrevPerformedActionId;
private long myLastTimeEditorWasTypedIn;
private boolean myTransparentOnlyUpdate;
private final Map<OverridingAction, AnAction> myBaseActions = new HashMap<>();
private int myAnonymousGroupIdCounter;
ActionManagerImpl() {
Application app = ApplicationManager.getApplication();
if (!app.isUnitTestMode()) {
LoadingState.COMPONENTS_LOADED.checkOccurred();
if (!app.isHeadlessEnvironment() && !app.isCommandLine()) {
LOG.assertTrue(!app.isDispatchThread());
}
}
registerActions(PluginManagerCore.getLoadedPlugins(null), true);
EP.forEachExtensionSafe(customizer -> customizer.customize(this));
DYNAMIC_EP_NAME.forEachExtensionSafe(customizer -> customizer.registerActions(this));
DYNAMIC_EP_NAME.addExtensionPointListener(new ExtensionPointListener<>() {
@Override
public void extensionAdded(@NotNull DynamicActionConfigurationCustomizer extension, @NotNull PluginDescriptor pluginDescriptor) {
extension.registerActions(ActionManagerImpl.this);
}
@Override
public void extensionRemoved(@NotNull DynamicActionConfigurationCustomizer extension, @NotNull PluginDescriptor pluginDescriptor) {
extension.unregisterActions(ActionManagerImpl.this);
}
}, this);
EDITOR_ACTION_HANDLER_EP.addChangeListener(this::updateAllHandlers, this);
}
@ApiStatus.Internal
public void registerActions(@NotNull List<IdeaPluginDescriptorImpl> plugins, @SuppressWarnings("unused") boolean initialStartup) {
KeymapManager keymapManager = Objects.requireNonNull(KeymapManager.getInstance());
for (IdeaPluginDescriptorImpl plugin : plugins) {
registerPluginActions(plugin, keymapManager);
for (PluginDependency pluginDependency : plugin.getPluginDependencies()) {
IdeaPluginDescriptorImpl subPlugin = pluginDependency.isDisabledOrBroken ? null : pluginDependency.subDescriptor;
if (subPlugin == null) {
continue;
}
registerPluginActions(subPlugin, keymapManager);
for (PluginDependency subPluginDependency : subPlugin.getPluginDependencies()) {
IdeaPluginDescriptorImpl subSubPlugin = subPluginDependency.isDisabledOrBroken ? null : subPluginDependency.subDescriptor;
if (subSubPlugin != null) {
registerPluginActions(subSubPlugin, keymapManager);
}
}
}
}
}
private static @NotNull AnActionListener publisher() {
return ApplicationManager.getApplication().getMessageBus().syncPublisher(AnActionListener.TOPIC);
}
static @Nullable AnAction convertStub(@NotNull ActionStub stub) {
AnAction anAction = instantiate(stub.getClassName(), stub.getPlugin(), AnAction.class);
if (anAction == null) {
return null;
}
stub.initAction(anAction);
updateIconFromStub(stub, anAction);
return anAction;
}
private static @Nullable <T> T instantiate(@NotNull String stubClassName, @NotNull PluginDescriptor pluginDescriptor, @NotNull Class<T> expectedClass) {
Object obj;
try {
Class<?> aClass = Class.forName(stubClassName, true, pluginDescriptor.getPluginClassLoader());
Constructor<?> constructor = aClass.getDeclaredConstructor();
try {
constructor.setAccessible(true);
}
catch (SecurityException ignored) {
}
obj = constructor.newInstance();
}
catch (ProcessCanceledException e) {
throw e;
}
catch (PluginException e) {
LOG.error(e);
return null;
}
catch (Throwable e) {
LOG.error(new PluginException(e, pluginDescriptor.getPluginId()));
return null;
}
if (!expectedClass.isInstance(obj)) {
LOG.error(new PluginException("class with name '" +
stubClassName + "' must be an instance of '" + expectedClass.getName() + "'; got " + obj, pluginDescriptor.getPluginId()));
return null;
}
//noinspection unchecked
return (T)obj;
}
private static void updateIconFromStub(@NotNull ActionStubBase stub, @NotNull AnAction anAction) {
String iconPath = stub.getIconPath();
if (iconPath != null) {
setIconFromClass(anAction.getClass(), stub.getPlugin(), iconPath, anAction.getTemplatePresentation());
}
}
private static @Nullable ActionGroup convertGroupStub(@NotNull ActionGroupStub stub, @NotNull ActionManager actionManager) {
IdeaPluginDescriptor plugin = stub.getPlugin();
ActionGroup group = instantiate(stub.getActionClass(), plugin, ActionGroup.class);
if (group == null) {
return null;
}
stub.initGroup(group, actionManager);
updateIconFromStub(stub, group);
return group;
}
private static void processAbbreviationNode(@NotNull Element e, @NotNull String id) {
String abbr = e.getAttributeValue(VALUE_ATTR_NAME);
if (!Strings.isEmpty(abbr)) {
AbbreviationManagerImpl abbreviationManager = (AbbreviationManagerImpl)AbbreviationManager.getInstance();
abbreviationManager.register(abbr, id, true);
}
}
private static boolean isSecondary(Element element) {
return "true".equalsIgnoreCase(element.getAttributeValue(SECONDARY));
}
private static void setIconFromClass(@Nullable Class<?> actionClass,
@NotNull PluginDescriptor pluginDescriptor,
@NotNull String iconPath,
@NotNull Presentation presentation) {
long start = StartUpMeasurer.getCurrentTimeIfEnabled();
Icon icon = IconLoader.findIcon(iconPath, actionClass, pluginDescriptor.getPluginClassLoader(), null, true);
if (icon == null) {
reportActionError(pluginDescriptor.getPluginId(), "Icon cannot be found in '" + iconPath + "', action '" + actionClass + "'");
icon = AllIcons.Nodes.Unknown;
}
IconLoadMeasurer.actionIcon.end(start);
presentation.setIcon(icon);
}
@SuppressWarnings("HardCodedStringLiteral")
private static @NlsActions.ActionDescription String computeDescription(@NotNull ResourceBundle bundle, String id, String elementType, String descriptionValue) {
String key = elementType + "." + id + ".description";
return AbstractBundle.messageOrDefault(bundle, key, Strings.notNullize(descriptionValue));
}
@SuppressWarnings("HardCodedStringLiteral")
private static @NlsActions.ActionText String computeActionText(@Nullable ResourceBundle bundle, String id, String elementType, @Nullable String textValue) {
String defaultValue = Strings.notNullize(textValue);
return bundle == null ? defaultValue : AbstractBundle.messageOrDefault(bundle, elementType + "." + id + "." + TEXT_ATTR_NAME, defaultValue);
}
private static boolean checkRelativeToAction(String relativeToActionId,
@NotNull Anchor anchor,
@NotNull String actionName,
@Nullable PluginId pluginId) {
if ((Anchor.BEFORE == anchor || Anchor.AFTER == anchor) && relativeToActionId == null) {
reportActionError(pluginId, actionName + ": \"relative-to-action\" cannot be null if anchor is \"after\" or \"before\"");
return false;
}
return true;
}
@Nullable
private static Anchor parseAnchor(String anchorStr, @Nullable String actionName, @Nullable PluginId pluginId) {
if (anchorStr == null) {
return Anchor.LAST;
}
if (FIRST.equalsIgnoreCase(anchorStr)) {
return Anchor.FIRST;
}
else if (LAST.equalsIgnoreCase(anchorStr)) {
return Anchor.LAST;
}
else if (BEFORE.equalsIgnoreCase(anchorStr)) {
return Anchor.BEFORE;
}
else if (AFTER.equalsIgnoreCase(anchorStr)) {
return Anchor.AFTER;
}
else {
reportActionError(pluginId, actionName + ": anchor should be one of the following constants: \"first\", \"last\", \"before\" or \"after\"");
return null;
}
}
private static void processMouseShortcutNode(Element element, String actionId, PluginId pluginId, @NotNull KeymapManager keymapManager) {
String keystrokeString = element.getAttributeValue(KEYSTROKE_ATTR_NAME);
if (keystrokeString == null || keystrokeString.trim().isEmpty()) {
reportActionError(pluginId, "\"keystroke\" attribute must be specified for action with id=" + actionId);
return;
}
MouseShortcut shortcut;
try {
shortcut = KeymapUtil.parseMouseShortcut(keystrokeString);
}
catch (Exception ex) {
reportActionError(pluginId, "\"keystroke\" attribute has invalid value for action with id=" + actionId);
return;
}
String keymapName = element.getAttributeValue(KEYMAP_ATTR_NAME);
if (keymapName == null || keymapName.isEmpty()) {
reportActionError(pluginId, "attribute \"keymap\" should be defined");
return;
}
Keymap keymap = keymapManager.getKeymap(keymapName);
if (keymap == null) {
reportKeymapNotFoundWarning(pluginId, keymapName);
return;
}
processRemoveAndReplace(element, actionId, keymap, shortcut);
}
private static void reportActionError(@Nullable PluginId pluginId, @NotNull String message) {
reportActionError(pluginId, message, null);
}
private static void reportActionError(@Nullable PluginId pluginId, @NotNull String message, @Nullable Throwable cause) {
if (pluginId != null) {
LOG.error(new PluginException(message, cause, pluginId));
}
else if (cause != null) {
LOG.error(message, cause);
}
else {
LOG.error(message);
}
}
private static void reportKeymapNotFoundWarning(@Nullable PluginId pluginId, @NotNull String keymapName) {
if (DefaultKeymap.isBundledKeymapHidden(keymapName)) {
return;
}
String message = "keymap \"" + keymapName + "\" not found";
LOG.warn(pluginId == null ? message : new PluginException(message, null, pluginId).getMessage());
}
private static String getPluginInfo(@Nullable PluginId id) {
IdeaPluginDescriptor plugin = id == null ? null : PluginManagerCore.getPlugin(id);
if (plugin == null) {
return "";
}
String name = plugin.getName();
if (name == null) {
name = id.getIdString();
}
return " (Plugin: " + name + ")";
}
private static @NotNull DataContext getContextBy(Component contextComponent) {
DataManager dataManager = DataManager.getInstance();
return contextComponent != null ? dataManager.getDataContext(contextComponent) : dataManager.getDataContext();
}
@Override
public void dispose() {
if (myTimer != null) {
myTimer.stop();
myTimer = null;
}
}
@Override
public void addTimerListener(int delay, @NotNull final TimerListener listener) {
_addTimerListener(listener, false);
}
@Override
public void removeTimerListener(@NotNull TimerListener listener) {
_removeTimerListener(listener, false);
}
@Override
public void addTransparentTimerListener(int delay, @NotNull TimerListener listener) {
_addTimerListener(listener, true);
}
@Override
public void removeTransparentTimerListener(@NotNull TimerListener listener) {
_removeTimerListener(listener, true);
}
private void _addTimerListener(final TimerListener listener, boolean transparent) {
if (ApplicationManager.getApplication().isUnitTestMode()) return;
if (myTimer == null) {
myTimer = new MyTimer();
myTimer.start();
}
myTimer.addTimerListener(listener, transparent);
}
private void _removeTimerListener(TimerListener listener, boolean transparent) {
if (ApplicationManager.getApplication().isUnitTestMode()) return;
if (LOG.assertTrue(myTimer != null)) {
myTimer.removeTimerListener(listener, transparent);
}
}
@NotNull
public ActionPopupMenu createActionPopupMenu(@NotNull String place, @NotNull ActionGroup group, @Nullable PresentationFactory presentationFactory) {
return new ActionPopupMenuImpl(place, group, this, presentationFactory);
}
@NotNull
@Override
public ActionPopupMenu createActionPopupMenu(@NotNull String place, @NotNull ActionGroup group) {
return new ActionPopupMenuImpl(place, group, this, null);
}
@NotNull
@Override
public ActionToolbar createActionToolbar(@NotNull final String place, @NotNull final ActionGroup group, final boolean horizontal) {
return createActionToolbar(place, group, horizontal, false);
}
@NotNull
@Override
public ActionToolbar createActionToolbar(@NotNull final String place, @NotNull final ActionGroup group, final boolean horizontal, final boolean decorateButtons) {
return new ActionToolbarImpl(place, group, horizontal, decorateButtons);
}
private void registerPluginActions(@NotNull IdeaPluginDescriptorImpl plugin, @NotNull KeymapManager keymapManager) {
List<Element> elements = plugin.getActionDescriptionElements();
if (elements == null) {
return;
}
long startTime = StartUpMeasurer.getCurrentTime();
String lastBundleName = null;
ResourceBundle lastBundle = null;
for (Element element : elements) {
Element parent = element.getParentElement();
String bundleName = parent == null ? null : parent.getAttributeValue(RESOURCE_BUNDLE_ATTR_NAME);
if (bundleName == null) {
bundleName = plugin.getPluginId() == PluginManagerCore.CORE_ID ? ACTIONS_BUNDLE : plugin.getResourceBundleBaseName();
}
ResourceBundle bundle;
if (bundleName == null) {
bundle = null;
}
else if (bundleName.equals(lastBundleName)) {
bundle = lastBundle;
}
else {
try {
bundle = DynamicBundle.INSTANCE.getResourceBundle(bundleName, plugin.getPluginClassLoader());
lastBundle = bundle;
lastBundleName = bundleName;
}
catch (MissingResourceException e) {
LOG.error(new PluginException("Cannot resolve resource bundle " + bundleName + " for action " + JDOMUtil.writeElement(element), e, plugin.getPluginId()));
bundle = null;
}
}
switch (element.getName()) {
case ACTION_ELEMENT_NAME:
processActionElement(element, plugin, bundle, keymapManager);
break;
case GROUP_ELEMENT_NAME:
processGroupElement(element, plugin, bundle, keymapManager);
break;
case SEPARATOR_ELEMENT_NAME:
processSeparatorNode(null, element, plugin.getPluginId(), bundle);
break;
case REFERENCE_ELEMENT_NAME:
processReferenceNode(element, plugin.getPluginId(), bundle);
break;
case UNREGISTER_ELEMENT_NAME:
processUnregisterNode(element, plugin.getPluginId());
break;
default:
LOG.error(new PluginException("Unexpected name of element" + element.getName(), plugin.getPluginId()));
break;
}
}
StartUpMeasurer.addPluginCost(plugin.getPluginId().getIdString(), "Actions", StartUpMeasurer.getCurrentTime() - startTime);
}
@Override
@Nullable
public AnAction getAction(@NotNull String id) {
return getActionImpl(id, false);
}
@Nullable
private AnAction getActionImpl(@NotNull String id, boolean canReturnStub) {
AnAction action;
synchronized (myLock) {
action = idToAction.get(id);
if (canReturnStub || !(action instanceof ActionStubBase)) {
return action;
}
}
AnAction converted = action instanceof ActionStub ? convertStub((ActionStub)action) : convertGroupStub((ActionGroupStub)action, this);
if (converted == null) {
unregisterAction(id);
return null;
}
synchronized (myLock) {
action = idToAction.get(id);
if (action instanceof ActionStubBase) {
action = replaceStub((ActionStubBase)action, converted);
}
return action;
}
}
@NotNull
private AnAction replaceStub(@NotNull ActionStubBase stub, AnAction anAction) {
LOG.assertTrue(actionToId.containsKey(stub));
actionToId.remove(stub);
LOG.assertTrue(idToAction.containsKey(stub.getId()));
AnAction action = idToAction.remove(stub.getId());
LOG.assertTrue(action != null);
LOG.assertTrue(action.equals(stub));
actionToId.put(anAction, stub.getId());
updateHandlers(anAction);
return addToMap(stub.getId(), anAction, stub.getPlugin().getPluginId(), stub instanceof ActionStub ? ((ActionStub)stub).getProjectType() : null);
}
@Override
public String getId(@NotNull AnAction action) {
if (action instanceof ActionStubBase) {
return ((ActionStubBase)action).getId();
}
synchronized (myLock) {
return actionToId.get(action);
}
}
@Override
public @NotNull List<String> getActionIdList(@NotNull String idPrefix) {
List<String> result = new ArrayList<>();
synchronized (myLock) {
for (String id : idToAction.keySet()) {
if (id.startsWith(idPrefix)) {
result.add(id);
}
}
}
return result;
}
@Override
public String @NotNull [] getActionIds(@NotNull String idPrefix) {
return ArrayUtilRt.toStringArray(getActionIdList(idPrefix));
}
@Override
public boolean isGroup(@NotNull String actionId) {
return getActionImpl(actionId, true) instanceof ActionGroup;
}
@NotNull
@Override
public JComponent createButtonToolbar(@NotNull final String actionPlace, @NotNull final ActionGroup messageActionGroup) {
return new ButtonToolbarImpl(actionPlace, messageActionGroup);
}
@Override
public AnAction getActionOrStub(@NotNull String id) {
return getActionImpl(id, true);
}
/**
* @return instance of ActionGroup or ActionStub. The method never returns real subclasses of {@code AnAction}.
*/
private @Nullable AnAction processActionElement(@NotNull Element element,
@NotNull IdeaPluginDescriptorImpl plugin,
@Nullable ResourceBundle bundle,
@NotNull KeymapManager keymapManager) {
String className = element.getAttributeValue(CLASS_ATTR_NAME);
if (className == null || className.isEmpty()) {
reportActionError(plugin.getPluginId(), "action element should have specified \"class\" attribute");
return null;
}
// read ID and register loaded action
String id = obtainActionId(element, className);
if (Boolean.parseBoolean(element.getAttributeValue(INTERNAL_ATTR_NAME)) &&
!ApplicationManager.getApplication().isInternal()) {
myNotRegisteredInternalActionIds.add(id);
return null;
}
String iconPath = element.getAttributeValue(ICON_ATTR_NAME);
String projectType = element.getAttributeValue(PROJECT_TYPE);
String textValue = element.getAttributeValue(TEXT_ATTR_NAME);
//noinspection HardCodedStringLiteral
String descriptionValue = element.getAttributeValue(DESCRIPTION);
ActionStub stub = new ActionStub(className, id, plugin, iconPath, projectType, () -> {
Supplier<String> text = () -> computeActionText(bundle, id, ACTION_ELEMENT_NAME, textValue);
if (text.get() == null) {
reportActionError(plugin.getPluginId(), "'text' attribute is mandatory (actionId=" + id +
", plugin=" + plugin + ")");
}
Presentation presentation = new Presentation();
presentation.setText(text);
if (bundle == null) {
presentation.setDescription(descriptionValue);
}
else {
presentation.setDescription(() -> computeDescription(bundle, id, ACTION_ELEMENT_NAME, descriptionValue));
}
return presentation;
});
// process all links and key bindings if any
for (Element e : element.getChildren()) {
switch (e.getName()) {
case ADD_TO_GROUP_ELEMENT_NAME:
processAddToGroupNode(stub, e, plugin.getPluginId(), isSecondary(e));
break;
case SHORTCUT_ELEMENT_NAME:
processKeyboardShortcutNode(e, id, plugin.getPluginId(), keymapManager);
break;
case MOUSE_SHORTCUT_ELEMENT_NAME:
processMouseShortcutNode(e, id, plugin.getPluginId(), keymapManager);
break;
case ABBREVIATION_ELEMENT_NAME:
processAbbreviationNode(e, id);
break;
case OVERRIDE_TEXT_ELEMENT_NAME:
processOverrideTextNode(stub, stub.getId(), e, plugin.getPluginId(), bundle);
break;
case SYNONYM_ELEMENT_NAME:
processSynonymNode(stub, e, plugin.getPluginId(), bundle);
break;
default:
reportActionError(plugin.getPluginId(), "unexpected name of element \"" + e.getName() + "\"");
return null;
}
}
String shortcutOfActionId = element.getAttributeValue(USE_SHORTCUT_OF_ATTR_NAME);
if (shortcutOfActionId != null) {
keymapManager.bindShortcuts(shortcutOfActionId, id);
}
registerOrReplaceActionInner(element, id, stub, plugin);
return stub;
}
private static String obtainActionId(Element element, String className) {
String id = element.getAttributeValue(ID_ATTR_NAME);
return Strings.isEmpty(id) ? StringUtilRt.getShortName(className) : id;
}
private void registerOrReplaceActionInner(@NotNull Element element,
@NotNull String id,
@NotNull AnAction action,
@NotNull IdeaPluginDescriptor plugin) {
synchronized (myLock) {
if (Boolean.parseBoolean(element.getAttributeValue(OVERRIDES_ATTR_NAME))) {
if (getActionOrStub(id) == null) {
LOG.error(element.getName() + " '" + id + "' doesn't override anything");
return;
}
AnAction prev = replaceAction(id, action, plugin.getPluginId());
if (action instanceof DefaultActionGroup && prev instanceof DefaultActionGroup) {
if (Boolean.parseBoolean(element.getAttributeValue(KEEP_CONTENT_ATTR_NAME))) {
((DefaultActionGroup)action).copyFromGroup((DefaultActionGroup)prev);
}
}
}
else {
registerAction(id, action, plugin.getPluginId(), element.getAttributeValue(PROJECT_TYPE));
}
ActionsCollectorImpl.onActionLoadedFromXml(action, id, plugin);
}
}
private AnAction processGroupElement(@NotNull Element element,
@NotNull IdeaPluginDescriptorImpl plugin,
@Nullable ResourceBundle bundle,
@NotNull KeymapManager keymapManager) {
if (!GROUP_ELEMENT_NAME.equals(element.getName())) {
reportActionError(plugin.getPluginId(), "unexpected name of element \"" + element.getName() + "\"");
return null;
}
String className = element.getAttributeValue(CLASS_ATTR_NAME);
if (className == null) {
// use default group if class isn't specified
className = "true".equals(element.getAttributeValue(COMPACT_ATTR_NAME))
? DefaultCompactActionGroup.class.getName()
: DefaultActionGroup.class.getName();
}
try {
String id = element.getAttributeValue(ID_ATTR_NAME);
if (id != null && id.isEmpty()) {
reportActionError(plugin.getPluginId(), "ID of the group cannot be an empty string");
return null;
}
ActionGroup group;
boolean customClass = false;
if (DefaultActionGroup.class.getName().equals(className)) {
group = new DefaultActionGroup();
}
else if (DefaultCompactActionGroup.class.getName().equals(className)) {
group = new DefaultCompactActionGroup();
}
else if (id == null) {
Object obj = ApplicationManager.getApplication().instantiateClass(className, plugin);
if (!(obj instanceof ActionGroup)) {
reportActionError(plugin.getPluginId(), "class with name \"" + className + "\" should be instance of " + ActionGroup.class.getName());
return null;
}
if (element.getChildren().size() != element.getChildren(ADD_TO_GROUP_ELEMENT_NAME).size() ) {
if (!(obj instanceof DefaultActionGroup)) {
reportActionError(plugin.getPluginId(), "class with name \"" + className + "\" should be instance of " + DefaultActionGroup.class.getName() +
" because there are children specified");
return null;
}
}
customClass = true;
group = (ActionGroup)obj;
}
else {
group = new ActionGroupStub(id, className, plugin);
customClass = true;
}
// read ID and register loaded group
if (Boolean.parseBoolean(element.getAttributeValue(INTERNAL_ATTR_NAME)) && !ApplicationManager.getApplication().isInternal()) {
myNotRegisteredInternalActionIds.add(id);
return null;
}
if (id == null) {
id = "<anonymous-group-" + myAnonymousGroupIdCounter++ + ">";
}
registerOrReplaceActionInner(element, id, group, plugin);
Presentation presentation = group.getTemplatePresentation();
String finalId = id;
// text
Supplier<String> text = () -> computeActionText(bundle, finalId, GROUP_ELEMENT_NAME, element.getAttributeValue(TEXT_ATTR_NAME));
// don't override value which was set in API with empty value from xml descriptor
if (!Strings.isEmpty(text.get()) || presentation.getText() == null) {
presentation.setText(text);
}
// description
String description = element.getAttributeValue(DESCRIPTION); //NON-NLS
if (bundle == null) {
// don't override value which was set in API with empty value from xml descriptor
if (!Strings.isEmpty(description) || presentation.getDescription() == null) {
presentation.setDescription(description);
}
}
else {
Supplier<String> descriptionSupplier = () -> computeDescription(bundle, finalId, GROUP_ELEMENT_NAME, description);
// don't override value which was set in API with empty value from xml descriptor
if (!Strings.isEmpty(descriptionSupplier.get()) || presentation.getDescription() == null) {
presentation.setDescription(descriptionSupplier);
}
}
// icon
String iconPath = element.getAttributeValue(ICON_ATTR_NAME);
if (group instanceof ActionGroupStub) {
((ActionGroupStub)group).setIconPath(iconPath);
}
else if (iconPath != null) {
setIconFromClass(null, plugin, iconPath, presentation);
}
// popup
String popup = element.getAttributeValue(POPUP_ATTR_NAME);
if (popup != null) {
group.setPopup(Boolean.parseBoolean(popup));
if (group instanceof ActionGroupStub) {
((ActionGroupStub)group).setPopupDefinedInXml(true);
}
}
String searchable = element.getAttributeValue(SEARCHABLE_ATTR_NAME);
if (searchable != null) {
group.setSearchable(Boolean.parseBoolean(searchable));
}
String shortcutOfActionId = element.getAttributeValue(USE_SHORTCUT_OF_ATTR_NAME);
if (customClass && shortcutOfActionId != null) {
KeymapManagerEx.getInstanceEx().bindShortcuts(shortcutOfActionId, id);
}
// process all group's children. There are other groups, actions, references and links
for (Element child : element.getChildren()) {
String name = child.getName();
if (ACTION_ELEMENT_NAME.equals(name)) {
AnAction action = processActionElement(child, plugin, bundle, keymapManager);
if (action != null) {
addToGroupInner(group, action, Constraints.LAST, isSecondary(child));
}
}
else if (SEPARATOR_ELEMENT_NAME.equals(name)) {
processSeparatorNode((DefaultActionGroup)group, child, plugin.getPluginId(), bundle);
}
else if (GROUP_ELEMENT_NAME.equals(name)) {
AnAction action = processGroupElement(child, plugin, bundle, keymapManager);
if (action != null) {
addToGroupInner(group, action, Constraints.LAST, false);
}
}
else if (ADD_TO_GROUP_ELEMENT_NAME.equals(name)) {
processAddToGroupNode(group, child, plugin.getPluginId(), isSecondary(child));
}
else if (REFERENCE_ELEMENT_NAME.equals(name)) {
AnAction action = processReferenceElement(child, plugin.getPluginId());
if (action != null) {
addToGroupInner(group, action, Constraints.LAST, isSecondary(child));
}
}
else if (OVERRIDE_TEXT_ELEMENT_NAME.equals(name)) {
processOverrideTextNode(group, id, child, plugin.getPluginId(), bundle);
}
else {
reportActionError(plugin.getPluginId(), "unexpected name of element \"" + name + "\n");
return null;
}
}
return group;
}
catch (Exception e) {
String message = "cannot create class \"" + className + "\"";
reportActionError(plugin.getPluginId(), message, e);
return null;
}
}
private void processReferenceNode(@NotNull Element element, @Nullable PluginId pluginId, @Nullable ResourceBundle bundle) {
AnAction action = processReferenceElement(element, pluginId);
if (action == null) {
return;
}
for (Element child : element.getChildren()) {
if (ADD_TO_GROUP_ELEMENT_NAME.equals(child.getName())) {
processAddToGroupNode(action, child, pluginId, isSecondary(child));
}
else if (SYNONYM_ELEMENT_NAME.equals(child.getName())) {
processSynonymNode(action, child, pluginId, bundle);
}
}
}
/**
* @param element description of link
*/
private void processAddToGroupNode(AnAction action, Element element, PluginId pluginId, boolean secondary) {
String name = action instanceof ActionStub ? ((ActionStub)action).getClassName() : action.getClass().getName();
String id = action instanceof ActionStub ? ((ActionStub)action).getId() : actionToId.get(action);
String actionName = name + " (" + id + ")";
if (!ADD_TO_GROUP_ELEMENT_NAME.equals(element.getName())) {
reportActionError(pluginId, "unexpected name of element \"" + element.getName() + "\"");
return;
}
// parent group
final AnAction parentGroup = getParentGroup(element.getAttributeValue(GROUPID_ATTR_NAME), actionName, pluginId);
if (parentGroup == null) {
return;
}
// anchor attribute
final Anchor anchor = parseAnchor(element.getAttributeValue(ANCHOR_ELEMENT_NAME), actionName, pluginId);
if (anchor == null) {
return;
}
final String relativeToActionId = element.getAttributeValue(RELATIVE_TO_ACTION_ATTR_NAME);
if (!checkRelativeToAction(relativeToActionId, anchor, actionName, pluginId)) {
return;
}
addToGroupInner(parentGroup, action, new Constraints(anchor, relativeToActionId), secondary);
}
private void addToGroupInner(AnAction group, AnAction action, Constraints constraints, boolean secondary) {
String actionId = action instanceof ActionStub ? ((ActionStub)action).getId() : actionToId.get(action);
((DefaultActionGroup)group).addAction(action, constraints, this).setAsSecondary(secondary);
idToGroupId.putValue(actionId, actionToId.get(group));
}
@Nullable
public DefaultActionGroup getParentGroup(final String groupId,
@Nullable final String actionName,
@Nullable final PluginId pluginId) {
if (groupId == null || groupId.isEmpty()) {
reportActionError(pluginId, actionName + ": attribute \"group-id\" should be defined");
return null;
}
AnAction parentGroup = getActionImpl(groupId, true);
if (parentGroup == null) {
reportActionError(pluginId, actionName + ": group with id \"" + groupId + "\" isn't registered; action will be added to the \"Other\" group", null);
parentGroup = getActionImpl(IdeActions.GROUP_OTHER_MENU, true);
}
if (!(parentGroup instanceof DefaultActionGroup)) {
reportActionError(pluginId, actionName + ": group with id \"" + groupId + "\" should be instance of " + DefaultActionGroup.class.getName() +
" but was " + (parentGroup != null ? parentGroup.getClass() : "[null]"));
return null;
}
return (DefaultActionGroup)parentGroup;
}
private static void processOverrideTextNode(AnAction action, String id, Element element, PluginId pluginId,
@Nullable ResourceBundle bundle) {
if (!OVERRIDE_TEXT_ELEMENT_NAME.equals(element.getName())) {
reportActionError(pluginId, "unexpected name of element \"" + element.getName() + "\"");
return;
}
String place = element.getAttributeValue(PLACE_ATTR_NAME);
if (place == null) {
reportActionError(pluginId, id + ": override-text specified without place");
return;
}
String useTextOfPlace = element.getAttributeValue(USE_TEXT_OF_PLACE_ATTR_NAME);
if (useTextOfPlace != null) {
action.copyActionTextOverride(useTextOfPlace, place, id);
}
else {
String text = element.getAttributeValue(TEXT_ATTR_NAME, "");
if (text.isEmpty() && bundle != null) {
String prefix = action instanceof ActionGroup ? "group" : "action";
String key = prefix + "." + id + "." + place + ".text";
action.addTextOverride(place, () -> BundleBase.message(bundle, key));
}
else {
action.addTextOverride(place, () -> text);
}
}
}
private static void processSynonymNode(AnAction action, Element element, PluginId pluginId, @Nullable ResourceBundle bundle) {
if (!SYNONYM_ELEMENT_NAME.equals(element.getName())) {
reportActionError(pluginId, "unexpected name of element \"" + element.getName() + "\"");
return;
}
//noinspection HardCodedStringLiteral
String text = element.getAttributeValue(TEXT_ATTR_NAME, "");
if (!text.isEmpty()) {
action.addSynonym(() -> text);
}
else {
String key = element.getAttributeValue(KEY_ATTR_NAME);
if (key != null && bundle != null) {
action.addSynonym(() -> BundleBase.message(bundle, key));
}
else {
reportActionError(pluginId, "Can't process synonym: neither text nor resource bundle key is specified");
}
}
}
/**
* @param parentGroup group which is the parent of the separator. It can be {@code null} in that
* case separator will be added to group described in the <add-to-group ....> subelement.
* @param element XML element which represent separator.
*/
private void processSeparatorNode(@Nullable DefaultActionGroup parentGroup, @NotNull Element element, PluginId pluginId, @Nullable ResourceBundle bundle) {
if (!SEPARATOR_ELEMENT_NAME.equals(element.getName())) {
reportActionError(pluginId, "unexpected name of element \"" + element.getName() + "\"");
return;
}
@SuppressWarnings("HardCodedStringLiteral")
String text = element.getAttributeValue(TEXT_ATTR_NAME);
String key = element.getAttributeValue(KEY_ATTR_NAME);
Separator separator =
text != null ? new Separator(text) : key != null ? createSeparator(bundle, key) : Separator.getInstance();
if (parentGroup != null) {
parentGroup.add(separator, this);
}
// try to find inner <add-to-parent...> tag
for (Element child : element.getChildren()) {
if (ADD_TO_GROUP_ELEMENT_NAME.equals(child.getName())) {
processAddToGroupNode(separator, child, pluginId, isSecondary(child));
}
}
}
@NotNull
private static Separator createSeparator(@Nullable ResourceBundle bundle, @NotNull String key) {
String text = bundle != null ? AbstractBundle.messageOrNull(bundle, key) : null;
return text != null ? new Separator(text) : Separator.getInstance();
}
private void processUnregisterNode(Element element, PluginId pluginId) {
String id = element.getAttributeValue(ID_ATTR_NAME);
if (id == null) {
reportActionError(pluginId, "'id' attribute is required for 'unregister' elements");
return;
}
AnAction action = getAction(id);
if (action == null) {
reportActionError(pluginId, "Trying to unregister non-existing action " + id);
return;
}
AbbreviationManager.getInstance().removeAllAbbreviations(id);
unregisterAction(id);
}
private static void processKeyboardShortcutNode(Element element,
String actionId,
PluginId pluginId,
@NotNull KeymapManager keymapManager) {
String firstStrokeString = element.getAttributeValue(FIRST_KEYSTROKE_ATTR_NAME);
if (firstStrokeString == null) {
reportActionError(pluginId, "\"first-keystroke\" attribute must be specified for action with id=" + actionId);
return;
}
KeyStroke firstKeyStroke = getKeyStroke(firstStrokeString);
if (firstKeyStroke == null) {
reportActionError(pluginId, "\"first-keystroke\" attribute has invalid value for action with id=" + actionId);
return;
}
KeyStroke secondKeyStroke = null;
String secondStrokeString = element.getAttributeValue(SECOND_KEYSTROKE_ATTR_NAME);
if (secondStrokeString != null) {
secondKeyStroke = getKeyStroke(secondStrokeString);
if (secondKeyStroke == null) {
reportActionError(pluginId, "\"second-keystroke\" attribute has invalid value for action with id=" + actionId);
return;
}
}
String keymapName = element.getAttributeValue(KEYMAP_ATTR_NAME);
if (keymapName == null || keymapName.trim().isEmpty()) {
reportActionError(pluginId, "attribute \"keymap\" should be defined");
return;
}
Keymap keymap = keymapManager.getKeymap(keymapName);
if (keymap == null) {
reportKeymapNotFoundWarning(pluginId, keymapName);
return;
}
final KeyboardShortcut shortcut = new KeyboardShortcut(firstKeyStroke, secondKeyStroke);
processRemoveAndReplace(element, actionId, keymap, shortcut);
}
private static void processRemoveAndReplace(@NotNull Element element, String actionId, @NotNull Keymap keymap, @NotNull Shortcut shortcut) {
boolean remove = Boolean.parseBoolean(element.getAttributeValue(REMOVE_SHORTCUT_ATTR_NAME));
boolean replace = Boolean.parseBoolean(element.getAttributeValue(REPLACE_SHORTCUT_ATTR_NAME));
if (remove) {
keymap.removeShortcut(actionId, shortcut);
}
if (replace) {
keymap.removeAllActionShortcuts(actionId);
}
if (!remove) {
keymap.addShortcut(actionId, shortcut);
}
}
private @Nullable AnAction processReferenceElement(Element element, PluginId pluginId) {
if (!REFERENCE_ELEMENT_NAME.equals(element.getName())) {
reportActionError(pluginId, "unexpected name of element \"" + element.getName() + "\"", null);
return null;
}
String ref = getReferenceActionId(element);
if (ref == null || ref.isEmpty()) {
reportActionError(pluginId, "ID of reference element should be defined", null);
return null;
}
AnAction action = getActionImpl(ref, true);
if (action == null) {
if (!myNotRegisteredInternalActionIds.contains(ref)) {
reportActionError(pluginId, "action specified by reference isn't registered (ID=" + ref + ")", null);
}
return null;
}
return action;
}
private static String getReferenceActionId(@NotNull Element element) {
String ref = element.getAttributeValue(REF_ATTR_NAME);
if (ref == null) {
// support old style references by id
ref = element.getAttributeValue(ID_ATTR_NAME);
}
return ref;
}
@ApiStatus.Internal
public static @Nullable String checkUnloadActions(PluginId pluginId, @NotNull IdeaPluginDescriptorImpl pluginDescriptor) {
List<Element> elements = pluginDescriptor.getActionDescriptionElements();
if (elements == null) {
return null;
}
for (Element element : elements) {
if (!element.getName().equals(ACTION_ELEMENT_NAME) &&
!(element.getName().equals(GROUP_ELEMENT_NAME) && canUnloadGroup(element)) &&
!element.getName().equals(REFERENCE_ELEMENT_NAME)) {
return "Plugin " + pluginId + " is not unload-safe because of action element " + element.getName();
}
}
return null;
}
private static boolean canUnloadGroup(@NotNull Element element) {
if (element.getAttributeValue(ID_ATTR_NAME) == null) {
return false;
}
for (Element child : element.getChildren()) {
if (child.getName().equals(GROUP_ELEMENT_NAME) && !canUnloadGroup(child)) return false;
}
return true;
}
public void unloadActions(@NotNull IdeaPluginDescriptorImpl pluginDescriptor) {
List<Element> elements = pluginDescriptor.getActionDescriptionElements();
if (elements == null) {
return;
}
for (Element element : ContainerUtil.reverse(elements)) {
switch (element.getName()) {
case ACTION_ELEMENT_NAME:
unloadActionElement(element);
break;
case GROUP_ELEMENT_NAME:
unloadGroupElement(element);
break;
case REFERENCE_ELEMENT_NAME:
PluginId pluginId = pluginDescriptor.getPluginId();
AnAction action = processReferenceElement(element, pluginId);
if (action == null) return;
String actionId = getReferenceActionId(element);
for (Element child : element.getChildren(ADD_TO_GROUP_ELEMENT_NAME)) {
String groupId = child.getAttributeValue(GROUPID_ATTR_NAME);
final DefaultActionGroup parentGroup = getParentGroup(groupId, actionId, pluginId);
if (parentGroup == null) return;
parentGroup.remove(action);
idToGroupId.remove(actionId, groupId);
}
break;
}
}
}
private void unloadGroupElement(Element element) {
String id = element.getAttributeValue(ID_ATTR_NAME);
if (id == null) {
throw new IllegalStateException("Cannot unload groups with no ID");
}
for (Element groupChild : element.getChildren()) {
if (groupChild.getName().equals(ACTION_ELEMENT_NAME)) {
unloadActionElement(groupChild);
}
else if (groupChild.getName().equals(GROUP_ELEMENT_NAME)) {
unloadGroupElement(groupChild);
}
}
unregisterAction(id);
}
private void unloadActionElement(@NotNull Element element) {
String className = element.getAttributeValue(CLASS_ATTR_NAME);
String id = obtainActionId(element, className);
unregisterAction(id);
}
@Override
public void registerAction(@NotNull String actionId, @NotNull AnAction action, @Nullable PluginId pluginId) {
registerAction(actionId, action, pluginId, null);
}
public void registerAction(@NotNull String actionId,
@NotNull AnAction action,
@Nullable PluginId pluginId,
@Nullable String projectType) {
synchronized (myLock) {
if (addToMap(actionId, action, pluginId, projectType) == null) return;
if (actionToId.containsKey(action)) {
reportActionError(pluginId,
"ID \"" + actionToId.get(action) + "\" is already taken by action \"" + action + "\"" + getPluginInfo(pluginId) +
". ID \"" + actionId + "\" cannot be registered for the same action");
return;
}
idToIndex.put(actionId, myRegisteredActionsCount++);
actionToId.put(action, actionId);
if (pluginId != null && !(action instanceof ActionGroup)) {
pluginToId.putValue(pluginId, actionId);
}
action.registerCustomShortcutSet(new ProxyShortcutSet(actionId), null);
notifyCustomActionsSchema(actionId);
updateHandlers(action);
}
}
private static void notifyCustomActionsSchema(@NotNull String registeredID) {
CustomActionsSchema schema = ApplicationManager.getApplication().getServiceIfCreated(CustomActionsSchema.class);
if (schema == null) return;
for (ActionUrl url : schema.getActions()) {
if (registeredID.equals(url.getComponent())) {
schema.incrementModificationStamp();
break;
}
}
}
private AnAction addToMap(String actionId, AnAction action, PluginId pluginId, String projectType) {
if (projectType != null || idToAction.containsKey(actionId)) {
return registerChameleon(actionId, action, pluginId, projectType);
}
else {
idToAction.put(actionId, action);
return action;
}
}
private AnAction registerChameleon(String actionId, AnAction action, PluginId pluginId, String projectType) {
ProjectType type = projectType == null ? null : new ProjectType(projectType);
// make sure id+projectType is unique
AnAction o = idToAction.get(actionId);
ChameleonAction chameleonAction;
if (o == null) {
chameleonAction = new ChameleonAction(action, type);
idToAction.put(actionId, chameleonAction);
return chameleonAction;
}
if (o instanceof ChameleonAction) {
chameleonAction = (ChameleonAction)o;
}
else {
chameleonAction = new ChameleonAction(o, type);
idToAction.put(actionId, chameleonAction);
}
AnAction old = chameleonAction.addAction(action, type);
if (old != null) {
String oldPluginInfo = pluginToId.keySet().stream()
.filter(p -> pluginToId.get(p).contains(actionId))
.map(ActionManagerImpl::getPluginInfo).collect(Collectors.joining(","));
reportActionError(pluginId,
"ID \"" + actionId + "\" is already taken by action \"" + idToAction.get(actionId) + "\"" + oldPluginInfo +
". Action \"" + action + "\"" + getPluginInfo(pluginId) + " cannot use the same ID");
return null;
}
return chameleonAction;
}
@Override
public void registerAction(@NotNull String actionId, @NotNull AnAction action) {
registerAction(actionId, action, null);
}
@Override
public void unregisterAction(@NotNull String actionId) {
unregisterAction(actionId, true);
}
private void unregisterAction(@NotNull String actionId, boolean removeFromGroups) {
synchronized (myLock) {
if (!idToAction.containsKey(actionId)) {
if (LOG.isDebugEnabled()) {
LOG.debug("action with ID " + actionId + " wasn't registered");
}
return;
}
AnAction actionToRemove = idToAction.remove(actionId);
actionToId.remove(actionToRemove);
idToIndex.removeInt(actionId);
for (Map.Entry<PluginId, Collection<String>> entry : pluginToId.entrySet()) {
entry.getValue().remove(actionId);
}
if (removeFromGroups) {
CustomActionsSchema customActionSchema = ApplicationManager.getApplication().getServiceIfCreated(CustomActionsSchema.class);
for (String groupId : idToGroupId.get(actionId)) {
if (customActionSchema != null) {
customActionSchema.invalidateCustomizedActionGroup(groupId);
}
DefaultActionGroup group = (DefaultActionGroup)getActionOrStub(groupId);
if (group == null) {
LOG.error("Trying to remove action " + actionId + " from non-existing group " + groupId);
continue;
}
group.remove(actionToRemove, actionId);
if (!(group instanceof ActionGroupStub)) {
//group can be used as a stub in other actions
for (String parentOfGroup : idToGroupId.get(groupId)) {
DefaultActionGroup parentOfGroupAction = (DefaultActionGroup) getActionOrStub(parentOfGroup);
if (parentOfGroupAction == null) {
LOG.error("Trying to remove action " + actionId + " from non-existing group " + parentOfGroup);
continue;
}
for (AnAction stub : parentOfGroupAction.getChildActionsOrStubs()) {
if (stub instanceof ActionGroupStub && ((ActionGroupStub)stub).getId() == groupId) {
((ActionGroupStub)stub).remove(actionToRemove, actionId);
}
}
}
}
}
}
if (actionToRemove instanceof ActionGroup) {
for (Map.Entry<String, Collection<String>> entry : idToGroupId.entrySet()) {
entry.getValue().remove(actionId);
}
}
updateHandlers(actionToRemove);
}
}
@NotNull
@Override
public Comparator<String> getRegistrationOrderComparator() {
return Comparator.comparingInt(idToIndex::getInt);
}
@Override
public String @NotNull [] getPluginActions(@NotNull PluginId pluginName) {
return ArrayUtilRt.toStringArray(pluginToId.get(pluginName));
}
public void addActionPopup(@NotNull Object menu) {
myPopups.add(menu);
if (menu instanceof ActionPopupMenu) {
for (ActionPopupMenuListener listener : myActionPopupMenuListeners) {
listener.actionPopupMenuCreated((ActionPopupMenu)menu);
}
}
}
void removeActionPopup(@NotNull Object menu) {
final boolean removed = myPopups.remove(menu);
if (removed && menu instanceof ActionPopupMenu) {
for (ActionPopupMenuListener listener : myActionPopupMenuListeners) {
listener.actionPopupMenuReleased((ActionPopupMenu)menu);
}
}
}
@Override
public void queueActionPerformedEvent(@NotNull final AnAction action, @NotNull DataContext context, @NotNull AnActionEvent event) {
if (myPopups.isEmpty()) {
fireAfterActionPerformed(action, context, event);
}
}
public boolean isToolWindowContextMenuVisible() {
for (Object popup : myPopups) {
if (popup instanceof ActionPopupMenuImpl &&
((ActionPopupMenuImpl)popup).isToolWindowContextMenu()) {
return true;
}
}
return false;
}
@Override
public boolean isActionPopupStackEmpty() {
return myPopups.isEmpty();
}
@Override
public boolean isTransparentOnlyActionsUpdateNow() {
return myTransparentOnlyUpdate;
}
@Override
public void addActionPopupMenuListener(@NotNull ActionPopupMenuListener listener, @NotNull Disposable parentDisposable) {
myActionPopupMenuListeners.add(listener);
Disposer.register(parentDisposable, () -> myActionPopupMenuListeners.remove(listener));
}
@Override
public void replaceAction(@NotNull String actionId, @NotNull AnAction newAction) {
Class<?> callerClass = ReflectionUtil.getGrandCallerClass();
PluginId pluginId = callerClass != null ? PluginManagerCore.getPluginByClassName(callerClass.getName()) : null;
replaceAction(actionId, newAction, pluginId);
}
private AnAction replaceAction(@NotNull String actionId, @NotNull AnAction newAction, @Nullable PluginId pluginId) {
AnAction oldAction = newAction instanceof OverridingAction ? getAction(actionId) : getActionOrStub(actionId);
if (oldAction != null) {
if (newAction instanceof OverridingAction) {
myBaseActions.put((OverridingAction)newAction, oldAction);
}
boolean isGroup = oldAction instanceof ActionGroup;
if (isGroup != newAction instanceof ActionGroup) {
throw new IllegalStateException("cannot replace a group with an action and vice versa: " + actionId);
}
for (String groupId : idToGroupId.get(actionId)) {
DefaultActionGroup group = (DefaultActionGroup)getActionOrStub(groupId);
if (group == null) {
throw new IllegalStateException("Trying to replace action which has been added to a non-existing group " + groupId);
}
group.replaceAction(oldAction, newAction);
}
unregisterAction(actionId, false);
}
registerAction(actionId, newAction, pluginId);
return oldAction;
}
/**
* Returns the action overridden by the specified overriding action (with overrides="true" in plugin.xml).
*/
public AnAction getBaseAction(OverridingAction overridingAction) {
return myBaseActions.get(overridingAction);
}
public Collection<String> getParentGroupIds(String actionId) {
return idToGroupId.get(actionId);
}
@Override
public void addAnActionListener(AnActionListener listener) {
myActionListeners.add(listener);
}
@Override
public void removeAnActionListener(AnActionListener listener) {
myActionListeners.remove(listener);
}
@Override
public void fireBeforeActionPerformed(@NotNull AnAction action, @NotNull DataContext dataContext, @NotNull AnActionEvent event) {
myPrevPerformedActionId = myLastPreformedActionId;
myLastPreformedActionId = getId(action);
if (myLastPreformedActionId == null && action instanceof ActionIdProvider) {
myLastPreformedActionId = ((ActionIdProvider)action).getId();
}
//noinspection AssignmentToStaticFieldFromInstanceMethod
IdeaLogger.ourLastActionId = myLastPreformedActionId;
final List<EventPair<?>> customData = new ArrayList<>();
Project project = CommonDataKeys.PROJECT.getData(dataContext);
Language hostFileLanguage = getHostFileLanguage(dataContext, project);
customData.add(EventFields.CurrentFile.with(hostFileLanguage));
if (hostFileLanguage == null || hostFileLanguage == PlainTextLanguage.INSTANCE) {
final PsiFile file = CommonDataKeys.PSI_FILE.getData(dataContext);
final Language language = file != null ? file.getLanguage() : null;
customData.add(EventFields.Language.with(language));
}
if (action instanceof FusAwareAction) {
List<EventPair<?>> additionalUsageData = ((FusAwareAction)action).getAdditionalUsageData(event);
customData.add(ActionsEventLogGroup.ADDITIONAL.with(new ObjectEventData(additionalUsageData)));
}
ActionsCollectorImpl.recordActionInvoked(project, action, event, customData);
for (AnActionListener listener : myActionListeners) {
listener.beforeActionPerformed(action, dataContext, event);
}
publisher().beforeActionPerformed(action, dataContext, event);
}
private static @Nullable Language getHostFileLanguage(@NotNull DataContext dataContext, @Nullable Project project) {
if (project == null) return null;
Editor editor = CommonDataKeys.HOST_EDITOR.getData(dataContext);
if (editor == null) return null;
PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
return file != null ? file.getLanguage() : null;
}
@Override
public void fireAfterActionPerformed(@NotNull AnAction action, @NotNull DataContext dataContext, @NotNull AnActionEvent event) {
myPrevPerformedActionId = myLastPreformedActionId;
myLastPreformedActionId = getId(action);
//noinspection AssignmentToStaticFieldFromInstanceMethod
IdeaLogger.ourLastActionId = myLastPreformedActionId;
for (AnActionListener listener : myActionListeners) {
try {
listener.afterActionPerformed(action, dataContext, event);
}
catch (AbstractMethodError ignored) {
}
}
publisher().afterActionPerformed(action, dataContext, event);
}
@Override
public KeyboardShortcut getKeyboardShortcut(@NotNull String actionId) {
AnAction action = ActionManager.getInstance().getAction(actionId);
final ShortcutSet shortcutSet = action.getShortcutSet();
final Shortcut[] shortcuts = shortcutSet.getShortcuts();
for (final Shortcut shortcut : shortcuts) {
// Shortcut can be MouseShortcut here.
// For example IdeaVIM often assigns them
if (shortcut instanceof KeyboardShortcut) {
final KeyboardShortcut kb = (KeyboardShortcut)shortcut;
if (kb.getSecondKeyStroke() == null) {
return (KeyboardShortcut)shortcut;
}
}
}
return null;
}
@Override
public void fireBeforeEditorTyping(char c, @NotNull DataContext dataContext) {
myLastTimeEditorWasTypedIn = System.currentTimeMillis();
for (AnActionListener listener : myActionListeners) {
listener.beforeEditorTyping(c, dataContext);
}
publisher().beforeEditorTyping(c, dataContext);
}
@Override
public void fireAfterEditorTyping(char c, @NotNull DataContext dataContext) {
for (AnActionListener listener : myActionListeners) {
listener.afterEditorTyping(c, dataContext);
}
publisher().afterEditorTyping(c, dataContext);
}
@Override
public String getLastPreformedActionId() {
return myLastPreformedActionId;
}
@Override
public String getPrevPreformedActionId() {
return myPrevPerformedActionId;
}
public @NotNull Set<String> getActionIds() {
synchronized (myLock) {
return new HashSet<>(idToAction.keySet());
}
}
public void preloadActions(@NotNull ProgressIndicator indicator) {
List<String> ids;
synchronized (myLock) {
ids = new ArrayList<>(idToAction.keySet());
}
for (String id : ids) {
indicator.checkCanceled();
getActionImpl(id, false);
// don't preload ActionGroup.getChildren() because that would un-stub child actions
// and make it impossible to replace the corresponding actions later
// (via unregisterAction+registerAction, as some app components do)
}
}
@NotNull
@Override
public ActionCallback tryToExecute(@NotNull AnAction action,
@NotNull InputEvent inputEvent,
@Nullable Component contextComponent,
@Nullable String place,
boolean now) {
assert ApplicationManager.getApplication().isDispatchThread();
ActionCallback result = new ActionCallback();
Runnable doRunnable = () -> tryToExecuteNow(action, inputEvent, contextComponent, place, result);
if (now) {
doRunnable.run();
}
else {
//noinspection SSBasedInspection
SwingUtilities.invokeLater(doRunnable);
}
return result;
}
private void tryToExecuteNow(@NotNull AnAction action, @NotNull InputEvent inputEvent, @Nullable Component contextComponent, String place, ActionCallback result) {
Presentation presentation = action.getTemplatePresentation().clone();
IdeFocusManager.findInstanceByContext(getContextBy(contextComponent)).doWhenFocusSettlesDown(() -> {
((TransactionGuardImpl)TransactionGuard.getInstance()).performUserActivity(() -> {
DataContext context = getContextBy(contextComponent);
AnActionEvent event = new AnActionEvent(
inputEvent, context,
place != null ? place : ActionPlaces.UNKNOWN,
presentation, this,
inputEvent.getModifiersEx()
);
ActionUtil.performDumbAwareUpdate(LaterInvocator.isInModalContext(), action, event, false);
if (!event.getPresentation().isEnabled()) {
result.setRejected();
return;
}
ActionUtil.lastUpdateAndCheckDumb(action, event, false);
if (!event.getPresentation().isEnabled()) {
result.setRejected();
return;
}
Component component = PlatformDataKeys.CONTEXT_COMPONENT.getData(context);
if (component != null && !component.isShowing() && !ActionPlaces.TOUCHBAR_GENERAL.equals(place)) {
result.setRejected();
return;
}
fireBeforeActionPerformed(action, context, event);
UIUtil.addAwtListener(event1 -> {
if (event1.getID() == WindowEvent.WINDOW_OPENED || event1.getID() == WindowEvent.WINDOW_ACTIVATED) {
if (!result.isProcessed()) {
final WindowEvent we = (WindowEvent)event1;
IdeFocusManager.findInstanceByComponent(we.getWindow()).doWhenFocusSettlesDown(result.createSetDoneRunnable(),
ModalityState.defaultModalityState());
}
}
}, AWTEvent.WINDOW_EVENT_MASK, result);
ActionUtil.performActionDumbAware(action, event);
result.setDone();
queueActionPerformedEvent(action, context, event);
});
}, ModalityState.defaultModalityState());
}
@Override
public @NotNull List<EditorActionHandlerBean> getRegisteredHandlers(@NotNull EditorAction editorAction) {
List<EditorActionHandlerBean> result = new ArrayList<>();
String id = getId(editorAction);
if (id != null) {
List<EditorActionHandlerBean> extensions = EDITOR_ACTION_HANDLER_EP.getExtensionList();
for (int i = extensions.size() - 1; i >= 0; i
EditorActionHandlerBean handlerBean = extensions.get(i);
if (handlerBean.action.equals(id)) {
result.add(handlerBean);
}
}
}
return result;
}
private void updateAllHandlers() {
synchronized (myLock) {
actionToId.keySet().forEach(ActionManagerImpl::updateHandlers);
}
}
private static void updateHandlers(Object action) {
if (action instanceof EditorAction) {
((EditorAction)action).clearDynamicHandlersCache();
}
}
private final class MyTimer extends Timer implements ActionListener {
private final List<TimerListener> myTimerListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private final List<TimerListener> myTransparentTimerListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private int myLastTimePerformed;
private MyTimer() {
super(TIMER_DELAY, null);
addActionListener(this);
setRepeats(true);
final MessageBusConnection connection = ApplicationManager.getApplication().getMessageBus().connect();
connection.subscribe(ApplicationActivationListener.TOPIC, new ApplicationActivationListener() {
@Override
public void applicationActivated(@NotNull IdeFrame ideFrame) {
setDelay(TIMER_DELAY);
restart();
}
@Override
public void applicationDeactivated(@NotNull IdeFrame ideFrame) {
setDelay(DEACTIVATED_TIMER_DELAY);
}
});
}
@Override
public String toString() {
return "Action manager timer";
}
void addTimerListener(@NotNull TimerListener listener, boolean transparent) {
(transparent ? myTransparentTimerListeners : myTimerListeners).add(listener);
}
void removeTimerListener(@NotNull TimerListener listener, boolean transparent) {
(transparent ? myTransparentTimerListeners : myTimerListeners).remove(listener);
}
@Override
public void actionPerformed(ActionEvent e) {
if (myLastTimeEditorWasTypedIn + UPDATE_DELAY_AFTER_TYPING > System.currentTimeMillis()) {
return;
}
final int lastEventCount = myLastTimePerformed;
myLastTimePerformed = ActivityTracker.getInstance().getCount();
if (myLastTimePerformed == lastEventCount && !Registry.is("actionSystem.always.update.toolbar.actions")) {
return;
}
boolean transparentOnly = myLastTimePerformed == lastEventCount;
try {
myTransparentOnlyUpdate = transparentOnly;
Set<TimerListener> notified = new HashSet<>();
notifyListeners(myTransparentTimerListeners, notified);
if (transparentOnly) {
return;
}
notifyListeners(myTimerListeners, notified);
}
finally {
myTransparentOnlyUpdate = false;
}
}
private void notifyListeners(final List<? extends TimerListener> timerListeners, final Set<? super TimerListener> notified) {
for (TimerListener listener : timerListeners) {
if (notified.add(listener)) {
runListenerAction(listener);
}
}
}
private void runListenerAction(@NotNull TimerListener listener) {
ModalityState modalityState = listener.getModalityState();
if (modalityState == null) return;
LOG.debug("notify ", listener);
if (!ModalityState.current().dominates(modalityState)) {
try {
listener.run();
}
catch (ProcessCanceledException ex) {
// ignore
}
catch (Throwable e) {
LOG.error(e);
}
}
}
}
}
|
package com.intellij.openapi.actionSystem.impl;
import com.intellij.icons.AllIcons;
import com.intellij.ide.DataManager;
import com.intellij.ide.HelpTooltip;
import com.intellij.ide.impl.DataManagerImpl;
import com.intellij.internal.statistic.customUsageCollectors.ui.ToolbarClicksCollector;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionButtonLook;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.actionSystem.ex.AnActionListener;
import com.intellij.openapi.actionSystem.ex.CustomComponentAction;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.impl.LaterInvocator;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.keymap.ex.KeymapManagerEx;
import com.intellij.openapi.ui.popup.*;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.Gray;
import com.intellij.ui.JBColor;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.awt.RelativeRectangle;
import com.intellij.ui.switcher.QuickActionProvider;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.*;
import com.intellij.util.ui.update.Activatable;
import com.intellij.util.ui.update.UiNotifyConnector;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class ActionToolbarImpl extends JPanel implements ActionToolbar, QuickActionProvider {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.actionSystem.impl.ActionToolbarImpl");
private static final List<ActionToolbarImpl> ourToolbars = new LinkedList<>();
private static final String RIGHT_ALIGN_KEY = "RIGHT_ALIGN";
static {
JBUI.addPropertyChangeListener(JBUI.USER_SCALE_FACTOR_PROPERTY, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent e) {
((JBDimension)ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE).update();
((JBDimension)ActionToolbar.NAVBAR_MINIMUM_BUTTON_SIZE).update();
}
});
}
public static void updateAllToolbarsImmediately() {
for (ActionToolbarImpl toolbar : new ArrayList<>(ourToolbars)) {
toolbar.updateActionsImmediately();
for (Component c : toolbar.getComponents()) {
if (c instanceof ActionButton) {
((ActionButton)c).updateToolTipText();
((ActionButton)c).updateIcon();
}
}
}
}
/**
* This array contains Rectangles which define bounds of the corresponding
* components in the toolbar. This list can be consider as a cache of the
* Rectangle objects that are used in calculation of preferred sizes and
* components layout.
*/
private final List<Rectangle> myComponentBounds = new ArrayList<>();
private JBDimension myMinimumButtonSize = JBUI.emptySize();
/**
* @see ActionToolbar#getLayoutPolicy()
*/
private int myLayoutPolicy;
private int myOrientation;
private final ActionGroup myActionGroup;
private final String myPlace;
protected List<AnAction> myVisibleActions;
private final PresentationFactory myPresentationFactory = new PresentationFactory();
private final boolean myDecorateButtons;
private final ToolbarUpdater myUpdater;
/**
* @see ActionToolbar#adjustTheSameSize(boolean)
*/
private boolean myAdjustTheSameSize;
private final ActionButtonLook myButtonLook = null;
private final ActionButtonLook myMinimalButtonLook = ActionButtonLook.INPLACE_LOOK;
private final DataManager myDataManager;
protected final ActionManagerEx myActionManager;
private Rectangle myAutoPopupRec;
private final DefaultActionGroup mySecondaryActions = new DefaultActionGroup();
private PopupStateModifier mySecondaryButtonPopupStateModifier = null;
private boolean myForceMinimumSize = false;
private boolean myMinimalMode;
private boolean myForceUseMacEnhancements;
public ActionButton getSecondaryActionsButton() {
return mySecondaryActionsButton;
}
private ActionButton mySecondaryActionsButton;
private int myFirstOutsideIndex = -1;
private JBPopup myPopup;
private JComponent myTargetComponent;
private boolean myReservePlaceAutoPopupIcon = true;
private boolean myAddSeparatorFirst;
public ActionToolbarImpl(String place,
@NotNull final ActionGroup actionGroup,
boolean horizontal,
@NotNull DataManager dataManager,
@NotNull ActionManagerEx actionManager,
@NotNull KeymapManagerEx keymapManager) {
this(place, actionGroup, horizontal, false, dataManager, actionManager, keymapManager, false);
}
public ActionToolbarImpl(String place,
@NotNull ActionGroup actionGroup,
boolean horizontal,
boolean decorateButtons,
@NotNull DataManager dataManager,
@NotNull ActionManagerEx actionManager,
@NotNull KeymapManagerEx keymapManager) {
this(place, actionGroup, horizontal, decorateButtons, dataManager, actionManager, keymapManager, false);
}
public ActionToolbarImpl(String place,
@NotNull ActionGroup actionGroup,
final boolean horizontal,
final boolean decorateButtons,
@NotNull DataManager dataManager,
@NotNull ActionManagerEx actionManager,
@NotNull KeymapManagerEx keymapManager,
boolean updateActionsNow) {
super(null);
myActionManager = actionManager;
myPlace = place;
myActionGroup = actionGroup;
myVisibleActions = new ArrayList<>();
myDataManager = dataManager;
myDecorateButtons = decorateButtons;
myUpdater = new ToolbarUpdater(actionManager, keymapManager, this) {
@Override
protected void updateActionsImpl(boolean transparentOnly, boolean forced) {
ActionToolbarImpl.this.updateActionsImpl(transparentOnly, forced);
}
};
setLayout(new BorderLayout());
setOrientation(horizontal ? SwingConstants.HORIZONTAL : SwingConstants.VERTICAL);
mySecondaryActions.getTemplatePresentation().setIcon(AllIcons.General.SecondaryGroup);
mySecondaryActions.setPopup(true);
myUpdater.updateActions(updateActionsNow, false);
// If the panel doesn't handle mouse event then it will be passed to its parent.
// It means that if the panel is in sliding mode then the focus goes to the editor
// and panel will be automatically hidden.
enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK | AWTEvent.COMPONENT_EVENT_MASK | AWTEvent.CONTAINER_EVENT_MASK);
setMiniMode(false);
}
@Override
public void updateUI() {
super.updateUI();
for (Component component : getComponents()) {
tweakActionComponentUI(component);
}
}
public String getPlace() {
return myPlace;
}
@Override
public void addNotify() {
super.addNotify();
ourToolbars.add(this);
// should update action right on the showing, otherwise toolbar may not be displayed at all,
// since by default all updates are postponed until frame gets focused.
updateActionsImmediately();
}
private boolean doMacEnhancementsForMainToolbar() {
return UIUtil.isUnderAquaLookAndFeel() && (ActionPlaces.MAIN_TOOLBAR.equals(myPlace) || myForceUseMacEnhancements);
}
public void setForceUseMacEnhancements(boolean useMacEnhancements) {
myForceUseMacEnhancements = useMacEnhancements;
}
private boolean isInsideNavBar() {
return ActionPlaces.NAVIGATION_BAR_TOOLBAR.equals(myPlace);
}
@Override
public void removeNotify() {
super.removeNotify();
ourToolbars.remove(this);
}
@NotNull
@Override
public JComponent getComponent() {
return this;
}
@Override
public int getLayoutPolicy() {
return myLayoutPolicy;
}
@Override
public void setLayoutPolicy(final int layoutPolicy) {
if (layoutPolicy != NOWRAP_LAYOUT_POLICY && layoutPolicy != WRAP_LAYOUT_POLICY && layoutPolicy != AUTO_LAYOUT_POLICY) {
throw new IllegalArgumentException("wrong layoutPolicy: " + layoutPolicy);
}
myLayoutPolicy = layoutPolicy;
}
@Override
protected Graphics getComponentGraphics(Graphics graphics) {
return JBSwingUtilities.runGlobalCGTransform(this, super.getComponentGraphics(graphics));
}
@Override
protected void paintComponent(final Graphics g) {
if (doMacEnhancementsForMainToolbar()) {
final Rectangle r = getBounds();
UIUtil.drawGradientHToolbarBackground(g, r.width, r.height);
} else {
super.paintComponent(g);
}
if (myLayoutPolicy == AUTO_LAYOUT_POLICY) {
if (myAutoPopupRec != null) {
if (myOrientation == SwingConstants.HORIZONTAL) {
final int dy = myAutoPopupRec.height / 2 - AllIcons.Ide.Link.getIconHeight() / 2;
AllIcons.Ide.Link.paintIcon(this, g, (int)myAutoPopupRec.getMaxX() - AllIcons.Ide.Link.getIconWidth() - 1, myAutoPopupRec.y + dy);
}
else {
final int dx = myAutoPopupRec.width / 2 - AllIcons.Ide.Link.getIconWidth() / 2;
AllIcons.Ide.Link.paintIcon(this, g, myAutoPopupRec.x + dx, (int)myAutoPopupRec.getMaxY() - AllIcons.Ide.Link.getIconWidth() - 1);
}
}
}
}
public void setSecondaryButtonPopupStateModifier(PopupStateModifier popupStateModifier) {
mySecondaryButtonPopupStateModifier = popupStateModifier;
}
private void fillToolBar(final List<AnAction> actions, boolean layoutSecondaries) {
final List<AnAction> rightAligned = new ArrayList<>();
if (myAddSeparatorFirst) {
add(new MySeparator());
}
for (int i = 0; i < actions.size(); i++) {
final AnAction action = actions.get(i);
if (action instanceof RightAlignedToolbarAction) {
rightAligned.add(action);
continue;
}
// if (action instanceof Separator && isNavBar()) {
// continue;
//if (action instanceof ComboBoxAction) {
// ((ComboBoxAction)action).setSmallVariant(true);
if (layoutSecondaries) {
if (!myActionGroup.isPrimary(action)) {
mySecondaryActions.add(action);
continue;
}
}
if (action instanceof Separator) {
if (i > 0 && i < actions.size() - 1) {
add(new MySeparator());
}
}
else if (action instanceof CustomComponentAction) {
add(getCustomComponent(action));
}
else {
add(createToolbarButton(action));
}
}
if (mySecondaryActions.getChildrenCount() > 0) {
mySecondaryActionsButton = new ActionButton(mySecondaryActions, myPresentationFactory.getPresentation(mySecondaryActions), myPlace, getMinimumButtonSize()) {
@Override
@ButtonState
public int getPopState() {
return mySecondaryButtonPopupStateModifier != null && mySecondaryButtonPopupStateModifier.willModify()
? mySecondaryButtonPopupStateModifier.getModifiedPopupState()
: super.getPopState();
}
};
mySecondaryActionsButton.setNoIconsInPopup(true);
add(mySecondaryActionsButton);
}
for (AnAction action : rightAligned) {
JComponent button = action instanceof CustomComponentAction ? getCustomComponent(action) : createToolbarButton(action);
if (!isInsideNavBar()) {
button.putClientProperty(RIGHT_ALIGN_KEY, Boolean.TRUE);
}
add(button);
}
//if ((ActionPlaces.MAIN_TOOLBAR.equals(myPlace) || ActionPlaces.NAVIGATION_BAR_TOOLBAR.equals(myPlace))) {
// final AnAction searchEverywhereAction = ActionManager.getInstance().getAction("SearchEverywhere");
// if (searchEverywhereAction != null) {
// try {
// final CustomComponentAction searchEveryWhereAction = (CustomComponentAction)searchEverywhereAction;
// final JComponent searchEverywhere = searchEveryWhereAction.createCustomComponent(searchEverywhereAction.getTemplatePresentation());
// searchEverywhere.putClientProperty("SEARCH_EVERYWHERE", Boolean.TRUE);
// add(searchEverywhere);
// catch (Exception ignore) {}
}
private JComponent getCustomComponent(AnAction action) {
Presentation presentation = myPresentationFactory.getPresentation(action);
JComponent customComponent = ObjectUtils.tryCast(presentation.getClientProperty(CustomComponentAction.CUSTOM_COMPONENT_PROPERTY), JComponent.class);
if (customComponent == null) {
customComponent = ((CustomComponentAction)action).createCustomComponent(presentation);
presentation.putClientProperty(CustomComponentAction.CUSTOM_COMPONENT_PROPERTY, customComponent);
}
if (customComponent instanceof JCheckBox) {
customComponent.setBorder(JBUI.Borders.emptyLeft(9));
}
tweakActionComponentUI(customComponent);
AbstractButton clickable = UIUtil.findComponentOfType(customComponent, AbstractButton.class);
if (clickable != null) {
clickable.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
ToolbarClicksCollector.record(action, myPlace);
}
});
}
return customComponent;
}
private void tweakActionComponentUI(@NotNull Component actionComponent) {
if (ActionPlaces.EDITOR_TOOLBAR.equals(myPlace)) {
// tweak font & color for editor toolbar to match editor tabs style
actionComponent.setFont(UIUtil.getLabelFont(UIUtil.FontSize.SMALL));
actionComponent.setForeground(ColorUtil.dimmer(JBColor.BLACK));
}
}
private Dimension getMinimumButtonSize() {
return isInsideNavBar() ? NAVBAR_MINIMUM_BUTTON_SIZE : DEFAULT_MINIMUM_BUTTON_SIZE;
}
public ActionButton createToolbarButton(final AnAction action, final ActionButtonLook look, final String place, final Presentation presentation, final Dimension minimumSize) {
if (action.displayTextInToolbar()) {
int mnemonic = KeyEvent.getExtendedKeyCodeForChar(action.getTemplatePresentation().getMnemonic());
ActionButtonWithText buttonWithText = new ActionButtonWithText(action, presentation, place, minimumSize) {
@Override protected HelpTooltip.Alignment getTooltipLocation() {
return tooltipLocation();
}
};
if (mnemonic != KeyEvent.VK_UNDEFINED) {
buttonWithText.registerKeyboardAction(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
buttonWithText.click();
}
}, KeyStroke.getKeyStroke(mnemonic,
/*SystemInfo.isMac
? InputEvent.CTRL_DOWN_MASK |
InputEvent.ALT_DOWN_MASK
:*/ InputEvent.ALT_DOWN_MASK), WHEN_IN_FOCUSED_WINDOW);
}
tweakActionComponentUI(buttonWithText);
return buttonWithText;
}
ActionButton actionButton = new ActionButton(action, presentation, place, minimumSize) {
@Override
protected DataContext getDataContext() {
return getToolbarDataContext();
}
@Override
protected HelpTooltip.Alignment getTooltipLocation() {
return tooltipLocation();
}
};
actionButton.setLook(look);
return actionButton;
}
private HelpTooltip.Alignment tooltipLocation() {
return myOrientation == SwingConstants.VERTICAL ? HelpTooltip.Alignment.RIGHT: HelpTooltip.Alignment.BOTTOM;
}
private ActionButton createToolbarButton(final AnAction action) {
return createToolbarButton(
action,
myMinimalMode ? myMinimalButtonLook : myDecorateButtons ? new ActionButtonLook() {
@Override
public void paintBorder(Graphics g, JComponent c, int state) {
g.setColor(JBColor.border());
g.drawLine(c.getWidth()-1, 0, c.getWidth()-1, c.getHeight());
}
@Override
public void paintBackground(Graphics g, JComponent component, int state) {
if (state == ActionButtonComponent.PUSHED) {
g.setColor(component.getBackground().darker());
((Graphics2D)g).fill(g.getClip());
}
}
} : myButtonLook,
myPlace, myPresentationFactory.getPresentation(action),
myMinimumButtonSize.size());
}
@Override
public void doLayout() {
if (!isValid()) {
calculateBounds(getSize(), myComponentBounds);
}
final int componentCount = getComponentCount();
LOG.assertTrue(componentCount <= myComponentBounds.size());
for (int i = componentCount - 1; i >= 0; i
final Component component = getComponent(i);
component.setBounds(myComponentBounds.get(i));
}
}
@Override
public void validate() {
if (!isValid()) {
calculateBounds(getSize(), myComponentBounds);
super.validate();
}
}
private Dimension getChildPreferredSize(int index) {
Component component = getComponent(index);
return component.isVisible() ? component.getPreferredSize() : new Dimension();
}
/**
* @return maximum button width
*/
private int getMaxButtonWidth() {
int width = 0;
for (int i = 0; i < getComponentCount(); i++) {
final Dimension dimension = getChildPreferredSize(i);
width = Math.max(width, dimension.width);
}
return width;
}
/**
* @return maximum button height
*/
@Override
public int getMaxButtonHeight() {
int height = 0;
for (int i = 0; i < getComponentCount(); i++) {
final Dimension dimension = getChildPreferredSize(i);
height = Math.max(height, dimension.height);
}
return height;
}
private void calculateBoundsNowrapImpl(List<Rectangle> bounds) {
final int componentCount = getComponentCount();
LOG.assertTrue(componentCount <= bounds.size());
final int width = getWidth();
final int height = getHeight();
final Insets insets = getInsets();
if (myAdjustTheSameSize) {
final int maxWidth = getMaxButtonWidth();
final int maxHeight = getMaxButtonHeight();
if (myOrientation == SwingConstants.HORIZONTAL) {
int offset = 0;
for (int i = 0; i < componentCount; i++) {
final Rectangle r = bounds.get(i);
r.setBounds(insets.left + offset, insets.top + (height - maxHeight) / 2, maxWidth, maxHeight);
offset += maxWidth;
}
}
else {
int offset = 0;
for (int i = 0; i < componentCount; i++) {
final Rectangle r = bounds.get(i);
r.setBounds(insets.left + (width - maxWidth) / 2, insets.top + offset, maxWidth, maxHeight);
offset += maxHeight;
}
}
}
else {
if (myOrientation == SwingConstants.HORIZONTAL) {
final int maxHeight = getMaxButtonHeight();
int offset = 0;
for (int i = 0; i < componentCount; i++) {
final Dimension d = getChildPreferredSize(i);
final Rectangle r = bounds.get(i);
r.setBounds(insets.left + offset, insets.top + (maxHeight - d.height) / 2, d.width, d.height);
offset += d.width;
}
}
else {
final int maxWidth = getMaxButtonWidth();
int offset = 0;
for (int i = 0; i < componentCount; i++) {
final Dimension d = getChildPreferredSize(i);
final Rectangle r = bounds.get(i);
r.setBounds(insets.left + (maxWidth - d.width) / 2, insets.top + offset, d.width, d.height);
offset += d.height;
}
}
}
}
private void calculateBoundsAutoImp(Dimension sizeToFit, List<Rectangle> bounds) {
final int componentCount = getComponentCount();
LOG.assertTrue(componentCount <= bounds.size());
final boolean actualLayout = bounds == myComponentBounds;
if (actualLayout) {
myAutoPopupRec = null;
}
int autoButtonSize = AllIcons.Ide.Link.getIconWidth();
boolean full = false;
final Insets insets = getInsets();
int widthToFit = sizeToFit.width - insets.left - insets.right;
int heightToFit = sizeToFit.height - insets.top - insets.bottom;
if (myOrientation == SwingConstants.HORIZONTAL) {
int eachX = 0;
int maxHeight = heightToFit;
for (int i = 0; i < componentCount; i++) {
final Component eachComp = getComponent(i);
final boolean isLast = i == componentCount - 1;
final Rectangle eachBound = new Rectangle(getChildPreferredSize(i));
maxHeight = Math.max(eachBound.height, maxHeight);
if (!full) {
boolean inside;
if (isLast) {
inside = eachX + eachBound.width <= widthToFit;
} else {
inside = eachX + eachBound.width + autoButtonSize <= widthToFit;
}
if (inside) {
if (eachComp == mySecondaryActionsButton) {
assert isLast;
if (sizeToFit.width != Integer.MAX_VALUE) {
eachBound.x = sizeToFit.width - insets.right - eachBound.width;
eachX = (int)eachBound.getMaxX() - insets.left;
}
else {
eachBound.x = insets.left + eachX;
}
} else {
eachBound.x = insets.left + eachX;
eachX += eachBound.width;
}
eachBound.y = insets.top;
}
else {
full = true;
}
}
if (full) {
if (myAutoPopupRec == null) {
myAutoPopupRec = new Rectangle(insets.left + eachX, insets.top, widthToFit - eachX, heightToFit);
myFirstOutsideIndex = i;
}
eachBound.x = Integer.MAX_VALUE;
eachBound.y = Integer.MAX_VALUE;
}
bounds.get(i).setBounds(eachBound);
}
for (final Rectangle r : bounds) {
if (r.height < maxHeight) {
r.y += (maxHeight - r.height) / 2;
}
}
}
else {
int eachY = 0;
for (int i = 0; i < componentCount; i++) {
final Rectangle eachBound = new Rectangle(getChildPreferredSize(i));
if (!full) {
boolean outside;
if (i < componentCount - 1) {
outside = eachY + eachBound.height + autoButtonSize < heightToFit;
}
else {
outside = eachY + eachBound.height < heightToFit;
}
if (outside) {
eachBound.x = insets.left;
eachBound.y = insets.top + eachY;
eachY += eachBound.height;
}
else {
full = true;
}
}
if (full) {
if (myAutoPopupRec == null) {
myAutoPopupRec = new Rectangle(insets.left, insets.top + eachY, widthToFit, heightToFit - eachY);
myFirstOutsideIndex = i;
}
eachBound.x = Integer.MAX_VALUE;
eachBound.y = Integer.MAX_VALUE;
}
bounds.get(i).setBounds(eachBound);
}
}
}
private void calculateBoundsWrapImpl(Dimension sizeToFit, List<Rectangle> bounds) {
// We have to graceful handle case when toolbar was not laid out yet.
// In this case we calculate bounds as it is a NOWRAP toolbar.
if (getWidth() == 0 || getHeight() == 0) {
try {
setLayoutPolicy(NOWRAP_LAYOUT_POLICY);
calculateBoundsNowrapImpl(bounds);
}
finally {
setLayoutPolicy(WRAP_LAYOUT_POLICY);
}
return;
}
final int componentCount = getComponentCount();
LOG.assertTrue(componentCount <= bounds.size());
final Insets insets = getInsets();
int widthToFit = sizeToFit.width - insets.left - insets.right;
int heightToFit = sizeToFit.height - insets.top - insets.bottom;
if (myAdjustTheSameSize) {
if (myOrientation == SwingConstants.HORIZONTAL) {
final int maxWidth = getMaxButtonWidth();
final int maxHeight = getMaxButtonHeight();
// Lay components out
int xOffset = 0;
int yOffset = 0;
// Calculate max size of a row. It's not possible to make more than 3 row toolbar
final int maxRowWidth = Math.max(widthToFit, componentCount * maxWidth / 3);
for (int i = 0; i < componentCount; i++) {
if (xOffset + maxWidth > maxRowWidth) { // place component at new row
xOffset = 0;
yOffset += maxHeight;
}
final Rectangle each = bounds.get(i);
each.setBounds(insets.left + xOffset, insets.top + yOffset, maxWidth, maxHeight);
xOffset += maxWidth;
}
}
else {
final int maxWidth = getMaxButtonWidth();
final int maxHeight = getMaxButtonHeight();
// Lay components out
int xOffset = 0;
int yOffset = 0;
// Calculate max size of a row. It's not possible to make more then 3 column toolbar
final int maxRowHeight = Math.max(heightToFit, componentCount * myMinimumButtonSize.height() / 3);
for (int i = 0; i < componentCount; i++) {
if (yOffset + maxHeight > maxRowHeight) { // place component at new row
yOffset = 0;
xOffset += maxWidth;
}
final Rectangle each = bounds.get(i);
each.setBounds(insets.left + xOffset, insets.top + yOffset, maxWidth, maxHeight);
yOffset += maxHeight;
}
}
}
else {
if (myOrientation == SwingConstants.HORIZONTAL) {
// Calculate row height
int rowHeight = 0;
final Dimension[] dims = new Dimension[componentCount]; // we will use this dimensions later
for (int i = 0; i < componentCount; i++) {
dims[i] = getChildPreferredSize(i);
final int height = dims[i].height;
rowHeight = Math.max(rowHeight, height);
}
// Lay components out
int xOffset = 0;
int yOffset = 0;
// Calculate max size of a row. It's not possible to make more then 3 row toolbar
final int maxRowWidth = Math.max(widthToFit, componentCount * myMinimumButtonSize.width() / 3);
for (int i = 0; i < componentCount; i++) {
final Dimension d = dims[i];
if (xOffset + d.width > maxRowWidth) { // place component at new row
xOffset = 0;
yOffset += rowHeight;
}
final Rectangle each = bounds.get(i);
each.setBounds(insets.left + xOffset, insets.top + yOffset + (rowHeight - d.height) / 2, d.width, d.height);
xOffset += d.width;
}
}
else {
// Calculate row width
int rowWidth = 0;
final Dimension[] dims = new Dimension[componentCount]; // we will use this dimensions later
for (int i = 0; i < componentCount; i++) {
dims[i] = getChildPreferredSize(i);
final int width = dims[i].width;
rowWidth = Math.max(rowWidth, width);
}
// Lay components out
int xOffset = 0;
int yOffset = 0;
// Calculate max size of a row. It's not possible to make more then 3 column toolbar
final int maxRowHeight = Math.max(heightToFit, componentCount * myMinimumButtonSize.height() / 3);
for (int i = 0; i < componentCount; i++) {
final Dimension d = dims[i];
if (yOffset + d.height > maxRowHeight) { // place component at new row
yOffset = 0;
xOffset += rowWidth;
}
final Rectangle each = bounds.get(i);
each.setBounds(insets.left + xOffset + (rowWidth - d.width) / 2, insets.top + yOffset, d.width, d.height);
yOffset += d.height;
}
}
}
}
/**
* Calculates bounds of all the components in the toolbar
*/
private void calculateBounds(Dimension size2Fit, List<Rectangle> bounds) {
bounds.clear();
for (int i = 0; i < getComponentCount(); i++) {
bounds.add(new Rectangle());
}
if (myLayoutPolicy == NOWRAP_LAYOUT_POLICY) {
calculateBoundsNowrapImpl(bounds);
}
else if (myLayoutPolicy == WRAP_LAYOUT_POLICY) {
calculateBoundsWrapImpl(size2Fit, bounds);
}
else if (myLayoutPolicy == AUTO_LAYOUT_POLICY) {
calculateBoundsAutoImp(size2Fit, bounds);
}
else {
throw new IllegalStateException("unknown layoutPolicy: " + myLayoutPolicy);
}
if (getComponentCount() > 0 && size2Fit.width < Integer.MAX_VALUE) {
int maxHeight = 0;
for (int i = 0; i < bounds.size() - 2; i++) {
maxHeight = Math.max(maxHeight, bounds.get(i).height);
}
int rightOffset = 0;
Insets insets = getInsets();
for (int i = getComponentCount() - 1, j = 1; i > 0; i
final Component component = getComponent(i);
if (component instanceof JComponent && ((JComponent)component).getClientProperty(RIGHT_ALIGN_KEY) == Boolean.TRUE) {
rightOffset += bounds.get(i).width;
Rectangle r = bounds.get(bounds.size() - j);
r.x = size2Fit.width - rightOffset;
r.y = insets.top + (getHeight() - insets.top - insets.bottom - bounds.get(i).height) / 2;
}
}
}
}
@Override
public Dimension getPreferredSize() {
final ArrayList<Rectangle> bounds = new ArrayList<>();
calculateBounds(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE), bounds);
if (bounds.isEmpty()) return JBUI.emptySize();
int xLeft = Integer.MAX_VALUE;
int yTop = Integer.MAX_VALUE;
int xRight = Integer.MIN_VALUE;
int yBottom = Integer.MIN_VALUE;
for (int i = bounds.size() - 1; i >= 0; i
final Rectangle each = bounds.get(i);
if (each.x == Integer.MAX_VALUE) continue;
xLeft = Math.min(xLeft, each.x);
yTop = Math.min(yTop, each.y);
xRight = Math.max(xRight, each.x + each.width);
yBottom = Math.max(yBottom, each.y + each.height);
}
final Dimension dimension = new Dimension(xRight - xLeft, yBottom - yTop);
if (myLayoutPolicy == AUTO_LAYOUT_POLICY && myReservePlaceAutoPopupIcon && !isInsideNavBar()) {
if (myOrientation == SwingConstants.HORIZONTAL) {
dimension.width += AllIcons.Ide.Link.getIconWidth();
}
else {
dimension.height += AllIcons.Ide.Link.getIconHeight();
}
}
JBInsets.addTo(dimension, getInsets());
return dimension;
}
public void setForceMinimumSize(boolean force) {
myForceMinimumSize = force;
}
@Override
public Dimension getMinimumSize() {
if (myForceMinimumSize) {
return getPreferredSize();
}
if (myLayoutPolicy == AUTO_LAYOUT_POLICY) {
final Insets i = getInsets();
return new Dimension(AllIcons.Ide.Link.getIconWidth() + i.left + i.right, myMinimumButtonSize.height() + i.top + i.bottom);
}
else {
return super.getMinimumSize();
}
}
private static class ToolbarReference extends WeakReference<ActionToolbarImpl> {
private static final ReferenceQueue<ActionToolbarImpl> ourQueue = new ReferenceQueue<>();
private volatile Disposable myDisposable;
ToolbarReference(ActionToolbarImpl toolbar) {
super(toolbar, ourQueue);
processQueue();
}
private static void processQueue() {
while (true) {
ToolbarReference ref = (ToolbarReference)ourQueue.poll();
if (ref == null) break;
ref.disposeReference();
}
}
private void disposeReference() {
Disposable disposable = myDisposable;
if (disposable != null) {
myDisposable = null;
Disposer.dispose(disposable);
}
}
}
private final class MySeparator extends JComponent {
private final JBDimension mySize;
public MySeparator() {
if (myOrientation == SwingConstants.HORIZONTAL) {
mySize = JBUI.size(6, 24);
}
else {
mySize = JBUI.size(24, 6);
}
}
@Override
public Dimension getPreferredSize() {
return mySize.size();
}
@Override
protected void paintComponent(final Graphics g) {
final Insets i = getInsets();
int gap = JBUI.scale(2);
int offset = JBUI.scale(3);
if (UIUtil.isUnderAquaBasedLookAndFeel() || UIUtil.isUnderDarcula()) {
if (getParent() != null) {
final JBColor col = new JBColor(Gray._128, Gray._111);
final Graphics2D g2 = (Graphics2D)g;
if (myOrientation == SwingConstants.HORIZONTAL) {
UIUtil.drawDoubleSpaceDottedLine(g2, i.top + gap, getParent().getSize().height - gap - i.top - i.bottom, offset, col, false);
} else {
UIUtil.drawDoubleSpaceDottedLine(g2, i.left + gap, getParent().getSize().width - gap - i.left - i.right, offset, col, true);
}
}
}
else {
g.setColor(UIUtil.getSeparatorColor());
if (getParent() != null) {
if (myOrientation == SwingConstants.HORIZONTAL) {
UIUtil.drawLine(g, offset, gap, offset, getParent().getSize().height - gap);
}
else {
UIUtil.drawLine(g, gap, offset, getParent().getSize().width - gap, offset);
}
}
}
}
}
@Override
public void adjustTheSameSize(final boolean value) {
if (myAdjustTheSameSize == value) {
return;
}
myAdjustTheSameSize = value;
revalidate();
}
@Override
public void setMinimumButtonSize(@NotNull final Dimension size) {
myMinimumButtonSize = JBDimension.create(size, true);
for (int i = getComponentCount() - 1; i >= 0; i
final Component component = getComponent(i);
if (component instanceof ActionButton) {
final ActionButton button = (ActionButton)component;
button.setMinimumButtonSize(size);
}
}
revalidate();
}
@Override
public void setOrientation(@MagicConstant(intValues = {SwingConstants.HORIZONTAL, SwingConstants.VERTICAL}) int orientation) {
if (SwingConstants.HORIZONTAL != orientation && SwingConstants.VERTICAL != orientation) {
throw new IllegalArgumentException("wrong orientation: " + orientation);
}
myOrientation = orientation;
}
@Override
public void updateActionsImmediately() {
ApplicationManager.getApplication().assertIsDispatchThread();
myUpdater.updateActions(true, false);
}
private void updateActionsImpl(boolean transparentOnly, boolean forced) {
List<AnAction> newVisibleActions = ContainerUtil.newArrayListWithCapacity(myVisibleActions.size());
DataContext dataContext = getDataContext();
Utils.expandActionGroup(LaterInvocator.isInModalContext(), myActionGroup, newVisibleActions, myPresentationFactory, dataContext,
myPlace, myActionManager, transparentOnly, false, false, true);
if (forced || !newVisibleActions.equals(myVisibleActions)) {
boolean shouldRebuildUI = newVisibleActions.isEmpty() || myVisibleActions.isEmpty();
myVisibleActions = newVisibleActions;
Dimension oldSize = getPreferredSize();
removeAll();
mySecondaryActions.removeAll();
mySecondaryActionsButton = null;
fillToolBar(myVisibleActions, getLayoutPolicy() == AUTO_LAYOUT_POLICY && myOrientation == SwingConstants.HORIZONTAL);
Dimension newSize = getPreferredSize();
((WindowManagerEx)WindowManager.getInstance()).adjustContainerWindow(this, oldSize, newSize);
if (shouldRebuildUI) {
revalidate();
} else {
Container parent = getParent();
if (parent != null) {
parent.invalidate();
parent.validate();
}
}
repaint();
}
}
@Override
public boolean hasVisibleActions() {
return !myVisibleActions.isEmpty();
}
@Override
public void setTargetComponent(final JComponent component) {
myTargetComponent = component;
if (myTargetComponent != null) {
updateWhenFirstShown(myTargetComponent, new ToolbarReference(this));
}
}
private static void updateWhenFirstShown(JComponent targetComponent, final ToolbarReference ref) {
Activatable activatable = new Activatable.Adapter() {
public void showNotify() {
ActionToolbarImpl toolbar = ref.get();
if (toolbar != null) {
toolbar.myUpdater.updateActions(false, false);
}
}
};
ref.myDisposable = new UiNotifyConnector(targetComponent, activatable) {
@Override
protected void showNotify() {
super.showNotify();
ref.disposeReference();
}
};
}
@Override
public DataContext getToolbarDataContext() {
return getDataContext();
}
protected DataContext getDataContext() {
return myTargetComponent != null ? myDataManager.getDataContext(myTargetComponent) : ((DataManagerImpl)myDataManager).getDataContextTest(this);
}
@Override
protected void processMouseMotionEvent(final MouseEvent e) {
super.processMouseMotionEvent(e);
if (getLayoutPolicy() != AUTO_LAYOUT_POLICY) {
return;
}
if (myAutoPopupRec != null && myAutoPopupRec.contains(e.getPoint())) {
IdeFocusManager.getInstance(null).doWhenFocusSettlesDown(() -> showAutoPopup());
}
}
private void showAutoPopup() {
if (isPopupShowing()) return;
final ActionGroup group;
if (myOrientation == SwingConstants.HORIZONTAL) {
group = myActionGroup;
}
else {
final DefaultActionGroup outside = new DefaultActionGroup();
for (int i = myFirstOutsideIndex; i < myVisibleActions.size(); i++) {
outside.add(myVisibleActions.get(i));
}
group = outside;
}
PopupToolbar popupToolbar = new PopupToolbar(myPlace, group, true, myDataManager, myActionManager, myUpdater.getKeymapManager(), this) {
@Override
protected void onOtherActionPerformed() {
hidePopup();
}
@Override
protected DataContext getDataContext() {
return ActionToolbarImpl.this.getDataContext();
}
};
popupToolbar.setLayoutPolicy(NOWRAP_LAYOUT_POLICY);
popupToolbar.updateActionsImmediately();
Point location;
if (myOrientation == SwingConstants.HORIZONTAL) {
location = getLocationOnScreen();
}
else {
location = getLocationOnScreen();
location.y = location.y + getHeight() - popupToolbar.getPreferredSize().height;
}
final ComponentPopupBuilder builder = JBPopupFactory.getInstance().createComponentPopupBuilder(popupToolbar, null);
builder.setResizable(false)
.setMovable(true) // fit the screen automatically
.setRequestFocus(false)
.setTitle(null)
.setCancelOnClickOutside(true)
.setCancelOnOtherWindowOpen(true)
.setCancelCallback(() -> {
final boolean toClose = myActionManager.isActionPopupStackEmpty();
if (toClose) {
myUpdater.updateActions(false, true);
}
return toClose;
})
.setCancelOnMouseOutCallback(new MouseChecker() {
@Override
public boolean check(final MouseEvent event) {
return myAutoPopupRec != null &&
myActionManager.isActionPopupStackEmpty() &&
!new RelativeRectangle(ActionToolbarImpl.this, myAutoPopupRec).contains(new RelativePoint(event));
}
});
builder.addListener(new JBPopupAdapter() {
@Override
public void onClosed(LightweightWindowEvent event) {
processClosed();
}
});
myPopup = builder.createPopup();
final AnActionListener.Adapter listener = new AnActionListener.Adapter() {
@Override
public void afterActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) {
final JBPopup popup = myPopup;
if (popup != null && !popup.isDisposed() && popup.isVisible()) {
popup.cancel();
}
}
};
ActionManager.getInstance().addAnActionListener(listener);
Disposer.register(myPopup, popupToolbar);
Disposer.register(popupToolbar, new Disposable() {
@Override
public void dispose() {
ActionManager.getInstance().removeAnActionListener(listener);
}
});
myPopup.showInScreenCoordinates(this, location);
final Window window = SwingUtilities.getWindowAncestor(this);
if (window != null) {
final ComponentAdapter componentAdapter = new ComponentAdapter() {
@Override
public void componentResized(final ComponentEvent e) {
hidePopup();
}
@Override
public void componentMoved(final ComponentEvent e) {
hidePopup();
}
@Override
public void componentShown(final ComponentEvent e) {
hidePopup();
}
@Override
public void componentHidden(final ComponentEvent e) {
hidePopup();
}
};
window.addComponentListener(componentAdapter);
Disposer.register(popupToolbar, new Disposable() {
@Override
public void dispose() {
window.removeComponentListener(componentAdapter);
}
});
}
}
private boolean isPopupShowing() {
if (myPopup != null) {
if (myPopup.getContent() != null) {
return true;
}
}
return false;
}
private void hidePopup() {
if (myPopup != null) {
myPopup.cancel();
processClosed();
}
}
private void processClosed() {
if (myPopup == null) return;
Disposer.dispose(myPopup);
myPopup = null;
myUpdater.updateActions(false, false);
}
abstract static class PopupToolbar extends ActionToolbarImpl implements AnActionListener, Disposable {
private final JComponent myParent;
public PopupToolbar(final String place,
final ActionGroup actionGroup,
final boolean horizontal,
final DataManager dataManager,
@NotNull ActionManagerEx actionManager,
final KeymapManagerEx keymapManager,
JComponent parent) {
super(place, actionGroup, horizontal, false, dataManager, actionManager, keymapManager, true);
myActionManager.addAnActionListener(this);
myParent = parent;
}
@Override
public Container getParent() {
Container parent = super.getParent();
return parent != null ? parent : myParent;
}
@Override
public void dispose() {
myActionManager.removeAnActionListener(this);
}
@Override
public void beforeActionPerformed(final AnAction action, final DataContext dataContext, AnActionEvent event) {
}
@Override
public void afterActionPerformed(final AnAction action, final DataContext dataContext, AnActionEvent event) {
if (!myVisibleActions.contains(action)) {
onOtherActionPerformed();
}
}
protected abstract void onOtherActionPerformed();
@Override
public void beforeEditorTyping(final char c, final DataContext dataContext) {
}
}
@Override
public void setReservePlaceAutoPopupIcon(final boolean reserve) {
myReservePlaceAutoPopupIcon = reserve;
}
@Override
public void setSecondaryActionsTooltip(String secondaryActionsTooltip) {
mySecondaryActions.getTemplatePresentation().setDescription(secondaryActionsTooltip);
}
@Override
public void setSecondaryActionsIcon(Icon icon) {
mySecondaryActions.getTemplatePresentation().setIcon(icon);
}
@NotNull
@Override
public List<AnAction> getActions(boolean originalProvider) {
return getActions();
}
@NotNull
@Override
public List<AnAction> getActions() {
ArrayList<AnAction> result = new ArrayList<>();
ArrayList<AnAction> secondary = new ArrayList<>();
AnAction[] kids = myActionGroup.getChildren(null);
for (AnAction each : kids) {
if (myActionGroup.isPrimary(each)) {
result.add(each);
} else {
secondary.add(each);
}
}
result.add(new Separator());
result.addAll(secondary);
return result;
}
@Override
public void setMiniMode(boolean minimalMode) {
//if (myMinimalMode == minimalMode) return;
myMinimalMode = minimalMode;
if (myMinimalMode) {
setMinimumButtonSize(JBUI.emptySize());
setLayoutPolicy(NOWRAP_LAYOUT_POLICY);
setBorder(JBUI.Borders.empty());
setOpaque(false);
} else {
if (UIUtil.isUnderWin10LookAndFeel()) {
setBorder(JBUI.Borders.empty(0));
setMinimumButtonSize(myDecorateButtons ? JBUI.size(30, 22) : JBUI.size(25, 22));
} else {
setBorder(JBUI.Borders.empty(2));
setMinimumButtonSize(myDecorateButtons ? JBUI.size(30, 20) : DEFAULT_MINIMUM_BUTTON_SIZE);
}
setOpaque(true);
setLayoutPolicy(AUTO_LAYOUT_POLICY);
}
myUpdater.updateActions(false, true);
}
public void setAddSeparatorFirst(boolean addSeparatorFirst) {
myAddSeparatorFirst = addSeparatorFirst;
myUpdater.updateActions(false, true);
}
@TestOnly
public Presentation getPresentation(AnAction action) {
return myPresentationFactory.getPresentation(action);
}
public void clearPresentationCache() {
myPresentationFactory.reset();
}
public interface PopupStateModifier {
@ActionButtonComponent.ButtonState
int getModifiedPopupState();
boolean willModify();
}
}
|
package com.intellij.openapi.vfs.newvfs.persistent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.SystemInfoRt;
import com.intellij.openapi.util.io.FileAttributes;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vfs.VFileProperty;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.ex.temp.TempFileSystem;
import com.intellij.openapi.vfs.newvfs.ChildInfoImpl;
import com.intellij.openapi.vfs.newvfs.NewVirtualFile;
import com.intellij.openapi.vfs.newvfs.NewVirtualFileSystem;
import com.intellij.openapi.vfs.newvfs.events.ChildInfo;
import com.intellij.openapi.vfs.newvfs.events.VFileEvent;
import com.intellij.openapi.vfs.newvfs.impl.FakeVirtualFile;
import com.intellij.openapi.vfs.newvfs.impl.VirtualDirectoryImpl;
import com.intellij.openapi.vfs.newvfs.impl.VirtualFileSystemEntry;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.OpenTHashSet;
import com.intellij.util.containers.Queue;
import com.intellij.util.text.FilePathHashingStrategy;
import gnu.trove.TObjectHashingStrategy;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import static com.intellij.openapi.util.Pair.pair;
import static com.intellij.openapi.vfs.newvfs.persistent.VfsEventGenerationHelper.LOG;
import static com.intellij.util.containers.ContainerUtil.newTroveSet;
/**
* @author max
*/
public class RefreshWorker {
private final boolean myIsRecursive;
private final Queue<NewVirtualFile> myRefreshQueue = new Queue<>(100);
private final VfsEventGenerationHelper myHelper = new VfsEventGenerationHelper();
private volatile boolean myCancelled;
private final LocalFileSystemRefreshWorker myLocalFileSystemRefreshWorker;
public RefreshWorker(@NotNull NewVirtualFile refreshRoot, boolean isRecursive) {
boolean canUseNioRefresher = refreshRoot.isInLocalFileSystem() &&
!(refreshRoot.getFileSystem() instanceof TempFileSystem) &&
Registry.is("vfs.use.nio-based.local.refresh.worker");
myLocalFileSystemRefreshWorker = canUseNioRefresher ? new LocalFileSystemRefreshWorker(refreshRoot, isRecursive) : null;
myIsRecursive = isRecursive;
myRefreshQueue.addLast(refreshRoot);
}
@NotNull
public List<VFileEvent> getEvents() {
if (myLocalFileSystemRefreshWorker != null) return myLocalFileSystemRefreshWorker.getEvents();
return myHelper.getEvents();
}
public void cancel() {
if (myLocalFileSystemRefreshWorker != null) myLocalFileSystemRefreshWorker.cancel();
myCancelled = true;
}
public void scan() {
if (myLocalFileSystemRefreshWorker != null) {
myLocalFileSystemRefreshWorker.scan();
return;
}
NewVirtualFile root = myRefreshQueue.pullFirst();
NewVirtualFileSystem fs = root.getFileSystem();
if (root.isDirectory()) {
fs = PersistentFS.replaceWithNativeFS(fs);
}
PersistentFS persistence = PersistentFS.getInstance();
FileAttributes attributes = fs.getAttributes(root);
if (attributes == null) {
myHelper.scheduleDeletion(root);
root.markClean();
return;
}
checkAndScheduleChildRefresh(fs, persistence, root.getParent(), root, attributes);
if (root.isDirty()) {
if (myRefreshQueue.isEmpty()) {
myRefreshQueue.addLast(root);
}
try {
processQueue(fs, persistence);
}
catch (RefreshCancelledException e) {
LOG.trace("refresh cancelled");
}
}
}
private void processQueue(@NotNull NewVirtualFileSystem fs, @NotNull PersistentFS persistence) throws RefreshCancelledException {
TObjectHashingStrategy<String> strategy = FilePathHashingStrategy.create(fs.isCaseSensitive());
while (!myRefreshQueue.isEmpty()) {
VirtualDirectoryImpl dir = (VirtualDirectoryImpl)myRefreshQueue.pullFirst();
boolean fullSync = dir.allChildrenLoaded();
boolean succeeded;
do {
myHelper.beginTransaction();
succeeded = fullSync ? fullDirRefresh(fs, persistence, strategy, dir) : partialDirRefresh(fs, persistence, strategy, dir);
myHelper.endTransaction(succeeded);
if (!succeeded && LOG.isTraceEnabled()) LOG.trace("retry: " + dir);
}
while (!succeeded);
if (myIsRecursive) {
dir.markClean();
}
}
}
private boolean fullDirRefresh(@NotNull NewVirtualFileSystem fs,
@NotNull PersistentFS persistence,
@NotNull TObjectHashingStrategy<String> strategy,
@NotNull VirtualDirectoryImpl dir) {
Pair<String[], VirtualFile[]> snapshot = LocalFileSystemRefreshWorker.getDirectorySnapshot(persistence, dir);
if (snapshot == null) return false;
String[] persistedNames = snapshot.getFirst();
VirtualFile[] children = snapshot.getSecond();
String[] upToDateNames = VfsUtil.filterNames(fs.list(dir));
Set<String> newNames = newTroveSet(strategy, upToDateNames);
if (dir.allChildrenLoaded() && children.length < upToDateNames.length) {
for (VirtualFile child : children) {
newNames.remove(child.getName());
}
}
else {
ContainerUtil.removeAll(newNames, persistedNames);
}
Set<String> deletedNames = newTroveSet(strategy, persistedNames);
ContainerUtil.removeAll(deletedNames, upToDateNames);
OpenTHashSet<String> actualNames = fs.isCaseSensitive() ? null : new OpenTHashSet<>(strategy, upToDateNames);
if (LOG.isTraceEnabled()) LOG.trace("current=" + Arrays.toString(persistedNames) + " +" + newNames + " -" + deletedNames);
List<ChildInfo> newKids = new ArrayList<>(newNames.size());
for (String newName : newNames) {
checkCancelled(dir);
ChildInfo record = childRecord(fs, dir, newName);
if (record != null) {
newKids.add(record);
}
else {
if (LOG.isTraceEnabled()) LOG.trace("[+] fs=" + fs + " dir=" + dir + " name=" + newName);
}
}
List<Pair<VirtualFile, FileAttributes>> updatedMap = new ArrayList<>(children.length);
for (VirtualFile child : children) {
checkCancelled(dir);
if (!deletedNames.contains(child.getName())) {
updatedMap.add(pair(child, fs.getAttributes(child)));
}
}
if (isDirectoryChanged(persistence, dir, persistedNames, children)) {
return false;
}
for (String name : deletedNames) {
VirtualFileSystemEntry child = dir.findChild(name);
if (child != null) {
myHelper.scheduleDeletion(child);
}
}
for (ChildInfo record : newKids) {
myHelper.scheduleCreation(dir, record.getName().toString(), record.getFileAttributes(), record.getSymLinkTarget(), () -> checkCancelled(dir));
}
for (Pair<VirtualFile, FileAttributes> pair : updatedMap) {
NewVirtualFile child = (NewVirtualFile)pair.first;
checkCancelled(child);
FileAttributes childAttributes = pair.second;
if (childAttributes != null) {
checkAndScheduleChildRefresh(fs, persistence, dir, child, childAttributes);
checkAndScheduleFileNameChange(actualNames, child);
}
else {
if (LOG.isTraceEnabled()) LOG.warn("[x] fs=" + fs + " dir=" + dir + " name=" + child.getName());
myHelper.scheduleDeletion(child);
}
}
return !isDirectoryChanged(persistence, dir, persistedNames, children);
}
private boolean isDirectoryChanged(@NotNull PersistentFS persistence,
@NotNull VirtualDirectoryImpl dir,
@NotNull String[] persistedNames,
@NotNull VirtualFile[] children) {
return ReadAction.compute(() -> {
checkCancelled(dir);
return !Arrays.equals(persistedNames, persistence.list(dir)) || !Arrays.equals(children, dir.getChildren());
});
}
private boolean partialDirRefresh(@NotNull NewVirtualFileSystem fs,
@NotNull PersistentFS persistence,
@NotNull TObjectHashingStrategy<String> strategy,
@NotNull VirtualDirectoryImpl dir) {
Pair<List<VirtualFile>, List<String>> snapshot = ReadAction.compute(() -> {
checkCancelled(dir);
return pair(dir.getCachedChildren(), dir.getSuspiciousNames());
});
List<VirtualFile> cached = snapshot.getFirst();
List<String> wanted = snapshot.getSecond();
OpenTHashSet<String> actualNames =
fs.isCaseSensitive() || cached.isEmpty() ? null : new OpenTHashSet<>(strategy, VfsUtil.filterNames(fs.list(dir)));
if (LOG.isTraceEnabled()) LOG.trace("cached=" + cached + " actual=" + actualNames + " suspicious=" + wanted);
List<Pair<VirtualFile, FileAttributes>> existingMap = new ArrayList<>(cached.size());
for (VirtualFile child : cached) {
checkCancelled(dir);
existingMap.add(pair(child, fs.getAttributes(child)));
}
List<ChildInfo> newKids = new ArrayList<>(wanted.size());
for (String name : wanted) {
if (name.isEmpty()) continue;
checkCancelled(dir);
ChildInfo record = childRecord(fs, dir, name);
if (record != null) {
newKids.add(record);
}
}
if (isDirectoryChanged(dir, cached, wanted)) {
return false;
}
for (Pair<VirtualFile, FileAttributes> pair : existingMap) {
NewVirtualFile child = (NewVirtualFile)pair.first;
checkCancelled(child);
FileAttributes childAttributes = pair.second;
if (childAttributes != null) {
checkAndScheduleChildRefresh(fs, persistence, dir, child, childAttributes);
checkAndScheduleFileNameChange(actualNames, child);
}
else {
myHelper.scheduleDeletion(child);
}
}
for (ChildInfo record : newKids) {
myHelper.scheduleCreation(dir, record.getName().toString(), record.getFileAttributes(), record.getSymLinkTarget(), () -> checkCancelled(dir));
}
return !isDirectoryChanged(dir, cached, wanted);
}
private boolean isDirectoryChanged(@NotNull VirtualDirectoryImpl dir, @NotNull List<VirtualFile> cached, @NotNull List<String> wanted) {
return ReadAction.compute(() -> {
checkCancelled(dir);
return !cached.equals(dir.getCachedChildren()) || !wanted.equals(dir.getSuspiciousNames());
});
}
@Nullable
private static ChildInfo childRecord(@NotNull NewVirtualFileSystem fs, @NotNull VirtualFile dir, @NotNull String name) {
FakeVirtualFile file = new FakeVirtualFile(dir, name);
FileAttributes attributes = fs.getAttributes(file);
if (attributes == null) return null;
boolean isEmptyDir = attributes.isDirectory() && !fs.hasChildren(file);
String symlinkTarget = attributes.isSymLink() ? fs.resolveSymLink(file) : null;
return new ChildInfoImpl(ChildInfoImpl.UNKNOWN_ID_YET, name, attributes, isEmptyDir ? ChildInfo.EMPTY_ARRAY : null, symlinkTarget);
}
static class RefreshCancelledException extends RuntimeException {
@Override
public synchronized Throwable fillInStackTrace() {
return this;
}
}
private void checkCancelled(@NotNull NewVirtualFile stopAt) throws RefreshCancelledException {
if (ourTestListener != null) {
ourTestListener.accept(stopAt);
}
if (myCancelled) {
if (LOG.isTraceEnabled()) LOG.trace("cancelled at: " + stopAt);
forceMarkDirty(stopAt);
while (!myRefreshQueue.isEmpty()) {
forceMarkDirty(myRefreshQueue.pullFirst());
}
throw new RefreshCancelledException();
}
}
private static void forceMarkDirty(@NotNull NewVirtualFile file) {
file.markClean(); // otherwise consequent markDirty() won't have any effect
file.markDirty();
}
private void checkAndScheduleChildRefresh(@NotNull NewVirtualFileSystem fs,
@NotNull PersistentFS persistence,
@Nullable NewVirtualFile parent,
@NotNull NewVirtualFile child,
@NotNull FileAttributes childAttributes) {
if (!VfsEventGenerationHelper.checkDirty(child)) {
return;
}
if (checkAndScheduleFileTypeChange(fs, parent, child, childAttributes)) {
child.markClean();
return;
}
myHelper.checkWritableAttributeChange(child, persistence.isWritable(child), childAttributes.isWritable());
if (SystemInfoRt.isWindows) {
myHelper.checkHiddenAttributeChange(child, child.is(VFileProperty.HIDDEN), childAttributes.isHidden());
}
if (childAttributes.isSymLink()) {
myHelper.checkSymbolicLinkChange(child, child.getCanonicalPath(), fs.resolveSymLink(child));
}
if (!childAttributes.isDirectory()) {
long oltTS = persistence.getTimeStamp(child);
long newTS = childAttributes.lastModified;
long oldLength = persistence.getLastRecordedLength(child);
long newLength = childAttributes.length;
myHelper.checkContentChanged(child, oltTS, newTS, oldLength, newLength);
child.markClean();
}
else if (myIsRecursive) {
myRefreshQueue.addLast(child);
}
}
private boolean checkAndScheduleFileTypeChange(@NotNull NewVirtualFileSystem fs,
@Nullable NewVirtualFile parent,
@NotNull NewVirtualFile child,
@NotNull FileAttributes childAttributes) {
boolean currentIsDirectory = child.isDirectory();
boolean currentIsSymlink = child.is(VFileProperty.SYMLINK);
boolean currentIsSpecial = child.is(VFileProperty.SPECIAL);
boolean upToDateIsDirectory = childAttributes.isDirectory();
boolean upToDateIsSymlink = childAttributes.isSymLink();
boolean upToDateIsSpecial = childAttributes.isSpecial();
if (currentIsDirectory != upToDateIsDirectory || currentIsSymlink != upToDateIsSymlink || currentIsSpecial != upToDateIsSpecial) {
myHelper.scheduleDeletion(child);
assert parent != null : "transgender orphan: " + child + ' ' + childAttributes;
String symlinkTarget = upToDateIsSymlink ? fs.resolveSymLink(child) : null;
myHelper.scheduleCreation(parent, child.getName(), childAttributes, symlinkTarget, () -> checkCancelled(parent));
return true;
}
return false;
}
private void checkAndScheduleFileNameChange(@Nullable OpenTHashSet<String> actualNames, @NotNull VirtualFile child) {
if (actualNames != null) {
String currentName = child.getName();
String actualName = actualNames.get(currentName);
if (actualName != null && !currentName.equals(actualName)) {
myHelper.scheduleAttributeChange(child, VirtualFile.PROP_NAME, currentName, actualName);
}
}
}
private static Consumer<? super VirtualFile> ourTestListener;
@TestOnly
public static void setTestListener(@Nullable Consumer<? super VirtualFile> testListener) {
assert ApplicationManager.getApplication().isUnitTestMode();
ourTestListener = testListener;
LocalFileSystemRefreshWorker.setTestListener(testListener);
}
}
|
package com.smartnsoft.droid4me.app;
import java.io.InterruptedIOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import javax.net.ssl.SSLException;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.Window;
import com.smartnsoft.droid4me.LifeCycle;
import com.smartnsoft.droid4me.LifeCycle.BusinessObjectUnavailableException;
import com.smartnsoft.droid4me.log.Logger;
import com.smartnsoft.droid4me.log.LoggerFactory;
public class ActivityController
{
/**
* An interface which is requested when a new {@link Activity} is bound to be {@link Context#startActivity(Intent) started}.
* <p>
* <p>
* The redirector acts as a controller over the activities starting phase: if an activity should be started before another one is really
* {@link Activity#onResume() active}, this is the right place to handle this at runtime.
* </p>
* <p>
* <p>
* This component is especially useful when ones need to make sure that an {@link Activity} has actually been submitted to the end-user before
* resuming a workflow. The common cases are the traditional application splash screen, or a signin/signup process.
* </p>
*
* @see ActivityController#registerRedirector(Redirector)
*/
public interface Redirector
{
/**
* Will be invoked by the {@link ActivityController#needsRedirection(Activity) framework}, in order to know whether an {@link Activity} should be
* started instead of the provided one, which is supposed to have just {@link Activity#onCreate(Bundle) started}, or when the
* {@link Activity#onNewIntent(Intent)} method is invoked. However, the method will be not been invoked when those methods are invoked due to a
* {@link Activity#onConfigurationChanged(android.content.res.Configuration) configuration change}.
* <p>
* <p>
* Caution: if an exception is thrown during the method execution, the application will crash!
* </p>
*
* @param activity the activity which is bound to be displayed
* @return {@code null} if and only if nothing is to be done, i.e. no activity should be started instead. Otherwise, the given intent will be
* executed: in that case, the provided activity {@link Activity#finish finishes}
* @see ActivityController#needsRedirection(Activity)
*/
Intent getRedirection(Activity activity);
}
/**
* An empty interface which should be used as a marker on an {@link Activity}, which does not want to be requested by the
* {@link ActivityController.Redirector}.
* <p>
* <p>
* When an {@link Activity} implements this interface, the {@link ActivityController.Redirector#getRedirection(Activity)} method will not be
* invoked.
* </p>
*
* @see ActivityController#needsRedirection(Activity)
* @see ActivityController.EscapeToRedirectorAnnotation
* @since 2012.04.11
* @deprecated now use the {@link ActivityController.EscapeToRedirectorAnnotation} annotation instead
*/
@Deprecated
public interface EscapeToRedirector
{
}
/**
* An annotation which offers the same effect as the {@link ActivityController.EscapeToRedirector} interface.
*
* @see ActivityController#needsRedirection(Activity)
* @see ActivityController.EscapeToRedirector
* @since 2014.04.26
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface EscapeToRedirectorAnnotation
{
}
/**
* An interface responsible for providing Android system services, given their name. It enables to override in one place all the {@code Activity}
* system services.
*
* @since 2012.02.12
*/
public interface SystemServiceProvider
{
/**
* Returns the handle to a system-level service by name. The class of the returned object varies by the requested name.
*
* @param activity the {@link Activity} asking for the service
* @param name the name of the desired service
* @param defaultService the provided {@code activity} default system service (retrieved by invoking the {@link Activity#getSystemService(String)} method)
* @return the desired service, or {@code null} if no service corresponding to the provided {@code name} is available nor exists
* @see Activity#getSystemService(String)
*/
Object getSystemService(Activity activity, String name, Object defaultService);
}
/**
* An interface which is queried during the various life cycle events of a {@link LifeCycle}.
* <p>
* <p>
* An interceptor is the ideal place for centralizing in one place many of the {@link Activity}/{@link Fragment} entity life cycle
* events.
* </p>
*
* @see ActivityController#registerInterceptor(Interceptor)
*/
public interface Interceptor
{
/**
* Defines all the events handled by the {@link ActivityController.Interceptor}.
*/
enum InterceptorEvent
{
/**
* Called during the {@code Activity.onCreate()} / {@code Fragment.onCreate()} method, before the Android built-in super method
* {@link Activity#onCreate} method is invoked.
* <p>
* <p>
* This is an ideal place where to {@link Window#requestFeature(int)} request for window features}.
* </p>
*/
onSuperCreateBefore,
/**
* Called during the {@code Activity.onCreate()} / {@code Fragment.onCreate()} method, at the beginning of the method, but after the
* parent's call, provided no {@link ActivityController.Redirector activity redirection} is requested.
*/
onCreate,
/**
* Called during the {@code Activity.onCreate()} / {@code Fragment.onCreate()} method, at the very end of the method, after the
* parent's call, provided no {@link ActivityController.Redirector activity redirection} is requested.
*/
onCreateDone,
/**
* <b>Only applies to {@link Activity} entities!</b>.Called during the {@code Activity#onPostCreate()} method, at the beginning of the method,
* but after the parent's call, provided no {@link ActivityController.Redirector activity redirection} is requested.
*/
onPostCreate,
/**
* <b>Only applies to {@link Activity} entities!</b>.Called at the end of the {@link Activity#onContentChanged()} method execution, but after
* the parent's call, provided no {@link ActivityController.Redirector activity redirection} is requested.
*/
onContentChanged,
/**
* Called during the {@link Activity#onStart} / {@link Fragment#onStart()} method, at the beginning of the method, but after the
* parent's call, provided no {@link ActivityController.Redirector activity redirection} is requested and that the instance has not been
* recreated due a configuration change.
*/
onStart,
/**
* <b>Only applies to {@link Activity} entities!</b>.Called during the {@link Activity#onRestart()} method, after the parent's call, provided no
* {@link ActivityController.Redirector activity redirection} is requested and that the instance has not been recreated due a configuration
* change.
*/
onRestart,
/**
* Called during the {@link Activity#onResume()} / {@link Fragment#onResume()} method, at the beginning of the method, but after the
* parent's call, provided no {@link ActivityController.Redirector activity redirection} is requested.
*/
onResume,
/**
* <b>Only applies to {@link Activity} entities!</b>.Called during the {@link Activity#onPostResume()} method, at the beginning of the method,
* but after the parent's call, provided no {@link ActivityController.Redirector activity redirection} is requested.
*/
onPostResume,
/**
* Called during the {@link Activity#onPause()} / {@link Fragment#onPause()} method, at the beginning of the method, but after the
* parent's call, provided no {@link ActivityController.Redirector activity redirection} is requested.
*/
onPause,
/**
* Called during the {@link Activity#onStop()} / {@link Fragment#onPause()} method, at the beginning of the method, before the
* parent's call.
*/
onStop,
/**
* Called just after the {@link LifeCycle#onFulfillDisplayObjects()} method.
*/
onFulfillDisplayObjectsDone,
/**
* Called just after the {@link LifeCycle#onSynchronizeDisplayObjects()} method.
*/
onSynchronizeDisplayObjectsDone,
/**
* Called during the {@link Activity#onDestroy()} / {@link Fragment#onDestroy()} method, at the very end of the method.
*/
onDestroy
}
/**
* A logger which may be used by the classes implementing this interface.
*/
Logger log = LoggerFactory.getInstance(Interceptor.class);
/**
* Invoked every time a new event occurs on the provided {@code activity}/{@code component}. For instance, this is an ideal for logging
* application usage analytics.
* <p>
* <p>
* The framework ensures that this method will be invoked from the UI thread, hence the method implementation should last a very short time!
* <p>
* <p>
* <p>
* Caution: if an exception is thrown during the method execution, the application will crash!
* </p>
*
* @param activity the activity on which a life cycle event occurs ; cannot be {@code null}
* @param component the component on which the life cycle event occurs ; may be {@code null}
* @param event the event that has just happened
* @see ActivityController#onLifeCycleEvent(Activity, Object, InterceptorEvent)
*/
void onLifeCycleEvent(Activity activity, Object component, ActivityController.Interceptor.InterceptorEvent event);
}
/**
* Defines and splits the handling of various exceptions in a single place. This handler will be invoked once it has been
* {@link ActivityController#registerExceptionHandler(ExceptionHandler) registered}.
* <p>
* <p>
* The exception handler will be invoked at runtime when an exception is thrown and is not handled. You do not need to log the exception, because
* the {@link ActivityController} already takes care of logging it, before invoking the current interface methods.
* </p>
*
* @see ActivityController#registerExceptionHandler(ExceptionHandler)
*/
public interface ExceptionHandler
{
/**
* Is invoked whenever the {@link LifeCycle#onRetrieveBusinessObjects()} throws an exception.
* <p>
* <p>
* Warning, it is not ensured that this method will be invoked from the UI thread!
* </p>
*
* @param activity the activity that issued the exception, and which is ensured not to be {@link Activity#finish() finishing} ; cannot be {@code null}
* @param component the component that issued the exception ; may be {@code null}
* @param exception the exception that has been thrown
* @return {@code true} if the handler has actually handled the exception: this indicates to the framework that it does not need to investigate
* for a further exception handler anymore
*/
boolean onBusinessObjectAvailableException(Activity activity, Object component,
BusinessObjectUnavailableException exception);
/**
* Is invoked whenever an activity implementing {@link LifeCycle} throws an unexpected exception outside from the
* {@link LifeCycle#onRetrieveBusinessObjects()} method.
* <p>
* <p>
* This method serves as a fallback on the framework, in order to handle gracefully exceptions and prevent the application from crashing.
* </p>
* <p>
* <p>
* Warning, it is not ensured that this method will be invoked from the UI thread!
* </p>
*
* @param activity the activity that issued the exception ; cannot be {@code null}
* @param component the component that issued the exception ; may be {@code null}
* @param throwable the exception that has been triggered
* @return {@code true} if the handler has actually handled the exception: this indicates to the framework that it does not need to investigate
* for a further exception handler anymore
*/
boolean onActivityException(Activity activity, Object component, Throwable throwable);
/**
* Is invoked whenever a handled exception is thrown with a non-{@link Activity} / {@link Fragment} {@link Context context}.
* <p>
* <p>
* This method serves as a fallback on the framework, in order to handle gracefully exceptions and prevent the application from crashing.
* </p>
* <p>
* <p>
* Warning, it is not ensured that this method will be invoked from the UI thread!
* </p>
*
* @param isRecoverable indicates whether the application is about to crash when the exception has been triggered
* @param context the context that issued the exception
* @param throwable the exception that has been triggered
* @return {@code true} if the handler has actually handled the exception: this indicates to the framework that it does not need to investigate
* for a further exception handler anymore
*/
boolean onContextException(boolean isRecoverable, Context context, Throwable throwable);
/**
* Is invoked whenever a handled exception is thrown outside from an available {@link Context context}.
* <p>
* <p>
* This method serves as a fallback on the framework, in order to handle gracefully exceptions and prevent the application from crashing.
* </p>
* <p>
* <p>
* Warning, it is not ensured that this method will be invoked from the UI thread!
* </p>
*
* @param isRecoverable indicates whether the application is about to crash when the exception has been triggered
* @param throwable the exception that has been triggered
* @return {@code true} if the handler has actually handled the exception: this indicates to the framework that it does not need to investigate
* for a further exception handler anymore
*/
boolean onException(boolean isRecoverable, Throwable throwable);
}
/**
* Responsible for analyzing issues resulting from {@link Throwable} entities.
*
* @since 2013.12.23
*/
public static abstract class IssueAnalyzer
{
/**
* A default implementation.
*
* @since 2017.06.02
*/
public static final class DefaultIssueAnalyzer
extends IssueAnalyzer
{
public DefaultIssueAnalyzer(Context context)
{
super(context);
}
@Override
public boolean handleIssue(Throwable throwable)
{
return false;
}
}
public static final class IssueContext
{
private static final String SPLITTER = ";";
public final String applicationName;
public final String applicationVersionName;
public final int applicationVersionCode;
public final String deviceModel;
public final String firmwareVersion;
public final String buildNumber;
public IssueContext(String string)
{
final String[] tokens = string.split(IssueContext.SPLITTER);
int index = 0;
applicationName = tokens[index++];
applicationVersionName = tokens[index++];
applicationVersionCode = Integer.parseInt(tokens[index++]);
deviceModel = tokens[index++];
firmwareVersion = tokens[index++];
buildNumber = tokens[index++];
}
public IssueContext(Context context)
{
applicationName = context.getString(context.getApplicationInfo().labelRes);
PackageInfo packageInfo = null;
try
{
packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_META_DATA);
}
catch (NameNotFoundException exception)
{
// Cannot happen
}
applicationVersionName = packageInfo == null ? "" : packageInfo.versionName;
applicationVersionCode = packageInfo == null ? -1 : packageInfo.versionCode;
deviceModel = Build.MODEL;
firmwareVersion = Build.VERSION.RELEASE;
buildNumber = Build.DISPLAY;
}
@Override
public String toString()
{
return applicationName + IssueContext.SPLITTER + applicationVersionName + IssueContext.SPLITTER + applicationVersionCode + IssueContext.SPLITTER + deviceModel + IssueContext.SPLITTER + firmwareVersion + IssueContext.SPLITTER + buildNumber;
}
public String toHumanString()
{
final StringBuilder sb = new StringBuilder();
sb.append("applicationName = ").append(applicationName).append("\n");
sb.append("applicationVersionName = ").append(applicationVersionName).append("\n");
sb.append("applicationVersionCode = ").append(applicationVersionCode).append("\n");
sb.append("deviceModel = ").append(deviceModel).append("\n");
sb.append("firmwareVersion = ").append(firmwareVersion).append("\n");
sb.append("buildNumber = ").append(buildNumber).append("\n");
return sb.toString();
}
}
protected final static Logger log = LoggerFactory.getInstance(IssueAnalyzer.class);
/**
* Attempts to find a specific exception in the provided exception by iterating over the causes, starting with the provided exception itself.
*
* @param throwable the exception to be inspected
* @param exceptionClass a list of exception classes to look after
* @return {@code null} if and only one of the provided exception classes has not been detected ; the matching cause otherwise
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static final Throwable searchForCause(Throwable throwable, Class... exceptionClass)
{
Throwable newThrowable = throwable;
Throwable cause = throwable;
// We investigate over the whole causes stack
while (cause != null)
{
for (Class<? extends Throwable> anExceptionClass : exceptionClass)
{
final Class<? extends Throwable> causeClass = cause.getClass();
if (causeClass == anExceptionClass)
{
return cause;
}
// We scan the cause class hierarchy
Class<?> superclass = causeClass.getSuperclass();
while (superclass != null)
{
if (superclass == anExceptionClass)
{
return cause;
}
superclass = superclass.getSuperclass();
}
}
// It seems that when there are no more causes, the exception itself is returned as a cause: stupid implementation!
if (newThrowable.getCause() == newThrowable)
{
break;
}
newThrowable = cause;
cause = newThrowable.getCause();
}
return null;
}
/**
* @param throwable the exception to investigate
* @return {@code true} if and only if the exception results from a connectivity issue by inspecting its causes tree
*/
public static boolean isAConnectivityProblem(Throwable throwable)
{
return ActivityController.IssueAnalyzer.searchForCause(throwable, UnknownHostException.class, SocketException.class, SocketTimeoutException.class, InterruptedIOException.class, SSLException.class) != null;
}
/**
* @param throwable the exception to investigate
* @return {@code true} if and only if the exception results from a memory saturation issue (i.e. a {@link OutOfMemoryError} exception) by
* inspecting its causes tree
*/
public static boolean isAMemoryProblem(Throwable throwable)
{
return ActivityController.IssueAnalyzer.searchForCause(throwable, OutOfMemoryError.class) != null;
}
protected final Context context;
/**
* @param context should be an application {@link Context}
*/
public IssueAnalyzer(Context context)
{
this.context = context;
}
/**
* Is responsible for analyzing the provided exception, and indicates whether it has been handled.
*
* @param throwable the issue to analyze
* @return {@code true} if and only if the issue has actually been handled by the implementation
*/
public abstract boolean handleIssue(Throwable throwable);
}
/**
* When a new activity is {@link Context#startActivity(Intent) started} because of a redirection, the newly started activity will receive the
* initial activity {@link Intent} through this {@link Parcelable} key.
*
* @see #needsRedirection(Activity)
* @see #registerInterceptor(Interceptor)
*/
public static final String CALLING_INTENT = "com.smartnsoft.droid4me.callingIntent";
private static final Logger log = LoggerFactory.getInstance(ActivityController.class);
/**
* A singleton pattern is available for the moment.
*/
private static volatile ActivityController instance;
/**
* The only way to access to the activity controller.
*/
// Implements a "double-checked locking" pattern.
public static ActivityController getInstance()
{
if (ActivityController.instance == null)
{
synchronized (ActivityController.class)
{
if (ActivityController.instance == null)
{
ActivityController.instance = new ActivityController();
}
}
}
return ActivityController.instance;
}
/**
* Attempts to decode from the provided {@code activity} the original {@code Intent} that was
*
* @param activity the Activity whose Intent will be analyzed
* @return an Intent that may be {@link Activity#startActivity(Intent) started} if the provided {@code activity} actually contains a reference to
* another {@link Activity} ; {@code null} otherwise
* @see ActivityController#CALLING_INTENT
* @see #needsRedirection(Activity)
* @see #registerInterceptor(Interceptor)
*/
public static Intent extractCallingIntent(Activity activity)
{
return activity.getIntent().getParcelableExtra(ActivityController.CALLING_INTENT);
}
private ActivityController.Redirector redirector;
private ActivityController.SystemServiceProvider systemServiceProvider;
private ActivityController.Interceptor interceptor;
private ActivityController.ExceptionHandler exceptionHandler;
/**
* No one else than the framework should create such an instance.
*/
private ActivityController()
{
}
/**
* Remembers the system service provider that will be used by the framework, for overriding the {@link Activity#getSystemService(String)} method.
*
* @param systemServiceProvider the system service provider which will be invoked at runtime, when an {@link Activity} asks for a service ; if {@code null}, the
* {@link Activity} default service will be used
*/
public void registerSystemServiceProvider(ActivityController.SystemServiceProvider systemServiceProvider)
{
this.systemServiceProvider = systemServiceProvider;
}
/**
* Remembers the activity redirector that will be used by the framework, before {@link Context#startActivity(Intent) starting} a new
* {@link Activity}.
*
* @param redirector the redirector that will be requested at runtime, when a new activity is being started; if {@code null}, no redirection mechanism will
* be set up
*/
public void registerRedirector(ActivityController.Redirector redirector)
{
this.redirector = redirector;
}
/**
* Remembers the activity interceptor that will be used by the framework, on every {@link ActivityController.Interceptor.InterceptorEvent event}
* during the underlying {@link Activity} life cycle.
*
* @param interceptor the interceptor that will be invoked at runtime, on every event; if {@code null}, no interception mechanism will be used
*/
public void registerInterceptor(ActivityController.Interceptor interceptor)
{
this.interceptor = interceptor;
}
/**
* Is responsible for returning a system service, just like the {@link Context#getSystemService(String)} method does.
*
* @param activity the activity asking for a system service
* @param name the name of the desired service
* @param defaultService the {@code activity} default service
* @return the service or {@code null} if the name does not exist
* @see #registerSystemServiceProvider(ActivityController.SystemServiceProvider)
*/
public Object getSystemService(Activity activity, String name, Object defaultService)
{
if (systemServiceProvider != null)
{
return systemServiceProvider.getSystemService(activity, name, defaultService);
}
return defaultService;
}
/**
* Gives access to the currently registered {@link ActivityController.ExceptionHandler}.
*
* @return the currently registered exception handler ; may be {@code null}, which is the default status
* @see #registerExceptionHandler(ActivityController.ExceptionHandler)
*/
public ActivityController.ExceptionHandler getExceptionHandler()
{
return exceptionHandler;
}
/**
* Remembers the exception handler that will be used by the framework.
*
* @param exceptionHandler the handler that will be invoked in case of exception; if {@code null}, no exception handler will be used
* @see #getExceptionHandler()
*/
public synchronized void registerExceptionHandler(ActivityController.ExceptionHandler exceptionHandler)
{
this.exceptionHandler = exceptionHandler;
}
/**
* Is invoked by the framework every time a life cycle event occurs for the provided activity. You should not invoke that method yourself!
* <p>
* <p>
* Note that the method is synchronized, which means that the previous call will block the next one, if no thread is spawn.
* </p>
*
* @param activity the activity which is involved with the event : cannot be {@code null}
* @param component the component the event occurs on ; may be {code null}
* @param event the event that has just happened for that activity
*/
public synchronized void onLifeCycleEvent(Activity activity, Object component,
ActivityController.Interceptor.InterceptorEvent event)
{
if (interceptor == null)
{
return;
}
interceptor.onLifeCycleEvent(activity, component, event);
}
/**
* Dispatches the exception to the {@link ActivityController.ExceptionHandler}, and invokes the right method depending on its nature.
* <p>
* <p>
* The framework is responsible for invoking that method every time an unhandled exception is thrown. If no
* {@link ActivityController#registerExceptionHandler(ExceptionHandler) exception handler is registered}, the exception will be only logged, and the
* method will return {@code false}.
* </p>
* <p>
* <p>
* Note that this method is {@code synchronized}, which prevents it from being invoking while it is already being executed, and which involves that
* only one {@link Throwable} may be handled at the same time.
* </p>
*
* @param isRecoverable indicates whether the application is about to crash when the exception has been triggered
* @param context the context that originated the exception ; may be {@code null}
* @param component when not {@code null}, this will be the {@link Fragment} the exception has been thrown from
* @param throwable the reported exception
* @return {@code true} if the exception has been handled ; in particular, if no {@link ActivityController#getExceptionHandler() exception handled
* has been set}, returns {@code false}
*/
public synchronized boolean handleException(boolean isRecoverable, Context context, Object component,
Throwable throwable)
{
if (exceptionHandler == null)
{
if (log.isWarnEnabled())
{
log.warn("Detected an exception which will not be handled during the processing of the context with name '" + (context == null ? "null" : context.getClass().getName()) + "'", throwable);
}
return false;
}
final Activity activity;
if (context instanceof Activity)
{
activity = (Activity) context;
}
else
{
activity = null;
}
try
{
if (activity != null && throwable instanceof BusinessObjectUnavailableException)
{
// Should only occur with a non-null activity
final BusinessObjectUnavailableException exception = (BusinessObjectUnavailableException) throwable;
if (log.isWarnEnabled())
{
log.warn("Caught an exception during the retrieval of the business objects from the activity from class with name '" + activity.getClass().getName() + "'", exception);
}
// We do nothing if the activity is dying
if (activity != null && activity.isFinishing() == true)
{
return true;
}
return exceptionHandler.onBusinessObjectAvailableException(activity, component, exception);
}
else
{
if (log.isWarnEnabled())
{
log.warn("Caught an exception during the processing of " + (context == null ? "a null Context" : "the Context from class with name '" + context.getClass().getName()) + "'", throwable);
}
// For this special case, we ignore the case when the activity is dying
if (activity != null)
{
return exceptionHandler.onActivityException(activity, component, throwable);
}
else if (context != null)
{
return exceptionHandler.onContextException(isRecoverable, context, throwable);
}
else
{
return exceptionHandler.onException(isRecoverable, throwable);
}
}
}
catch (Throwable otherThrowable)
{
// Just to make sure that handled exceptions do not trigger un-handled exceptions on their turn ;(
if (log.isErrorEnabled())
{
log.error("An error occurred while attempting to handle an exception coming from " + (context == null ? "a null Context" : "the Context from class with name '" + context.getClass().getName()) + "'", otherThrowable);
}
return false;
}
}
/**
* Indicates whether a redirection is required before letting the activity continue its life cycle. It launches the redirected {@link Activity} if a
* redirection is need, and provide to its {@link Intent} the initial activity {@link Intent} trough the extra {@link Parcelable}
* {@link ActivityController#CALLING_INTENT} key.
* <p>
* <p>
* If the provided {@code activity} implements the {@link ActivityController.EscapeToRedirector} interface or exposes the
* {@link ActivityController.EscapeToRedirectorAnnotation} annotation, the method returns {@code false}.
* </p>
* <p>
* <p>
* Note that this method does not need to be marked as {@code synchronized}, because it is supposed to be invoked systematically from the UI thread.
* </p>
*
* @param activity the activity which is being proved against the {@link ActivityController.Redirector}
* @return {@code true} if and only if the given activity should be paused (or ended) and if another activity should be launched instead through the
* {@link Activity#startActivity(Intent)} method
* @see ActivityController#extractCallingIntent(Activity)
* @see ActivityController.Redirector#getRedirection(Activity)
* @see ActivityController.EscapeToRedirector
* @see ActivityController.EscapeToRedirectorAnnotation
*/
public boolean needsRedirection(Activity activity)
{
if (redirector == null)
{
return false;
}
if (activity instanceof ActivityController.EscapeToRedirector || activity.getClass().getAnnotation(ActivityController.EscapeToRedirectorAnnotation.class) != null)
{
if (log.isDebugEnabled())
{
log.debug("The Activity with class '" + activity.getClass().getName() + "' is escaped regarding the Redirector");
}
return false;
}
final Intent intent = redirector.getRedirection(activity);
if (intent == null)
{
return false;
}
if (log.isDebugEnabled())
{
log.debug("A redirection is needed");
}
// We redirect to the right Activity
{
// We consider the parent activity in case it is embedded (like in an ActivityGroup)
final Intent formerIntent = activity.getParent() != null ? activity.getParent().getIntent() : activity.getIntent();
intent.putExtra(ActivityController.CALLING_INTENT, formerIntent);
// Disables the fact that the new started activity should belong to the tasks history and from the recent tasks
// intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
// intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
activity.startActivity(intent);
}
// We now finish the redirected Activity
activity.finish();
return true;
}
}
|
package com.intellij.structuralsearch;
import com.intellij.lang.Language;
import com.intellij.openapi.fileTypes.*;
import com.intellij.psi.PsiElement;
import com.intellij.structuralsearch.impl.matcher.MatchUtils;
import com.intellij.structuralsearch.plugin.ui.Configuration;
import com.intellij.tokenindex.LanguageTokenizer;
import com.intellij.tokenindex.Tokenizer;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
/**
* @author Eugene.Kudelevsky
*/
public class StructuralSearchUtil {
private static LanguageFileType ourDefaultFileType = null;
public static boolean ourUseUniversalMatchingAlgorithm = false;
private static StructuralSearchProfile[] ourNewStyleProfiles;
private static List<Configuration> ourPredefinedConfigurations = null;
private StructuralSearchUtil() {}
@Nullable
public static StructuralSearchProfile getProfileByPsiElement(@NotNull PsiElement element) {
return getProfileByLanguage(element.getLanguage());
}
@Contract("null -> false")
public static boolean isIdentifier(PsiElement element) {
if (element == null) return false;
final StructuralSearchProfile profile = getProfileByPsiElement(element);
return profile != null && profile.isIdentifier(element);
}
private static StructuralSearchProfile[] getNewStyleProfiles() {
if (ourNewStyleProfiles == null) {
final List<StructuralSearchProfile> list = new ArrayList<StructuralSearchProfile>();
for (StructuralSearchProfile profile : StructuralSearchProfile.EP_NAME.getExtensions()) {
if (profile instanceof StructuralSearchProfileBase) {
list.add(profile);
}
}
list.add(new XmlStructuralSearchProfile());
ourNewStyleProfiles = list.toArray(new StructuralSearchProfile[list.size()]);
}
return ourNewStyleProfiles;
}
private static StructuralSearchProfile[] getProfiles() {
return ourUseUniversalMatchingAlgorithm
? getNewStyleProfiles()
: StructuralSearchProfile.EP_NAME.getExtensions();
}
public static FileType getDefaultFileType() {
if (ourDefaultFileType == null) {
for (StructuralSearchProfile profile : getProfiles()) {
ourDefaultFileType = profile.getDefaultFileType(ourDefaultFileType);
}
if (ourDefaultFileType == null) {
ourDefaultFileType = StdFileTypes.XML;
}
}
assert ourDefaultFileType instanceof LanguageFileType : "file type not valid for structural search: " + ourDefaultFileType.getName();
return ourDefaultFileType;
}
@Nullable
public static StructuralSearchProfile getProfileByLanguage(@NotNull Language language) {
for (StructuralSearchProfile profile : getProfiles()) {
if (profile.isMyLanguage(language)) {
return profile;
}
}
return null;
}
@Nullable
public static Tokenizer getTokenizerForLanguage(@NotNull Language language) {
return LanguageTokenizer.INSTANCE.forLanguage(language);
}
public static boolean isTypedVariable(@NotNull final String name) {
return name.length() > 1 && name.charAt(0)=='$' && name.charAt(name.length()-1)=='$';
}
@Nullable
public static StructuralSearchProfile getProfileByFileType(FileType fileType) {
for (StructuralSearchProfile profile : getProfiles()) {
if (profile.canProcess(fileType)) {
return profile;
}
}
return null;
}
@NotNull
public static FileType[] getSuitableFileTypes() {
Set<FileType> allFileTypes = new HashSet<FileType>();
Collections.addAll(allFileTypes, FileTypeManager.getInstance().getRegisteredFileTypes());
for (Language language : Language.getRegisteredLanguages()) {
FileType fileType = language.getAssociatedFileType();
if (fileType != null) {
allFileTypes.add(fileType);
}
}
List<FileType> result = new ArrayList<FileType>();
for (FileType fileType : allFileTypes) {
if (fileType instanceof LanguageFileType) {
result.add(fileType);
}
}
return result.toArray(new FileType[result.size()]);
}
public static String shieldSpecialChars(String word) {
final StringBuilder buf = new StringBuilder(word.length());
for (int i = 0; i < word.length(); ++i) {
if (MatchUtils.SPECIAL_CHARS.indexOf(word.charAt(i)) != -1) {
buf.append("\\");
}
buf.append(word.charAt(i));
}
return buf.toString();
}
public static List<Configuration> getPredefinedTemplates() {
if (ourPredefinedConfigurations == null) {
final List<Configuration> result = new ArrayList<Configuration>();
for (StructuralSearchProfile profile : getProfiles()) {
Collections.addAll(result, profile.getPredefinedTemplates());
}
Collections.sort(result);
ourPredefinedConfigurations = Collections.unmodifiableList(result);
}
return ourPredefinedConfigurations;
}
public static boolean isDocCommentOwner(PsiElement match) {
final StructuralSearchProfile profile = getProfileByPsiElement(match);
return profile != null && profile.isDocCommentOwner(match);
}
}
|
package Sprites;
import javafx.scene.image.*;
import tankattack.*;
/**
*
* @author Ruslan
*/
public class Boss extends Enemy {
public static String imageName = "boss.png";
public Boss(double x, double y, World world) {
super(Boss.imageName, x, y, world);
// health, width parent, height parent, isEnemy
this.initHealthBar(2000.0, this.width(), this.height(), true);
}
@Override
public void updateEnemyXY() {
if (!isAlive) {
return;
}
double playerLocation = this.world.playerSprite.getTranslateX();
boolean isPlayerToTheRightOfBoss = (playerLocation > this.getTranslateX());
// TODO
if (isPlayerToTheRightOfBoss) {
goRight();
}
else {
goLeft();
}
}
@Override
public boolean isFiring() {
if (isAlive) {
return (Math.random() <= .13);
}
else {
return false;
}
}
@Override
public void displayDeath() {
this.setImage(new Image(getClass().getResourceAsStream("bossDeath.png")));
this.isAlive = false;
}
private void goRight() {
this.setTranslateX(this.getTranslateX() + TankAttack.BOSS_SPEED);
}
private void goLeft() {
this.setTranslateX(this.getTranslateX() - TankAttack.BOSS_SPEED);
}
}
|
package org.curriki.xwiki.plugin.asset.composite;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.web.XWikiMessageTool;
import com.xpn.xwiki.api.Document;
import com.xpn.xwiki.objects.BaseObject;
import org.curriki.xwiki.plugin.asset.Asset;
import org.curriki.xwiki.plugin.asset.Constants;
import org.curriki.xwiki.plugin.asset.AssetException;
import org.curriki.xwiki.plugin.asset.other.ProtectedAsset;
import org.curriki.xwiki.plugin.asset.other.InvalidAsset;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Collections;
import java.util.Iterator;
public abstract class CompositeAsset extends Asset {
private static final Log LOG = LogFactory.getLog(RootCollectionCompositeAsset.class);
public CompositeAsset(XWikiDocument doc, XWikiContext context) {
super(doc, context);
}
protected void initSubType() throws XWikiException {
super.initSubType();
BaseObject obj = doc.newObject(Constants.COMPOSITE_ASSET_CLASS, context);
obj.setStringValue(Constants.COMPOSITE_ASSET_CLASS_TYPE, compositeAssetType());
determineCategory();
setDefaultContent();
}
protected void setDefaultContent() throws XWikiException {
assertCanEdit();
doc.setContent(Constants.COMPOSITE_ASSET_COMPOSITE_CONTENT);
}
abstract protected String compositeAssetType();
public Map<String,Object> getCompositeInfo() {
Map<String,Object> docInfo = new HashMap<String, Object>();
// displayTitle
docInfo.put("displayTitle", getDisplayTitle());
// description
docInfo.put("description", getDescription());
// collection type
use(Constants.COMPOSITE_ASSET_CLASS);
docInfo.put("collectionType", getValue(Constants.COMPOSITE_ASSET_CLASS_TYPE));
docInfo.put("assetType", determineAssetSubtype().getSimpleName().replaceAll("Asset$", ""));
// access rights
docInfo.put("rights", getRightsList());
// Children
List<Map<String,Object>> subList = getSubassetsInfo();
if (subList.size() > 0) {
docInfo.put("children", subList);
}
return docInfo;
}
public List<Map<String, Object>> getSubassetsInfo() {
List<BaseObject> objs = doc.getObjects(Constants.SUBASSET_CLASS);
if (objs != null ) {
List<Map<String,Object>> subList = new ArrayList<Map<String,Object>>(objs.size());
for (BaseObject obj : objs) {
if (obj != null) {
String subPage = obj.getStringValue(Constants.SUBASSET_CLASS_PAGE);
Map<String,Object> subInfo = new HashMap<String, Object>(6);
subInfo.put(Constants.SUBASSET_CLASS_PAGE, subPage);
subInfo.put(Constants.SUBASSET_CLASS_ORDER, obj.getLongValue(Constants.SUBASSET_CLASS_ORDER));
com.xpn.xwiki.api.XWiki xwikiApi = new com.xpn.xwiki.api.XWiki(context.getWiki(), context);
try {
Document doc = xwikiApi.getDocument(subPage);
if (doc instanceof Asset) {
subInfo.put("displayTitle", doc.getDisplayTitle());
subInfo.put("description", ((Asset) doc).getDescription());
subInfo.put("assetType", ((Asset) doc).determineAssetSubtype().getSimpleName().replaceAll("Asset$", ""));
subInfo.put("rights", ((Asset) doc).getRightsList());
} else if (doc == null) {
// getDocument returns null if the page is not viewable by the user
subInfo.put("displayTitle", "");
subInfo.put("description", "");
subInfo.put("assetType", ProtectedAsset.class.getSimpleName().replaceAll("Asset$", ""));
Map<String,Boolean> rightsInfo = new HashMap<String, Boolean>();
rightsInfo.put("view", false);
rightsInfo.put("edit", false);
rightsInfo.put("delete", false);
subInfo.put("rights", rightsInfo);
}
} catch (Exception e) {
subInfo.put("displayTitle", "");
subInfo.put("description", "");
subInfo.put("assetType", InvalidAsset.class.getSimpleName().replaceAll("Asset$", ""));
Map<String,Boolean> rightsInfo = new HashMap<String, Boolean>();
rightsInfo.put("view", false);
rightsInfo.put("edit", false);
rightsInfo.put("delete", false);
subInfo.put("rights", rightsInfo);
}
subList.add(subInfo);
}
}
Collections.sort(subList, new Comparator<Map<String,Object>>(){
public int compare(Map<String,Object> s1, Map<String,Object> s2){
return ((Long) s1.get(Constants.SUBASSET_CLASS_ORDER)).compareTo((Long) s2.get(Constants.SUBASSET_CLASS_ORDER));
}
});
return subList;
}
return new ArrayList<Map<String,Object>>(1);
}
public List<String> getSubassetList() {
List<BaseObject> objs = doc.getObjects(Constants.SUBASSET_CLASS);
if (objs != null && objs.size() > 0) {
objs = sortSubassetList(objs);
List<String> list = new ArrayList<String>();
for (BaseObject obj : objs){
if (obj != null) {
list.add(obj.getStringValue(Constants.SUBASSET_CLASS_PAGE));
}
}
return filterViewablePages(list);
}
return new ArrayList<String>();
}
protected List<BaseObject> sortSubassetList(List<BaseObject> list) {
if (list != null && list.size() > 0) {
Collections.sort(list, new Comparator<BaseObject>(){
public int compare(BaseObject s1, BaseObject s2){
if (s1 == null) {
return s2 == null ? 0 : -1;
} else if (s2 == null) {
return 1;
}
Long c1 = s1.getLongValue(Constants.SUBASSET_CLASS_ORDER);
Long c2 = s2.getLongValue(Constants.SUBASSET_CLASS_ORDER);
if (c1 == null) {
return c2 == null ? 0 : -1;
} else if (c2 == null) {
return 1;
}
return (c1.compareTo(c2));
}
});
}
return list;
}
public Map<String,Object> getSubassetInfo(long subassetId) throws AssetException {
List<BaseObject> objs = doc.getObjects(Constants.SUBASSET_CLASS);
Map<String,Object> subInfo = new HashMap<String, Object>(5);
if (objs != null) {
for (BaseObject obj : objs){
if (obj != null) {
String subPage = obj.getStringValue(Constants.SUBASSET_CLASS_PAGE);
Long order = obj.getLongValue(Constants.SUBASSET_CLASS_ORDER);
if (order.equals(subassetId)) {
subInfo.put(Constants.SUBASSET_CLASS_PAGE, subPage);
subInfo.put(Constants.SUBASSET_CLASS_ORDER, order);
com.xpn.xwiki.api.XWiki xwikiApi = new com.xpn.xwiki.api.XWiki(context.getWiki(), context);
try {
Document doc = xwikiApi.getDocument(subPage);
if (doc instanceof Asset) {
subInfo.put("displayTitle", doc.getDisplayTitle());
subInfo.put("description", ((Asset) doc).getDescription());
subInfo.put("assetType", ((Asset) doc).determineAssetSubtype().getSimpleName().replaceAll("Asset$", ""));
} else {
subInfo.put("error", "Subasset does not exist");
}
} catch (Exception e) {
subInfo.put("error", "Subasset does not exist");
}
return subInfo;
}
}
}
}
throw new AssetException(AssetException.ERROR_ASSET_SUBASSET_NOTFOUND, "No subasset exists with the order number "+subassetId);
}
public long insertSubassetBefore(String page, String beforePage) throws XWikiException {
if (beforePage == null){
return addSubasset(page);
}
List<BaseObject> objs = doc.getObjects(Constants.SUBASSET_CLASS);
Long beforePosition = null;
if (objs != null) {
for (BaseObject obj : objs) {
if (obj != null) {
String objName = obj.getStringValue(Constants.SUBASSET_CLASS_PAGE);
if (objName.equals(beforePage)){
beforePosition = obj.getLongValue(Constants.SUBASSET_CLASS_ORDER);
}
}
}
}
return insertSubassetAt(page, beforePosition);
}
public long insertSubassetAt(String page, Long atPosition) throws XWikiException {
if (atPosition == null || atPosition == -1){
return addSubasset(page);
}
relocateAssets(atPosition);
createSubasset(page, atPosition);
return atPosition;
}
protected void relocateAssets(long freePosition) throws XWikiException {
List<BaseObject> objs = doc.getObjects(Constants.SUBASSET_CLASS);
if (objs == null) {
return ;
}
for (BaseObject obj : objs) {
if (obj != null) {
long objPos = obj.getLongValue(Constants.SUBASSET_CLASS_ORDER);
if (objPos >= freePosition) {
obj.setLongValue(Constants.SUBASSET_CLASS_ORDER, objPos + 1);
}
}
}
}
public long addSubasset(String page) throws XWikiException {
Long highestOrder = getLastPosition() + 1;
createSubasset(page, highestOrder);
return highestOrder;
}
public void createSubasset(String page, Long position) throws XWikiException {
com.xpn.xwiki.api.XWiki xwikiApi = new com.xpn.xwiki.api.XWiki(context.getWiki(), context);
try {
Document subAsset = xwikiApi.getDocument(page);
if (subAsset instanceof Asset) {
// Do not allow ancestor to be added as a sub-asset
boolean done = false;
List<String> searchFor = new ArrayList<String>();
searchFor.add(doc.getFullName());
while (!done){
String sql = null;
for (String item : searchFor) {
if (item.equals(page)) {
XWikiMessageTool msg = (XWikiMessageTool) context.get("msg");
throw new AssetException(AssetException.ERROR_ASSET_SUBASSET_RECURSION, msg.get("addsubasset.recursive_add_message"));
}
if (sql != null) {
sql = sql + ", '" + item + "'";
} else {
sql = "'" + item + "'";
}
}
sql = ", BaseObject as obj, StringProperty as prop where obj.name=doc.fullName and obj.className='XWiki.SubAssetClass' and prop.id.id = obj.id and prop.name='assetpage' and prop.value in (" + sql + ")";
List<String> list = context.getWiki().getStore().searchDocumentsNames(sql, context);
if ((list==null)||(list.size()==0)){
done = true;
} else {
searchFor = list;
}
}
// Is not being added to itself
BaseObject obj = doc.newObject(Constants.SUBASSET_CLASS, context);
obj.setStringValue(Constants.SUBASSET_CLASS_PAGE, subAsset.getFullName());
obj.setLongValue(Constants.SUBASSET_CLASS_ORDER, position);
} else {
throw new AssetException(AssetException.ERROR_ASSET_SUBASSET_NOTFOUND, "Subasset to add does not exist");
}
} catch (Exception e) {
throw new AssetException(AssetException.ERROR_ASSET_SUBASSET_NOTFOUND, "Subasset to add does not exist");
}
}
public void reorder(List<String> orig, List<String> want) throws XWikiException {
List<String> cur = getSubassetList();
// Check that the original list matches the current list
int i = 0;
for (String page : cur){
if (!page.equals(orig.get(i))){
throw new AssetException(AssetException.ERROR_ASSET_REORDER_NOTMATCH, "Original list does not match current list");
}
++i;
}
// This may seem a bit convoluted, but a simple delete all subassets and add new list seems to sometimes get a
// "Error number 3211 in 3: Exception while saving object <pagename>
// deleted instance passed to update(): [com.xpn.xwiki.objects.BaseObject#<null>]"
// exception from hibernate.
XWikiDocument assetDoc = getDoc();
List<BaseObject> existing = assetDoc.getObjects(Constants.SUBASSET_CLASS);
for (BaseObject b : existing) {
if (b != null) {
b.setLongValue(Constants.SUBASSET_CLASS_ORDER, -2);
}
}
long j = 0;
for (String page : want) {
// Set order for exisiting item or add a new item
boolean found = false;
for (BaseObject b : existing) {
if (b != null && b.getStringValue(Constants.SUBASSET_CLASS_PAGE).equals(page) && b.getLongValue(Constants.SUBASSET_CLASS_ORDER) == -2) {
// Put in new order location
b.setLongValue(Constants.SUBASSET_CLASS_ORDER, j);
j += 1;
found = true;
break;
}
}
if (!found) {
// Add as it doesn't already exist in the list
BaseObject sub = assetDoc.newObject(Constants.SUBASSET_CLASS, context);
sub.setStringValue(Constants.SUBASSET_CLASS_PAGE, page);
sub.setLongValue(Constants.SUBASSET_CLASS_ORDER, j);
j += 1;
}
}
// Now remove anything left
/*
List removeList = new ArrayList();
for (Iterator<BaseObject> ei = existing.iterator(); ei.hasNext(); ) {
BaseObject b = ei.next();
if (b != null && b.getLongValue(Constants.SUBASSET_CLASS_ORDER) == -2) {
removeList.add(b);
}
}
for (Iterator<BaseObject> eid = removeList.iterator(); eid.hasNext(); ) {
assetDoc.removeObject(eid.next());
}
*/
}
protected long getLastPosition() {
List<BaseObject> objs = doc.getObjects(Constants.SUBASSET_CLASS);
long highestOrder = (long) -1;
if (objs != null) {
for (BaseObject obj : objs) {
if (obj != null) {
long objOrder = obj.getLongValue(Constants.SUBASSET_CLASS_ORDER);
if (objOrder > highestOrder) {
highestOrder = objOrder;
}
}
}
}
return highestOrder;
}
protected List<String> filterViewablePages(List<String> pageList) {
List<String> results = new ArrayList<String>();
if (pageList!=null) {
for (String page : pageList) {
try {
if (context.getWiki().getRightService().hasAccessLevel("view", context.getUser(), page, context) && context.getWiki().exists(page, context)) {
results.add(page);
}
} catch (XWikiException e) {
// Ignore exception -- just don't add to result list
LOG.error("Error filtering collections", e);
}
}
}
return results;
}
protected void determineCategory() throws XWikiException {
BaseObject obj = doc.getObject(Constants.ASSET_CLASS);
if (obj != null) {
obj.setStringValue(Constants.ASSET_CLASS_CATEGORY, Constants.CATEGORY_COLLECTION);
}
}
}
|
package florian_haas.lucas.database.impl;
import java.lang.reflect.ParameterizedType;
import java.math.BigDecimal;
import java.util.*;
import javax.inject.Named;
import javax.persistence.*;
import javax.persistence.criteria.*;
import javax.persistence.metamodel.*;
import florian_haas.lucas.database.*;
import florian_haas.lucas.model.EntityBase;
import florian_haas.lucas.util.TriFunction;
@Named
public abstract class ReadOnlyDAOImpl<E extends EntityBase> implements ReadOnlyDAO<E> {
@PersistenceContext
protected EntityManager manager;
protected final Class<E> entityClass;
@SuppressWarnings("unchecked")
protected ReadOnlyDAOImpl() {
entityClass = (Class<E>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
@Override
public EntityManager getEntityManager() {
return manager;
}
@Override
public Class<E> getEntityClass() {
return entityClass;
}
@Override
public List<E> findAll() {
return readOnlyJPQLQuery("SELECT e FROM " + entityClass.getSimpleName() + " e");
}
@Override
public E findById(Long id) {
return manager.find(getEntityClass(), id);
}
@Override
public Boolean exists(Long id) {
return manager.createQuery("SELECT COUNT(e.id) FROM " + entityClass.getSimpleName() + " e WHERE e.id=:id", Long.class).getSingleResult() > 0;
}
@Override
public E refresh(E entity) {
manager.refresh(entity);
return entity;
}
public List<E> readOnlyJPQLQuery(String jpql, Object... params) {
TypedQuery<E> query = manager.createQuery(jpql, entityClass);
for (int i = 0; i < params.length; i++) {
query.setParameter(i + 1, params[i]);
}
return query.getResultList();
}
public List<E> readOnlyCriteriaQuery(TriFunction<CriteriaQuery<E>, Root<E>, CriteriaBuilder, Predicate[]> restrictions) {
CriteriaBuilder builder = manager.getCriteriaBuilder();
CriteriaQuery<E> query = builder.createQuery(entityClass);
Root<E> root = query.from(entityClass);
query.select(root).where(restrictions.apply(query, root, builder));
return manager.createQuery(query).getResultList();
}
@SuppressWarnings("unchecked")
protected final <T extends Comparable<? super T>> Predicate getSingularRestriction(SingularAttribute<? super E, T> attribute, T value,
EnumQueryComparator comparator, CriteriaBuilder builder, Path<E> path) {
Expression<T> comparableExpression = path.get(attribute);
if (comparator == null) comparator = EnumQueryComparator.EQUAL;
switch (comparator) {
case EQUAL:
if (value instanceof BigDecimal) {
return builder.and(builder.not(builder.greaterThan(comparableExpression, value)),
builder.not(builder.lessThan(comparableExpression, value)));
} else {
return builder.equal(comparableExpression, value);
}
case GREATHER_EQUAL:
return builder.greaterThanOrEqualTo(comparableExpression, value);
case GREATHER_THAN:
return builder.greaterThan(comparableExpression, value);
case LESS_EQUAL:
return builder.lessThanOrEqualTo(comparableExpression, value);
case LESS_THAN:
return builder.lessThan(comparableExpression, value);
case NOT_EQUAL:
return builder.notEqual(comparableExpression, value);
case LIKE:
if (value instanceof String) { return builder.like((Expression<String>) (Expression<?>) comparableExpression, (String) value); }
case NOT_LIKE:
if (value instanceof String) { return builder.notLike((Expression<String>) (Expression<?>) comparableExpression, (String) value); }
default:
return null;
}
}
protected final <T extends Comparable<? super T>> void getSingularRestriction(SingularAttribute<? super E, T> attribute, T value,
Boolean useValue, EnumQueryComparator comparator, List<Predicate> list, CriteriaBuilder builder, Path<E> path) {
if (useValue) {
Predicate val = getSingularRestriction(attribute, value, comparator, builder, path);
if (val != null) {
list.add(val);
}
}
}
@SuppressWarnings("hiding")
protected final <V, C extends Collection<V>, E extends EntityBase> List<Predicate> getPluralRestriction(PluralAttribute<E, C, V> attribute,
C value, EnumQueryComparator comparator, CriteriaBuilder builder, Root<E> root) {
List<Predicate> predicates = new ArrayList<>();
Expression<C> expression = root.get(attribute);
if (comparator == null) comparator = EnumQueryComparator.EQUAL;
switch (comparator) {
case MEMBER_OF:
if (value == null) {
predicates.add(builder.isEmpty(expression));
} else {
value.forEach(val -> {
predicates.add(builder.isMember(val, expression));
});
}
return predicates;
case NOT_MEMBER_OF:
if (value == null) {
predicates.add(builder.isNotEmpty(expression));
} else {
value.forEach(val -> {
predicates.add(builder.isNotMember(val, expression));
});
}
return predicates;
default:
return predicates;
}
}
@SuppressWarnings("hiding")
protected final <V, C extends Collection<V>, E extends EntityBase> void getPluralRestriction(PluralAttribute<E, C, V> attribute, C value,
Boolean useValue, EnumQueryComparator comparator, List<Predicate> list, CriteriaBuilder builder, Root<E> root) {
if (useValue) list.addAll(getPluralRestriction(attribute, value, comparator, builder, root));
}
}
|
package org.jetbrains.idea.svn.dialogs.browserCache;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.svn.browse.DirectoryEntry;
import java.util.List;
import java.util.Map;
public class SvnRepositoryCache {
private final Map<String, List<DirectoryEntry>> myMap = ContainerUtil.createSoftMap();
private final Map<String, String> myErrorsMap = ContainerUtil.createSoftMap();
public static SvnRepositoryCache getInstance() {
return ServiceManager.getService(SvnRepositoryCache.class);
}
private SvnRepositoryCache() {
}
@Nullable
public List<DirectoryEntry> getChildren(final String parent) {
return myMap.get(parent);
}
@Nullable
public String getError(final String parent) {
return myErrorsMap.get(parent);
}
public void put(final String parent, final String error) {
myMap.remove(parent);
myErrorsMap.put(parent, error);
}
public void put(final String parent, List<DirectoryEntry> children) {
myErrorsMap.remove(parent);
myMap.put(parent, children);
}
public void remove(final String parent) {
myErrorsMap.remove(parent);
myMap.remove(parent);
}
}
|
package com.charlesmadere.hummingbird.views;
import android.content.Context;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;
import com.charlesmadere.hummingbird.R;
import com.charlesmadere.hummingbird.misc.TypefaceStore;
import com.charlesmadere.hummingbird.models.AppNewsStatus;
import com.charlesmadere.hummingbird.models.TypefaceEntry;
import com.charlesmadere.hummingbird.preferences.Preference;
import com.charlesmadere.hummingbird.preferences.Preferences;
public class AppNewsDrawerTextView extends AppCompatTextView implements
Preference.OnPreferenceChangeListener<AppNewsStatus> {
public AppNewsDrawerTextView(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
public AppNewsDrawerTextView(final Context context, final AttributeSet attrs,
final int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (isInEditMode()) {
return;
}
Preferences.Misc.AppNewsAvailability.addListener(this);
refreshImportantNewsBadge();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (isInEditMode()) {
return;
}
Preferences.Misc.AppNewsAvailability.removeListener(this);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
if (isInEditMode()) {
return;
}
setTypeface(TypefaceStore.get(TypefaceEntry.OPEN_SANS_SEMIBOLD));
Preferences.Misc.AppNewsAvailability.addListener(this);
refreshImportantNewsBadge();
}
@Override
public void onPreferenceChange(final Preference<AppNewsStatus> preference) {
refreshImportantNewsBadge();
}
private void refreshImportantNewsBadge() {
final AppNewsStatus appNewsStatus = Preferences.Misc.AppNewsAvailability.get();
setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, appNewsStatus != null &&
appNewsStatus.isImportantNewsAvailable() ? R.drawable.badge : 0, 0);
}
}
|
package com.metamx.druid.merger.coordinator;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.metamx.common.IAE;
import com.metamx.common.guava.Comparators;
import com.metamx.common.guava.FunctionalIterable;
import com.metamx.druid.merger.common.TaskLock;
import com.metamx.druid.merger.common.task.Task;
import com.metamx.emitter.EmittingLogger;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.locks.ReentrantLock;
/**
* Remembers which tasks have locked which intervals. Tasks are permitted to lock an interval if no other task
* outside their group has locked an overlapping interval for the same datasource. When a task locks an interval,
* it is assigned a version string that it can use to publish segments.
*/
public class TaskLockbox
{
// Datasource -> Interval -> Tasks + TaskLock
private final Map<String, NavigableMap<Interval, TaskLockPosse>> running = Maps.newHashMap();
private final TaskStorage taskStorage;
private final ReentrantLock giant = new ReentrantLock();
private static final EmittingLogger log = new EmittingLogger(TaskLockbox.class);
public TaskLockbox(TaskStorage taskStorage)
{
this.taskStorage = taskStorage;
}
/**
* Attempt to lock a task, without removing it from the queue. Equivalent to the long form of {@code tryLock}
* with no preferred version.
*
* @param task task to attempt to lock
*
* @return lock version if lock was acquired, absent otherwise
*/
public Optional<TaskLock> tryLock(final Task task, final Interval interval)
{
return tryLock(task, interval, Optional.<String>absent());
}
/**
* Attempt to lock a task, without removing it from the queue. Can safely be called multiple times on the same task.
* This method will attempt to assign version strings that obey the invariant that every version string is
* lexicographically greater than any other version string previously assigned to the same interval. This invariant
* is only mostly guaranteed, however; we assume clock monotonicity and we assume that callers specifying
* {@code preferredVersion} are doing the right thing.
*
* @param task task to attempt to lock
* @param preferredVersion use this version string if one has not yet been assigned
*
* @return lock version if lock was acquired, absent otherwise
*/
public Optional<TaskLock> tryLock(final Task task, final Interval interval, final Optional<String> preferredVersion)
{
giant.lock();
try {
if(task.getFixedInterval().isPresent() && !task.getFixedInterval().get().equals(interval)) {
// Task may only lock its fixed interval, if present
throw new IAE("Task must lock its fixed interval: %s", task.getId());
}
final String dataSource = task.getDataSource();
final List<TaskLockPosse> foundPosses = findLockPossesForInterval(dataSource, interval);
final TaskLockPosse posseToUse;
if (foundPosses.size() > 1) {
// Too many existing locks.
return Optional.absent();
} else if (foundPosses.size() == 1) {
// One existing lock -- check if we can add to it.
final TaskLockPosse foundPosse = Iterables.getOnlyElement(foundPosses);
if (foundPosse.getTaskLock().getInterval().contains(interval) && foundPosse.getTaskLock().getGroupId().equals(task.getGroupId())) {
posseToUse = foundPosse;
} else {
return Optional.absent();
}
} else {
// No existing locks. We can make a new one.
if (!running.containsKey(dataSource)) {
running.put(dataSource, new TreeMap<Interval, TaskLockPosse>(Comparators.intervalsByStartThenEnd()));
}
// Create new TaskLock and assign it a version.
// Assumption: We'll choose a version that is greater than any previously-chosen version for our interval. (This
// may not always be true, unfortunately. See below.)
final String version;
if (preferredVersion.isPresent()) {
// We have a preferred version. We'll trust our caller to not break our ordering assumptions and just use it.
version = preferredVersion.get();
} else {
// We are running under an interval lock right now, so just using the current time works as long as we can trust
// our clock to be monotonic and have enough resolution since the last time we created a TaskLock for the same
// interval. This may not always be true; to assure it we would need to use some method of timekeeping other
// than the wall clock.
version = new DateTime().toString();
}
posseToUse = new TaskLockPosse(new TaskLock(task.getGroupId(), dataSource, interval, version));
running.get(dataSource)
.put(interval, posseToUse);
log.info("Created new TaskLockPosse: %s", posseToUse);
}
// Add to existing TaskLockPosse, if necessary
if (posseToUse.getTaskIds().add(task.getId())) {
log.info("Added task[%s] to TaskLock[%s]", task.getId(), posseToUse.getTaskLock().getGroupId());
// Best effort to update task storage facility
try {
taskStorage.addLock(task.getId(), posseToUse.getTaskLock());
} catch(Exception e) {
log.makeAlert("Failed to persist lock in storage")
.addData("task", task.getId())
.addData("dataSource", posseToUse.getTaskLock().getDataSource())
.addData("interval", posseToUse.getTaskLock().getInterval())
.addData("version", posseToUse.getTaskLock().getVersion())
.emit();
}
} else {
log.info("Task[%s] already present in TaskLock[%s]", task.getId(), posseToUse.getTaskLock().getGroupId());
}
return Optional.of(posseToUse.getTaskLock());
}
finally {
giant.unlock();
}
}
/**
* Return the currently-active locks for some task.
*
* @param task task for which to locate locks
*/
public List<TaskLock> findLocksForTask(final Task task)
{
giant.lock();
try {
return Lists.transform(
findLockPossesForTask(task), new Function<TaskLockPosse, TaskLock>()
{
@Override
public TaskLock apply(TaskLockPosse taskLockPosse)
{
return taskLockPosse.getTaskLock();
}
}
);
} finally {
giant.unlock();
}
}
/**
* Release lock held for a task on a particular interval. Does nothing if the task does not currently
* hold the mentioned lock.
*
* @param task task to unlock
* @param interval interval to unlock
*/
public void unlock(final Task task, final Interval interval)
{
giant.lock();
try {
final String dataSource = task.getDataSource();
final NavigableMap<Interval, TaskLockPosse> dsRunning = running.get(dataSource);
// So we can alert if tasks try to release stuff they don't have
boolean removed = false;
if(dsRunning != null) {
final TaskLockPosse taskLockPosse = dsRunning.get(interval);
if(taskLockPosse != null) {
final TaskLock taskLock = taskLockPosse.getTaskLock();
// Remove task from live list
log.info("Removing task[%s] from TaskLock[%s]", task.getId(), taskLock.getGroupId());
removed = taskLockPosse.getTaskIds().remove(task.getId());
if (taskLockPosse.getTaskIds().isEmpty()) {
log.info("TaskLock is now empty: %s", taskLock);
running.get(dataSource).remove(taskLock.getInterval());
}
if (running.get(dataSource).size() == 0) {
running.remove(dataSource);
}
// Best effort to remove lock from storage
try {
taskStorage.removeLock(task.getId(), taskLock);
} catch(Exception e) {
log.makeAlert(e, "Failed to clean up lock from storage")
.addData("task", task.getId())
.addData("dataSource", taskLock.getDataSource())
.addData("interval", taskLock.getInterval())
.addData("version", taskLock.getVersion())
.emit();
}
}
}
if(!removed) {
log.makeAlert("Lock release without acquire")
.addData("task", task.getId())
.addData("interval", interval)
.emit();
}
} finally {
giant.unlock();
}
}
/**
* Release all locks for a task. Does nothing if the task is not currently locked.
*
* @param task task to unlock
*/
public void unlock(final Task task)
{
giant.lock();
try {
for(final TaskLockPosse taskLockPosse : findLockPossesForTask(task)) {
unlock(task, taskLockPosse.getTaskLock().getInterval());
}
}
finally {
giant.unlock();
}
}
/**
* Removes all locks from this lockbox.
*/
public void clear()
{
giant.lock();
try {
running.clear();
} finally {
giant.unlock();
}
}
/**
* Return the currently-active lock posses for some task.
*
* @param task task for which to locate locks
*/
private List<TaskLockPosse> findLockPossesForTask(final Task task)
{
giant.lock();
try {
final Iterable<TaskLockPosse> searchSpace;
if (task.getFixedInterval().isPresent()) {
// Narrow down search using findLockPossesForInterval
searchSpace = findLockPossesForInterval(task.getDataSource(), task.getFixedInterval().get());
} else {
// Scan through all locks for this datasource
final NavigableMap<Interval, TaskLockPosse> dsRunning = running.get(task.getDataSource());
if(dsRunning == null) {
searchSpace = ImmutableList.of();
} else {
searchSpace = dsRunning.values();
}
}
return ImmutableList.copyOf(
Iterables.filter(
searchSpace, new Predicate<TaskLockPosse>()
{
@Override
public boolean apply(TaskLockPosse taskLock)
{
return taskLock.getTaskIds().contains(task.getId());
}
}
)
);
}
finally {
giant.unlock();
}
}
/**
* Return all locks that overlap some search interval.
*/
private List<TaskLockPosse> findLockPossesForInterval(final String dataSource, final Interval interval)
{
giant.lock();
try {
final NavigableMap<Interval, TaskLockPosse> dsRunning = running.get(dataSource);
if (dsRunning == null) {
// No locks at all
return Collections.emptyList();
} else {
// Tasks are indexed by locked interval, which are sorted by interval start. Intervals are non-overlapping, so:
final NavigableSet<Interval> dsLockbox = dsRunning.navigableKeySet();
final Iterable<Interval> searchIntervals = Iterables.concat(
// Single interval that starts at or before ours
Collections.singletonList(dsLockbox.floor(new Interval(interval.getStart(), new DateTime(Long.MAX_VALUE)))),
// All intervals that start somewhere between our start instant (exclusive) and end instant (exclusive)
dsLockbox.subSet(
new Interval(interval.getStart(), new DateTime(Long.MAX_VALUE)),
false,
new Interval(interval.getEnd(), interval.getEnd()),
false
)
);
return Lists.newArrayList(
FunctionalIterable
.create(searchIntervals)
.filter(
new Predicate<Interval>()
{
@Override
public boolean apply(@Nullable Interval searchInterval)
{
return searchInterval != null && searchInterval.overlaps(interval);
}
}
)
.transform(
new Function<Interval, TaskLockPosse>()
{
@Override
public TaskLockPosse apply(Interval interval)
{
return dsRunning.get(interval);
}
}
)
);
}
}
finally {
giant.unlock();
}
}
private static class TaskLockPosse
{
final private TaskLock taskLock;
final private Set<String> taskIds;
public TaskLockPosse(TaskLock taskLock)
{
this.taskLock = taskLock;
taskIds = Sets.newHashSet();
}
public TaskLock getTaskLock()
{
return taskLock;
}
public Set<String> getTaskIds()
{
return taskIds;
}
@Override
public String toString()
{
return Objects.toStringHelper(this)
.add("taskLock", taskLock)
.add("taskIds", taskIds)
.toString();
}
}
}
|
package org.asynchttpclient.providers.netty.ws;
import org.asynchttpclient.websocket.WebSocket;
import org.asynchttpclient.websocket.WebSocketByteListener;
import org.asynchttpclient.websocket.WebSocketCloseCodeReasonListener;
import org.asynchttpclient.websocket.WebSocketListener;
import org.asynchttpclient.websocket.WebSocketTextListener;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.util.concurrent.ConcurrentLinkedQueue;
import static io.netty.buffer.Unpooled.wrappedBuffer;
public class NettyWebSocket implements WebSocket {
private final static Logger logger = LoggerFactory.getLogger(NettyWebSocket.class);
private final Channel channel;
private final ConcurrentLinkedQueue<WebSocketListener> listeners = new ConcurrentLinkedQueue<WebSocketListener>();
private final StringBuilder textBuffer = new StringBuilder();
private final ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
private int maxBufferSize = 128000000;
public NettyWebSocket(Channel channel) {
this.channel = channel;
}
@Override
public WebSocket sendMessage(byte[] message) {
channel.writeAndFlush(new BinaryWebSocketFrame(wrappedBuffer(message)));
return this;
}
@Override
public WebSocket stream(byte[] fragment, boolean last) {
throw new UnsupportedOperationException("Streaming currently only supported by the Grizzly provider.");
}
@Override
public WebSocket stream(byte[] fragment, int offset, int len, boolean last) {
throw new UnsupportedOperationException("Streaming currently only supported by the Grizzly provider.");
}
@Override
public WebSocket sendTextMessage(String message) {
channel.writeAndFlush(new TextWebSocketFrame(message));
return this;
}
@Override
public WebSocket streamText(String fragment, boolean last) {
throw new UnsupportedOperationException("Streaming currently only supported by the Grizzly provider.");
}
@Override
public WebSocket sendPing(byte[] payload) {
channel.writeAndFlush(new PingWebSocketFrame(wrappedBuffer(payload)));
return this;
}
@Override
public WebSocket sendPong(byte[] payload) {
channel.writeAndFlush(new PongWebSocketFrame(wrappedBuffer(payload)));
return this;
}
@Override
public WebSocket addWebSocketListener(WebSocketListener l) {
listeners.add(l);
return this;
}
@Override
public WebSocket removeWebSocketListener(WebSocketListener l) {
listeners.remove(l);
return this;
}
public int getMaxBufferSize() {
return maxBufferSize;
}
public void setMaxBufferSize(int bufferSize) {
maxBufferSize = bufferSize;
if (maxBufferSize < 8192)
maxBufferSize = 8192;
}
@Override
public boolean isOpen() {
return channel.isOpen();
}
@Override
public void close() {
onClose();
listeners.clear();
try {
channel.writeAndFlush(new CloseWebSocketFrame());
channel.closeFuture().awaitUninterruptibly();
} finally {
channel.close();
}
}
public void close(int statusCode, String reason) {
onClose(statusCode, reason);
listeners.clear();
try {
channel.writeAndFlush(new CloseWebSocketFrame());
channel.closeFuture().awaitUninterruptibly();
} finally {
channel.close();
}
}
public void onBinaryFragment(byte[] message, boolean last) {
if (!last) {
try {
byteBuffer.write(message);
} catch (Exception ex) {
byteBuffer.reset();
onError(ex);
return;
}
if (byteBuffer.size() > maxBufferSize) {
byteBuffer.reset();
Exception e = new Exception("Exceeded Netty Web Socket maximum buffer size of " + getMaxBufferSize());
onError(e);
this.close();
return;
}
}
for (WebSocketListener l : listeners) {
if (l instanceof WebSocketByteListener) {
try {
if (!last) {
WebSocketByteListener.class.cast(l).onFragment(message, last);
} else {
if (byteBuffer.size() > 0) {
byteBuffer.write(message);
WebSocketByteListener.class.cast(l).onFragment(message, last);
WebSocketByteListener.class.cast(l).onMessage(byteBuffer.toByteArray());
} else {
WebSocketByteListener.class.cast(l).onMessage(message);
}
}
} catch (Exception ex) {
l.onError(ex);
}
}
}
if (last) {
byteBuffer.reset();
}
}
public void onTextFragment(String message, boolean last) {
if (!last) {
textBuffer.append(message);
if (textBuffer.length() > maxBufferSize) {
textBuffer.setLength(0);
Exception e = new Exception("Exceeded Netty Web Socket maximum buffer size of " + getMaxBufferSize());
onError(e);
this.close();
return;
}
}
for (WebSocketListener l : listeners) {
if (l instanceof WebSocketTextListener) {
try {
if (!last) {
WebSocketTextListener.class.cast(l).onFragment(message, last);
} else {
if (textBuffer.length() > 0) {
WebSocketTextListener.class.cast(l).onFragment(message, last);
WebSocketTextListener.class.cast(l).onMessage(textBuffer.append(message).toString());
} else {
WebSocketTextListener.class.cast(l).onMessage(message);
}
}
} catch (Exception ex) {
l.onError(ex);
}
}
}
if (last) {
textBuffer.setLength(0);
}
}
public void onError(Throwable t) {
for (WebSocketListener l : listeners) {
try {
l.onError(t);
} catch (Throwable t2) {
logger.error("", t2);
}
}
}
public void onClose() {
onClose(1000, "Normal closure; the connection successfully completed whatever purpose for which it was created.");
}
public void onClose(int code, String reason) {
for (WebSocketListener l : listeners) {
try {
if (l instanceof WebSocketCloseCodeReasonListener) {
WebSocketCloseCodeReasonListener.class.cast(l).onClose(this, code, reason);
}
l.onClose(this);
} catch (Throwable t) {
l.onError(t);
}
}
}
@Override
public String toString() {
return "NettyWebSocket{" + "channel=" + channel + '}';
}
}
|
package org.metafacture.io;
import static java.util.Objects.requireNonNull;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.function.Supplier;
import org.metafacture.framework.helpers.DefaultObjectReceiver;
/**
* Writes byte arrays to regular output files.
* <p>
* The module opens a new output file when it receives a <i>reset-stream</i>
* event. The {@link #setFileNameSupplier(Supplier)} enables users to specify
* a new file name on each invocation. the {@link #setAppendIfFileExists(boolean)}
* can be used to control whether existing files should be overwritten or
* appended to.
*/
public class ByteStreamFileWriter extends DefaultObjectReceiver<byte[]> {
private Supplier<File> fileNameSupplier;
private boolean appendIfFileExists;
private boolean flushAfterWrite;
private OutputStream outputStream;
/**
* Supplier for file names.
* <p>
* A new output file is created when {@link #process(byte[])} is called
* for the first time or whenever {@link #resetStream()} is called. The
* name of the new file is fetched from the {@code fileNameSupplier}.
* <p>
* There is no default value. A file name supplier must be specified.
* <p>
* This property can be changed anytime during processing. It becomes
* effective the next time a new output file is opened.
*
* @param fileNameSupplier a supplier that returns file names.
*/
public void setFileNameSupplier(Supplier<File> fileNameSupplier) {
this.fileNameSupplier = requireNonNull(fileNameSupplier);
}
/**
* Controls whether to open files in append mode if they exist.
* <p>
* The default value is {@code false}.
* <p>
* This property can be changed anytime during processing. It becomes
* effective the next time a new output file is opened.
*
* @param appendIfFileExists true if new data should be appended,
* false to overwrite the existing file.
*/
public void setAppendIfFileExists(boolean appendIfFileExists) {
this.appendIfFileExists = appendIfFileExists;
}
/**
* Controls whether the output stream is flushed after each write
* operation in {@link #process(byte[])}.
* <p>
* The default value is {@code false}.
* <p>
* This property can be changed anytime during processing. It becomes
* effective on the next invocation of {@link #process(byte[])}.
*
* @param flushAfterWrite true if the output stream should be flushed
* after every write.
*/
public void setFlushAfterWrite(boolean flushAfterWrite) {
this.flushAfterWrite = flushAfterWrite;
}
/**
* Writes {@code bytes} to file.
*
* @param bytes to write to file
* @throws WriteFailed if an IO error occurred
*/
@Override
public void process(final byte[] bytes) {
ensureOpenStream();
try {
outputStream.write(bytes);
if (flushAfterWrite) {
outputStream.flush();
}
} catch (IOException e) {
throw new WriteFailed("Error while writing bytes to output stream", e);
}
}
/**
* Opens a new output file.
*
* @throws CloseFailed if the current output file could not be closed.
* @throws OpenFailed if the new output file could not be opened.
*/
@Override
public void resetStream() {
closeStream();
ensureOpenStream();
}
/**
* Closes the current output file.
*
* @throws CloseFailed if the output file could not be closed.
*/
@Override
public void closeStream() {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
throw new CloseFailed("Error while closing output stream", e);
}
outputStream = null;
}
}
private void ensureOpenStream() {
if (outputStream != null) {
return;
}
try {
outputStream = new FileOutputStream(fileNameSupplier.get(), appendIfFileExists);
} catch (FileNotFoundException e) {
throw new OpenFailed("Cannot open output stream. File not found.", e);
}
}
}
|
//FILE: VirtualAcquisitionDisplay.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
// Arthur Edelstein, arthuredelstein@gmail.com
// This file is distributed in the hope that it will be useful,
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
package org.micromanager.imageDisplay;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import ij.CompositeImage;
import ij.ImagePlus;
import ij.ImageStack;
import ij.WindowManager;
import ij.gui.ImageCanvas;
import ij.gui.ImageWindow;
import ij.gui.ScrollbarWithLabel;
import ij.gui.StackWindow;
import ij.gui.Toolbar;
import ij.io.FileInfo;
import ij.measure.Calibration;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.prefs.Preferences;
import javax.swing.event.MouseInputAdapter;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import mmcorej.TaggedImage;
import org.json.JSONException;
import org.json.JSONObject;
import org.micromanager.MMStudioMainFrame;
import org.micromanager.acquisition.AcquisitionEngine;
import org.micromanager.acquisition.TaggedImageStorageDiskDefault;
import org.micromanager.acquisition.TaggedImageStorageMultipageTiff;
import org.micromanager.api.events.PixelSizeChangedEvent;
import org.micromanager.api.ImageCache;
import org.micromanager.api.ImageCacheListener;
import org.micromanager.api.ScriptInterface;
import org.micromanager.api.TaggedImageStorage;
import org.micromanager.events.EventManager;
import org.micromanager.graph.HistogramControlsState;
import org.micromanager.graph.HistogramSettings;
import org.micromanager.graph.MultiChannelHistograms;
import org.micromanager.graph.SingleChannelHistogram;
import org.micromanager.internalinterfaces.DisplayControls;
import org.micromanager.internalinterfaces.Histograms;
import org.micromanager.utils.CanvasPaintPending;
import org.micromanager.utils.ContrastSettings;
import org.micromanager.utils.FileDialogs;
import org.micromanager.utils.GUIUtils;
import org.micromanager.utils.JavaUtils;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.MMScriptException;
import org.micromanager.utils.ReportingUtils;
public class VirtualAcquisitionDisplay implements ImageCacheListener {
public static VirtualAcquisitionDisplay getDisplay(ImagePlus imgp) {
ImageStack stack = imgp.getStack();
if (stack instanceof AcquisitionVirtualStack) {
return ((AcquisitionVirtualStack) stack).getVirtualAcquisitionDisplay();
} else {
return null;
}
}
// This class is used to signal when the animation state of our display
// (potentially) changes.
public class AnimationSetEvent {
public boolean isAnimated_;
public AnimationSetEvent(boolean isAnimated) {
isAnimated_ = isAnimated;
}
}
private static final int ANIMATION_AND_LOCK_RESTART_DELAY = 800;
final ImageCache imageCache_;
final Preferences prefs_ = Preferences.userNodeForPackage(this.getClass());
private static final String SIMPLE_WIN_X = "simple_x";
private static final String SIMPLE_WIN_Y = "simple_y";
private AcquisitionEngine eng_;
private boolean finished_ = false;
private boolean promptToSave_ = true;
private String name_;
private long lastDisplayTime_;
private int lastFrameShown_ = 0;
private int lastSliceShown_ = 0;
private int lastPositionShown_ = 0;
private int lockedSlice_ = -1, lockedPosition_ = -1, lockedChannel_ = -1, lockedFrame_ = -1;;
private int numComponents_;
private ImagePlus hyperImage_;
private ScrollbarWithLabel pSelector_;
private ScrollbarWithLabel tSelector_;
private ScrollbarWithLabel zSelector_;
private ScrollbarWithLabel cSelector_;
private DisplayControls controls_;
public AcquisitionVirtualStack virtualStack_;
private boolean isSimpleDisplay_ = false;
private boolean mda_ = false; //flag if display corresponds to MD acquisition
private MetadataPanel mdPanel_;
private boolean contrastInitialized_ = false; //used for autostretching on window opening
private boolean firstImage_ = true;
private String channelGroup_ = "none";
private double framesPerSec_ = 7;
private java.util.Timer animationTimer_ = new java.util.Timer();
private boolean zAnimated_ = false, tAnimated_ = false;
private int animatedSliceIndex_ = -1, animatedFrameIndex_ = -1;
private Component zAnimationIcon_, pIcon_, tAnimationIcon_, cIcon_;
private Component zLockIcon_, cLockIcon_, pLockIcon_, tLockIcon_;
private Timer resetToLockedTimer_;
private Histograms histograms_;
private HistogramControlsState histogramControlsState_;
private boolean albumSaved_ = false;
private static double snapWinMag_ = -1;
private JPopupMenu saveTypePopup_;
private AtomicBoolean updatePixelSize_ = new AtomicBoolean(false);
private AtomicLong newPixelSize_ = new AtomicLong();
private final Object imageReceivedObject_ = new Object();
private EventBus bus_;
@Subscribe
public void onPixelSizeChanged(PixelSizeChangedEvent event) {
// Signal that pixel size has changed so that the next image will update
// metadata and scale bar
newPixelSize_.set(Double.doubleToLongBits(event.getNewPixelSizeUm()));
updatePixelSize_.set(true);
}
/**
* Constructor that doesn't provide a title; an automatically-generated one
* is used instead.
*/
public VirtualAcquisitionDisplay(ImageCache imageCache, AcquisitionEngine eng) {
this(imageCache, eng, WindowManager.getUniqueName("Untitled"));
setupEventBus();
}
/**
* Standard constructor.
*/
public VirtualAcquisitionDisplay(ImageCache imageCache, AcquisitionEngine eng, String name) {
name_ = name;
imageCache_ = imageCache;
eng_ = eng;
pSelector_ = createPositionScrollbar();
mda_ = eng != null;
this.albumSaved_ = imageCache.isFinished();
setupEventBus();
}
/**
* Create a new EventBus that will be used for all events related to this
* display system.
*/
private void setupEventBus() {
bus_ = new EventBus();
bus_.register(this);
}
// Retrieve our EventBus.
public EventBus getEventBus() {
return bus_;
}
// Prepare for a drawing event.
@Subscribe
public void onDraw(DrawEvent event) {
imageChangedUpdate();
}
/**
* This constructor is used for the Snap and Live views. The main
* differences:
* - eng_ is null
* - isSimpleDisplay_ is true
* - We subscribe to the "pixel size changed" event.
*/
@SuppressWarnings("LeakingThisInConstructor")
public VirtualAcquisitionDisplay(ImageCache imageCache, String name) throws MMScriptException {
isSimpleDisplay_ = true;
imageCache_ = imageCache;
name_ = name;
mda_ = false;
this.albumSaved_ = imageCache.isFinished();
setupEventBus();
// Also register us for pixel size change events on the global EventBus.
EventManager.register(this);
}
/**
* Extract a lot of fields from the provided metadata (or, failing that,
* from getSummaryMetadata()), and set up our controls and view window.
*/
private void startup(JSONObject firstImageMetadata, AcquisitionVirtualStack virtualStack) {
mdPanel_ = MMStudioMainFrame.getInstance().getMetadataPanel();
JSONObject summaryMetadata = getSummaryMetadata();
int numSlices = 1;
int numFrames = 1;
int numChannels = 1;
int numGrayChannels;
int numPositions = 1;
int width = 0;
int height = 0;
int numComponents = 1;
try {
int imageChannelIndex;
if (firstImageMetadata != null) {
width = MDUtils.getWidth(firstImageMetadata);
height = MDUtils.getHeight(firstImageMetadata);
try {
imageChannelIndex = MDUtils.getChannelIndex(firstImageMetadata);
} catch (JSONException e) {
imageChannelIndex = -1;
}
} else {
width = MDUtils.getWidth(summaryMetadata);
height = MDUtils.getHeight(summaryMetadata);
imageChannelIndex = -1;
}
numSlices = Math.max(summaryMetadata.getInt("Slices"), 1);
numFrames = Math.max(summaryMetadata.getInt("Frames"), 1);
numChannels = Math.max(1 + imageChannelIndex,
Math.max(summaryMetadata.getInt("Channels"), 1));
numPositions = Math.max(summaryMetadata.getInt("Positions"), 1);
numComponents = Math.max(MDUtils.getNumberOfComponents(summaryMetadata), 1);
} catch (JSONException e) {
ReportingUtils.showError(e);
} catch (MMScriptException e) {
ReportingUtils.showError(e);
}
numComponents_ = numComponents;
numGrayChannels = numComponents_ * numChannels;
if (imageCache_.getDisplayAndComments() == null ||
imageCache_.getDisplayAndComments().isNull("Channels")) {
try {
imageCache_.setDisplayAndComments(DisplaySettings.getDisplaySettingsFromSummary(summaryMetadata));
} catch (Exception ex) {
ReportingUtils.logError(ex, "Problem setting display and Comments");
}
}
int type = 0;
try {
if (firstImageMetadata != null) {
type = MDUtils.getSingleChannelType(firstImageMetadata);
} else {
type = MDUtils.getSingleChannelType(summaryMetadata);
}
} catch (JSONException ex) {
ReportingUtils.showError(ex, "Unable to determine acquisition type.");
} catch (MMScriptException ex) {
ReportingUtils.showError(ex, "Unable to determine acquisition type.");
}
if (virtualStack != null) {
virtualStack_ = virtualStack;
} else {
virtualStack_ = new AcquisitionVirtualStack(width, height, type, null,
imageCache_, numGrayChannels * numSlices * numFrames, this);
}
if (summaryMetadata.has("PositionIndex")) {
try {
virtualStack_.setPositionIndex(
MDUtils.getPositionIndex(summaryMetadata));
} catch (JSONException ex) {
ReportingUtils.logError(ex);
}
}
// Hack: allow controls_ to be already set, so that overriding classes
// can implement their own custom controls.
if (controls_ == null) {
if (isSimpleDisplay_) {
controls_ = new SimpleWindowControls(this, bus_);
} else {
controls_ = new HyperstackControls(this, bus_);
}
}
hyperImage_ = createHyperImage(createMMImagePlus(virtualStack_),
numGrayChannels, numSlices, numFrames, virtualStack_);
applyPixelSizeCalibration(hyperImage_);
histogramControlsState_ = mdPanel_.getContrastPanel().createDefaultControlsState();
createWindow();
windowToFront();
cSelector_ = getSelector("c");
if (!isSimpleDisplay_) {
tSelector_ = getSelector("t");
zSelector_ = getSelector("z");
if (imageCache_.lastAcquiredFrame() > 0) {
setNumFrames(1 + imageCache_.lastAcquiredFrame());
} else {
setNumFrames(1);
}
configureAnimationControls();
setNumPositions(numPositions);
}
updateAndDraw(true);
updateWindowTitleAndStatus();
forceControlsRepaint();
}
/*
* Set display to one of three modes:
* ij.CompositeImage.COMPOSITE
* ij.CompositeImage.GRAYSCALE
* ij.CompositeImage.COLOR
*/
public void setDisplayMode(int displayMode) {
mdPanel_.getContrastPanel().setDisplayMode(displayMode);
}
///////Scrollbars and animation controls section///////
/**
* Force all of our controls to repaint themselves, and block until they
* have finished doing so.
*/
private void forceControlsRepaint() {
Runnable forcePaint = new Runnable() {
@Override
public void run() {
if (zAnimationIcon_ != null) {
zAnimationIcon_.repaint();
}
if (tAnimationIcon_ != null) {
tAnimationIcon_.repaint();
}
if (tLockIcon_ != null) {
tLockIcon_.repaint();
}
if (cIcon_ != null) {
cIcon_.repaint();
}
if (cLockIcon_ != null) {
cLockIcon_.repaint();
}
if (zLockIcon_ != null) {
zLockIcon_.repaint();
}
if (pLockIcon_ != null) {
pLockIcon_.repaint();
}
if (controls_ != null) {
controls_.repaint();
}
if (pIcon_ != null && pIcon_.isValid()) {
pIcon_.repaint();
}
}
};
try {
GUIUtils.invokeAndWait(forcePaint);
} catch (InterruptedException ex) {
ReportingUtils.logError(ex);
} catch (InvocationTargetException ex) {
ReportingUtils.logError(ex);
}
}
/**
* Toggle animation of Z-slices on and off.
*/
private synchronized void setStackAnimation(final boolean shouldAnimate) {
if (!shouldAnimate) {
// Just shut down current animation.
animationTimer_.cancel();
setZAnimated(false);
refreshScrollbarIcons();
moveScrollBarsToLockedPositions();
} else {
// Disable timewise animation now.
setTimepointAnimation(false);
// Create a new animation timer that steps through Z.
setAnimationTimer(1, 0);
setZAnimated(true);
refreshScrollbarIcons();
}
}
/**
* As setStackAnimation, except that we animate across timepoints instead.
*/
private synchronized void setTimepointAnimation(final boolean shouldAnimate) {
if (!shouldAnimate) {
// Just shut down current animation.
animationTimer_.cancel();
setTAnimated(false);
refreshScrollbarIcons();
moveScrollBarsToLockedPositions();
} else {
// Disable stack animation now.
setStackAnimation(false);
// Create a new animation timer that steps through T.
setAnimationTimer(0, 1);
setTAnimated(true);
refreshScrollbarIcons();
}
}
/**
* Set up animationTimer_ to update our display according to the provided
* settings. As a general rule, one of zStep or tStep will be 0 and the
* other will be 1, but theoretically we could call this function to step
* backwards or to step through both "dimensions" at the same time.
*/
private synchronized void setAnimationTimer(final int zStep, final int tStep) {
animationTimer_ = new java.util.Timer();
final int framesPerStep;
long interval = (long) (1000.0 / framesPerSec_);
if (interval < 33) {
// Enforce a maximum displayed framerate of 30FPS, but skip over
// images to make the perceived animation faster.
interval = 33;
framesPerStep = (int) Math.round(framesPerSec_ * 33.0 / 1000.0);
} else {
framesPerStep = 1;
}
TimerTask task = new TimerTask() {
@Override
public void run() {
int channel = lockedChannel_ == -1 ? hyperImage_.getChannel() : lockedChannel_;
int slice = lockedSlice_ == -1 ? hyperImage_.getSlice() : lockedSlice_;
int frame = lockedFrame_ == -1 ? hyperImage_.getFrame() : lockedFrame_;
if (lockedSlice_ == -1 && zSelector_ != null) {
// Advance the slice position.
slice += framesPerStep * zStep;
if (slice >= zSelector_.getMaximum()) {
// Wrap around to the other end of the stack
slice = 1;
}
}
if (lockedFrame_ == -1 && tSelector_ != null) {
// Advance the timepoint position.
frame += framesPerStep * tStep;
if (frame >= tSelector_.getMaximum()) {
// Wrap around to the other end of the timeseries
frame = 1;
}
}
hyperImage_.setPosition(channel, slice, frame);
}
};
animationTimer_.schedule(task, 0, interval);
}
/**
* Repaint all of our icons related to the scrollbars. Non-blocking.
*/
private void refreshScrollbarIcons() {
if (zAnimationIcon_ != null) {
zAnimationIcon_.repaint();
}
if (tAnimationIcon_ != null) {
tAnimationIcon_.repaint();
}
if (zLockIcon_ != null) {
zLockIcon_.repaint();
}
if (cLockIcon_ != null) {
cLockIcon_.repaint();
}
if (pLockIcon_ != null) {
pLockIcon_.repaint();
}
if (tLockIcon_ != null) {
tLockIcon_.repaint();
}
}
/**
* Set up the handling of the animation buttons, to turn animation on and
* off for Z and Time.
*/
private void configureAnimationControls() {
if (zAnimationIcon_ != null) {
zAnimationIcon_.addMouseListener(new MouseInputAdapter() {
@Override
public void mousePressed(MouseEvent e) {
setStackAnimation(!zAnimated_);
}
});
}
if (tAnimationIcon_ != null) {
tAnimationIcon_.addMouseListener(new MouseInputAdapter() {
@Override
public void mousePressed(MouseEvent e) {
setTimepointAnimation(!tAnimated_);
}
});
}
}
/**
* Update the number of sites this display handles.
*/
private void setNumPositions(int n) {
if (isSimpleDisplay_) {
return;
}
pSelector_.setMinimum(0);
pSelector_.setMaximum(n);
ImageWindow win = hyperImage_.getWindow();
if (n > 1 && pSelector_.getParent() == null) {
// Make certain that the site selector scrollbar is displayed.
win.add(pSelector_, win.getComponentCount() - 1);
} else if (n <= 1 && pSelector_.getParent() != null) {
// Conversely, make certain the site selector scrollbar *isn't*
// displayed, because there's only one site.
win.remove(pSelector_);
}
win.pack();
}
/**
* Update the number of timepoints this display handles.
*/
private void setNumFrames(int n) {
if (isSimpleDisplay_) {
return;
}
if (tSelector_ != null) {
((IMMImagePlus) hyperImage_).setNFramesUnverified(n);
tSelector_.setMaximum(n + 1);
}
}
/**
* Update the number of Z slices this display handles.
*/
private void setNumSlices(int n) {
if (isSimpleDisplay_) {
return;
}
if (zSelector_ != null) {
((IMMImagePlus) hyperImage_).setNSlicesUnverified(n);
zSelector_.setMaximum(n + 1);
}
}
/**
* Update the number of channels this display handles.
*/
private void setNumChannels(int n) {
if (cSelector_ != null) {
((IMMImagePlus) hyperImage_).setNChannelsUnverified(n);
cSelector_.setMaximum(1 + n);
}
}
/**
* If animation was running prior to showImage, restarts it with sliders at
* appropriate positions.
*/
private void restartAnimation(int frame, int slice,
boolean areFramesAnimated, boolean areSlicesAnimated) {
if (areFramesAnimated) {
hyperImage_.setPosition(hyperImage_.getChannel(),
hyperImage_.getSlice(), frame + 1);
setTimepointAnimation(true);
} else if (areSlicesAnimated) {
hyperImage_.setPosition(hyperImage_.getChannel(),
slice + 1, hyperImage_.getFrame());
setStackAnimation(true);
}
animatedSliceIndex_ = -1;
animatedFrameIndex_ = -1;
}
/**
* Reset the positions of the scrollbars to where they were when they were
* locked.
*/
private void moveScrollBarsToLockedPositions() {
int c = lockedChannel_ == -1 ? hyperImage_.getChannel() : lockedChannel_;
int s = lockedSlice_ == -1 ? hyperImage_.getSlice() : lockedSlice_;
int f = lockedFrame_ == -1 ? hyperImage_.getFrame() : lockedFrame_;
hyperImage_.setPosition(c,
zAnimated_ ? hyperImage_.getSlice() : s,
tAnimated_ ? hyperImage_.getFrame() : f);
if (pSelector_ != null && lockedPosition_ > -1) {
setPosition(lockedPosition_);
}
}
/**
* If we have active locks, set up a timer to reset our scrollbars to their
* locked positions if no new images arrive within
* ANIMATION_AND_LOCK_RESTART_DELAY milliseconds.
*/
private void resumeLocksAndAnimationAfterImageArrival() {
//if no locks activated or previous animation running, dont execute
if (lockedFrame_ == -1 && lockedChannel_ == -1 && lockedSlice_ == -1 &&
lockedPosition_ == -1 && animatedSliceIndex_ == -1 &&
animatedFrameIndex_ == -1) {
return;
}
//If no new images have arrived for some time, reset to locked positions
if (resetToLockedTimer_ == null) {
// Create a new timer to perform the reset after the specified delay.
resetToLockedTimer_ = new Timer(ANIMATION_AND_LOCK_RESTART_DELAY,
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
moveScrollBarsToLockedPositions();
restartAnimation(animatedFrameIndex_, animatedSliceIndex_,
animatedFrameIndex_ > -1,
animatedSliceIndex_ > -1);
resetToLockedTimer_.stop();
}
}
);
}
if (resetToLockedTimer_.isRunning()) {
// Already have a timer running; just reset its time-to-wait.
resetToLockedTimer_.restart();
} else {
resetToLockedTimer_.start();
}
}
/**
* Generate a scrollbar for navigating between the different
* timepoints/Z-slices/colors of the stack, as appropriate.
* @param label Label of the scrollbar; expected to be "t", "z", or "c".
* @return an ij.gui.ScrollbarWithLabel, with its events set up to adjust
* the appropriate view axis when scrolled.
*/
private ScrollbarWithLabel getSelector(String label) {
ScrollbarWithLabel selector = null;
ImageWindow win = hyperImage_.getWindow();
int slices = ((IMMImagePlus) hyperImage_).getNSlicesUnverified();
int frames = ((IMMImagePlus) hyperImage_).getNFramesUnverified();
int channels = ((IMMImagePlus) hyperImage_).getNChannelsUnverified();
if (win instanceof StackWindow) {
try {
//ImageJ bug workaround
if (frames > 1 && slices == 1 && channels == 1 && label.equals("t")) {
selector = (ScrollbarWithLabel) JavaUtils.getRestrictedFieldValue((StackWindow) win, StackWindow.class, "zSelector");
} else {
selector = (ScrollbarWithLabel) JavaUtils.getRestrictedFieldValue((StackWindow) win, StackWindow.class, label + "Selector");
}
} catch (NoSuchFieldException ex) {
selector = null;
ReportingUtils.logError(ex);
}
}
//replace default icon with custom one
if (selector != null) {
try {
Component icon = (Component) JavaUtils.getRestrictedFieldValue(
selector, ScrollbarWithLabel.class, "icon");
selector.remove(icon);
} catch (NoSuchFieldException ex) {
ReportingUtils.logError(ex);
}
ScrollbarAnimateIcon newIcon = new ScrollbarAnimateIcon(label.charAt(0), this);
if (label.equals("z")) {
zAnimationIcon_ = newIcon;
} else if (label.equals("t")) {
tAnimationIcon_ = newIcon;
} else if (label.equals("c")) {
cIcon_ = newIcon;
}
selector.add(newIcon, BorderLayout.WEST);
addSelectorLockIcon(selector, label);
//add adjustment so locks respond to mouse input
selector.addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
if (lockedSlice_ != -1) {
lockedSlice_ = zSelector_.getValue();
}
if (lockedChannel_ != -1) {
lockedChannel_ = cSelector_.getValue();
}
if (lockedFrame_ != -1) {
lockedFrame_ = tSelector_.getValue();
}
}
});
selector.invalidate();
selector.validate();
}
return selector;
}
private void addSelectorLockIcon(ScrollbarWithLabel selector, final String label) {
final ScrollbarLockIcon icon = new ScrollbarLockIcon(this, label);
selector.add(icon, BorderLayout.EAST);
if (label.equals("p")) {
pLockIcon_ = icon;
} else if (label.equals("z")) {
zLockIcon_ = icon;
} else if (label.equals("c")) {
cLockIcon_ = icon;
} else if (label.equals("t")) {
tLockIcon_ = icon;
}
icon.addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (label.equals("p")) {
if (lockedPosition_ == -1) {
lockedPosition_ = pSelector_.getValue();
} else {
lockedPosition_ = -1;
}
} else if (label.equals("z")) {
if (lockedSlice_ == -1) {
if (isZAnimated()) {
setStackAnimation(false);
}
lockedSlice_ = zSelector_.getValue();
} else {
lockedSlice_ = -1;
}
} else if (label.equals("c")) {
if (lockedChannel_ == -1) {
lockedChannel_ = cSelector_.getValue();
} else {
lockedChannel_ = -1;
}
} else if (label.equals("t")) {
if (lockedFrame_ == -1) {
lockedFrame_ = tSelector_.getValue();
} else {
lockedFrame_ = -1;
}
}
resumeLocksAndAnimationAfterImageArrival();
refreshScrollbarIcons();
}
});
}
//Used by icon to know hoe to paint itself
boolean isScrollbarLocked(String label) {
if (label.equals("z")) {
return lockedSlice_ > -1;
} else if (label.equals("c")) {
return lockedChannel_ > -1;
} else if (label.equals("p")) {
return lockedPosition_ > -1;
} else {
return lockedFrame_ > -1;
}
}
private ScrollbarWithLabel createPositionScrollbar() {
final ScrollbarWithLabel pSelector = new ScrollbarWithLabel(null, 1, 1, 1, 2, 'p') {
@Override
public void setValue(int v) {
if (this.getValue() != v) {
super.setValue(v);
updatePosition(v);
}
}
};
// prevents scroll bar from blinking on Windows:
pSelector.setFocusable(false);
pSelector.setUnitIncrement(1);
pSelector.setBlockIncrement(1);
pSelector.addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
if (lockedPosition_ != -1) {
lockedPosition_ = pSelector_.getValue();
}
updatePosition(pSelector.getValue());
}
});
try {
Component icon = (Component) JavaUtils.getRestrictedFieldValue(
pSelector, ScrollbarWithLabel.class, "icon");
pSelector.remove(icon);
} catch (NoSuchFieldException ex) {
ReportingUtils.logError(ex);
}
pIcon_ = new ScrollbarAnimateIcon('p', this);
pSelector.add(pIcon_, BorderLayout.WEST);
addSelectorLockIcon(pSelector, "p");
pSelector.invalidate();
pSelector.validate();
return pSelector;
}
////////End of animation controls and scrollbars section///////////////////////
/**
* Allows bypassing the prompt to Save
* @param promptToSave boolean flag
*/
public void promptToSave(boolean promptToSave) {
promptToSave_ = promptToSave;
}
/**
* required by ImageCacheListener
* @param taggedImage
*/
@Override
public void imageReceived(final TaggedImage taggedImage) {
if (hyperImage_ == null) {
updateDisplay(taggedImage, false);
return;
}
if (!CanvasPaintPending.isMyPaintPending(hyperImage_.getCanvas(), imageReceivedObject_)) {
// If we do not sleep here, the window never updates
// I do not understand why, but this fixes it
try {
Thread.sleep(25);
} catch (InterruptedException ex) {
ReportingUtils.logError(ex, "Sleeping Thread was woken");
}
CanvasPaintPending.setPaintPending(hyperImage_.getCanvas(), imageReceivedObject_);
updateDisplay(taggedImage, false);
}
}
/**
* Method required by ImageCacheListener
* @param path
*/
@Override
public void imagingFinished(String path) {
updateDisplay(null, true);
updateAndDraw(true);
if (!(eng_ != null && eng_.abortRequested())) {
updateWindowTitleAndStatus();
}
}
private void updateDisplay(TaggedImage taggedImage, boolean finalUpdate) {
try {
long t = System.currentTimeMillis();
JSONObject tags;
if (taggedImage != null) {
tags = taggedImage.tags;
} else {
tags = imageCache_.getLastImageTags();
}
if (tags == null) {
return;
}
int frame = MDUtils.getFrameIndex(tags);
int ch = MDUtils.getChannelIndex(tags);
int slice = MDUtils.getSliceIndex(tags);
int position = MDUtils.getPositionIndex(tags);
int updateTime = 30;
//update display if: final update, frame is 0, more than 30 ms since last update,
//last channel for given frame/slice/position, or final slice and channel for first frame and position
boolean show = finalUpdate || frame == 0 || (Math.abs(t - lastDisplayTime_) > updateTime)
|| (ch == getNumChannels() - 1 && lastFrameShown_ == frame && lastSliceShown_ == slice && lastPositionShown_ == position)
|| (slice == getNumSlices() - 1 && frame == 0 && position == 0 && ch == getNumChannels() - 1);
if (show) {
showImage(tags, true);
lastFrameShown_ = frame;
lastSliceShown_ = slice;
lastPositionShown_ = position;
lastDisplayTime_ = t;
}
} catch (JSONException e) {
ReportingUtils.logError(e);
} catch (InterruptedException e) {
ReportingUtils.logError(e);
} catch (InvocationTargetException e) {
ReportingUtils.logError(e);
}
}
public int rgbToGrayChannel(int channelIndex) {
try {
if (MDUtils.getNumberOfComponents(imageCache_.getSummaryMetadata()) == 3) {
return channelIndex * 3;
}
return channelIndex;
} catch (MMScriptException ex) {
ReportingUtils.logError(ex);
return 0;
} catch (JSONException ex) {
ReportingUtils.logError(ex);
return 0;
}
}
public int grayToRGBChannel(int grayIndex) {
try {
if (imageCache_ != null) {
if (imageCache_.getSummaryMetadata() != null)
if (MDUtils.getNumberOfComponents(imageCache_.getSummaryMetadata()) == 3) {
return grayIndex / 3;
}
}
return grayIndex;
} catch (MMScriptException ex) {
ReportingUtils.logError(ex);
return 0;
} catch (JSONException ex) {
ReportingUtils.logError(ex);
return 0;
}
}
/**
* Sets ImageJ pixel size calibration
* @param hyperImage
*/
private void applyPixelSizeCalibration(final ImagePlus hyperImage) {
final String pixSizeTag = "PixelSizeUm";
try {
JSONObject tags = this.getCurrentMetadata();
JSONObject summary = getSummaryMetadata();
double pixSizeUm;
if (tags != null && tags.has(pixSizeTag)) {
pixSizeUm = tags.getDouble(pixSizeTag);
} else {
pixSizeUm = summary.getDouble("PixelSize_um");
}
if (pixSizeUm > 0) {
Calibration cal = new Calibration();
cal.setUnit("um");
cal.pixelWidth = pixSizeUm;
cal.pixelHeight = pixSizeUm;
String intMs = "Interval_ms";
if (summary.has(intMs))
cal.frameInterval = summary.getDouble(intMs) / 1000.0;
String zStepUm = "z-step_um";
if (summary.has(zStepUm))
cal.pixelDepth = summary.getDouble(zStepUm);
hyperImage.setCalibration(cal);
// this call is needed to update the top status line with image size
ImageWindow win = hyperImage.getWindow();
if (win != null) {
win.repaint();
}
}
} catch (JSONException ex) {
// no pixelsize defined. Nothing to do
}
}
public ImagePlus getHyperImage() {
return hyperImage_;
}
public int getStackSize() {
if (hyperImage_ == null) {
return -1;
}
int s = hyperImage_.getNSlices();
int c = hyperImage_.getNChannels();
int f = hyperImage_.getNFrames();
if ((s > 1 && c > 1) || (c > 1 && f > 1) || (f > 1 && s > 1)) {
return s * c * f;
}
return Math.max(Math.max(s, c), f);
}
private void imageChangedWindowUpdate() {
if (hyperImage_ != null && hyperImage_.isVisible()) {
JSONObject md = getCurrentMetadata();
if (md != null) {
controls_.newImageUpdate(md);
}
}
}
public void updateAndDraw(boolean force) {
imageChangedUpdate();
if (hyperImage_ != null && hyperImage_.isVisible()) {
if (hyperImage_ instanceof MMCompositeImage) {
((MMCompositeImage) hyperImage_).updateAndDraw(force);
} else {
hyperImage_.updateAndDraw();
}
}
}
public void updateWindowTitleAndStatus() {
if (isSimpleDisplay_) {
int mag = (int) (100 * hyperImage_.getCanvas().getMagnification());
String title = hyperImage_.getTitle() + " ("+mag+"%)";
hyperImage_.getWindow().setTitle(title);
return;
}
if (controls_ == null) {
return;
}
String status = "";
final AcquisitionEngine eng = eng_;
if (eng != null) {
if (acquisitionIsRunning()) {
if (!abortRequested()) {
controls_.acquiringImagesUpdate(true);
if (isPaused()) {
status = "paused";
} else {
status = "running";
}
} else {
controls_.acquiringImagesUpdate(false);
status = "interrupted";
}
} else {
controls_.acquiringImagesUpdate(false);
if (!status.contentEquals("interrupted")) {
if (eng.isFinished()) {
status = "finished";
eng_ = null;
}
}
}
status += ", ";
if (eng.isFinished()) {
eng_ = null;
finished_ = true;
}
} else {
if (finished_ == true) {
status = "finished, ";
}
controls_.acquiringImagesUpdate(false);
}
if (isDiskCached() || albumSaved_) {
status += "on disk";
} else {
status += "not yet saved";
}
controls_.imagesOnDiskUpdate(imageCache_.getDiskLocation() != null);
String path = isDiskCached()
? new File(imageCache_.getDiskLocation()).getName() : name_;
if (hyperImage_.isVisible()) {
int mag = (int) (100 * hyperImage_.getCanvas().getMagnification());
hyperImage_.getWindow().setTitle(path + " (" + status + ") (" + mag + "%)" );
}
}
private void windowToFront() {
if (hyperImage_ == null || hyperImage_.getWindow() == null) {
return;
}
hyperImage_.getWindow().toFront();
}
/**
* Displays tagged image in the multi-D viewer
* Will wait for the screen update
*
* @param taggedImg
* @throws Exception
*/
public void showImage(TaggedImage taggedImg) throws Exception {
showImage(taggedImg, true);
}
/**
* Displays tagged image in the multi-D viewer
* Optionally waits for the display to draw the image
* *
* @param taggedImg
* @param waitForDisplay
* @throws java.lang.InterruptedException
* @throws java.lang.reflect.InvocationTargetException
*/
public void showImage(TaggedImage taggedImg, boolean waitForDisplay) throws InterruptedException, InvocationTargetException {
showImage(taggedImg.tags, waitForDisplay);
}
public void showImage(final JSONObject tags, boolean waitForDisplay) throws InterruptedException, InvocationTargetException {
SwingUtilities.invokeLater( new Runnable() {
@Override
public void run() {
updateWindowTitleAndStatus();
if (tags == null) {
return;
}
if (hyperImage_ == null) {
// this has to run on the EDT
startup(tags, null);
}
int channel = 0, frame = 0, slice = 0, position = 0, superChannel = 0;
try {
frame = MDUtils.getFrameIndex(tags);
slice = MDUtils.getSliceIndex(tags);
channel = MDUtils.getChannelIndex(tags);
position = MDUtils.getPositionIndex(tags);
superChannel = VirtualAcquisitionDisplay.this.rgbToGrayChannel(
MDUtils.getChannelIndex(tags));
} catch (JSONException ex) {
ReportingUtils.logError(ex);
}
// This block allows animation to be reset to where it was before
// images were added
if (isTAnimated()) {
animatedFrameIndex_ = hyperImage_.getFrame();
setTimepointAnimation(false);
}
if (isZAnimated()) {
animatedSliceIndex_ = hyperImage_.getSlice();
setStackAnimation(false);
}
//make sure pixels get properly set
if (hyperImage_ != null && frame == 0) {
IMMImagePlus img = (IMMImagePlus) hyperImage_;
if (img.getNChannelsUnverified() == 1) {
if (img.getNSlicesUnverified() == 1) {
hyperImage_.getProcessor().setPixels(virtualStack_.getPixels(1));
}
} else if (hyperImage_ instanceof MMCompositeImage) {
//reset rebuilds each of the channel ImageProcessors with the correct pixels
//from AcquisitionVirtualStack
MMCompositeImage ci = ((MMCompositeImage) hyperImage_);
ci.reset();
//This line is neccessary for image processor to have correct pixels in grayscale mode
ci.getProcessor().setPixels(virtualStack_.getPixels(ci.getCurrentSlice()));
}
} else if (hyperImage_ instanceof MMCompositeImage) {
MMCompositeImage ci = ((MMCompositeImage) hyperImage_);
ci.reset();
}
if (cSelector_ != null) {
if (cSelector_.getMaximum() <= (1 + superChannel)) {
VirtualAcquisitionDisplay.this.setNumChannels(1 + superChannel);
((CompositeImage) hyperImage_).reset();
//JavaUtils.invokeRestrictedMethod(hyperImage_, CompositeImage.class,
// "setupLuts", 1 + superChannel, Integer.TYPE);
}
}
if (!isSimpleDisplay_) {
if (tSelector_ != null) {
if (tSelector_.getMaximum() <= (1 + frame)) {
VirtualAcquisitionDisplay.this.setNumFrames(1 + frame);
}
}
if (position + 1 > getNumPositions()) {
setNumPositions(position + 1);
}
setPosition(position);
hyperImage_.setPosition(1 + superChannel, 1 + slice, 1 + frame);
}
if (frame == 0) {
initializeContrast();
}
//dont't force an update with live win
boolean forceUpdate = ! isSimpleDisplay_;
if (isSimpleDisplay_ && !MMStudioMainFrame.getInstance().isLiveModeOn()) {
//unless this is a snap or live mode has stopped
forceUpdate = true;
}
updateAndDraw(forceUpdate);
resumeLocksAndAnimationAfterImageArrival();
//get channelgroup name for use in loading contrast setttings
if (firstImage_) {
try {
channelGroup_ = tags.getString("Core-ChannelGroup");
} catch (JSONException ex) {
ReportingUtils.logError("Couldn't find Core-ChannelGroup in image metadata");
}
firstImage_ = false;
}
if (cSelector_ != null) {
if (histograms_.getNumberOfChannels() < (1 + superChannel)) {
if (histograms_ != null) {
histograms_.setupChannelControls(imageCache_);
}
}
}
}
});
}
private void initializeContrast() {
if (contrastInitialized_ ) {
return;
}
int numChannels = imageCache_.getNumDisplayChannels();
for (int channel = 0; channel < numChannels; channel++) {
String channelName = imageCache_.getChannelName(channel);
HistogramSettings settings = MMStudioMainFrame.getInstance().loadStoredChannelHisotgramSettings(
channelGroup_, channelName, mda_);
histograms_.setChannelContrast(channel, settings.min_, settings.max_, settings.gamma_);
histograms_.setChannelHistogramDisplayMax(channel, settings.histMax_);
if (imageCache_.getNumDisplayChannels() > 1) {
setDisplayMode(settings.displayMode_);
}
}
histograms_.applyLUTToImage();
contrastInitialized_ = true;
}
public void storeChannelHistogramSettings(int channelIndex, int min, int max,
double gamma, int histMax, int displayMode) {
if (!contrastInitialized_ ) {
return; //don't erroneously initialize c ontrast
}
//store for this dataset
imageCache_.storeChannelDisplaySettings(channelIndex, min, max, gamma, histMax, displayMode);
//store global preference for channel contrast settings
if (mda_ || isSimpleDisplay_) {
//only store for datasets that were just acquired or snap/live (i.e. no loaded datasets)
MMStudioMainFrame.getInstance().saveChannelHistogramSettings(channelGroup_,
imageCache_.getChannelName(channelIndex), mda_,
new HistogramSettings(min,max, gamma, histMax, displayMode));
}
}
private void updatePosition(int p) {
if (isSimpleDisplay_) {
return;
}
virtualStack_.setPositionIndex(p);
if (!hyperImage_.isComposite()) {
Object pixels = virtualStack_.getPixels(hyperImage_.getCurrentSlice());
hyperImage_.getProcessor().setPixels(pixels);
} else {
CompositeImage ci = (CompositeImage) hyperImage_;
if (ci.getMode() == CompositeImage.COMPOSITE) {
for (int i = 0; i < ((MMCompositeImage) ci).getNChannelsUnverified(); i++) {
//Dont need to set pixels if processor is null because it will get them from stack automatically
if (ci.getProcessor(i + 1) != null)
ci.getProcessor(i + 1).setPixels(virtualStack_.getPixels(ci.getCurrentSlice() - ci.getChannel() + i + 1));
}
}
ci.getProcessor().setPixels(virtualStack_.getPixels(hyperImage_.getCurrentSlice()));
}
//need to call this even though updateAndDraw also calls it to get autostretch to work properly
imageChangedUpdate();
updateAndDraw(true);
}
public void setPosition(int p) {
if (isSimpleDisplay_) {
return;
}
pSelector_.setValue(p);
}
public void setSliceIndex(int i) {
if (isSimpleDisplay_) {
return;
}
final int f = hyperImage_.getFrame();
final int c = hyperImage_.getChannel();
hyperImage_.setPosition(c, i + 1, f);
}
public int getSliceIndex() {
return hyperImage_.getSlice() - 1;
}
boolean pause() {
if (eng_ != null) {
if (eng_.isPaused()) {
eng_.setPause(false);
} else {
eng_.setPause(true);
}
updateWindowTitleAndStatus();
return (eng_.isPaused());
}
return false;
}
public boolean abort() {
if (eng_ != null) {
if (eng_.abortRequest()) {
updateWindowTitleAndStatus();
return true;
}
}
return false;
}
public boolean acquisitionIsRunning() {
if (eng_ != null) {
return eng_.isAcquisitionRunning();
} else {
return false;
}
}
public long getNextWakeTime() {
return eng_.getNextWakeTime();
}
public boolean abortRequested() {
if (eng_ != null) {
return eng_.abortRequested();
} else {
return false;
}
}
private boolean isPaused() {
if (eng_ != null) {
return eng_.isPaused();
} else {
return false;
}
}
public void albumChanged() {
albumSaved_ = false;
}
private Class createSaveTypePopup() {
if (saveTypePopup_ != null) {
saveTypePopup_.setVisible(false);
saveTypePopup_ = null;
}
final JPopupMenu menu = new JPopupMenu();
saveTypePopup_ = menu;
JMenuItem single = new JMenuItem("Save as separate image files");
JMenuItem multi = new JMenuItem("Save as image stack file");
JMenuItem cancel = new JMenuItem("Cancel");
menu.add(single);
menu.add(multi);
menu.addSeparator();
menu.add(cancel);
final AtomicInteger ai = new AtomicInteger(-1);
cancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ai.set(0);
}
});
single.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ai.set(1);
}
});
multi.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ai.set(2);
}
});
MouseInputAdapter highlighter = new MouseInputAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
((JMenuItem) e.getComponent()).setArmed(true);
}
@Override
public void mouseExited(MouseEvent e) {
((JMenuItem) e.getComponent()).setArmed(false);
}
};
single.addMouseListener(highlighter);
multi.addMouseListener(highlighter);
cancel.addMouseListener(highlighter);
Point mouseLocation = MouseInfo.getPointerInfo().getLocation();
menu.show(null, mouseLocation.x, mouseLocation.y);
while (ai.get() == -1) {
try {
Thread.sleep(10);
} catch (InterruptedException ex) {}
if (!menu.isVisible()) {
return null;
}
}
menu.setVisible(false);
saveTypePopup_ = null;
if (ai.get() == 0) {
return null;
} else if (ai.get() == 1) {
return TaggedImageStorageDiskDefault.class;
} else {
return TaggedImageStorageMultipageTiff.class;
}
}
boolean saveAs() {
return saveAs(null,true);
}
boolean saveAs(boolean pointToNewStorage) {
return saveAs(null, pointToNewStorage);
}
private boolean saveAs(Class<?> storageClass, boolean pointToNewStorage) {
if (eng_ != null && eng_.isAcquisitionRunning()) {
JOptionPane.showMessageDialog(null,
"Data can not be saved while acquisition is running.");
return false;
}
if (storageClass == null) {
storageClass = createSaveTypePopup();
}
if (storageClass == null) {
return false;
}
String prefix;
String root;
for (;;) {
File f = FileDialogs.save(hyperImage_.getWindow(),
"Please choose a location for the data set",
MMStudioMainFrame.MM_DATA_SET);
if (f == null) // Canceled.
{
return false;
}
prefix = f.getName();
root = new File(f.getParent()).getAbsolutePath();
if (f.exists()) {
ReportingUtils.showMessage(prefix
+ " is write only! Please choose another name.");
} else {
break;
}
}
try {
if (getSummaryMetadata() != null) {
getSummaryMetadata().put("Prefix", prefix);
}
TaggedImageStorage newFileManager =
(TaggedImageStorage) storageClass.getConstructor(
String.class, Boolean.class, JSONObject.class).newInstance(
root + "/" + prefix, true, getSummaryMetadata());
if (pointToNewStorage) {
albumSaved_ = true;
}
imageCache_.saveAs(newFileManager, pointToNewStorage);
} catch (IllegalAccessException ex) {
ReportingUtils.showError(ex, "Failed to save file");
} catch (IllegalArgumentException ex) {
ReportingUtils.showError(ex, "Failed to save file");
} catch (InstantiationException ex) {
ReportingUtils.showError(ex, "Failed to save file");
} catch (NoSuchMethodException ex) {
ReportingUtils.showError(ex, "Failed to save file");
} catch (SecurityException ex) {
ReportingUtils.showError(ex, "Failed to save file");
} catch (InvocationTargetException ex) {
ReportingUtils.showError(ex, "Failed to save file");
} catch (JSONException ex) {
ReportingUtils.showError(ex, "Failed to save file");
}
MMStudioMainFrame.getInstance().setAcqDirectory(root);
updateWindowTitleAndStatus();
return true;
}
final public MMImagePlus createMMImagePlus(AcquisitionVirtualStack virtualStack) {
MMImagePlus img = new MMImagePlus(imageCache_.getDiskLocation(),
virtualStack, virtualStack.getVirtualAcquisitionDisplay().getEventBus());
FileInfo fi = new FileInfo();
fi.width = virtualStack.getWidth();
fi.height = virtualStack.getHeight();
fi.fileName = virtualStack.getDirectory();
fi.url = null;
img.setFileInfo(fi);
return img;
}
final public ImagePlus createHyperImage(MMImagePlus mmIP, int channels, int slices,
int frames, final AcquisitionVirtualStack virtualStack) {
final ImagePlus hyperImage;
mmIP.setNChannelsUnverified(channels);
mmIP.setNFramesUnverified(frames);
mmIP.setNSlicesUnverified(slices);
if (channels > 1) {
hyperImage = new MMCompositeImage(mmIP, imageCache_.getDisplayMode(),
name_, bus_);
hyperImage.setOpenAsHyperStack(true);
} else {
hyperImage = mmIP;
mmIP.setOpenAsHyperStack(true);
}
return hyperImage;
}
public void liveModeEnabled(boolean enabled) {
if (isSimpleDisplay_) {
controls_.acquiringImagesUpdate(enabled);
}
}
private void createWindow() {
makeHistograms();
final DisplayWindow win = new DisplayWindow(hyperImage_, bus_);
win.getCanvas().addMouseListener(new MouseInputAdapter() {
//used to store preferred zoom
@Override
public void mousePressed(MouseEvent me) {
if (Toolbar.getToolId() == 11) {//zoom tool selected
storeWindowSizeAfterZoom(win);
}
updateWindowTitleAndStatus();
}
//updates the histogram after an ROI is drawn
@Override
public void mouseReleased(MouseEvent me) {
if (hyperImage_ instanceof MMCompositeImage) {
((MMCompositeImage) hyperImage_).updateAndDraw(true);
} else {
hyperImage_.updateAndDraw();
}
}
});
win.setBackground(MMStudioMainFrame.getInstance().getBackgroundColor());
MMStudioMainFrame.getInstance().addMMBackgroundListener(win);
win.add(controls_);
win.pack();
if (isSimpleDisplay_) {
win.setLocation(prefs_.getInt(SIMPLE_WIN_X, 0), prefs_.getInt(SIMPLE_WIN_Y, 0));
}
//Set magnification
zoomToPreferredSize(win);
mdPanel_.displayChanged(win);
imageChangedUpdate();
}
public void storeWindowSizeAfterZoom(ImageWindow win) {
if (isSimpleDisplay_) {
snapWinMag_ = win.getCanvas().getMagnification();
}
}
private void zoomToPreferredSize(DisplayWindow win) {
Point location = win.getLocation();
win.setLocation(new Point(0,0));
double mag;
if (isSimpleDisplay_ && snapWinMag_ != -1) {
mag = snapWinMag_;
} else {
mag = MMStudioMainFrame.getInstance().getPreferredWindowMag();
}
ImageCanvas canvas = win.getCanvas();
if (mag < canvas.getMagnification()) {
while (mag < canvas.getMagnification()) {
canvas.zoomOut(canvas.getWidth() / 2, canvas.getHeight() / 2);
}
} else if (mag > canvas.getMagnification()) {
while (mag > canvas.getMagnification()) {
canvas.zoomIn(canvas.getWidth() / 2, canvas.getHeight() / 2);
}
}
//Make sure the window is fully on the screen
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Point newLocation = new Point(location.x,location.y);
if (newLocation.x + win.getWidth() > screenSize.width && win.getWidth() < screenSize.width) {
newLocation.x = screenSize.width - win.getWidth();
}
if (newLocation.y + win.getHeight() > screenSize.height && win.getHeight() < screenSize.height) {
newLocation.y = screenSize.height - win.getHeight();
}
win.setLocation(newLocation);
}
// A window wants to close; check if it's okay. If it is, then we call its
// forceClosed() function.
// TODO: for now, assuming we only have one window.
@Subscribe
public void onWindowClose(DisplayWindow.WindowClosingEvent event) {
if (eng_ != null && eng_.isAcquisitionRunning()) {
if (!abort()) {
// Can't close now; the acquisition is still running.
return;
}
}
// Ask if the user wants to save data.
if (imageCache_.getDiskLocation() == null &&
promptToSave_ && !albumSaved_) {
String[] options = {"Save single", "Save multi", "No", "Cancel"};
int result = JOptionPane.showOptionDialog(
event.window_, "This data set has not yet been saved. " +
"Do you want to save it?\n" +
"Data can be saved as single-image files or multi-image files.",
"Micro-Manager",
JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null,
options, options[0]);
if (result == 0) {
if (!saveAs(TaggedImageStorageDiskDefault.class, true)) {
return;
}
} else if (result == 1) {
if (!saveAs(TaggedImageStorageMultipageTiff.class, true)) {
return;
}
} else if (result == 3) {
return;
}
}
// Record window position information.
if (isSimpleDisplay_ && hyperImage_ != null && hyperImage_.getWindow() != null &&
hyperImage_.getWindow().getLocation() != null) {
Point loc = hyperImage_.getWindow().getLocation();
prefs_.putInt(SIMPLE_WIN_X, loc.x);
prefs_.putInt(SIMPLE_WIN_Y, loc.y);
}
if (imageCache_ != null) {
imageCache_.close();
}
removeFromAcquisitionManager(MMStudioMainFrame.getInstance());
//Call this because for some reason WindowManager doesnt always fire
mdPanel_.displayChanged(null);
animationTimer_.cancel();
animationTimer_.cancel();
// Finally, tell the window to close now.
DisplayWindow window = event.window_;
window.forceClosed();
}
// Toggle one of our animation bits. Publish an event so our DisplayWindows
// (and anyone else who cares) can be notified.
private void setTAnimated(boolean isTAnimated) {
tAnimated_ = isTAnimated;
bus_.post(new AnimationSetEvent(isAnimated()));
}
// Toggle one of our animation bits. Publish an event so our DisplayWindows
// (and anyone else who cares) can be notified.
private void setZAnimated(boolean isZAnimated) {
zAnimated_ = isZAnimated;
bus_.post(new AnimationSetEvent(isAnimated()));
}
// Animation needs to be turned on/off.
@Subscribe
public void setAnimated(DisplayWindow.ToggleAnimatedEvent event) {
if (((IMMImagePlus) hyperImage_).getNFramesUnverified() > 1) {
setTimepointAnimation(event.shouldSetAnimated_);
} else {
setStackAnimation(event.shouldSetAnimated_);
}
}
/*
* Removes the VirtualAcquisitionDisplay from the Acquisition Manager.
*/
private void removeFromAcquisitionManager(ScriptInterface gui) {
try {
if (gui.acquisitionExists(name_)) {
gui.closeAcquisition(name_);
}
} catch (MMScriptException ex) {
ReportingUtils.logError(ex);
}
}
//Return metadata associated with image currently shown in the viewer
public JSONObject getCurrentMetadata() {
if (hyperImage_ != null) {
JSONObject md = virtualStack_.getImageTags(hyperImage_.getCurrentSlice());
return md;
} else {
return null;
}
}
public int getCurrentPosition() {
return virtualStack_.getPositionIndex();
}
public int getNumSlices() {
if (isSimpleDisplay_) {
return 1;
}
return hyperImage_ == null ? 1 : ((IMMImagePlus) hyperImage_).getNSlicesUnverified();
}
public int getNumFrames() {
if (isSimpleDisplay_) {
return 1;
}
return ((IMMImagePlus) hyperImage_).getNFramesUnverified();
}
public int getNumPositions() {
if (isSimpleDisplay_) {
return 1;
}
return pSelector_.getMaximum();
}
public ImagePlus getImagePlus() {
return hyperImage_;
}
public ImageCache getImageCache() {
return imageCache_;
}
public ImagePlus getImagePlus(int position) {
ImagePlus iP = new ImagePlus();
iP.setStack(virtualStack_);
iP.setDimensions(numComponents_ * getNumChannels(), getNumSlices(), getNumFrames());
iP.setFileInfo(hyperImage_.getFileInfo());
return iP;
}
public void setComment(String comment) throws MMScriptException {
try {
getSummaryMetadata().put("Comment", comment);
} catch (JSONException ex) {
ReportingUtils.logError(ex);
}
}
public final JSONObject getSummaryMetadata() {
return imageCache_.getSummaryMetadata();
}
/*
public final JSONObject getImageMetadata(int channel, int slice, int frame, int position) {
return imageCache_.getImageTags(channel, slice, frame, position);
}
*/
/**
* Closes the ImageWindow and associated ImagePlus
*
* @return false if canceled by user, true otherwise
*/
public boolean close() {
try {
if (hyperImage_ != null) {
if (!hyperImage_.getWindow().close()) {
return false;
}
hyperImage_.close();
}
} catch (NullPointerException npe) {
// instead of handing when exiting MM, log the issue
ReportingUtils.logError(npe);
}
return true;
}
public synchronized boolean windowClosed() {
if (hyperImage_ != null) {
ImageWindow win = hyperImage_.getWindow();
return (win == null || win.isClosed());
}
return true;
}
public void showFolder() {
if (isDiskCached()) {
try {
File location = new File(imageCache_.getDiskLocation());
if (JavaUtils.isWindows()) {
Runtime.getRuntime().exec("Explorer /n,/select," + location.getAbsolutePath());
} else if (JavaUtils.isMac()) {
if (!location.isDirectory()) {
location = location.getParentFile();
}
Runtime.getRuntime().exec("open " + location.getAbsolutePath());
}
} catch (IOException ex) {
ReportingUtils.logError(ex);
}
}
}
public void setPlaybackFPS(double fps) {
framesPerSec_ = fps;
if (zAnimated_ || tAnimated_) {
setTimepointAnimation(false);
setTimepointAnimation(true);
}
}
public double getPlaybackFPS() {
return framesPerSec_;
}
public boolean isZAnimated() {
return zAnimated_;
}
public boolean isTAnimated() {
return tAnimated_;
}
public boolean isAnimated() {
return isTAnimated() || isZAnimated();
}
public String getSummaryComment() {
return imageCache_.getComment();
}
public void setSummaryComment(String comment) {
imageCache_.setComment(comment);
}
void setImageComment(String comment) {
imageCache_.setImageComment(comment, getCurrentMetadata());
}
String getImageComment() {
try {
return imageCache_.getImageComment(getCurrentMetadata());
} catch (NullPointerException ex) {
return "";
}
}
public boolean isDiskCached() {
ImageCache imageCache = imageCache_;
if (imageCache == null) {
return false;
} else {
return imageCache.getDiskLocation() != null;
}
}
//This method exists in addition to the other show method
// so that plugins can utilize virtual acqusition display with a custom virtual stack
//allowing manipulation of displayed images without changing underlying data
//should probably be reconfigured to work through some sort of interface in the future
public void show(final AcquisitionVirtualStack virtualStack) {
if (hyperImage_ == null) {
try {
GUIUtils.invokeAndWait(new Runnable() {
@Override
public void run() {
startup(null, virtualStack);
}
});
} catch (InterruptedException ex) {
ReportingUtils.logError(ex);
} catch (InvocationTargetException ex) {
ReportingUtils.logError(ex);
}
}
hyperImage_.show();
hyperImage_.getWindow().toFront();
}
public void show() {
show(null);
}
public int getNumChannels() {
return hyperImage_ == null ? 1 : ((IMMImagePlus) hyperImage_).getNChannelsUnverified();
}
public int getNumGrayChannels() {
return getNumChannels();
}
public void setWindowTitle(String name) {
name_ = name;
updateWindowTitleAndStatus();
}
public boolean isSimpleDisplay() {
return isSimpleDisplay_;
}
public void displayStatusLine(String status) {
controls_.setStatusLabel(status);
}
public void setChannelContrast(int channelIndex, int min, int max, double gamma) {
histograms_.setChannelContrast(channelIndex, min, max, gamma);
histograms_.applyLUTToImage();
drawWithoutUpdate();
}
public void updateChannelNamesAndColors() {
if (histograms_ != null && histograms_ instanceof MultiChannelHistograms) {
((MultiChannelHistograms) histograms_).updateChannelNamesAndColors();
}
}
public void setChannelHistogramDisplayMax(int channelIndex, int histMax) {
histograms_.setChannelHistogramDisplayMax(channelIndex, histMax);
}
/*
* Called just before image is drawn. Notifies metadata panel to update
* metadata or comments if this display is the active window. Notifies histograms
* that image is change to create appropriate LUTs and to draw themselves if this
* is the active window
*/
private void imageChangedUpdate() {
boolean updatePixelSize = updatePixelSize_.get();
if (updatePixelSize) {
try {
JSONObject summary = getSummaryMetadata();
if (summary != null) {
summary.put("PixelSize_um", Double.longBitsToDouble(newPixelSize_.get()));
}
if (hyperImage_ != null) {
applyPixelSizeCalibration(hyperImage_);
}
} catch (JSONException ex) {
ReportingUtils.logError("Error in imageChangedUpdate in VirtualAcquisitionDisplay.java");
}
updatePixelSize_.set(false);
} else {
if (hyperImage_ != null) {
Calibration cal = hyperImage_.getCalibration();
double calPixSize = cal.pixelWidth;
JSONObject tags = this.getCurrentMetadata();
if (tags != null) {
try {
double imgPixSize = tags.getDouble("PixelSizeUm");
if (calPixSize != imgPixSize) {
applyPixelSizeCalibration(hyperImage_);
}
} catch (JSONException ex) {
ReportingUtils.logError("Found Image without PixelSizeUm tag");
}
}
}
}
if (histograms_ != null) {
histograms_.imageChanged();
}
if (isActiveDisplay()) {
mdPanel_.imageChangedUpdate(this);
if (updatePixelSize) {
mdPanel_.redrawSizeBar();
}
}
imageChangedWindowUpdate(); //used to update status line
}
public boolean isActiveDisplay() {
if (hyperImage_ == null || hyperImage_.getWindow() == null)
return false;
return hyperImage_.getWindow() == mdPanel_.getCurrentWindow();
}
/*
* Called when contrast changes as a result of user or programmtic input, but underlying pixels
* remain unchanges
*/
public void drawWithoutUpdate() {
if (hyperImage_ != null) {
((IMMImagePlus) hyperImage_).drawWithoutUpdate();
}
}
private void makeHistograms() {
if (getNumChannels() == 1 )
histograms_ = new SingleChannelHistogram(this);
else
histograms_ = new MultiChannelHistograms(this);
}
public Histograms getHistograms() {
return histograms_;
}
public HistogramControlsState getHistogramControlsState() {
return histogramControlsState_;
}
public void disableAutoStretchCheckBox() {
if (isActiveDisplay() ) {
mdPanel_.getContrastPanel().disableAutostretch();
} else {
histogramControlsState_.autostretch = false;
}
}
public ContrastSettings getChannelContrastSettings(int channel) {
return histograms_.getChannelContrastSettings(channel);
}
}
|
package org.apache.sandesha2.workers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPFault;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.AddressingConstants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ContextFactory;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.context.OperationContext;
import org.apache.axis2.context.ServiceContext;
import org.apache.axis2.description.AxisOperation;
import org.apache.axis2.engine.AxisEngine;
import org.apache.axis2.engine.Handler.InvocationResponse;
import org.apache.axis2.transport.RequestResponseTransport;
import org.apache.axis2.transport.TransportUtils;
import org.apache.axis2.transport.RequestResponseTransport.RequestResponseTransportStatus;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.axis2.wsdl.WSDLConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.sandesha2.RMMsgContext;
import org.apache.sandesha2.Sandesha2Constants;
import org.apache.sandesha2.SandeshaException;
import org.apache.sandesha2.i18n.SandeshaMessageHelper;
import org.apache.sandesha2.i18n.SandeshaMessageKeys;
import org.apache.sandesha2.policy.SandeshaPolicyBean;
import org.apache.sandesha2.storage.StorageManager;
import org.apache.sandesha2.storage.Transaction;
import org.apache.sandesha2.storage.beanmanagers.SenderBeanMgr;
import org.apache.sandesha2.storage.beans.RMSBean;
import org.apache.sandesha2.storage.beans.RMSequenceBean;
import org.apache.sandesha2.storage.beans.SenderBean;
import org.apache.sandesha2.util.AcknowledgementManager;
import org.apache.sandesha2.util.MessageRetransmissionAdjuster;
import org.apache.sandesha2.util.MsgInitializer;
import org.apache.sandesha2.util.SandeshaUtil;
import org.apache.sandesha2.util.SpecSpecificConstants;
import org.apache.sandesha2.util.TerminateManager;
import org.apache.sandesha2.wsrm.AckRequested;
import org.apache.sandesha2.wsrm.CloseSequence;
import org.apache.sandesha2.wsrm.Identifier;
import org.apache.sandesha2.wsrm.LastMessage;
import org.apache.sandesha2.wsrm.MessageNumber;
import org.apache.sandesha2.wsrm.Sequence;
import org.apache.sandesha2.wsrm.TerminateSequence;
public class SenderWorker extends SandeshaWorker implements Runnable {
private static final Log log = LogFactory.getLog(SenderWorker.class);
private ConfigurationContext configurationContext = null;
private SenderBean senderBean = null;
private RMMsgContext messageToSend = null;
private String rmVersion = null;
public SenderWorker (ConfigurationContext configurationContext, SenderBean senderBean, String rmVersion) {
this.configurationContext = configurationContext;
this.senderBean = senderBean;
this.rmVersion = rmVersion;
}
public void setMessage(RMMsgContext msg) {
this.messageToSend = msg;
}
public void run () {
if (log.isDebugEnabled())
log.debug("Enter: SenderWorker::run");
Transaction transaction = null;
try {
StorageManager storageManager = SandeshaUtil.getSandeshaStorageManager(configurationContext, configurationContext.getAxisConfiguration());
SenderBeanMgr senderBeanMgr = storageManager.getSenderBeanMgr();
transaction = storageManager.getTransaction();
String key = senderBean.getMessageContextRefKey();
MessageContext msgCtx = null;
RMMsgContext rmMsgCtx = null;
if(messageToSend != null) {
msgCtx = messageToSend.getMessageContext();
rmMsgCtx = messageToSend;
} else {
msgCtx = storageManager.retrieveMessageContext(key, configurationContext);
if (msgCtx == null) {
// This sender bean has already been processed
return;
}
rmMsgCtx = MsgInitializer.initializeMessage(msgCtx);
}
// sender will not send the message if following property is
// set and not true.
// But it will set if it is not set (null)
// This is used to make sure that the mesage get passed the
// Sandesha2TransportSender.
String qualifiedForSending = (String) msgCtx.getProperty(Sandesha2Constants.QUALIFIED_FOR_SENDING);
if (qualifiedForSending != null && !qualifiedForSending.equals(Sandesha2Constants.VALUE_TRUE)) {
if (log.isDebugEnabled())
log.debug("Exit: SenderWorker::run, !qualified for sending");
return;
}
if (msgCtx == null) {
if (log.isDebugEnabled())
log.debug(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.sendHasUnavailableMsgEntry));
return;
}
// operation is the lowest level Sandesha2 should be attached
ArrayList msgsNotToSend = SandeshaUtil.getPropertyBean(msgCtx.getAxisOperation()).getMsgTypesToDrop();
if (msgsNotToSend != null && msgsNotToSend.contains(new Integer(rmMsgCtx.getMessageType()))) {
if (log.isDebugEnabled())
log.debug("Exit: SenderWorker::run, message type to be dropped " + rmMsgCtx.getMessageType());
return;
}
// If we are sending to the anonymous URI then we _must_ have a transport waiting,
// or the message can't go anywhere. If there is nothing here then we leave the
// message in the sender queue, and a MakeConnection (or a retransmitted request)
// will hopefully pick it up soon.
RequestResponseTransport t = null;
Boolean makeConnection = (Boolean) msgCtx.getProperty(Sandesha2Constants.MAKE_CONNECTION_RESPONSE);
EndpointReference toEPR = msgCtx.getTo();
MessageContext inMsg = null;
OperationContext op = msgCtx.getOperationContext();
if (op != null)
inMsg = op.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
if (inMsg != null)
t = (RequestResponseTransport) inMsg.getProperty(RequestResponseTransport.TRANSPORT_CONTROL);
// If we are anonymous, and this is not a makeConnection, then we must have a transport waiting
if((toEPR==null || toEPR.hasAnonymousAddress()) &&
(makeConnection == null || !makeConnection.booleanValue()) &&
(t != null && !t.getStatus().equals(RequestResponseTransportStatus.WAITING))) {
// Mark this sender bean so that we know that the transport is unavailable, if the
// bean is still stored.
SenderBean bean = senderBeanMgr.retrieve(senderBean.getMessageID());
if(bean != null && bean.isTransportAvailable()) {
bean.setTransportAvailable(false);
senderBeanMgr.update(bean);
}
// Commit the update
if(transaction != null && transaction.isActive()) transaction.commit();
transaction = null;
if (log.isDebugEnabled())
log.debug("Exit: SenderWorker::run, no response transport for anonymous message");
return;
}
boolean continueSending = updateMessage(rmMsgCtx,senderBean,storageManager);
if (!continueSending) {
if (log.isDebugEnabled())
log.debug("Exit: SenderWorker::run, !continueSending");
return;
}
int messageType = senderBean.getMessageType();
if (isAckPiggybackableMsgType(messageType)) {
// Piggyback ack messages based on the 'To' address of the message
AcknowledgementManager.piggybackAcksIfPresent(rmMsgCtx, storageManager);
}
// sending the message
boolean successfullySent = false;
// have to commit the transaction before sending. This may
// get changed when WS-AT is available.
if(transaction != null) {
transaction.commit();
transaction = null;
transaction = storageManager.getTransaction();
}
// Although not actually sent yet, update the send count to indicate an attempt
if (senderBean.isReSend()) {
SenderBean bean2 = senderBeanMgr.retrieve(senderBean.getMessageID());
if (bean2 != null) {
bean2.setSentCount(senderBean.getSentCount());
senderBeanMgr.update(bean2);
}
}
// have to commit the transaction before sending. This may
// get changed when WS-AT is available.
if(transaction != null) {
transaction.commit();
transaction = null;
}
msgCtx.getOptions().setTimeOutInMilliSeconds(1000000);
try {
AxisEngine engine = new AxisEngine (msgCtx.getConfigurationContext());
InvocationResponse response = InvocationResponse.CONTINUE;
SandeshaPolicyBean policy = SandeshaUtil.getPropertyBean(msgCtx.getAxisOperation());
if(policy.isUseMessageSerialization()) {
if(msgCtx.isPaused()) {
if (log.isDebugEnabled())
log.debug("Resuming a send for message : " + msgCtx.getEnvelope().getHeader());
msgCtx.setPaused(false);
msgCtx.setProperty(MessageContext.TRANSPORT_NON_BLOCKING, Boolean.FALSE);
response = engine.resumeSend(msgCtx);
} else {
if (log.isDebugEnabled())
log.debug("Sending a message : " + msgCtx.getEnvelope().getHeader());
msgCtx.setProperty(MessageContext.TRANSPORT_NON_BLOCKING, Boolean.FALSE);
engine.send(msgCtx); // TODO check if this should return an invocation response
}
} else {
// had to fully build the SOAP envelope to support
// retransmissions.
// Otherwise a 'parserAlreadyAccessed' exception could
// get thrown in retransmissions.
// But this has a performance reduction.
msgCtx.getEnvelope().build();
ArrayList retransmittablePhases = (ArrayList) msgCtx.getProperty(Sandesha2Constants.RETRANSMITTABLE_PHASES);
if (retransmittablePhases!=null) {
msgCtx.setExecutionChain(retransmittablePhases);
} else {
ArrayList emptyExecutionChain = new ArrayList ();
msgCtx.setExecutionChain(emptyExecutionChain);
}
msgCtx.setCurrentHandlerIndex(0);
msgCtx.setCurrentPhaseIndex(0);
msgCtx.setPaused(false);
if (log.isDebugEnabled())
log.debug("Resuming a send for message : " + msgCtx.getEnvelope().getHeader());
response = engine.resumeSend(msgCtx);
}
if(log.isDebugEnabled()) log.debug("Engine resume returned " + response);
if(response != InvocationResponse.SUSPEND) {
if(t != null) {
if(log.isDebugEnabled()) log.debug("Signalling transport in " + t);
t.signalResponseReady();
}
}
successfullySent = true;
} catch (Exception e) {
String message = SandeshaMessageHelper.getMessage(
SandeshaMessageKeys.sendMsgError, e.toString());
if (log.isErrorEnabled())
log.error(message, e);
// Store the Exception as a sequence property to enable the client to lookup the last
// exception time and timestamp.
// Create a new Transaction
transaction = storageManager.getTransaction();
try
{
// Get the internal sequence id from the context
String internalSequenceId = (String)rmMsgCtx.getProperty(Sandesha2Constants.MessageContextProperties.INTERNAL_SEQUENCE_ID);
RMSBean bean = SandeshaUtil.getRMSBeanFromInternalSequenceId(storageManager, internalSequenceId);
if (bean != null) {
bean.setLastSendError(e);
bean.setLastSendErrorTimestamp(System.currentTimeMillis());
}
// Update the RMSBean
storageManager.getRMSBeanMgr().update(bean);
// Commit the properties
if(transaction != null) {
transaction.commit();
transaction = null;
}
}
catch (Exception e1)
{
if (log.isErrorEnabled())
log.error(e1);
if (transaction != null) {
transaction.rollback();
transaction = null;
}
}
}
// Establish the transaction for post-send processing
transaction = storageManager.getTransaction();
// update or delete only if the object is still present.
SenderBean bean1 = senderBeanMgr
.retrieve(senderBean.getMessageID());
if (bean1 != null) {
if (senderBean.isReSend()) {
bean1.setTimeToSend(senderBean.getTimeToSend());
senderBeanMgr.update(bean1);
} else {
senderBeanMgr.delete(bean1.getMessageID());
// removing the message from the storage.
String messageStoredKey = bean1.getMessageContextRefKey();
storageManager.removeMessageContext(messageStoredKey);
}
}
// Commit the transaction to release the SenderBean
if (transaction!=null)
transaction.commit();
transaction = null;
if (successfullySent && !msgCtx.isServerSide())
checkForSyncResponses(msgCtx);
if ((rmMsgCtx.getMessageType() == Sandesha2Constants.MessageTypes.TERMINATE_SEQ)
&&
(Sandesha2Constants.SPEC_2005_02.NS_URI.equals(rmMsgCtx.getRMNamespaceValue()))) {
transaction = storageManager.getTransaction();
//terminate message sent using the SandeshaClient. Since the terminate message will simply get the
//InFlow of the reference message get called which could be zero sized (OutOnly operations).
// terminate sending side if this is the WSRM 1.0 spec.
// If the WSRM versoion is 1.1 termination will happen in the terminate sequence response message.
TerminateSequence terminateSequence = (TerminateSequence) rmMsgCtx
.getMessagePart(Sandesha2Constants.MessageParts.TERMINATE_SEQ);
String sequenceID = terminateSequence.getIdentifier().getIdentifier();
RMSBean rmsBean = SandeshaUtil.getRMSBeanFromSequenceId(storageManager, sequenceID);
TerminateManager.terminateSendingSide(rmsBean, storageManager);
transaction.commit();
}
} catch (Exception e) {
if (log.isErrorEnabled()) log.error("Caught exception", e);
if (transaction!=null) {
transaction.rollback();
transaction = null;
}
} finally {
if (transaction!=null) transaction.commit();
if (lock!=null && workId!=null) {
lock.removeWork(workId);
}
}
if (log.isDebugEnabled())
log.debug("Exit: SenderWorker::run");
}
/**
* Update the message before sending it. We adjust the retransmission intervals and send counts
* for the message. If the message is an application message then we ensure that we have added
* the Sequence header.
*/
private boolean updateMessage(RMMsgContext rmMsgContext, SenderBean senderBean, StorageManager storageManager) throws AxisFault {
// Lock the message to enable retransmission update
senderBean = storageManager.getSenderBeanMgr().retrieve(senderBean.getMessageID());
boolean continueSending = MessageRetransmissionAdjuster.adjustRetransmittion(
rmMsgContext, senderBean, rmMsgContext.getConfigurationContext(), storageManager);
if(!continueSending) return false;
Identifier id = null;
if(senderBean.getMessageType() == Sandesha2Constants.MessageTypes.APPLICATION) {
String namespace = SpecSpecificConstants.getRMNamespaceValue(rmVersion);
Sequence sequence = (Sequence) rmMsgContext.getMessagePart(Sandesha2Constants.MessageParts.SEQUENCE);
if(sequence == null) {
sequence = new Sequence(namespace);
MessageNumber msgNumber = new MessageNumber(namespace);
msgNumber.setMessageNumber(senderBean.getMessageNumber());
sequence.setMessageNumber(msgNumber);
if(senderBean.isLastMessage() &&
SpecSpecificConstants.isLastMessageIndicatorRequired(rmVersion)) {
sequence.setLastMessage(new LastMessage(namespace));
}
// We just create the id here, we will add the value in later
id = new Identifier(namespace);
sequence.setIdentifier(id);
rmMsgContext.setMessagePart(Sandesha2Constants.MessageParts.SEQUENCE, sequence);
}
} else if(senderBean.getMessageType() == Sandesha2Constants.MessageTypes.TERMINATE_SEQ) {
TerminateSequence terminate = (TerminateSequence) rmMsgContext.getMessagePart(Sandesha2Constants.MessageParts.TERMINATE_SEQ);
id = terminate.getIdentifier();
} else if(senderBean.getMessageType() == Sandesha2Constants.MessageTypes.CLOSE_SEQUENCE) {
CloseSequence close = (CloseSequence) rmMsgContext.getMessagePart(Sandesha2Constants.MessageParts.CLOSE_SEQUENCE);
id = close.getIdentifier();
} else if(senderBean.getMessageType() == Sandesha2Constants.MessageTypes.ACK_REQUEST) {
// The only time that we can have a message of this type is when we are sending a
// stand-alone ack request, and in that case we only expect to find a single ack
// request header in the message.
Iterator ackRequests = rmMsgContext.getMessageParts(Sandesha2Constants.MessageParts.ACK_REQUEST);
AckRequested ackRequest = (AckRequested) ackRequests.next();
if (ackRequests.hasNext()) {
throw new SandeshaException (SandeshaMessageHelper.getMessage(SandeshaMessageKeys.ackRequestMultipleParts));
}
id = ackRequest.getIdentifier();
}
// TODO consider adding an extra ack request, as we are about to send the message and we
// know which sequence it is associated with.
if(id != null && !senderBean.getSequenceID().equals(id.getIdentifier())) {
id.setIndentifer(senderBean.getSequenceID());
// Write the changes back into the message context
rmMsgContext.addSOAPEnvelope();
}
return true;
}
private boolean isAckPiggybackableMsgType(int messageType) {
if (log.isDebugEnabled())
log.debug("Enter: SenderWorker::isAckPiggybackableMsgType, " + messageType);
boolean piggybackable = true;
if (messageType == Sandesha2Constants.MessageTypes.ACK)
piggybackable = false;
if (log.isDebugEnabled())
log.debug("Exit: SenderWorker::isAckPiggybackableMsgType, " + piggybackable);
return piggybackable;
}
private void checkForSyncResponses(MessageContext msgCtx) {
if (log.isDebugEnabled())
log.debug("Enter: SenderWorker::checkForSyncResponses, " + msgCtx.getEnvelope().getHeader());
try {
boolean responsePresent = (msgCtx.getProperty(MessageContext.TRANSPORT_IN) != null);
if (!responsePresent) {
if(log.isDebugEnabled()) log.debug("Exit: SenderWorker::checkForSyncResponses, no response present");
return;
}
// create the responseMessageContext
MessageContext responseMessageContext = new MessageContext();
OperationContext requestMsgOpCtx = msgCtx.getOperationContext();
responseMessageContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, requestMsgOpCtx
.getProperty(Constants.Configuration.CHARACTER_SET_ENCODING));
responseMessageContext.setProperty(Constants.Configuration.CONTENT_TYPE, requestMsgOpCtx
.getProperty(Constants.Configuration.CONTENT_TYPE));
responseMessageContext.setProperty(HTTPConstants.MTOM_RECEIVED_CONTENT_TYPE, requestMsgOpCtx
.getProperty(HTTPConstants.MTOM_RECEIVED_CONTENT_TYPE));
//If the response MsgCtx was not available Axis2 would hv put the transport info into a
//HashMap, getting the data from it.
HashMap transportInfoMap = (HashMap) msgCtx.getProperty(Constants.Configuration.TRANSPORT_INFO_MAP);
if (transportInfoMap != null) {
responseMessageContext.setProperty(Constants.Configuration.CONTENT_TYPE,
transportInfoMap.get(Constants.Configuration.CONTENT_TYPE));
responseMessageContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING,
transportInfoMap.get(Constants.Configuration.CHARACTER_SET_ENCODING));
}
//setting the message as serverSide will let it go through the MessageReceiver (may be callback MR).
responseMessageContext.setServerSide(true);
if (responseMessageContext.getSoapAction()==null) {
//if there is no SOAP action in the response message, Axis2 will wrongly identify it as a REST message
//This happens because we set serverSide to True in a previous step.
//So we have to add a empty SOAPAction here.
responseMessageContext.setSoapAction("");
}
responseMessageContext.setConfigurationContext(msgCtx.getConfigurationContext());
responseMessageContext.setTransportIn(msgCtx.getTransportIn());
responseMessageContext.setTransportOut(msgCtx.getTransportOut());
responseMessageContext.setProperty(MessageContext.TRANSPORT_IN, msgCtx
.getProperty(MessageContext.TRANSPORT_IN));
responseMessageContext.setServiceContext(msgCtx.getServiceContext());
responseMessageContext.setServiceGroupContext(msgCtx.getServiceGroupContext());
responseMessageContext.setProperty(Sandesha2Constants.MessageContextProperties.MAKECONNECTION_ENTRY,
msgCtx.getProperty(Sandesha2Constants.MessageContextProperties.MAKECONNECTION_ENTRY));
// If request is REST we assume the responseMessageContext is REST,
// so set the variable
responseMessageContext.setDoingREST(msgCtx.isDoingREST());
SOAPEnvelope resenvelope = null;
try {
// MessageContext is modified in TransportUtils.createSOAPMessage(). It might be used by axis.engine or handler.
resenvelope = TransportUtils.createSOAPMessage(responseMessageContext);
} catch (AxisFault e) {
//Cannot find a valid SOAP envelope.
if (log.isErrorEnabled() ) {
log.error (SandeshaMessageHelper
.getMessage(SandeshaMessageKeys.soapEnvNotSet));
log.error ("Caught exception", e);
}
return;
}
if (resenvelope != null) {
if (log.isDebugEnabled())
log.debug("Response " + resenvelope.getHeader());
responseMessageContext.setEnvelope(resenvelope);
// //If this message is an RM Control message it should not be assumed as an application message.
// //So dispatching etc should happen just like for a new message comming into the system.
// RMMsgContext responseRMMsg = MsgInitializer.initializeMessage(responseMessageContext);
// if (responseRMMsg.getMessageType()!=Sandesha2Constants.MessageTypes.UNKNOWN &&
// responseRMMsg.getMessageType()!=Sandesha2Constants.MessageTypes.APPLICATION ) {
// responseMessageContext.setAxisOperation(null);
// responseMessageContext.setOperationContext(null);
//If addressing is disabled we will be adding this message simply as the application response of the request message.
Boolean addressingDisabled = (Boolean) msgCtx.getOptions().getProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES);
if (addressingDisabled!=null && Boolean.TRUE.equals(addressingDisabled)) {
// If the AxisOperation object doesn't have a message receiver, it means that this was
// an out only op where we have added an ACK to the response. Set the requestMsgOpCtx to
// be the RMIn
OperationContext responseMsgOpCtx = requestMsgOpCtx;
if (requestMsgOpCtx.getAxisOperation().getMessageReceiver() == null) {
// Generate a new RM In Only operation
ServiceContext serviceCtx = responseMessageContext.getServiceContext();
AxisOperation op = msgCtx.getAxisService().getOperation(Sandesha2Constants.RM_IN_ONLY_OPERATION);
responseMsgOpCtx = ContextFactory.createOperationContext (op, serviceCtx);
}
responseMessageContext.setOperationContext(responseMsgOpCtx);
}
RMMsgContext responseRMMessage = MsgInitializer.initializeMessage(responseMessageContext);
if (responseRMMessage.getMessageType()==Sandesha2Constants.MessageTypes.ACK) {
responseMessageContext.setAxisOperation(SpecSpecificConstants.getWSRMOperation
(Sandesha2Constants.MessageTypes.ACK, responseRMMessage.getRMSpecVersion(), responseMessageContext.getAxisService()));
responseMessageContext.setOperationContext(null);
}
AxisEngine engine = new AxisEngine(msgCtx.getConfigurationContext());
if (isFaultEnvelope(resenvelope)) {
engine.receiveFault(responseMessageContext);
} else {
engine.receive(responseMessageContext);
}
}
} catch (Exception e) {
String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.noValidSyncResponse);
if (log.isWarnEnabled())
log.warn(message, e);
}
if (log.isDebugEnabled())
log.debug("Exit: SenderWorker::checkForSyncResponses");
}
private boolean isFaultEnvelope(SOAPEnvelope envelope) {
if (log.isDebugEnabled())
log.debug("Enter: SenderWorker::isFaultEnvelope, " + envelope.getBody().getFault());
SOAPFault fault = envelope.getBody().getFault();
if (fault != null) {
if (log.isDebugEnabled())
log.debug("Exit: SenderWorker::isFaultEnvelope, TRUE");
return true;
}
if (log.isDebugEnabled())
log.debug("Exit: SenderWorker::isFaultEnvelope, FALSE");
return false;
}
}
|
package org.apache.sandesha2.workers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.axiom.om.impl.builder.StAXBuilder;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.AddressingConstants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.context.OperationContext;
import org.apache.axis2.context.OperationContextFactory;
import org.apache.axis2.context.ServiceContext;
import org.apache.axis2.description.AxisOperation;
import org.apache.axis2.description.OutOnlyAxisOperation;
import org.apache.axis2.engine.AxisEngine;
import org.apache.axis2.engine.Handler.InvocationResponse;
import org.apache.axis2.transport.RequestResponseTransport;
import org.apache.axis2.transport.TransportUtils;
import org.apache.axis2.transport.RequestResponseTransport.RequestResponseTransportStatus;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.axis2.wsdl.WSDLConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.sandesha2.RMMsgContext;
import org.apache.sandesha2.Sandesha2Constants;
import org.apache.sandesha2.SandeshaException;
import org.apache.sandesha2.i18n.SandeshaMessageHelper;
import org.apache.sandesha2.i18n.SandeshaMessageKeys;
import org.apache.sandesha2.storage.SandeshaStorageException;
import org.apache.sandesha2.storage.StorageManager;
import org.apache.sandesha2.storage.Transaction;
import org.apache.sandesha2.storage.beanmanagers.SenderBeanMgr;
import org.apache.sandesha2.storage.beans.RMDBean;
import org.apache.sandesha2.storage.beans.RMSBean;
import org.apache.sandesha2.storage.beans.SenderBean;
import org.apache.sandesha2.util.AcknowledgementManager;
import org.apache.sandesha2.util.MessageRetransmissionAdjuster;
import org.apache.sandesha2.util.MsgInitializer;
import org.apache.sandesha2.util.RMMsgCreator;
import org.apache.sandesha2.util.SandeshaUtil;
import org.apache.sandesha2.util.SpecSpecificConstants;
import org.apache.sandesha2.util.TerminateManager;
import org.apache.sandesha2.wsrm.AckRequested;
import org.apache.sandesha2.wsrm.CloseSequence;
import org.apache.sandesha2.wsrm.Identifier;
import org.apache.sandesha2.wsrm.LastMessage;
import org.apache.sandesha2.wsrm.MessageNumber;
import org.apache.sandesha2.wsrm.Sequence;
import org.apache.sandesha2.wsrm.TerminateSequence;
public class SenderWorker extends SandeshaWorker implements Runnable {
private static final Log log = LogFactory.getLog(SenderWorker.class);
private ConfigurationContext configurationContext = null;
private SenderBean senderBean = null;
private RMMsgContext messageToSend = null;
private String rmVersion = null;
public SenderWorker (ConfigurationContext configurationContext, SenderBean senderBean, String rmVersion) {
this.configurationContext = configurationContext;
this.senderBean = senderBean;
this.rmVersion = rmVersion;
}
public void setMessage(RMMsgContext msg) {
this.messageToSend = msg;
}
public void run () {
if (log.isDebugEnabled())
log.debug("Enter: SenderWorker::run");
// If we are not the holder of the correct lock, then we have to stop
if(lock != null && !lock.ownsLock(workId, this)) {
if (log.isDebugEnabled()) log.debug("Exit: SenderWorker::run, another worker holds the lock");
return;
}
Transaction transaction = null;
try {
StorageManager storageManager = SandeshaUtil.getSandeshaStorageManager(configurationContext, configurationContext.getAxisConfiguration());
SenderBeanMgr senderBeanMgr = storageManager.getSenderBeanMgr();
transaction = storageManager.getTransaction();
String key = senderBean.getMessageContextRefKey();
MessageContext msgCtx = null;
RMMsgContext rmMsgCtx = null;
if(messageToSend != null) {
msgCtx = messageToSend.getMessageContext();
rmMsgCtx = messageToSend;
} else {
msgCtx = storageManager.retrieveMessageContext(key, configurationContext);
if (msgCtx == null) {
// This sender bean has already been processed
if(transaction != null && transaction.isActive()) transaction.commit();
transaction = null;
return;
}
rmMsgCtx = MsgInitializer.initializeMessage(msgCtx);
}
// sender will not send the message if following property is
// set and not true.
// But it will set if it is not set (null)
// This is used to make sure that the mesage get passed the
// Sandesha2TransportSender.
String qualifiedForSending = (String) msgCtx.getProperty(Sandesha2Constants.QUALIFIED_FOR_SENDING);
if (qualifiedForSending != null && !qualifiedForSending.equals(Sandesha2Constants.VALUE_TRUE)) {
if (log.isDebugEnabled())
log.debug("Exit: SenderWorker::run, !qualified for sending");
if(transaction != null && transaction.isActive()) {
transaction.commit();
transaction = null;
}
return;
}
if (msgCtx == null) {
if (log.isDebugEnabled())
log.debug(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.sendHasUnavailableMsgEntry));
if(transaction != null && transaction.isActive()) {
transaction.commit();
transaction = null;
}
return;
}
// operation is the lowest level Sandesha2 should be attached
ArrayList msgsNotToSend = SandeshaUtil.getPropertyBean(msgCtx.getAxisOperation()).getMsgTypesToDrop();
if (msgsNotToSend != null && msgsNotToSend.contains(new Integer(rmMsgCtx.getMessageType()))) {
if (log.isDebugEnabled())
log.debug("Exit: SenderWorker::run, message type to be dropped " + rmMsgCtx.getMessageType());
if(transaction != null && transaction.isActive()) {
transaction.commit();
transaction = null;
}
return;
}
// If we are sending to the anonymous URI then we _must_ have a transport waiting,
// or the message can't go anywhere. If there is nothing here then we leave the
// message in the sender queue, and a MakeConnection (or a retransmitted request)
// will hopefully pick it up soon.
Boolean makeConnection = (Boolean) msgCtx.getProperty(Sandesha2Constants.MAKE_CONNECTION_RESPONSE);
EndpointReference toEPR = msgCtx.getTo();
MessageContext inMsg = null;
OperationContext op = msgCtx.getOperationContext();
RequestResponseTransport t = (RequestResponseTransport) msgCtx.getProperty(RequestResponseTransport.TRANSPORT_CONTROL);
if (t==null) {
if (op != null)
inMsg = op.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
if (inMsg != null)
t = (RequestResponseTransport) inMsg.getProperty(RequestResponseTransport.TRANSPORT_CONTROL);
}
// If we are anonymous, and this is not a makeConnection, then we must have a transport waiting
if((toEPR==null || toEPR.hasAnonymousAddress()) &&
(makeConnection == null || !makeConnection.booleanValue()) &&
(t != null && !t.getStatus().equals(RequestResponseTransportStatus.WAITING))) {
// Mark this sender bean so that we know that the transport is unavailable, if the
// bean is still stored.
SenderBean bean = senderBeanMgr.retrieve(senderBean.getMessageID());
if(bean != null && bean.isTransportAvailable()) {
bean.setTransportAvailable(false);
senderBeanMgr.update(bean);
}
// Commit the update
if(transaction != null && transaction.isActive()) transaction.commit();
transaction = null;
if (log.isDebugEnabled())
log.debug("Exit: SenderWorker::run, no response transport for anonymous message");
return;
}
int messageType = senderBean.getMessageType();
if (isAckPiggybackableMsgType(messageType)) {
// Commit the update
if(transaction != null && transaction.isActive()) transaction.commit();
transaction = storageManager.getTransaction();
// Piggyback ack messages based on the 'To' address of the message
transaction = AcknowledgementManager.piggybackAcksIfPresent(rmMsgCtx, storageManager, transaction);
}
if (transaction != null && transaction.isActive())
transaction.commit();
transaction = storageManager.getTransaction();
senderBean = updateMessage(rmMsgCtx,senderBean,storageManager);
if (senderBean == null) {
if (log.isDebugEnabled())
log.debug("Exit: SenderWorker::run, !continueSending");
if(transaction != null && transaction.isActive()) {
transaction.rollback();
transaction = null;
}
return;
}
// Although not actually sent yet, update the send count to indicate an attempt
if (senderBean.isReSend()) {
senderBeanMgr.update(senderBean);
}
// sending the message
boolean successfullySent = false;
//try to redecorate the EPR if necessary
if (log.isDebugEnabled())
log.debug("Redecorate EPR : " + msgCtx.getEnvelope().getHeader());
EndpointReference replyToEPR = msgCtx.getReplyTo();
if(replyToEPR!=null){
replyToEPR = SandeshaUtil.getEPRDecorator(msgCtx.getConfigurationContext()).decorateEndpointReference(replyToEPR);
msgCtx.setReplyTo(replyToEPR);
}
// have to commit the transaction before sending. This may
// get changed when WS-AT is available.
if(transaction != null) {
transaction.commit();
transaction = null;
}
msgCtx.getOptions().setTimeOutInMilliSeconds(1000000);
boolean processResponseForFaults = false ;
try {
InvocationResponse response = InvocationResponse.CONTINUE;
if(storageManager.requiresMessageSerialization()) {
if(msgCtx.isPaused()) {
if (log.isDebugEnabled())
log.debug("Resuming a send for message : " + msgCtx.getEnvelope().getHeader());
msgCtx.setPaused(false);
msgCtx.setProperty(MessageContext.TRANSPORT_NON_BLOCKING, Boolean.FALSE);
response = AxisEngine.resumeSend(msgCtx);
} else {
if (log.isDebugEnabled())
log.debug("Sending a message : " + msgCtx.getEnvelope().getHeader());
msgCtx.setProperty(MessageContext.TRANSPORT_NON_BLOCKING, Boolean.FALSE);
AxisEngine.send(msgCtx); // TODO check if this should return an invocation response
}
} else {
ArrayList retransmittablePhases = (ArrayList) msgCtx.getProperty(Sandesha2Constants.RETRANSMITTABLE_PHASES);
if (retransmittablePhases!=null) {
msgCtx.setExecutionChain(retransmittablePhases);
} else {
ArrayList emptyExecutionChain = new ArrayList ();
msgCtx.setExecutionChain(emptyExecutionChain);
}
msgCtx.setCurrentHandlerIndex(0);
msgCtx.setCurrentPhaseIndex(0);
msgCtx.setPaused(false);
if (log.isDebugEnabled())
log.debug("Resuming a send for message : " + msgCtx.getEnvelope().getHeader());
msgCtx.setProperty(MessageContext.TRANSPORT_NON_BLOCKING, Boolean.FALSE);
response = AxisEngine.resumeSend(msgCtx);
}
if(log.isDebugEnabled()) log.debug("Engine resume returned " + response);
if(response != InvocationResponse.SUSPEND) {
if(t != null) {
if(log.isDebugEnabled()) log.debug("Signalling transport in " + t);
t.signalResponseReady();
}
}
successfullySent = true;
} catch (AxisFault e) {
//this is a possible SOAP 1.2 Fault. So letting it proceed.
processResponseForFaults = true;
recordError(e, rmMsgCtx, storageManager);
} catch (Exception e) {
String message = SandeshaMessageHelper.getMessage(
SandeshaMessageKeys.sendMsgError, e.toString());
if (log.isErrorEnabled())
log.error(message, e);
recordError(e, rmMsgCtx, storageManager);
}
// Establish the transaction for post-send processing
transaction = storageManager.getTransaction();
// update or delete only if the object is still present.
SenderBean bean1 = senderBeanMgr
.retrieve(senderBean.getMessageID());
if (bean1 != null) {
if (senderBean.isReSend()) {
bean1.setTimeToSend(senderBean.getTimeToSend());
senderBeanMgr.update(bean1);
} else {
senderBeanMgr.delete(bean1.getMessageID());
// removing the message from the storage.
String messageStoredKey = bean1.getMessageContextRefKey();
storageManager.removeMessageContext(messageStoredKey);
}
}
// Commit the transaction to release the SenderBean
if (transaction!=null)
transaction.commit();
transaction = null;
if ((processResponseForFaults || successfullySent) && !msgCtx.isServerSide())
checkForSyncResponses(msgCtx);
if ((rmMsgCtx.getMessageType() == Sandesha2Constants.MessageTypes.TERMINATE_SEQ)
&&
(Sandesha2Constants.SPEC_2005_02.NS_URI.equals(rmMsgCtx.getRMNamespaceValue()))) {
try {
transaction = storageManager.getTransaction();
//terminate message sent using the SandeshaClient. Since the terminate message will simply get the
//InFlow of the reference message get called which could be zero sized (OutOnly operations).
// terminate sending side if this is the WSRM 1.0 spec.
// If the WSRM versoion is 1.1 termination will happen in the terminate sequence response message.
TerminateSequence terminateSequence = (TerminateSequence) rmMsgCtx
.getMessagePart(Sandesha2Constants.MessageParts.TERMINATE_SEQ);
String sequenceID = terminateSequence.getIdentifier().getIdentifier();
RMSBean rmsBean = SandeshaUtil.getRMSBeanFromSequenceId(storageManager, sequenceID);
TerminateManager.terminateSendingSide(rmsBean, storageManager);
if(transaction != null && transaction.isActive()) transaction.commit();
transaction = null;
} finally {
if(transaction != null && transaction.isActive()) {
transaction.rollback();
transaction = null;
}
}
}
} catch (Exception e) {
if (log.isDebugEnabled()) log.debug("Caught exception", e);
} finally {
if (lock!=null && workId!=null) {
lock.removeWork(workId);
}
if (transaction!=null && transaction.isActive()) {
try {
transaction.rollback();
} catch (SandeshaStorageException e) {
if (log.isWarnEnabled())
log.warn("Caught exception rolling back transaction", e);
}
}
}
if (log.isDebugEnabled())
log.debug("Exit: SenderWorker::run");
}
/**
* Update the message before sending it. We adjust the retransmission intervals and send counts
* for the message. If the message is an application message then we ensure that we have added
* the Sequence header.
*/
private SenderBean updateMessage(RMMsgContext rmMsgContext, SenderBean senderBean, StorageManager storageManager) throws AxisFault {
// Lock the message to enable retransmission update
senderBean = storageManager.getSenderBeanMgr().retrieve(senderBean.getMessageID());
// Only continue if we find a SenderBean
if (senderBean == null)
return senderBean;
int messageType = senderBean.getMessageType();
boolean continueSending = MessageRetransmissionAdjuster.adjustRetransmittion(
rmMsgContext, senderBean, rmMsgContext.getConfigurationContext(), storageManager);
if(!continueSending) return null;
Identifier id = null;
if(messageType == Sandesha2Constants.MessageTypes.APPLICATION ||
messageType == Sandesha2Constants.MessageTypes.LAST_MESSAGE) {
String namespace = SpecSpecificConstants.getRMNamespaceValue(rmVersion);
Sequence sequence = (Sequence) rmMsgContext.getMessagePart(Sandesha2Constants.MessageParts.SEQUENCE);
if(sequence == null) {
sequence = new Sequence(namespace);
MessageNumber msgNumber = new MessageNumber(namespace);
msgNumber.setMessageNumber(senderBean.getMessageNumber());
sequence.setMessageNumber(msgNumber);
if(senderBean.isLastMessage() &&
SpecSpecificConstants.isLastMessageIndicatorRequired(rmVersion)) {
sequence.setLastMessage(new LastMessage(namespace));
}
// We just create the id here, we will add the value in later
id = new Identifier(namespace);
sequence.setIdentifier(id);
rmMsgContext.setMessagePart(Sandesha2Constants.MessageParts.SEQUENCE, sequence);
}
} else if(messageType == Sandesha2Constants.MessageTypes.TERMINATE_SEQ) {
TerminateSequence terminate = (TerminateSequence) rmMsgContext.getMessagePart(Sandesha2Constants.MessageParts.TERMINATE_SEQ);
id = terminate.getIdentifier();
} else if(messageType == Sandesha2Constants.MessageTypes.CLOSE_SEQUENCE) {
CloseSequence close = (CloseSequence) rmMsgContext.getMessagePart(Sandesha2Constants.MessageParts.CLOSE_SEQUENCE);
id = close.getIdentifier();
} else if(messageType == Sandesha2Constants.MessageTypes.ACK_REQUEST) {
// The only time that we can have a message of this type is when we are sending a
// stand-alone ack request, and in that case we only expect to find a single ack
// request header in the message.
Iterator ackRequests = rmMsgContext.getMessageParts(Sandesha2Constants.MessageParts.ACK_REQUEST);
AckRequested ackRequest = (AckRequested) ackRequests.next();
if (ackRequests.hasNext()) {
throw new SandeshaException (SandeshaMessageHelper.getMessage(SandeshaMessageKeys.ackRequestMultipleParts));
}
id = ackRequest.getIdentifier();
}
// TODO consider adding an extra ack request, as we are about to send the message and we
// know which sequence it is associated with.
if(id != null && !senderBean.getSequenceID().equals(id.getIdentifier())) {
id.setIndentifer(senderBean.getSequenceID());
// Write the changes back into the message context
rmMsgContext.addSOAPEnvelope();
}
//if this is an sync WSRM 1.0 case we always have to add an ack
boolean ackPresent = false;
Iterator it = rmMsgContext.getMessageParts (Sandesha2Constants.MessageParts.SEQ_ACKNOWLEDGEMENT);
if (it.hasNext())
ackPresent = true;
if (!ackPresent && rmMsgContext.getMessageContext().isServerSide()
&&
(messageType==Sandesha2Constants.MessageTypes.APPLICATION ||
messageType==Sandesha2Constants.MessageTypes.APPLICATION ||
messageType==Sandesha2Constants.MessageTypes.UNKNOWN ||
messageType==Sandesha2Constants.MessageTypes.LAST_MESSAGE)) {
String inboundSequenceId = senderBean.getInboundSequenceId();
if (inboundSequenceId==null)
throw new SandeshaException ("InboundSequenceID is not set for the sequence:" + id);
RMDBean incomingSequenceBean = SandeshaUtil.getRMDBeanFromSequenceId(storageManager, inboundSequenceId);
if (incomingSequenceBean!=null)
RMMsgCreator.addAckMessage(rmMsgContext, inboundSequenceId, incomingSequenceBean);
}
return senderBean;
}
private boolean isAckPiggybackableMsgType(int messageType) {
if (log.isDebugEnabled())
log.debug("Enter: SenderWorker::isAckPiggybackableMsgType, " + messageType);
boolean piggybackable = true;
if (messageType == Sandesha2Constants.MessageTypes.ACK)
piggybackable = false;
if (log.isDebugEnabled())
log.debug("Exit: SenderWorker::isAckPiggybackableMsgType, " + piggybackable);
return piggybackable;
}
private void checkForSyncResponses(MessageContext msgCtx) {
if (log.isDebugEnabled())
log.debug("Enter: SenderWorker::checkForSyncResponses, " + msgCtx.getEnvelope().getHeader());
try {
// create the responseMessageContext
MessageContext responseMessageContext = msgCtx.getOperationContext().getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
SOAPEnvelope resenvelope = null;
if (responseMessageContext!=null)
resenvelope = responseMessageContext.getEnvelope();
boolean transportInPresent = (msgCtx.getProperty(MessageContext.TRANSPORT_IN) != null);
if (!transportInPresent && (responseMessageContext==null || responseMessageContext.getEnvelope()==null)) {
if(log.isDebugEnabled()) log.debug("Exit: SenderWorker::checkForSyncResponses, no response present");
return;
}
//to find out weather the response was built by me.
boolean syncResponseBuilt = false;
if (responseMessageContext==null || responseMessageContext.getEnvelope()==null) {
if (responseMessageContext==null)
responseMessageContext = new MessageContext();
OperationContext requestMsgOpCtx = msgCtx.getOperationContext();
responseMessageContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, requestMsgOpCtx
.getProperty(Constants.Configuration.CHARACTER_SET_ENCODING));
responseMessageContext.setProperty(Constants.Configuration.CONTENT_TYPE, requestMsgOpCtx
.getProperty(Constants.Configuration.CONTENT_TYPE));
responseMessageContext.setProperty(HTTPConstants.MTOM_RECEIVED_CONTENT_TYPE, requestMsgOpCtx
.getProperty(HTTPConstants.MTOM_RECEIVED_CONTENT_TYPE));
//If the response MsgCtx was not available Axis2 would hv put the transport info into a
//HashMap, getting the data from it.
HashMap transportInfoMap = (HashMap) msgCtx.getProperty(Constants.Configuration.TRANSPORT_INFO_MAP);
if (transportInfoMap != null) {
responseMessageContext.setProperty(Constants.Configuration.CONTENT_TYPE,
transportInfoMap.get(Constants.Configuration.CONTENT_TYPE));
responseMessageContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING,
transportInfoMap.get(Constants.Configuration.CHARACTER_SET_ENCODING));
}
responseMessageContext.setConfigurationContext(msgCtx.getConfigurationContext());
responseMessageContext.setTransportIn(msgCtx.getTransportIn());
responseMessageContext.setTransportOut(msgCtx.getTransportOut());
responseMessageContext.setProperty(MessageContext.TRANSPORT_IN, msgCtx
.getProperty(MessageContext.TRANSPORT_IN));
//we will not be setting the operation context here since this msgs may not be an application reply.
//we let other dispatchers find it.
responseMessageContext.setServiceContext(msgCtx.getServiceContext());
responseMessageContext.setServiceGroupContext(msgCtx.getServiceGroupContext());
responseMessageContext.setProperty(Sandesha2Constants.MessageContextProperties.MAKECONNECTION_ENTRY,
msgCtx.getProperty(Sandesha2Constants.MessageContextProperties.MAKECONNECTION_ENTRY));
// If request is REST we assume the responseMessageContext is REST,
// so set the variable
responseMessageContext.setDoingREST(msgCtx.isDoingREST());
resenvelope = responseMessageContext.getEnvelope();
try {
// MessageContext is modified in TransportUtils.createSOAPMessage(). It might be used by axis.engine or handler.
if (resenvelope==null) {
//We try to build the response out of the transport stream.
resenvelope = TransportUtils.createSOAPMessage(responseMessageContext);
responseMessageContext.setEnvelope(resenvelope);
syncResponseBuilt = true;
}
} catch (AxisFault e) {
//Cannot find a valid SOAP envelope.
if (log.isErrorEnabled() ) {
log.error (SandeshaMessageHelper
.getMessage(SandeshaMessageKeys.soapEnvNotSet));
log.error ("Caught exception", e);
}
return;
}
//If addressing is disabled we will be adding this message simply as the application response of the request message.
Boolean addressingDisabled = (Boolean) msgCtx.getProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES);
if (addressingDisabled!=null && Boolean.TRUE.equals(addressingDisabled)) {
// If the AxisOperation object doesn't have a message receiver, it means that this was
// an out only op where we have added an ACK to the response. Set the requestMsgOpCtx to
// be the RMIn
OperationContext responseMsgOpCtx = requestMsgOpCtx;
if (requestMsgOpCtx.getAxisOperation().getMessageReceiver() == null) {
// Generate a new RM In Only operation
ServiceContext serviceCtx = responseMessageContext.getServiceContext();
AxisOperation op = msgCtx.getAxisService().getOperation(Sandesha2Constants.RM_IN_ONLY_OPERATION);
responseMsgOpCtx = OperationContextFactory.createOperationContext (op.getAxisSpecificMEPConstant(), op, serviceCtx);
}
responseMessageContext.setOperationContext(responseMsgOpCtx);
}
AxisOperation operation = msgCtx.getAxisOperation();
if (operation!=null && responseMessageContext.getAxisMessage()==null
&& !(operation instanceof OutOnlyAxisOperation))
responseMessageContext.setAxisMessage(operation.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE));
RMMsgContext responseRMMessage = MsgInitializer.initializeMessage(responseMessageContext);
if (responseRMMessage.getMessageType()==Sandesha2Constants.MessageTypes.ACK) {
responseMessageContext.setAxisOperation(SpecSpecificConstants.getWSRMOperation
(Sandesha2Constants.MessageTypes.ACK, responseRMMessage.getRMSpecVersion(), responseMessageContext.getAxisService()));
responseMessageContext.setOperationContext(null);
}
}
//if the syncResponseWas not built here and the client was not expecting a sync response. We will not try to execute
//here. Doing so will cause a double invocation for a async message.
if (msgCtx.getOptions().isUseSeparateListener()==true && !syncResponseBuilt) {
return;
}
//setting the message as serverSide will let it go through the MessageReceiver (may be callback MR).
responseMessageContext.setServerSide(true);
if (responseMessageContext.getSoapAction()==null) {
//if there is no SOAP action in the response message, Axis2 will wrongly identify it as a REST message
//This happens because we set serverSide to True in a previous step.
//So we have to add a empty SOAPAction here.
responseMessageContext.setSoapAction("");
}
InvocationResponse response = null;
if (resenvelope!=null) {
response = AxisEngine.receive(responseMessageContext);
}
if(!InvocationResponse.SUSPEND.equals(response)) {
// Performance work - need to close the XMLStreamReader to prevent GC thrashing.
SOAPEnvelope env = responseMessageContext.getEnvelope();
if(env!=null){
StAXBuilder sb = (StAXBuilder)responseMessageContext.getEnvelope().getBuilder();
if(sb!=null){
sb.close();
}
}
}
} catch (Exception e) {
String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.noValidSyncResponse);
if (log.isDebugEnabled())
log.debug(message, e);
}
if (log.isDebugEnabled())
log.debug("Exit: SenderWorker::checkForSyncResponses");
}
private void recordError (Exception e, RMMsgContext outRMMsg, StorageManager storageManager) throws SandeshaStorageException {
// Store the Exception as a sequence property to enable the client to lookup the last
// exception time and timestamp.
Transaction transaction = null;
try
{
// Get the internal sequence id from the context
String internalSequenceId = (String)outRMMsg.getProperty(Sandesha2Constants.MessageContextProperties.INTERNAL_SEQUENCE_ID);
if(internalSequenceId == null) internalSequenceId = senderBean.getInternalSequenceID();
if(internalSequenceId != null) {
// Create a new Transaction
transaction = storageManager.getTransaction();
RMSBean bean = SandeshaUtil.getRMSBeanFromInternalSequenceId(storageManager, internalSequenceId);
if (bean != null) {
bean.setLastSendError(e);
bean.setLastSendErrorTimestamp(System.currentTimeMillis());
// Update the RMSBean
storageManager.getRMSBeanMgr().update(bean);
}
// Commit the properties
if(transaction != null) {
transaction.commit();
transaction = null;
}
}
}
catch (Exception e1)
{
if (log.isErrorEnabled())
log.error(e1);
} finally {
if (transaction != null) {
transaction.rollback();
transaction = null;
}
}
}
}
|
package org.rabix.engine.processor.handler.impl;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.rabix.bindings.model.dag.DAGContainer;
import org.rabix.bindings.model.dag.DAGLinkPort;
import org.rabix.bindings.model.dag.DAGLinkPort.LinkPortType;
import org.rabix.common.helper.CloneHelper;
import org.rabix.bindings.model.dag.DAGNode;
import org.rabix.engine.db.DAGNodeDB;
import org.rabix.engine.event.Event;
import org.rabix.engine.event.impl.InitEvent;
import org.rabix.engine.event.impl.InputUpdateEvent;
import org.rabix.engine.model.ContextRecord;
import org.rabix.engine.model.ContextRecord.ContextStatus;
import org.rabix.engine.model.JobRecord;
import org.rabix.engine.model.VariableRecord;
import org.rabix.engine.processor.EventProcessor;
import org.rabix.engine.processor.handler.EventHandler;
import org.rabix.engine.processor.handler.EventHandlerException;
import org.rabix.engine.service.ContextRecordService;
import org.rabix.engine.service.JobRecordService;
import org.rabix.engine.service.JobRecordService.JobState;
import org.rabix.engine.service.VariableRecordService;
import com.google.inject.Inject;
/**
* Handles {@link InitEvent} events.
*/
public class InitEventHandler implements EventHandler<InitEvent> {
private DAGNodeDB nodeDB;
private EventProcessor eventProcessor;
private JobRecordService jobRecordService;
private ContextRecordService contextRecordService;
private VariableRecordService variableRecordService;
@Inject
public InitEventHandler(EventProcessor eventProcessor, JobRecordService jobRecordService, VariableRecordService variableRecordService, ContextRecordService contextRecordService, DAGNodeDB dagNodeDB) {
this.nodeDB = dagNodeDB;
this.eventProcessor = eventProcessor;
this.jobRecordService = jobRecordService;
this.contextRecordService = contextRecordService;
this.variableRecordService = variableRecordService;
}
public void handle(final InitEvent event) throws EventHandlerException {
ContextRecord context = new ContextRecord(event.getContext().getId(), event.getContext().getConfig(), ContextStatus.RUNNING);
contextRecordService.create(context);
nodeDB.loadDB(event.getNode(), event.getContextId());
DAGNode node = nodeDB.get(event.getNode().getId(), event.getContextId());
JobRecord job = new JobRecord(event.getContextId(), event.getNode().getId(), event.getContextId(), JobState.PENDING, node instanceof DAGContainer, false, true);
for (DAGLinkPort inputPort : node.getInputPorts()) {
if (job.getState().equals(JobState.PENDING)) {
job.incrementPortCounter(inputPort, LinkPortType.INPUT);
}
VariableRecord variable = new VariableRecord(event.getContextId(), event.getNode().getId(), inputPort.getId(), LinkPortType.INPUT, null);
variableRecordService.create(variable);
}
for (DAGLinkPort outputPort : node.getOutputPorts()) {
job.incrementPortCounter(outputPort, LinkPortType.OUTPUT);
VariableRecord variable = new VariableRecord(event.getContextId(), event.getNode().getId(), outputPort.getId(), LinkPortType.OUTPUT, null);
variableRecordService.create(variable);
}
jobRecordService.create(job);
Map<String, Object> mixedInputs = mixInputs(node, event.getValue());
for (DAGLinkPort inputPort : node.getInputPorts()) {
Object value = mixedInputs.get(inputPort.getId());
Event updateInputEvent = new InputUpdateEvent(event.getContextId(), event.getNode().getId(), inputPort.getId(), value, null);
eventProcessor.send(updateInputEvent);
}
}
@SuppressWarnings("unchecked")
private Map<String, Object> mixInputs(DAGNode dagNode, Map<String, Object> inputs) {
Map<String, Object> mixedInputs;
try {
mixedInputs = (Map<String, Object>) CloneHelper.deepCopy(dagNode.getDefaults());
if (inputs == null) {
return mixedInputs;
}
for (Entry<String, Object> inputEntry : inputs.entrySet()) {
mixedInputs.put(inputEntry.getKey(), inputEntry.getValue());
}
return mixedInputs;
} catch (Exception e) {
throw new RuntimeException("Failed to clone default inputs for node " + dagNode.getId());
}
}
}
|
package net.sandius.rembulan.compiler.gen.block;
import net.sandius.rembulan.compiler.gen.PrototypeContext;
import net.sandius.rembulan.compiler.gen.SlotState;
import net.sandius.rembulan.core.ControlThrowable;
import net.sandius.rembulan.core.Dispatch;
import net.sandius.rembulan.core.LuaState;
import net.sandius.rembulan.core.ObjectSink;
import net.sandius.rembulan.core.ResumeInfo;
import net.sandius.rembulan.core.Table;
import net.sandius.rembulan.core.TableFactory;
import net.sandius.rembulan.core.Upvalue;
import net.sandius.rembulan.util.Check;
import net.sandius.rembulan.util.asm.ASMUtils;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FrameNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.LineNumberNode;
import org.objectweb.asm.tree.LocalVariableNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TableSwitchInsnNode;
import org.objectweb.asm.tree.TryCatchBlockNode;
import org.objectweb.asm.tree.TypeInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.objectweb.asm.Opcodes.*;
public class CodeEmitter {
public final int REGISTER_OFFSET = 4;
public final int LV_STATE = 1;
public final int LV_OBJECTSINK = 2;
public final int LV_RESUME = 3;
private final ClassEmitter parent;
private final PrototypeContext context;
private final MethodNode methodNode;
private final Map<Object, LabelNode> labels;
private final ArrayList<LabelNode> resumptionPoints;
private final InsnList resumeSwitch;
private final InsnList code;
private final InsnList errorState;
private final InsnList resumeHandler;
public CodeEmitter(ClassEmitter parent, PrototypeContext context) {
this.parent = Check.notNull(parent);
this.context = Check.notNull(context);
this.labels = new HashMap<>();
this.resumptionPoints = new ArrayList<>();
this.methodNode = new MethodNode(ACC_PRIVATE, methodName(), methodType().getDescriptor(), null, exceptions());
resumeSwitch = new InsnList();
code = new InsnList();
errorState = new InsnList();
resumeHandler = new InsnList();
}
public MethodNode node() {
return methodNode;
}
private String methodName() {
return "run";
}
private Type methodType() {
Type[] args = new Type[3 + numOfRegisters()];
args[0] = Type.getType(LuaState.class);
args[1] = Type.getType(ObjectSink.class);
args[2] = Type.INT_TYPE;
for (int i = 3; i < args.length; i++) {
args[i] = Type.getType(Object.class);
}
return Type.getMethodType(Type.VOID_TYPE, args);
}
private String[] exceptions() {
return new String[] { Type.getInternalName(ControlThrowable.class) };
}
protected LabelNode _l(Object key) {
LabelNode l = labels.get(key);
if (l != null) {
return l;
}
else {
LabelNode nl = new LabelNode();
labels.put(key, nl);
return nl;
}
}
protected String thisClassName() {
return context.className();
}
public void _note(String text) {
System.out.println("// " + text);
}
public void _dup() {
code.add(new InsnNode(DUP));
}
public void _swap() {
code.add(new InsnNode(SWAP));
}
public void _push_this() {
code.add(new VarInsnNode(ALOAD, 0));
}
public void _push_null() {
code.add(new InsnNode(ACONST_NULL));
}
public void _push_int(int i) {
switch (i) {
case -1: code.add(new InsnNode(ICONST_M1)); break;
case 0: code.add(new InsnNode(ICONST_0)); break;
case 1: code.add(new InsnNode(ICONST_1)); break;
case 2: code.add(new InsnNode(ICONST_2)); break;
case 3: code.add(new InsnNode(ICONST_3)); break;
case 4: code.add(new InsnNode(ICONST_4)); break;
case 5: code.add(new InsnNode(ICONST_5)); break;
default: code.add(new LdcInsnNode(i)); break;
}
}
private void _push_long(long l) {
if (l == 0L) code.add(new InsnNode(LCONST_0));
else if (l == 1L) code.add(new InsnNode(LCONST_1));
else code.add(new LdcInsnNode(l));
}
public void _push_double(double d) {
if (d == 0.0) code.add(new InsnNode(DCONST_0));
else if (d == 1.0) code.add(new InsnNode(DCONST_1));
else code.add(new LdcInsnNode(d));
}
public void _load_k(int idx, Class castTo) {
Object k = context.getConst(idx);
if (k == null) {
_push_null();
}
else if (k instanceof Boolean) {
_push_int((Boolean) k ? 1 : 0);
_invokeStatic(Boolean.class, "valueOf", Type.getMethodType(Type.getType(Boolean.class), Type.BOOLEAN_TYPE));
}
else if (k instanceof Double || k instanceof Float) {
_push_double(((Number) k).doubleValue());
_invokeStatic(Double.class, "valueOf", Type.getMethodType(Type.getType(Double.class), Type.DOUBLE_TYPE));
}
else if (k instanceof Number) {
_push_long(((Number) k).longValue());
_invokeStatic(Long.class, "valueOf", Type.getMethodType(Type.getType(Long.class), Type.LONG_TYPE));
}
else if (k instanceof String) {
code.add(new LdcInsnNode((String) k));
}
else {
_note("load const #" + idx + " of type " + PrototypeContext.constantType(k));
}
if (castTo != null) {
if (!castTo.isAssignableFrom(k.getClass())) {
_checkCast(castTo);
}
}
}
public void _load_k(int idx) {
_load_k(idx, null);
}
public void _load_reg_value(int idx) {
code.add(new VarInsnNode(ALOAD, REGISTER_OFFSET + idx));
}
public void _load_reg(int idx, SlotState slots, Class castTo) {
Check.notNull(slots);
Check.nonNegative(idx);
if (slots.isCaptured(idx)) {
_get_downvalue(idx);
_get_upvalue_value();
}
else {
_load_reg_value(idx);
}
Class clazz = Object.class;
if (castTo != null) {
if (!castTo.isAssignableFrom(clazz)) {
_checkCast(castTo);
}
}
}
public void _load_reg(int idx, SlotState slots) {
_load_reg(idx, slots, null);
}
public void _get_downvalue(int idx) {
code.add(new VarInsnNode(ALOAD, REGISTER_OFFSET + idx));
_checkCast(Upvalue.class);
}
public void _load_reg_or_const(int rk, SlotState slots, Class castTo) {
Check.notNull(slots);
if (rk < 0) {
// it's a constant
_load_k(-rk - 1, castTo);
}
else {
_load_reg(rk, slots, castTo);
}
}
public void _load_reg_or_const(int rk, SlotState slots) {
_load_reg_or_const(rk, slots, null);
}
private void _store_reg_value(int r) {
code.add(new VarInsnNode(ASTORE, REGISTER_OFFSET + r));
}
public void _store(int r, SlotState slots) {
Check.notNull(slots);
if (slots.isCaptured(r)) {
_get_downvalue(r);
_swap();
_set_upvalue_value();
}
else {
_store_reg_value(r);
}
}
@Deprecated
public String _className(String cn) {
return cn.replace('.', '/');
}
@Deprecated
public String _classDesc(String cn) {
return "L" + _className(cn) + ";";
}
@Deprecated
public String _classDesc(Class clazz) {
if (clazz.isPrimitive()) {
if (clazz.equals(void.class)) return "V";
else if (clazz.equals(byte.class)) return "B";
else if (clazz.equals(boolean.class)) return "Z";
else if (clazz.equals(char.class)) return "C";
else if (clazz.equals(double.class)) return "D";
else if (clazz.equals(float.class)) return "F";
else if (clazz.equals(int.class)) return "I";
else if (clazz.equals(long.class)) return "J";
else if (clazz.equals(short.class)) return "S";
else throw new IllegalArgumentException();
}
else {
if (clazz.isArray()) {
return _className(clazz.getName());
}
else {
return "L" + _className(clazz.getName()) + ";";
}
}
}
public void _invokeStatic(Class clazz, String methodName, Type methodSignature) {
code.add(new MethodInsnNode(
INVOKESTATIC,
Type.getInternalName(clazz),
methodName,
methodSignature.getDescriptor(),
false
));
}
public void _invokeVirtual(Class clazz, String methodName, Type methodSignature) {
code.add(new MethodInsnNode(
INVOKEVIRTUAL,
Type.getInternalName(clazz),
methodName,
methodSignature.getDescriptor(),
false
));
}
public void _invokeInterface(Class clazz, String methodName, Type methodSignature) {
code.add(new MethodInsnNode(
INVOKEINTERFACE,
Type.getInternalName(clazz),
methodName,
methodSignature.getDescriptor(),
true
));
}
public void _invokeSpecial(String className, String methodName, Type methodSignature) {
code.add(new MethodInsnNode(
INVOKESPECIAL,
_className(className),
methodName,
methodSignature.getDescriptor(),
false
));
}
// public void _invokeSpecial(Class clazz, String methodName, String methodSignature) {
// _invokeSpecial(clazz.getName(), methodName, methodSignature);
public String _methodSignature(Class returnType, Class... parameters) {
StringBuilder bld = new StringBuilder();
bld.append("(");
for (Class p : parameters) {
bld.append(_classDesc(p));
}
bld.append(")");
bld.append(_classDesc(returnType));
return bld.toString();
}
public void _dispatchCall(String methodName, Type signature) {
_invokeStatic(Dispatch.class, methodName, signature);
}
public void _dispatch_binop(String name, Class clazz) {
Type t = Type.getType(clazz);
_invokeStatic(Dispatch.class, name, Type.getMethodType(t, t, t));
}
public void _dispatch_generic_mt_2(String name) {
_invokeStatic(
Dispatch.class,
name,
Type.getMethodType(
Type.VOID_TYPE,
Type.getType(LuaState.class),
Type.getType(ObjectSink.class),
Type.getType(Object.class),
Type.getType(Object.class)
)
);
}
public void _dispatch_index() {
_dispatch_generic_mt_2("index");
}
public void _checkCast(Class clazz) {
code.add(new TypeInsnNode(CHECKCAST, Type.getInternalName(clazz)));
}
public void _loadState() {
code.add(new VarInsnNode(ALOAD, LV_STATE));
}
public void _loadObjectSink() {
code.add(new VarInsnNode(ALOAD, LV_OBJECTSINK));
}
public void _retrieve_1() {
_invokeVirtual(ObjectSink.class, "_1", Type.getMethodType(Type.getType(Object.class)));
}
public void _save_pc(Object o) {
LabelNode rl = _l(o);
int idx = resumptionPoints.size();
resumptionPoints.add(rl);
_push_int(idx);
code.add(new VarInsnNode(ISTORE, LV_RESUME));
}
public void _resumptionPoint(Object label) {
_label_here(label);
}
private LabelNode l_insns_begin;
private LabelNode l_body_begin;
private LabelNode l_error_state;
private LabelNode l_body_end;
public void begin() {
l_insns_begin = new LabelNode();
methodNode.instructions.add(l_insns_begin);
l_body_begin = new LabelNode();
l_error_state = new LabelNode();
resumptionPoints.add(l_body_begin);
code.add(l_body_begin);
_frame_same(code);
}
public void end() {
l_body_end = new LabelNode();
code.add(l_body_end);
if (isResumable()) {
_error_state();
}
_dispatch_table();
if (isResumable()) {
_resumption_handler(l_body_begin, l_body_end);
}
// local variable declaration
LabelNode l_insns_end = new LabelNode();
List<LocalVariableNode> locals = methodNode.localVariables;
locals.add(new LocalVariableNode("this", parent.thisClassType().getDescriptor(), null, l_insns_begin, l_insns_end, 0));
locals.add(new LocalVariableNode("state", Type.getDescriptor(LuaState.class), null, l_insns_begin, l_insns_end, LV_STATE));
locals.add(new LocalVariableNode("sink", Type.getDescriptor(ObjectSink.class), null, l_insns_begin, l_insns_end, LV_OBJECTSINK));
locals.add(new LocalVariableNode("rp", Type.INT_TYPE.getDescriptor(), null, l_insns_begin, l_insns_end, LV_RESUME));
for (int i = 0; i < numOfRegisters(); i++) {
locals.add(new LocalVariableNode("r_" + (i + 1), Type.getDescriptor(Object.class), null, l_insns_begin, l_insns_end, REGISTER_OFFSET + i));
}
// TODO: check these
methodNode.maxLocals = numOfRegisters() + 4;
methodNode.maxStack = numOfRegisters() + 5;
methodNode.instructions.add(resumeSwitch);
methodNode.instructions.add(code);
methodNode.instructions.add(errorState);
methodNode.instructions.add(resumeHandler);
methodNode.instructions.add(l_insns_end);
}
protected void _error_state() {
errorState.add(l_error_state);
errorState.add(new TypeInsnNode(NEW, Type.getDescriptor(IllegalStateException.class)));
errorState.add(new InsnNode(DUP));
errorState.add(new MethodInsnNode(
INVOKESPECIAL,
Type.getInternalName(IllegalStateException.class),
"<init>",
Type.getMethodDescriptor(Type.VOID_TYPE),
false));
errorState.add(new InsnNode(ATHROW));
}
protected boolean isResumable() {
return resumptionPoints.size() > 1;
}
protected void _dispatch_table() {
if (isResumable()) {
LabelNode[] labels = resumptionPoints.toArray(new LabelNode[0]);
resumeSwitch.add(new VarInsnNode(ILOAD, LV_RESUME));
resumeSwitch.add(new TableSwitchInsnNode(0, resumptionPoints.size() - 1, l_error_state, labels));
}
}
protected int numOfRegisters() {
return context.prototype().getMaximumStackSize();
}
protected void _make_saved_state() {
_new(ResumeInfo.SavedState.class);
_dup();
// resumption point
code.add(new VarInsnNode(ILOAD, LV_RESUME));
// registers
int numRegs = numOfRegisters();
_push_int(numRegs);
code.add(new TypeInsnNode(ANEWARRAY, Type.getInternalName(Object.class)));
for (int i = 0; i < numRegs; i++) {
_dup();
_push_int(i);
_load_reg_value(i);
code.add(new InsnNode(AASTORE));
}
_ctor(Type.getType(ResumeInfo.SavedState.class), Type.INT_TYPE, ASMUtils.arrayTypeFor(Object.class));
}
protected void _resumption_handler(LabelNode begin, LabelNode end) {
LabelNode handler = new LabelNode();
code.add(handler);
code.add(new FrameNode(F_SAME1, 0, null, 1, new Object[] { Type.getInternalName(ControlThrowable.class) }));
_new(ResumeInfo.class);
_dup();
_make_saved_state();
_ctor(ResumeInfo.class, Object.class); // FIXME
_invokeVirtual(ControlThrowable.class, "push", Type.getMethodType(Type.VOID_TYPE, Type.getType(ResumeInfo.class)));
// rethrow
code.add(new InsnNode(ATHROW));
methodNode.tryCatchBlocks.add(new TryCatchBlockNode(begin, end, handler, Type.getInternalName(ControlThrowable.class)));
}
public void _get_upvalue_ref(int idx) {
code.add(new FieldInsnNode(
GETFIELD,
_className(thisClassName()),
parent.getUpvalueFieldName(idx),
Type.getDescriptor(Upvalue.class)));
}
public void _get_upvalue_value() {
_invokeVirtual(Upvalue.class, "get", Type.getMethodType(Type.getType(Object.class)));
}
public void _set_upvalue_value() {
_invokeVirtual(Upvalue.class, "set", Type.getMethodType(Type.VOID_TYPE, Type.getType(Object.class)));
}
public void _return() {
code.add(new InsnNode(RETURN));
}
public void _new(String className) {
code.add(new TypeInsnNode(NEW, _className(className)));
}
public void _new(Class clazz) {
_new(clazz.getName());
}
public void _ctor(Type clazz, Type... args) {
_invokeSpecial(clazz.getInternalName(), "<init>", Type.getMethodType(Type.VOID_TYPE, args));
}
public void _ctor(String className, Class... args) {
Type[] argTypes = new Type[args.length];
for (int i = 0; i < args.length; i++) {
argTypes[i] = Type.getType(args[i]);
}
_ctor(Type.getType(_classDesc(className)), argTypes);
}
public void _ctor(Class clazz, Class... args) {
_ctor(clazz.getName(), args);
}
public void _capture(int idx) {
_new(Upvalue.class);
_dup();
_load_reg_value(idx);
_ctor(Upvalue.class, Object.class);
_store_reg_value(idx);
}
public void _uncapture(int idx) {
_load_reg_value(idx);
_get_upvalue_value();
_store_reg_value(idx);
}
private void _frame_same(InsnList il) {
il.add(new FrameNode(F_SAME, 0, null, 0, null));
}
public void _label_here(Object identity) {
LabelNode l = _l(identity);
code.add(l);
_frame_same(code);
}
public void _goto(Object l) {
code.add(new JumpInsnNode(GOTO, _l(l)));
}
public void _next_insn(Target t) {
_goto(t);
// if (t.inSize() < 2) {
// // can be inlined, TODO: check this again
// _note("goto ignored: " + t.toString());
// else {
// _goto(t);
}
public void _new_table(int array, int hash) {
_loadState();
_invokeVirtual(LuaState.class, "tableFactory", Type.getMethodType(Type.getType(TableFactory.class)));
_push_int(array);
_push_int(hash);
_invokeVirtual(TableFactory.class, "newTable", Type.getMethodType(Type.getType(Table.class), Type.INT_TYPE, Type.INT_TYPE));
}
public void _if_null(Object target) {
code.add(new JumpInsnNode(IFNULL, _l(target)));
}
public void _if_nonnull(Object target) {
code.add(new JumpInsnNode(IFNONNULL, _l(target)));
}
public void _tailcall_0() {
_invokeInterface(ObjectSink.class, "tailCall", Type.getMethodType(Type.VOID_TYPE));
}
public void _tailcall_1() {
Type o = Type.getType(Object.class);
_invokeInterface(ObjectSink.class, "tailCall", Type.getMethodType(Type.VOID_TYPE, o));
}
public void _tailcall_2() {
Type o = Type.getType(Object.class);
_invokeInterface(ObjectSink.class, "tailCall", Type.getMethodType(Type.VOID_TYPE, o, o));
}
public void _tailcall_3() {
Type o = Type.getType(Object.class);
_invokeInterface(ObjectSink.class, "tailCall", Type.getMethodType(Type.VOID_TYPE, o, o, o));
}
public void _setret_0() {
_invokeInterface(ObjectSink.class, "reset", Type.getMethodType(Type.VOID_TYPE));
}
public void _setret_1() {
Type o = Type.getType(Object.class);
_invokeInterface(ObjectSink.class, "setTo", Type.getMethodType(Type.VOID_TYPE, o));
}
public void _setret_2() {
Type o = Type.getType(Object.class);
_invokeInterface(ObjectSink.class, "setTo", Type.getMethodType(Type.VOID_TYPE, o, o));
}
public void _setret_3() {
Type o = Type.getType(Object.class);
_invokeInterface(ObjectSink.class, "setTo", Type.getMethodType(Type.VOID_TYPE, o, o));
}
public void _line_here(int line) {
LabelNode l = _l(new Object());
code.add(l);
code.add(new LineNumberNode(line, l));
}
}
|
package be.ibridge.kettle.spoon;
import java.lang.reflect.InvocationTargetException;
import java.util.StringTokenizer;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Shell;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.DragAndDropContainer;
import be.ibridge.kettle.core.GUIResource;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.NotePadMeta;
import be.ibridge.kettle.core.Point;
import be.ibridge.kettle.core.Rectangle;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.dialog.EnterNumberDialog;
import be.ibridge.kettle.core.dialog.EnterTextDialog;
import be.ibridge.kettle.core.dialog.ErrorDialog;
import be.ibridge.kettle.core.dialog.StepFieldsDialog;
import be.ibridge.kettle.spoon.dialog.SearchFieldsProgressDialog;
import be.ibridge.kettle.trans.StepLoader;
import be.ibridge.kettle.trans.StepPlugin;
import be.ibridge.kettle.trans.TransHopMeta;
import be.ibridge.kettle.trans.TransMeta;
import be.ibridge.kettle.trans.step.StepMeta;
import be.ibridge.kettle.trans.step.StepMetaInterface;
import be.ibridge.kettle.trans.step.tableinput.TableInputMeta;
/**
* This class handles the display of the transformations in a graphical way using icons, arrows, etc.
*
* @author Matt
* @since 17-mei-2003
*
*/
public class SpoonGraph extends Canvas
{
private static final int HOP_SEL_MARGIN = 9;
private Shell shell;
private SpoonGraph canvas;
private LogWriter log;
private int iconsize;
private int linewidth;
private Point lastclick;
private Point lastMove;
private Point previous_step_locations[];
private Point previous_note_locations[];
private StepMeta selected_steps[];
private StepMeta selected_step;
private NotePadMeta selected_notes[];
private NotePadMeta selected_note;
private TransHopMeta candidate;
private Point drop_candidate;
private Spoon spoon;
private Point offset, iconoffset, noteoffset;
private ScrollBar hori;
private ScrollBar vert;
public boolean shift, control;
private boolean split_hop;
private int last_button;
private TransHopMeta last_hop_split;
private Rectangle selrect;
private int shadowsize;
private Menu mPop;
public SpoonGraph(Composite par, int style, LogWriter l, Spoon sp)
{
super(par, style);
shell = par.getShell();
log = l;
spoon = sp;
canvas = this;
iconsize = spoon.props.getIconSize();
clearSettings();
hori = getHorizontalBar();
vert = getVerticalBar();
hori.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
redraw();
}
});
vert.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
redraw();
}
});
hori.setThumb(100);
vert.setThumb(100);
hori.setVisible(true);
vert.setVisible(true);
setVisible(true);
newProps();
canvas.setBackground(GUIResource.getInstance().getColorBackground());
addPaintListener(new PaintListener()
{
public void paintControl(PaintEvent e)
{
if (!spoon.isStopped()) SpoonGraph.this.paintControl(e);
}
});
selected_steps = null;
lastclick = null;
addKeyListener(spoon.modKeys);
/*
* Handle the mouse...
*/
addMouseListener(new MouseAdapter()
{
public void mouseDoubleClick(MouseEvent e)
{
clearSettings();
control = (e.stateMask & SWT.CONTROL) != 0;
shift = (e.stateMask & SWT.SHIFT) != 0;
Point real = screen2real(e.x, e.y);
StepMeta stepMeta = spoon.getTransMeta().getStep(real.x, real.y, iconsize);
if (stepMeta != null)
{
if (e.button == 1)
editStep(stepMeta);
else
editDescription(stepMeta);
}
else
{
// Check if point lies on one of the many hop-lines...
TransHopMeta online = findHop(real.x, real.y);
if (online != null)
{
editHop(online);
}
else
{
NotePadMeta ni = spoon.getTransMeta().getNote(real.x, real.y);
if (ni != null)
{
selected_note = null;
editNote(ni);
}
}
}
}
public void mouseDown(MouseEvent e)
{
clearSettings();
control = (e.stateMask & SWT.CONTROL) != 0;
shift = (e.stateMask & SWT.SHIFT) != 0;
last_button = e.button;
Point real = screen2real(e.x, e.y);
// Clear the tooltip!
setToolTipText(null);
// Set the pop-up menu
setMenu(real.x, real.y);
// Did we click on a step?
StepMeta stepMeta = spoon.getTransMeta().getStep(real.x, real.y, iconsize);
if (stepMeta != null)
{
selected_steps = spoon.getTransMeta().getSelectedSteps();
selected_step = stepMeta;
// When an icon is moved that is not selected, it gets
// selected too late.
// It is not captured here, but in the mouseMoveListener...
previous_step_locations = spoon.getTransMeta().getSelectedStepLocations();
Point p = stepMeta.getLocation();
iconoffset = new Point(real.x - p.x, real.y - p.y);
}
else
{
// Dit we hit a note?
NotePadMeta ni = spoon.getTransMeta().getNote(real.x, real.y);
if (ni != null && last_button == 1)
{
selected_notes = spoon.getTransMeta().getSelectedNotes();
selected_note = ni;
Point loc = ni.getLocation();
previous_note_locations = spoon.getTransMeta().getSelectedNoteLocations();
noteoffset = new Point(real.x - loc.x, real.y - loc.y);
}
else
{
if (!control) selrect = new Rectangle(real.x, real.y, 0, 0);
}
}
lastclick = new Point(real.x, real.y);
redraw();
}
public void mouseUp(MouseEvent e)
{
control = (e.stateMask & SWT.CONTROL) != 0;
shift = (e.stateMask & SWT.SHIFT) != 0;
if (iconoffset == null) iconoffset = new Point(0, 0);
Point real = screen2real(e.x, e.y);
Point icon = new Point(real.x - iconoffset.x, real.y - iconoffset.y);
// Quick new hop option? (drag from one step to another)
if (candidate != null)
{
if (spoon.getTransMeta().findTransHop(candidate) == null)
{
spoon.getTransMeta().addTransHop(candidate);
spoon.refreshTree();
if (spoon.getTransMeta().hasLoop(candidate.getFromStep()))
{
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("SpoonGraph.Dialog.HopCausesLoop.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("SpoonGraph.Dialog.HopCausesLoop.Title")); //$NON-NLS-1$
mb.open();
int idx = spoon.getTransMeta().indexOfTransHop(candidate);
spoon.getTransMeta().removeTransHop(idx);
spoon.refreshTree();
}
else
{
spoon.addUndoNew(new TransHopMeta[] { candidate }, new int[] { spoon.getTransMeta().indexOfTransHop(candidate) });
}
}
candidate = null;
selected_steps = null;
last_button = 0;
redraw();
}
// Did we select a region on the screen? Mark steps in region as
// selected
else
if (selrect != null)
{
selrect.width = real.x - selrect.x;
selrect.height = real.y - selrect.y;
spoon.getTransMeta().unselectAll();
spoon.getTransMeta().selectInRect(selrect);
selrect = null;
redraw();
}
// Clicked on an icon?
else
if (selected_step != null)
{
if (e.button == 1)
{
if (lastclick.x == e.x && lastclick.y == e.y)
{
// Flip selection when control is pressed!
if (control)
{
selected_step.flipSelected();
}
else
{
// Otherwise, select only the icon clicked on!
spoon.getTransMeta().unselectAll();
selected_step.setSelected(true);
}
}
else
{
// Find out which Steps & Notes are selected
selected_steps = spoon.getTransMeta().getSelectedSteps();
selected_notes = spoon.getTransMeta().getSelectedNotes();
// We moved around some items: store undo info...
boolean also = false;
if (selected_notes != null && previous_note_locations != null)
{
int indexes[] = spoon.getTransMeta().getNoteIndexes(selected_notes);
spoon.addUndoPosition(selected_notes, indexes, previous_note_locations, spoon.getTransMeta()
.getSelectedNoteLocations(), also);
also = selected_steps != null && selected_steps.length > 0;
}
if (selected_steps != null && previous_step_locations != null)
{
int indexes[] = spoon.getTransMeta().getStepIndexes(selected_steps);
spoon.addUndoPosition(selected_steps, indexes, previous_step_locations, spoon.getTransMeta()
.getSelectedStepLocations(), also);
}
}
}
// OK, we moved the step, did we move it across a hop?
// If so, ask to split the hop!
if (split_hop)
{
TransHopMeta hi = findHop(icon.x + iconsize / 2, icon.y + iconsize / 2);
if (hi != null)
{
int id = 0;
if (!spoon.props.getAutoSplit())
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell, Messages.getString("SpoonGraph.Dialog.SplitHop.Title"), null, //$NON-NLS-1$
Messages.getString("SpoonGraph.Dialog.SplitHop.Message") + Const.CR + hi.toString(), MessageDialog.QUESTION, new String[] { //$NON-NLS-1$
Messages.getString("System.Button.Yes"), Messages.getString("System.Button.No") }, 0, Messages.getString("SpoonGraph.Dialog.Option.SplitHop.DoNotAskAgain"), spoon.props.getAutoSplit()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
id = md.open();
spoon.props.setAutoSplit(md.getToggleState());
}
if (id == 0) // Means: "Yes" button clicked!
{
TransHopMeta newhop1 = new TransHopMeta(hi.getFromStep(), selected_step);
spoon.getTransMeta().addTransHop(newhop1);
spoon
.addUndoNew(new TransHopMeta[] { newhop1 }, new int[] { spoon.getTransMeta().indexOfTransHop(newhop1) },
true);
TransHopMeta newhop2 = new TransHopMeta(selected_step, hi.getToStep());
spoon.getTransMeta().addTransHop(newhop2);
spoon
.addUndoNew(new TransHopMeta[] { newhop2 }, new int[] { spoon.getTransMeta().indexOfTransHop(newhop2) },
true);
int idx = spoon.getTransMeta().indexOfTransHop(hi);
spoon.addUndoDelete(new TransHopMeta[] { hi }, new int[] { idx }, true);
spoon.getTransMeta().removeTransHop(idx);
spoon.refreshTree();
}
}
split_hop = false;
}
selected_steps = null;
selected_notes = null;
selected_step = null;
selected_note = null;
redraw();
}
// Notes?
else
if (selected_note != null)
{
if (e.button == 1)
{
if (lastclick.x == e.x && lastclick.y == e.y)
{
// Flip selection when control is pressed!
if (control)
{
selected_note.flipSelected();
}
else
{
// Otherwise, select only the note clicked on!
spoon.getTransMeta().unselectAll();
selected_note.setSelected(true);
}
}
else
{
// Find out which Steps & Notes are selected
selected_steps = spoon.getTransMeta().getSelectedSteps();
selected_notes = spoon.getTransMeta().getSelectedNotes();
// We moved around some items: store undo info...
boolean also = false;
if (selected_notes != null && previous_note_locations != null)
{
int indexes[] = spoon.getTransMeta().getNoteIndexes(selected_notes);
spoon.addUndoPosition(selected_notes, indexes, previous_note_locations, spoon.getTransMeta()
.getSelectedNoteLocations(), also);
also = selected_steps != null && selected_steps.length > 0;
}
if (selected_steps != null && previous_step_locations != null)
{
int indexes[] = spoon.getTransMeta().getStepIndexes(selected_steps);
spoon.addUndoPosition(selected_steps, indexes, previous_step_locations, spoon.getTransMeta()
.getSelectedStepLocations(), also);
}
}
}
selected_notes = null;
selected_steps = null;
selected_step = null;
selected_note = null;
}
}
});
addMouseMoveListener(new MouseMoveListener()
{
public void mouseMove(MouseEvent e)
{
// Remember the last position of the mouse for paste with keyboard
lastMove = new Point(e.x, e.y);
Point real = screen2real(e.x, e.y);
if (iconoffset == null) iconoffset = new Point(0, 0);
Point icon = new Point(real.x - iconoffset.x, real.y - iconoffset.y);
if (noteoffset == null) noteoffset = new Point(0, 0);
Point note = new Point(real.x - noteoffset.x, real.y - noteoffset.y);
setToolTip(real.x, real.y);
// First see if the icon we clicked on was selected.
// If the icon was not selected, we should unselect all other
// icons,
// selected and move only the one icon
if (selected_step != null && !selected_step.isSelected())
{
// System.out.println("STEPS: Unselected all");
spoon.getTransMeta().unselectAll();
selected_step.setSelected(true);
selected_steps = new StepMeta[] { selected_step };
previous_step_locations = new Point[] { selected_step.getLocation() };
}
if (selected_note != null && !selected_note.isSelected())
{
// System.out.println("NOTES: Unselected all");
spoon.getTransMeta().unselectAll();
selected_note.setSelected(true);
selected_notes = new NotePadMeta[] { selected_note };
previous_note_locations = new Point[] { selected_note.getLocation() };
}
// Did we select a region...?
if (selrect != null)
{
selrect.width = real.x - selrect.x;
selrect.height = real.y - selrect.y;
redraw();
}
// Move around steps & notes
else
if (selected_step != null)
{
if (last_button == 1 && !shift)
{
/*
* One or more icons are selected and moved around...
*
* new : new position of the ICON (not the mouse pointer) dx : difference with previous
* position
*/
int dx = icon.x - selected_step.getLocation().x;
int dy = icon.y - selected_step.getLocation().y;
// See if we have a hop-split candidate
TransHopMeta hi = findHop(icon.x + iconsize / 2, icon.y + iconsize / 2);
if (hi != null)
{
if (!hi.getFromStep().equals(selected_step) && !hi.getToStep().equals(selected_step))
{
split_hop = true;
last_hop_split = hi;
hi.split = true;
}
}
else
{
if (last_hop_split != null)
{
last_hop_split.split = false;
last_hop_split = null;
split_hop = false;
}
}
selected_notes = spoon.getTransMeta().getSelectedNotes();
selected_steps = spoon.getTransMeta().getSelectedSteps();
// Adjust location of selected steps...
if (selected_steps != null) for (int i = 0; i < selected_steps.length; i++)
{
StepMeta stepMeta = selected_steps[i];
stepMeta.setLocation(stepMeta.getLocation().x + dx, stepMeta.getLocation().y + dy);
}
// Adjust location of selected hops...
if (selected_notes != null) for (int i = 0; i < selected_notes.length; i++)
{
NotePadMeta ni = selected_notes[i];
ni.setLocation(ni.getLocation().x + dx, ni.getLocation().y + dy);
}
redraw();
}
// The middle button perhaps?
else
if (last_button == 2 || (last_button == 1 && shift))
{
StepMeta stepMeta = spoon.getTransMeta().getStep(real.x, real.y, iconsize);
if (stepMeta != null && !selected_step.equals(stepMeta))
{
if (candidate == null)
{
candidate = new TransHopMeta(selected_step, stepMeta);
redraw();
}
}
else
{
if (candidate != null)
{
candidate = null;
redraw();
}
}
}
}
// Move around notes & steps
else
if (selected_note != null)
{
if (last_button == 1 && !shift)
{
/*
* One or more notes are selected and moved around...
*
* new : new position of the note (not the mouse pointer) dx : difference with previous
* position
*/
int dx = note.x - selected_note.getLocation().x;
int dy = note.y - selected_note.getLocation().y;
selected_notes = spoon.getTransMeta().getSelectedNotes();
selected_steps = spoon.getTransMeta().getSelectedSteps();
// Adjust location of selected steps...
if (selected_steps != null) for (int i = 0; i < selected_steps.length; i++)
{
StepMeta stepMeta = selected_steps[i];
stepMeta.setLocation(stepMeta.getLocation().x + dx, stepMeta.getLocation().y + dy);
}
// Adjust location of selected hops...
if (selected_notes != null) for (int i = 0; i < selected_notes.length; i++)
{
NotePadMeta ni = selected_notes[i];
ni.setLocation(ni.getLocation().x + dx, ni.getLocation().y + dy);
}
redraw();
}
}
}
});
// Drag & Drop for steps
Transfer[] ttypes = new Transfer[] { TextTransfer.getInstance() };
DropTarget ddTarget = new DropTarget(this, DND.DROP_MOVE | DND.DROP_COPY);
ddTarget.setTransfer(ttypes);
ddTarget.addDropListener(new DropTargetListener()
{
public void dragEnter(DropTargetEvent event)
{
clearSettings();
drop_candidate = getRealPosition(canvas, event.x, event.y);
redraw();
}
public void dragLeave(DropTargetEvent event)
{
drop_candidate = null;
redraw();
}
public void dragOperationChanged(DropTargetEvent event)
{
}
public void dragOver(DropTargetEvent event)
{
drop_candidate = getRealPosition(canvas, event.x, event.y);
redraw();
}
public void drop(DropTargetEvent event)
{
// no data to copy, indicate failure in event.detail
if (event.data == null)
{
event.detail = DND.DROP_NONE;
return;
}
// System.out.println("Dropping a step!!");
// What's the real drop position?
Point p = getRealPosition(canvas, event.x, event.y);
// We expect a piece of XML...
String xml = (String) event.data;
try
{
DragAndDropContainer container = new DragAndDropContainer(xml);
StepMeta stepMeta = null;
boolean newstep = false;
switch(container.getType())
{
// Put an existing one on the canvas.
case DragAndDropContainer.TYPE_STEP:
{
// Drop hidden step onto canvas....
stepMeta = spoon.getTransMeta().findStep(container.getData());
if (stepMeta!=null)
{
if (stepMeta.isDrawn() || spoon.getTransMeta().isStepUsedInTransHops(stepMeta))
{
MessageBox mb = new MessageBox(shell, SWT.OK);
mb.setMessage(Messages.getString("SpoonGraph.Dialog.StepIsAlreadyOnCanvas.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("SpoonGraph.Dialog.StepIsAlreadyOnCanvas.Title")); //$NON-NLS-1$
mb.open();
return;
}
// This step gets the drawn attribute and position set below.
}
else
{
// Unknown step dropped: ignore this to be safe!
return;
}
}
break;
// Create a new step
case DragAndDropContainer.TYPE_BASE_STEP_TYPE:
{
// Not an existing step: data refers to the type of step to create
String steptype = container.getData();
stepMeta = spoon.newStep(steptype, steptype, false, true);
if (stepMeta!=null)
{
newstep=true;
}
else
{
return; // Cancelled pressed in dialog or unable to create step.
}
}
break;
// Create a new TableInput step using the selected connection...
case DragAndDropContainer.TYPE_DATABASE_CONNECTION:
{
newstep = true;
String connectionName = container.getData();
TableInputMeta tii = new TableInputMeta();
tii.setDatabaseMeta(spoon.getTransMeta().findDatabase(connectionName));
StepLoader steploader = StepLoader.getInstance();
String stepID = steploader.getStepPluginID(tii);
StepPlugin stepPlugin = steploader.findStepPluginWithID(stepID);
String stepName = spoon.getTransMeta().getAlternativeStepname(stepPlugin.getDescription());
stepMeta = new StepMeta(log, stepID, stepName, tii);
if (spoon.editStepInfo(stepMeta) != null)
{
spoon.getTransMeta().addStep(stepMeta);
spoon.refreshTree(true);
spoon.refreshGraph();
}
else
{
return;
}
}
break;
// Drag hop on the canvas: create a new Hop...
case DragAndDropContainer.TYPE_TRANS_HOP:
{
newHop();
return;
}
default:
{
// Nothing we can use: give an error!
MessageBox mb = new MessageBox(shell, SWT.OK);
mb.setMessage(Messages.getString("SpoonGraph.Dialog.ItemCanNotBePlacedOnCanvas.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("SpoonGraph.Dialog.ItemCanNotBePlacedOnCanvas.Title")); //$NON-NLS-1$
mb.open();
return;
}
}
spoon.getTransMeta().unselectAll();
StepMeta before = (StepMeta) stepMeta.clone();
stepMeta.drawStep();
stepMeta.setSelected(true);
stepMeta.setLocation(p.x, p.y);
if (newstep)
{
spoon.addUndoNew(new StepMeta[] { stepMeta }, new int[] { spoon.getTransMeta().indexOfStep(stepMeta) });
}
else
{
spoon.addUndoChange(new StepMeta[] { before }, new StepMeta[] { (StepMeta) stepMeta.clone() }, new int[] { spoon.getTransMeta()
.indexOfStep(stepMeta) });
}
canvas.forceFocus();
redraw();
}
catch(Exception e)
{
new ErrorDialog(shell, spoon.props, Messages.getString("SpoonGraph.Dialog.ErrorDroppingObject.Message"), Messages.getString("SpoonGraph.Dialog.ErrorDroppingObject.Title"), e);
}
}
public void dropAccept(DropTargetEvent event)
{
}
});
// Keyboard shortcuts...
addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if ((int) e.character == 1) // CTRL-A
{
spoon.getTransMeta().selectAll();
redraw();
}
if ((int) e.character == 3) // CTRL-C
{
spoon.copySelected(spoon.getTransMeta().getSelectedSteps(), spoon.getTransMeta().getSelectedNotes());
}
if ((int) e.character == 22) // CTRL-V
{
String clipcontent = spoon.fromClipboard();
if (clipcontent != null)
{
if (lastMove != null)
{
spoon.pasteXML(clipcontent, lastMove);
}
}
// spoon.pasteSteps( );
}
if (e.keyCode == SWT.ESC)
{
spoon.getTransMeta().unselectAll();
clearSettings();
redraw();
}
if (e.keyCode == SWT.DEL)
{
StepMeta stepMeta[] = spoon.getTransMeta().getSelectedSteps();
if (stepMeta != null && stepMeta.length > 0)
{
delSelected(null);
}
}
// CTRL-UP : allignTop();
if (e.keyCode == SWT.ARROW_UP && (e.stateMask & SWT.CONTROL) != 0)
{
alligntop();
}
// CTRL-DOWN : allignBottom();
if (e.keyCode == SWT.ARROW_DOWN && (e.stateMask & SWT.CONTROL) != 0)
{
allignbottom();
}
// CTRL-LEFT : allignleft();
if (e.keyCode == SWT.ARROW_LEFT && (e.stateMask & SWT.CONTROL) != 0)
{
allignleft();
}
// CTRL-RIGHT : allignRight();
if (e.keyCode == SWT.ARROW_RIGHT && (e.stateMask & SWT.CONTROL) != 0)
{
allignright();
}
// ALT-RIGHT : distributeHorizontal();
if (e.keyCode == SWT.ARROW_RIGHT && (e.stateMask & SWT.ALT) != 0)
{
distributehorizontal();
}
// ALT-UP : distributeVertical();
if (e.keyCode == SWT.ARROW_UP && (e.stateMask & SWT.ALT) != 0)
{
distributevertical();
}
// ALT-HOME : snap to grid
if (e.keyCode == SWT.HOME && (e.stateMask & SWT.ALT) != 0)
{
snaptogrid(Const.GRID_SIZE);
}
// SPACE : over a step: show output fields...
if (e.character == ' ' && lastMove != null)
{
Point real = screen2real(lastMove.x, lastMove.y);
// Clear the tooltip!
setToolTipText(null);
// Set the pop-up menu
StepMeta stepMeta = spoon.getTransMeta().getStep(real.x, real.y, iconsize);
if (stepMeta != null)
{
// OK, we found a step, show the output fields...
inputOutputFields(stepMeta, false);
}
}
}
});
addKeyListener(spoon.defKeys);
setBackground(GUIResource.getInstance().getColorBackground());
}
public void clearSettings()
{
selected_step = null;
selected_note = null;
selected_steps = null;
selrect = null;
candidate = null;
last_hop_split = null;
last_button = 0;
iconoffset = null;
for (int i = 0; i < spoon.getTransMeta().nrTransHops(); i++)
spoon.getTransMeta().getTransHop(i).split = false;
}
public String[] getDropStrings(String str, String sep)
{
StringTokenizer strtok = new StringTokenizer(str, sep);
String retval[] = new String[strtok.countTokens()];
int i = 0;
while (strtok.hasMoreElements())
{
retval[i] = strtok.nextToken();
i++;
}
return retval;
}
public Point screen2real(int x, int y)
{
getOffset();
Point real;
if (offset != null)
{
real = new Point(x - offset.x, y - offset.y);
}
else
{
real = new Point(x, y);
}
return real;
}
public Point real2screen(int x, int y)
{
getOffset();
Point screen = new Point(x + offset.x, y + offset.y);
return screen;
}
public Point getRealPosition(Composite canvas, int x, int y)
{
Point p = new Point(0, 0);
Composite follow = canvas;
while (follow != null)
{
org.eclipse.swt.graphics.Point loc = follow.getLocation();
Point xy = new Point(loc.x, loc.y);
p.x += xy.x;
p.y += xy.y;
follow = follow.getParent();
}
p.x = x - p.x - 16;
p.y = y - p.y - 64;
return screen2real(p.x, p.y);
}
// See if location (x,y) is on a line between two steps: the hop!
// return the HopInfo if so, otherwise: null
private TransHopMeta findHop(int x, int y)
{
int i;
TransHopMeta online = null;
for (i = 0; i < spoon.getTransMeta().nrTransHops(); i++)
{
TransHopMeta hi = spoon.getTransMeta().getTransHop(i);
StepMeta fs = hi.getFromStep();
StepMeta ts = hi.getToStep();
if (fs == null || ts == null) return null;
int line[] = getLine(fs, ts);
if (pointOnLine(x, y, line)) online = hi;
}
return online;
}
private int[] getLine(StepMeta fs, StepMeta ts)
{
Point from = fs.getLocation();
Point to = ts.getLocation();
offset = getOffset();
int x1 = from.x + iconsize / 2;
int y1 = from.y + iconsize / 2;
int x2 = to.x + iconsize / 2;
int y2 = to.y + iconsize / 2;
return new int[] { x1, y1, x2, y2 };
}
/**
* This sets the popup-menu on the background of the canvas based on the xy coordinate of the mouse. This method is
* called after a mouse-click.
*
* @param x X-coordinate on screen
* @param y Y-coordinate on screen
*/
private void setMenu(int x, int y)
{
final int mousex = x;
final int mousey = y;
// Re-use the popup menu if it was allocated beforehand...
if (mPop==null)
{
mPop = new Menu((Control) this);
}
else
{
MenuItem children[] = mPop.getItems();
for (int i=0;i<children.length;i++) children[i].dispose();
}
final StepMeta stepMeta = spoon.getTransMeta().getStep(x, y, iconsize);
if (stepMeta != null) // We clicked on a Step!
{
MenuItem miNewHop = null;
MenuItem miHideStep = null;
int sels = spoon.getTransMeta().nrSelectedSteps();
if (sels == 2)
{
miNewHop = new MenuItem(mPop, SWT.CASCADE);
miNewHop.setText(Messages.getString("SpoonGraph.PopupMenu.NewHop")); //$NON-NLS-1$
}
MenuItem miEditStep = new MenuItem(mPop, SWT.CASCADE);
miEditStep.setText(Messages.getString("SpoonGraph.PopupMenu.EditStep")); //$NON-NLS-1$
MenuItem miEditDesc = new MenuItem(mPop, SWT.CASCADE);
miEditDesc.setText(Messages.getString("SpoonGraph.PopupMenu.EditStepDescription")); //$NON-NLS-1$
new MenuItem(mPop, SWT.SEPARATOR);
MenuItem miPopDC = new MenuItem(mPop, SWT.CASCADE);
miPopDC.setText(Messages.getString("SpoonGraph.PopupMenu.DataMovement")); //$NON-NLS-1$
Menu mPopDC = new Menu(miPopDC);
MenuItem miStepDist = new MenuItem(mPopDC, SWT.CASCADE | SWT.CHECK);
miStepDist.setText(Messages.getString("SpoonGraph.PopupMenu.DistributeData")); //$NON-NLS-1$
MenuItem miStepCopy = new MenuItem(mPopDC, SWT.CASCADE | SWT.CHECK);
miStepCopy.setText(Messages.getString("SpoonGraph.PopupMenu.CopyData")); //$NON-NLS-1$
miPopDC.setMenu(mPopDC);
if (stepMeta.distributes)
miStepDist.setSelection(true);
else
miStepCopy.setSelection(true);
MenuItem miCopies = new MenuItem(mPop, SWT.CASCADE);
miCopies.setText(Messages.getString("SpoonGraph.PopupMenu.NumberOfCopies")); //$NON-NLS-1$
new MenuItem(mPop, SWT.SEPARATOR);
// Clipboard operations...
MenuItem miCopyStep = new MenuItem(mPop, SWT.CASCADE);
miCopyStep.setText(Messages.getString("SpoonGraph.PopupMenu.CopyToClipboard")); //$NON-NLS-1$
MenuItem miDupeStep = new MenuItem(mPop, SWT.CASCADE);
miDupeStep.setText(Messages.getString("SpoonGraph.PopupMenu.DuplicateStep")); //$NON-NLS-1$
MenuItem miDelStep = new MenuItem(mPop, SWT.CASCADE);
miDelStep.setText(Messages.getString("SpoonGraph.PopupMenu.DeleteStep")); //$NON-NLS-1$
if (stepMeta.isDrawn() && !spoon.getTransMeta().isStepUsedInTransHops(stepMeta))
{
miHideStep = new MenuItem(mPop, SWT.CASCADE);
miHideStep.setText(Messages.getString("SpoonGraph.PopupMenu.HideStep")); //$NON-NLS-1$
miHideStep.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
for (int i = 0; i < spoon.getTransMeta().nrSteps(); i++)
{
StepMeta sti = spoon.getTransMeta().getStep(i);
if (sti.isDrawn() && sti.isSelected())
{
sti.hideStep();
spoon.refreshTree();
}
}
stepMeta.hideStep();
spoon.refreshTree();
redraw();
}
});
}
if (spoon.getTransMeta().isStepUsedInTransHops(stepMeta))
{
MenuItem miDetach = new MenuItem(mPop, SWT.CASCADE);
miDetach.setText(Messages.getString("SpoonGraph.PopupMenu.DetachStep")); //$NON-NLS-1$
miDetach.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
detach(stepMeta);
selected_steps = null;
}
});
}
new MenuItem(mPop, SWT.SEPARATOR);
MenuItem miPopFieldsBef = new MenuItem(mPop, SWT.CASCADE);
miPopFieldsBef.setText(Messages.getString("SpoonGraph.PopupMenu.ShowInputFields")); //$NON-NLS-1$
MenuItem miPopFieldsAft = new MenuItem(mPop, SWT.CASCADE);
miPopFieldsAft.setText(Messages.getString("SpoonGraph.PopupMenu.ShowOutputFields")); //$NON-NLS-1$
// Allign & Distribute options...
new MenuItem(mPop, SWT.SEPARATOR);
MenuItem miPopAD = new MenuItem(mPop, SWT.CASCADE);
miPopAD.setText(Messages.getString("SpoonGraph.PopupMenu.AllignDistribute")); //$NON-NLS-1$
Menu mPopAD = new Menu(miPopAD);
MenuItem miPopALeft = new MenuItem(mPopAD, SWT.CASCADE);
miPopALeft.setText(Messages.getString("SpoonGraph.PopupMenu.AllignLeft")); //$NON-NLS-1$
MenuItem miPopARight = new MenuItem(mPopAD, SWT.CASCADE);
miPopARight.setText(Messages.getString("SpoonGraph.PopupMenu.AllignRight")); //$NON-NLS-1$
MenuItem miPopATop = new MenuItem(mPopAD, SWT.CASCADE);
miPopATop.setText(Messages.getString("SpoonGraph.PopupMenu.AllignTop")); //$NON-NLS-1$
MenuItem miPopABottom = new MenuItem(mPopAD, SWT.CASCADE);
miPopABottom.setText(Messages.getString("SpoonGraph.PopupMenu.AllignBottom")); //$NON-NLS-1$
new MenuItem(mPopAD, SWT.SEPARATOR);
MenuItem miPopDHoriz = new MenuItem(mPopAD, SWT.CASCADE);
miPopDHoriz.setText(Messages.getString("SpoonGraph.PopupMenu.DistributeHorizontally")); //$NON-NLS-1$
MenuItem miPopDVertic = new MenuItem(mPopAD, SWT.CASCADE);
miPopDVertic.setText(Messages.getString("SpoonGraph.PopupMenu.DistributeVertically")); //$NON-NLS-1$
new MenuItem(mPopAD, SWT.SEPARATOR);
MenuItem miPopSSnap = new MenuItem(mPopAD, SWT.CASCADE);
miPopSSnap.setText(Messages.getString("SpoonGraph.PopupMenu.SnapToGrid") + Const.GRID_SIZE + ")\tALT-HOME"); //$NON-NLS-1$ //$NON-NLS-2$
miPopAD.setMenu(mPopAD);
miPopALeft.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
allignleft();
}
});
miPopARight.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
allignright();
}
});
miPopATop.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
alligntop();
}
});
miPopABottom.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
allignbottom();
}
});
miPopDHoriz.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
distributehorizontal();
}
});
miPopDVertic.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
distributevertical();
}
});
miPopSSnap.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
snaptogrid(Const.GRID_SIZE);
}
});
if (sels <= 1)
{
miPopAD.setEnabled(false);
}
/*
*
* Check...
*/
new MenuItem(mPop, SWT.SEPARATOR);
MenuItem miPreview = new MenuItem(mPop, SWT.CASCADE);
miPreview.setText(Messages.getString("SpoonGraph.PopupMenu.CheckSelectedSteps")); //$NON-NLS-1$
miPreview.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
spoon.checkTrans(true);
}
});
/*
*
* Check...
*/
MenuItem miMapping = new MenuItem(mPop, SWT.CASCADE);
miMapping.setText(Messages.getString("SpoonGraph.PopupMenu.GenerateMappingToThisStep")); //$NON-NLS-1$
miMapping.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
spoon.generateMapping(stepMeta);
}
});
if (sels == 2)
{
miNewHop.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
selected_steps = null;
newHop();
}
});
}
miEditStep.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
selected_steps = null;
editStep(stepMeta);
}
});
miEditDesc.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
editDescription(stepMeta);
}
});
miStepDist.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
stepMeta.distributes = true;
spoon.refreshGraph();
spoon.refreshTree();
}
});
miStepCopy.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
stepMeta.distributes = false;
spoon.refreshGraph();
spoon.refreshTree();
}
});
miCopies.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
selected_steps = null;
String tt = Messages.getString("SpoonGraph.Dialog.NrOfCopiesOfStep.Title"); //$NON-NLS-1$
String mt = Messages.getString("SpoonGraph.Dialog.NrOfCopiesOfStep.Message"); //$NON-NLS-1$
EnterNumberDialog nd = new EnterNumberDialog(shell, spoon.props, stepMeta.getCopies(), tt, mt);
int cop = nd.open();
if (cop >= 0)
{
if (cop == 0) cop = 1;
if (stepMeta.getCopies() != cop)
{
stepMeta.setCopies(cop);
spoon.refreshGraph();
}
}
}
});
miDupeStep.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
if (spoon.getTransMeta().nrSelectedSteps() <= 1)
{
spoon.dupeStep(stepMeta.getName());
}
else
{
for (int i = 0; i < spoon.getTransMeta().nrSteps(); i++)
{
StepMeta stepMeta = spoon.getTransMeta().getStep(i);
if (stepMeta.isSelected())
{
spoon.dupeStep(stepMeta.getName());
}
}
}
}
});
// Copy the selected steps to the clipboard.
miCopyStep.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
spoon.copySelected(spoon.getTransMeta().getSelectedSteps(), spoon.getTransMeta().getSelectedNotes());
}
});
miDelStep.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
delSelected(stepMeta);
}
});
miPopFieldsBef.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
selected_steps = null;
inputOutputFields(stepMeta, true);
}
});
miPopFieldsAft.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
selected_steps = null;
inputOutputFields(stepMeta, false);
}
});
setMenu(mPop);
}
else
{
final TransHopMeta hi = findHop(x, y);
if (hi != null) // We clicked on a HOP!
{
MenuItem miEditHop = new MenuItem(mPop, SWT.CASCADE);
miEditHop.setText(Messages.getString("SpoonGraph.PopupMenu.EditHop")); //$NON-NLS-1$
MenuItem miFlipHop = new MenuItem(mPop, SWT.CASCADE);
miFlipHop.setText(Messages.getString("SpoonGraph.PopupMenu.FlipDirection")); //$NON-NLS-1$
MenuItem miDisHop = new MenuItem(mPop, SWT.CASCADE);
if (hi.isEnabled())
miDisHop.setText(Messages.getString("SpoonGraph.PopupMenu.DisableHop")); //$NON-NLS-1$
else
miDisHop.setText(Messages.getString("SpoonGraph.PopupMenu.EnableHop")); //$NON-NLS-1$
MenuItem miDelHop = new MenuItem(mPop, SWT.CASCADE);
miDelHop.setText(Messages.getString("SpoonGraph.PopupMenu.DeleteHop")); //$NON-NLS-1$
miEditHop.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
selrect = null;
editHop(hi);
}
});
miFlipHop.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
selrect = null;
hi.flip();
if (spoon.getTransMeta().hasLoop(hi.getFromStep()))
{
spoon.refreshGraph();
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("SpoonGraph.Dialog.LoopsAreNotAllowed.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("SpoonGraph.Dialog.LoopsAreNotAllowed.Title")); //$NON-NLS-1$
mb.open();
hi.flip();
spoon.refreshGraph();
}
else
{
hi.setChanged();
spoon.refreshGraph();
spoon.refreshTree();
spoon.setShellText();
}
}
});
miDisHop.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
selrect = null;
TransHopMeta before = (TransHopMeta) hi.clone();
hi.setEnabled(!hi.isEnabled());
if (spoon.getTransMeta().hasLoop(hi.getToStep()))
{
hi.setEnabled(!hi.isEnabled());
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("SpoonGraph.Dialog.LoopAfterHopEnabled.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("SpoonGraph.Dialog.LoopAfterHopEnabled.Title")); //$NON-NLS-1$
mb.open();
}
else
{
TransHopMeta after = (TransHopMeta) hi.clone();
spoon.addUndoChange(new TransHopMeta[] { before }, new TransHopMeta[] { after }, new int[] { spoon.getTransMeta()
.indexOfTransHop(hi) });
spoon.refreshGraph();
spoon.refreshTree();
}
}
});
miDelHop.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
selrect = null;
int idx = spoon.getTransMeta().indexOfTransHop(hi);
spoon.addUndoDelete(new TransHopMeta[] { (TransHopMeta) hi.clone() }, new int[] { idx });
spoon.getTransMeta().removeTransHop(idx);
spoon.refreshTree();
spoon.refreshGraph();
}
});
setMenu(mPop);
}
else
{
// Clicked on the background: maybe we hit a note?
final NotePadMeta ni = spoon.getTransMeta().getNote(x, y);
if (ni != null) // A note
{
// Delete note
// Edit note
MenuItem miNoteEdit = new MenuItem(mPop, SWT.CASCADE);
miNoteEdit.setText(Messages.getString("SpoonGraph.PopupMenu.EditNote")); //$NON-NLS-1$
MenuItem miNoteDel = new MenuItem(mPop, SWT.CASCADE);
miNoteDel.setText(Messages.getString("SpoonGraph.PopupMenu.DeleteNote")); //$NON-NLS-1$
miNoteEdit.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
selrect = null;
editNote(ni);
}
});
miNoteDel.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
selrect = null;
int idx = spoon.getTransMeta().indexOfNote(ni);
if (idx >= 0)
{
spoon.getTransMeta().removeNote(idx);
spoon.addUndoDelete(new NotePadMeta[] { (NotePadMeta) ni.clone() }, new int[] { idx });
redraw();
}
}
});
setMenu(mPop);
}
else
{
// No step, hop or note: clicked on the background....
MenuItem miNoteNew = new MenuItem(mPop, SWT.CASCADE);
miNoteNew.setText(Messages.getString("SpoonGraph.PopupMenu.NewNote")); //$NON-NLS-1$
miNoteNew.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
selrect = null;
String title = Messages.getString("SpoonGraph.Dialog.NoteEditor.Title"); //$NON-NLS-1$
String message = Messages.getString("SpoonGraph.Dialog.NoteEditor.Message"); //$NON-NLS-1$
EnterTextDialog dd = new EnterTextDialog(shell, title, message, ""); //$NON-NLS-1$
String n = dd.open();
if (n != null)
{
NotePadMeta npi = new NotePadMeta(n, lastclick.x, lastclick.y, Const.NOTE_MIN_SIZE, Const.NOTE_MIN_SIZE);
spoon.getTransMeta().addNote(npi);
spoon.addUndoNew(new NotePadMeta[] { npi }, new int[] { spoon.getTransMeta().indexOfNote(npi) });
redraw();
}
}
});
MenuItem miStepNew = new MenuItem(mPop, SWT.CASCADE);
miStepNew.setText(Messages.getString("SpoonGraph.PopupMenu.NewStep")); //$NON-NLS-1$
Menu mStep = new Menu(miStepNew);
StepLoader steploader = StepLoader.getInstance();
final StepPlugin sp[] = steploader.getStepsWithType(StepPlugin.TYPE_ALL);
for (int i = 0; i < sp.length; i++)
{
// System.out.println("Add step type :
// "+sp[i].getDescription());
MenuItem miStepX = new MenuItem(mStep, SWT.CASCADE);
miStepX.setText(sp[i].getDescription());
final String description = sp[i].getDescription();
miStepX.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
StepMeta stepMeta = spoon.newStep(description, description, false, true);
stepMeta.setLocation(mousex, mousey);
stepMeta.setDraw(true);
redraw();
}
});
}
MenuItem miPasteStep = new MenuItem(mPop, SWT.CASCADE);
miPasteStep.setText(Messages.getString("SpoonGraph.PopupMenu.PasteStepFromClipboard")); //$NON-NLS-1$
final String clipcontent = spoon.fromClipboard();
if (clipcontent == null) miPasteStep.setEnabled(false);
// Past steps on the clipboard to the transformation...
miPasteStep.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
Point loc = new Point(mousex, mousey);
spoon.pasteXML(clipcontent, loc);
}
});
miStepNew.setMenu(mStep);
setMenu(mPop);
}
}
}
}
private void setToolTip(int x, int y)
{
final StepMeta stepMeta = spoon.getTransMeta().getStep(x, y, iconsize);
if (stepMeta != null) // We clicked on a Step!
{
// Also: set the tooltip!
if (stepMeta.getDescription() != null)
{
String desc = stepMeta.getDescription();
int le = desc.length() >= 200 ? 200 : desc.length();
String tip = desc.substring(0, le);
if (!tip.equalsIgnoreCase(getToolTipText()))
{
setToolTipText(tip);
}
}
else
{
setToolTipText(stepMeta.getName());
}
}
else
{
final TransHopMeta hi = findHop(x, y);
if (hi != null) // We clicked on a HOP!
{
// Set the tooltip for the hop:
setToolTipText(hi.toString());
}
else
{
setToolTipText(null);
}
}
}
public void delSelected(StepMeta stMeta)
{
int nrsels = spoon.getTransMeta().nrSelectedSteps();
if (nrsels == 0)
{
spoon.delStep(stMeta.getName());
}
else
{
if (stMeta != null && !stMeta.isSelected()) nrsels++;
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.ICON_WARNING);
mb.setText(Messages.getString("SpoonGraph.Dialog.Warning.DeleteSteps.Title")); //$NON-NLS-1$
String message = Messages.getString("SpoonGraph.Dialog.Warning.DeleteSteps.Message") + nrsels + Messages.getString("SpoonGraph.Dialog.Warning.DeleteSteps2.Message") + Const.CR; //$NON-NLS-1$ //$NON-NLS-2$
for (int i = spoon.getTransMeta().nrSteps() - 1; i >= 0; i
{
StepMeta stepMeta = spoon.getTransMeta().getStep(i);
if (stepMeta.isSelected() || (stMeta != null && stMeta.equals(stepMeta)))
{
message += " --> " + stepMeta.getName() + Const.CR; //$NON-NLS-1$
}
}
mb.setMessage(message);
int result = mb.open();
if (result == SWT.YES)
{
for (int i = spoon.getTransMeta().nrSteps() - 1; i >= 0; i
{
StepMeta stepMeta = spoon.getTransMeta().getStep(i);
if (stepMeta.isSelected() || (stMeta != null && stMeta.equals(stepMeta)))
{
spoon.delStep(stepMeta.getName());
}
}
}
}
}
public void editDescription(StepMeta stepMeta)
{
String title = Messages.getString("SpoonGraph.Dialog.StepDescription.Title"); //$NON-NLS-1$
String message = Messages.getString("SpoonGraph.Dialog.StepDescription.Message"); //$NON-NLS-1$
EnterTextDialog dd = new EnterTextDialog(shell, title, message, stepMeta.getDescription());
String d = dd.open();
if (d != null) stepMeta.setDescription(d);
}
/**
* Display the input- or outputfields for a step.
*
* @param stepMeta The step (it's metadata) to query
* @param before set to true if you want to have the fields going INTO the step, false if you want to see all the
* fields that exit the step.
*/
private void inputOutputFields(StepMeta stepMeta, boolean before)
{
spoon.refreshGraph();
SearchFieldsProgressDialog op = new SearchFieldsProgressDialog(spoon.getTransMeta(), stepMeta, before);
try
{
final ProgressMonitorDialog pmd = new ProgressMonitorDialog(shell);
// Run something in the background to cancel active database queries, forecably if needed!
Runnable run = new Runnable()
{
public void run()
{
IProgressMonitor monitor = pmd.getProgressMonitor();
while (pmd.getShell()==null || ( !pmd.getShell().isDisposed() && !monitor.isCanceled() ))
{
try { Thread.sleep(250); } catch(InterruptedException e) { };
}
if (monitor.isCanceled()) // Disconnect and see what happens!
{
try { spoon.getTransMeta().cancelQueries(); } catch(Exception e) {};
}
}
};
// Dump the cancel looker in the background!
new Thread(run).start();
pmd.run(true, true, op);
}
catch (InvocationTargetException e)
{
new ErrorDialog(shell, spoon.props, Messages.getString("SpoonGraph.Dialog.GettingFields.Title"), Messages.getString("SpoonGraph.Dialog.GettingFields.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
catch (InterruptedException e)
{
new ErrorDialog(shell, spoon.props, Messages.getString("SpoonGraph.Dialog.GettingFields.Title"), Messages.getString("SpoonGraph.Dialog.GettingFields.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
Row fields = op.getFields();
if (fields != null && fields.size() > 0)
{
StepFieldsDialog sfd = new StepFieldsDialog(shell, SWT.NONE, log, stepMeta.getName(), fields, spoon.props);
String sn = (String) sfd.open();
if (sn != null)
{
StepMeta esi = spoon.getTransMeta().findStep(sn);
if (esi != null)
{
editStep(esi);
}
}
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
mb.setMessage(Messages.getString("SpoonGraph.Dialog.CouldntFindFields.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("SpoonGraph.Dialog.CouldntFindFields.Title")); //$NON-NLS-1$
mb.open();
}
}
public void paintControl(PaintEvent e)
{
Point area = getArea();
if (area.x == 0 || area.y == 0) return; // nothing to do!
Display disp = shell.getDisplay();
Image img = getTransformationImage(disp, area.x, area.y);
e.gc.drawImage(img, 0, 0);
img.dispose();
spoon.setShellText();
}
public Image getTransformationImage(Display disp, int x, int y)
{
TransPainter transPainter = new TransPainter(spoon.getTransMeta(), new Point(x, y), hori, vert, candidate, drop_candidate, selrect);
Image img = transPainter.getTransformationImage();
return img;
}
public void drawTrans(GC gc)
{
if (spoon.props.isAntiAliasingEnabled()) gc.setAntialias(SWT.ON);
shadowsize = spoon.props.getShadowSize();
Point area = getArea();
Point max = spoon.getTransMeta().getMaximum();
Point thumb = getThumb(area, max);
offset = getOffset(thumb, area);
hori.setThumb(thumb.x);
vert.setThumb(thumb.y);
gc.setFont(GUIResource.getInstance().getFontNote());
// First the notes
for (int i = 0; i < spoon.getTransMeta().nrNotes(); i++)
{
NotePadMeta ni = spoon.getTransMeta().getNote(i);
drawNote(gc, ni);
}
gc.setFont(GUIResource.getInstance().getFontGraph());
gc.setBackground(GUIResource.getInstance().getColorGraph());
if (shadowsize > 0)
{
for (int i = 0; i < spoon.getTransMeta().nrSteps(); i++)
{
StepMeta stepMeta = spoon.getTransMeta().getStep(i);
if (stepMeta.isDrawn()) drawStepShadow(gc, stepMeta);
}
}
for (int i = 0; i < spoon.getTransMeta().nrTransHops(); i++)
{
TransHopMeta hi = spoon.getTransMeta().getTransHop(i);
drawHop(gc, hi);
}
if (candidate != null)
{
drawHop(gc, candidate, true);
}
for (int i = 0; i < spoon.getTransMeta().nrSteps(); i++)
{
StepMeta stepMeta = spoon.getTransMeta().getStep(i);
if (stepMeta.isDrawn()) drawStep(gc, stepMeta);
}
if (drop_candidate != null)
{
gc.setLineStyle(SWT.LINE_SOLID);
gc.setForeground(GUIResource.getInstance().getColorBlack());
Point screen = real2screen(drop_candidate.x, drop_candidate.y);
gc.drawRectangle(screen.x, screen.y, iconsize, iconsize);
}
drawRect(gc, selrect);
}
private void drawHop(GC gc, TransHopMeta hi)
{
drawHop(gc, hi, false);
}
private void drawNote(GC gc, NotePadMeta ni)
{
int flags = SWT.DRAW_DELIMITER | SWT.DRAW_TAB | SWT.DRAW_TRANSPARENT;
if (ni.isSelected())
gc.setLineWidth(2);
else
gc.setLineWidth(1);
org.eclipse.swt.graphics.Point ext = gc.textExtent(ni.getNote(), flags);
Point p = new Point(ext.x, ext.y);
Point loc = ni.getLocation();
Point note = real2screen(loc.x, loc.y);
int margin = Const.NOTE_MARGIN;
p.x += 2 * margin;
p.y += 2 * margin;
int width = ni.width;
int height = ni.height;
if (p.x > width) width = p.x;
if (p.y > height) height = p.y;
int noteshape[] = new int[] { note.x, note.y, // Top left
note.x + width + 2 * margin, note.y, // Top right
note.x + width + 2 * margin, note.y + height, // bottom right 1
note.x + width, note.y + height + 2 * margin, // bottom right 2
note.x + width, note.y + height, // bottom right 3
note.x + width + 2 * margin, note.y + height, // bottom right 1
note.x + width, note.y + height + 2 * margin, // bottom right 2
note.x, note.y + height + 2 * margin // bottom left
};
int s = spoon.props.getShadowSize();
int shadow[] = new int[] { note.x + s, note.y + s, // Top left
note.x + width + 2 * margin + s, note.y + s, // Top right
note.x + width + 2 * margin + s, note.y + height + s, // bottom
// right 1
note.x + width + s, note.y + height + 2 * margin + s, // bottom
// right 2
note.x + s, note.y + height + 2 * margin + s // bottom left
};
gc.setForeground(GUIResource.getInstance().getColorLightGray());
gc.setBackground(GUIResource.getInstance().getColorLightGray());
gc.fillPolygon(shadow);
gc.setForeground(GUIResource.getInstance().getColorGray());
gc.setBackground(GUIResource.getInstance().getColorYellow());
gc.fillPolygon(noteshape);
gc.drawPolygon(noteshape);
// gc.fillRectangle(ni.xloc, ni.yloc, width+2*margin, heigth+2*margin);
// gc.drawRectangle(ni.xloc, ni.yloc, width+2*margin, heigth+2*margin);
gc.setForeground(GUIResource.getInstance().getColorBlack());
gc.drawText(ni.getNote(), note.x + margin, note.y + margin, flags);
ni.width = width; // Save for the "mouse" later on...
ni.height = height;
if (ni.isSelected())
gc.setLineWidth(1);
else
gc.setLineWidth(2);
}
private void drawHop(GC gc, TransHopMeta hi, boolean is_candidate)
{
StepMeta fs = hi.getFromStep();
StepMeta ts = hi.getToStep();
if (fs != null && ts != null)
{
if (shadowsize > 0) drawLineShadow(gc, fs, ts, hi, false);
drawLine(gc, fs, ts, hi, is_candidate);
}
}
private void drawStepShadow(GC gc, StepMeta stepMeta)
{
if (stepMeta == null) return;
Point pt = stepMeta.getLocation();
int x, y;
if (pt != null)
{
x = pt.x;
y = pt.y;
}
else
{
x = 50;
y = 50;
}
Point screen = real2screen(x, y);
// First draw the shadow...
gc.setBackground(GUIResource.getInstance().getColorLightGray());
gc.setForeground(GUIResource.getInstance().getColorLightGray());
int s = shadowsize;
gc.fillRectangle(screen.x + s, screen.y + s, iconsize, iconsize);
}
private void drawStep(GC gc, StepMeta stepMeta)
{
if (stepMeta == null) return;
Point pt = stepMeta.getLocation();
int x, y;
if (pt != null)
{
x = pt.x;
y = pt.y;
}
else
{
x = 50;
y = 50;
}
Point screen = real2screen(x, y);
String name = stepMeta.getName();
if (stepMeta.isSelected())
gc.setLineWidth(linewidth + 2);
else
gc.setLineWidth(linewidth);
gc.setBackground(GUIResource.getInstance().getColorRed());
gc.setForeground(GUIResource.getInstance().getColorBlack());
gc.fillRectangle(screen.x, screen.y, iconsize, iconsize);
String steptype = stepMeta.getStepID();
Image im = (Image) GUIResource.getInstance().getImagesSteps().get(steptype);
if (im != null) // Draw the icon!
{
org.eclipse.swt.graphics.Rectangle bounds = im.getBounds();
gc.drawImage(im, 0, 0, bounds.width, bounds.height, screen.x, screen.y, iconsize, iconsize);
}
gc.setBackground(GUIResource.getInstance().getColorBackground());
gc.drawRectangle(screen.x - 1, screen.y - 1, iconsize + 1, iconsize + 1);
// gc.setXORMode(true);
org.eclipse.swt.graphics.Point textsize = gc.textExtent(name);
int xpos = screen.x + (iconsize / 2) - (textsize.x / 2);
int ypos = screen.y + iconsize + 5;
if (shadowsize > 0)
{
gc.setForeground(GUIResource.getInstance().getColorLightGray());
gc.drawText(name, xpos + shadowsize, ypos + shadowsize, SWT.DRAW_TRANSPARENT);
}
gc.setForeground(GUIResource.getInstance().getColorBlack());
gc.drawText(name, xpos, ypos, SWT.DRAW_TRANSPARENT);
if (stepMeta.getCopies() > 1)
{
gc.setBackground(GUIResource.getInstance().getColorBackground());
gc.setForeground(GUIResource.getInstance().getColorBlack());
gc.drawText("x" + stepMeta.getCopies(), screen.x - 5, screen.y - 5); //$NON-NLS-1$
}
}
private void drawLineShadow(GC gc, StepMeta fs, StepMeta ts, TransHopMeta hi, boolean is_candidate)
{
int line[] = getLine(fs, ts);
int s = shadowsize;
for (int i = 0; i < line.length; i++)
line[i] += s;
gc.setLineWidth(linewidth);
gc.setForeground(GUIResource.getInstance().getColorLightGray());
drawArrow(gc, line);
}
private void drawLine(GC gc, StepMeta fs, StepMeta ts, TransHopMeta hi, boolean is_candidate)
{
StepMetaInterface fsii = fs.getStepMetaInterface();
StepMetaInterface tsii = ts.getStepMetaInterface();
int line[] = getLine(fs, ts);
gc.setLineWidth(linewidth);
Color col;
if (is_candidate)
{
col = GUIResource.getInstance().getColorBlue();
}
else
{
if (hi.isEnabled())
{
String[] targetSteps = fsii.getTargetSteps();
String[] infoSteps = tsii.getInfoSteps();
// System.out.println("Normal step: "+fs+" --> "+ts+",
// "+(infoSteps!=null)+", "+(targetSteps!=null));
if (targetSteps == null) // Normal link: distribute or copy data...
{
// Or perhaps it's an informational link: draw different
// color...
if (Const.indexOfString(fs.getName(), infoSteps) >= 0)
{
if (fs.distributes)
col = GUIResource.getInstance().getColorYellow();
else
col = GUIResource.getInstance().getColorMagenta();
}
else
{
if (fs.distributes)
col = GUIResource.getInstance().getColorGreen();
else
col = GUIResource.getInstance().getColorRed();
}
}
else
{
// Visual check to see if the target step is specified...
if (Const.indexOfString(ts.getName(), fsii.getTargetSteps()) >= 0)
{
col = GUIResource.getInstance().getColorBlack();
}
else
{
gc.setLineStyle(SWT.LINE_DOT);
col = GUIResource.getInstance().getColorOrange();
}
}
}
else
{
col = GUIResource.getInstance().getColorGray();
}
}
gc.setForeground(col);
if (hi.split) gc.setLineWidth(linewidth + 2);
drawArrow(gc, line);
if (hi.split) gc.setLineWidth(linewidth);
gc.setForeground(GUIResource.getInstance().getColorBlack());
gc.setBackground(GUIResource.getInstance().getColorBackground());
gc.setLineStyle(SWT.LINE_SOLID);
}
private Point getArea()
{
org.eclipse.swt.graphics.Rectangle rect = getClientArea();
Point area = new Point(rect.width, rect.height);
return area;
}
private Point getThumb(Point area, Point max)
{
Point thumb = new Point(0, 0);
if (max.x <= area.x)
thumb.x = 100;
else
thumb.x = 100 * area.x / max.x;
if (max.y <= area.y)
thumb.y = 100;
else
thumb.y = 100 * area.y / max.y;
return thumb;
}
private Point getOffset()
{
Point area = getArea();
Point max = spoon.getTransMeta().getMaximum();
Point thumb = getThumb(area, max);
Point offset = getOffset(thumb, area);
return offset;
}
private Point getOffset(Point thumb, Point area)
{
Point p = new Point(0, 0);
Point sel = new Point(hori.getSelection(), vert.getSelection());
if (thumb.x == 0 || thumb.y == 0) return p;
p.x = -sel.x * area.x / thumb.x;
p.y = -sel.y * area.y / thumb.y;
return p;
}
public int sign(int n)
{
return n < 0 ? -1 : (n > 0 ? 1 : 1);
}
private void editStep(StepMeta stepMeta)
{
spoon.editStepInfo(stepMeta);
}
private void editNote(NotePadMeta ni)
{
NotePadMeta before = (NotePadMeta) ni.clone();
String title = Messages.getString("SpoonGraph.Dialog.EditNote.Title"); //$NON-NLS-1$
String message = Messages.getString("SpoonGraph.Dialog.EditNote.Message"); //$NON-NLS-1$
EnterTextDialog dd = new EnterTextDialog(shell, title, message, ni.getNote());
String n = dd.open();
if (n != null)
{
ni.setChanged();
ni.setNote(n);
ni.width = Const.NOTE_MIN_SIZE;
ni.height = Const.NOTE_MIN_SIZE;
NotePadMeta after = (NotePadMeta) ni.clone();
spoon.addUndoChange(new NotePadMeta[] { before }, new NotePadMeta[] { after }, new int[] { spoon.getTransMeta().indexOfNote(ni) });
spoon.refreshGraph();
}
}
private void editHop(TransHopMeta hopinfo)
{
String name = hopinfo.toString();
log.logDebug(toString(), Messages.getString("SpoonGraph.Logging.EditingHop") + name); //$NON-NLS-1$
spoon.editHop(name);
}
private void newHop()
{
StepMeta fr = spoon.getTransMeta().getSelectedStep(0);
StepMeta to = spoon.getTransMeta().getSelectedStep(1);
spoon.newHop(fr, to);
}
private void drawArrow(GC gc, int line[])
{
double theta = Math.toRadians(10); // arrowhead sharpness
int size = 30 + (linewidth - 1) * 5; // arrowhead length
Point screen_from = real2screen(line[0], line[1]);
Point screen_to = real2screen(line[2], line[3]);
int mx, my;
int x1 = screen_from.x;
int y1 = screen_from.y;
int x2 = screen_to.x;
int y2 = screen_to.y;
int x3;
int y3;
int x4;
int y4;
int a, b, dist;
double factor, angle;
gc.drawLine(x1, y1, x2, y2);
// in between 2 points
mx = x1 + (x2 - x1) / 2;
my = y1 + (y2 - y1) / 2;
a = Math.abs(x2 - x1);
b = Math.abs(y2 - y1);
dist = (int) Math.sqrt(a * a + b * b);
// determine factor (position of arrow to left side or right side
// 0-->100%)
if (dist >= 2 * iconsize)
factor = 1.5;
else
factor = 1.2;
// in between 2 points
mx = (int) (x1 + factor * (x2 - x1) / 2);
my = (int) (y1 + factor * (y2 - y1) / 2);
// calculate points for arrowhead
angle = Math.atan2(y2 - y1, x2 - x1) + Math.PI;
x3 = (int) (mx + Math.cos(angle - theta) * size);
y3 = (int) (my + Math.sin(angle - theta) * size);
x4 = (int) (mx + Math.cos(angle + theta) * size);
y4 = (int) (my + Math.sin(angle + theta) * size);
// draw arrowhead
// gc.drawLine( mx, my, x3, y3 );
// gc.drawLine( mx, my, x4, y4 );
// gc.drawLine( x3, y3, x4, y4 );
Color fore = gc.getForeground();
Color back = gc.getBackground();
gc.setBackground(fore);
gc.fillPolygon(new int[] { mx, my, x3, y3, x4, y4 });
gc.setBackground(back);
}
private boolean pointOnLine(int x, int y, int line[])
{
int dx, dy;
int pm = HOP_SEL_MARGIN / 2;
boolean retval = false;
for (dx = -pm; dx <= pm && !retval; dx++)
{
for (dy = -pm; dy <= pm && !retval; dy++)
{
retval = pointOnThinLine(x + dx, y + dy, line);
}
}
return retval;
}
private boolean pointOnThinLine(int x, int y, int line[])
{
int x1 = line[0];
int y1 = line[1];
int x2 = line[2];
int y2 = line[3];
// Not in the square formed by these 2 points: ignore!
if (!(((x >= x1 && x <= x2) || (x >= x2 && x <= x1)) && ((y >= y1 && y <= y2) || (y >= y2 && y <= y1)))) return false;
double angle_line = Math.atan2(y2 - y1, x2 - x1) + Math.PI;
double angle_point = Math.atan2(y - y1, x - x1) + Math.PI;
// Same angle, or close enough?
if (angle_point >= angle_line - 0.01 && angle_point <= angle_line + 0.01) return true;
return false;
}
private void snaptogrid(int size)
{
if (spoon.getTransMeta().nrSelectedSteps() == 0) return;
// First look for the minimum x coordinate...
StepMeta steps[] = new StepMeta[spoon.getTransMeta().nrSelectedSteps()];
Point before[] = new Point[spoon.getTransMeta().nrSelectedSteps()];
Point after[] = new Point[spoon.getTransMeta().nrSelectedSteps()];
int nr = 0;
for (int i = 0; i < spoon.getTransMeta().nrSteps(); i++)
{
StepMeta stepMeta = spoon.getTransMeta().getStep(i);
if (stepMeta.isSelected() && stepMeta.isDrawn())
{
steps[nr] = stepMeta;
Point p = stepMeta.getLocation();
before[nr] = new Point(p.x, p.y);
// What's the modulus ?
int dx = p.x % size;
int dy = p.y % size;
// Correct the location to the nearest grid line!
// This means for size = 10
// x = 3: dx=3, dx<=5 --> x=3-3 = 0;
// x = 7: dx=7, dx> 5 --> x=3+10-3 = 10;
// x = 10: dx=0, dx<=5 --> x=10-0 = 10;
if (dx > size / 2)
p.x += size - dx;
else
p.x -= dx;
if (dy > size / 2)
p.y += size - dy;
else
p.y -= dy;
after[nr] = new Point(p.x, p.y);
nr++;
}
}
spoon.addUndoPosition(steps, spoon.getTransMeta().getStepIndexes(steps), before, after);
redraw();
}
private void allignleft()
{
if (spoon.getTransMeta().nrSelectedSteps() == 0) return;
StepMeta steps[] = new StepMeta[spoon.getTransMeta().nrSelectedSteps()];
Point before[] = new Point[spoon.getTransMeta().nrSelectedSteps()];
Point after[] = new Point[spoon.getTransMeta().nrSelectedSteps()];
int nr = 0;
int min = 99999;
// First look for the minimum x coordinate...
for (int i = 0; i < spoon.getTransMeta().nrSteps(); i++)
{
StepMeta stepMeta = spoon.getTransMeta().getStep(i);
if (stepMeta.isSelected() && stepMeta.isDrawn())
{
Point p = stepMeta.getLocation();
if (p.x < min) min = p.x;
}
}
// Then apply the coordinate...
for (int i = 0; i < spoon.getTransMeta().nrSteps(); i++)
{
StepMeta stepMeta = spoon.getTransMeta().getStep(i);
if (stepMeta.isSelected() && stepMeta.isDrawn())
{
steps[nr] = stepMeta;
Point p = stepMeta.getLocation();
before[nr] = new Point(p.x, p.y);
stepMeta.setLocation(min, p.y);
after[nr] = new Point(min, p.y);
nr++;
}
}
spoon.addUndoPosition(steps, spoon.getTransMeta().getStepIndexes(steps), before, after);
redraw();
}
private void allignright()
{
if (spoon.getTransMeta().nrSelectedSteps() == 0) return;
StepMeta steps[] = new StepMeta[spoon.getTransMeta().nrSelectedSteps()];
Point before[] = new Point[spoon.getTransMeta().nrSelectedSteps()];
Point after[] = new Point[spoon.getTransMeta().nrSelectedSteps()];
int nr = 0;
int max = -99999;
// First look for the maximum x coordinate...
for (int i = 0; i < spoon.getTransMeta().nrSteps(); i++)
{
StepMeta stepMeta = spoon.getTransMeta().getStep(i);
if (stepMeta.isSelected() && stepMeta.isDrawn())
{
Point p = stepMeta.getLocation();
if (p.x > max) max = p.x;
}
}
// Then apply the coordinate...
for (int i = 0; i < spoon.getTransMeta().nrSteps(); i++)
{
StepMeta stepMeta = spoon.getTransMeta().getStep(i);
if (stepMeta.isSelected() && stepMeta.isDrawn())
{
steps[nr] = stepMeta;
Point p = stepMeta.getLocation();
before[nr] = new Point(p.x, p.y);
stepMeta.setLocation(max, p.y);
after[nr] = new Point(max, p.y);
nr++;
}
}
spoon.addUndoPosition(steps, spoon.getTransMeta().getStepIndexes(steps), before, after);
redraw();
}
private void alligntop()
{
if (spoon.getTransMeta().nrSelectedSteps() == 0) return;
StepMeta steps[] = new StepMeta[spoon.getTransMeta().nrSelectedSteps()];
Point before[] = new Point[spoon.getTransMeta().nrSelectedSteps()];
Point after[] = new Point[spoon.getTransMeta().nrSelectedSteps()];
int nr = 0;
int min = 99999;
// First look for the minimum y coordinate...
for (int i = 0; i < spoon.getTransMeta().nrSteps(); i++)
{
StepMeta stepMeta = spoon.getTransMeta().getStep(i);
if (stepMeta.isSelected() && stepMeta.isDrawn())
{
Point p = stepMeta.getLocation();
if (p.y < min) min = p.y;
}
}
// Then apply the coordinate...
for (int i = 0; i < spoon.getTransMeta().nrSteps(); i++)
{
StepMeta stepMeta = spoon.getTransMeta().getStep(i);
if (stepMeta.isSelected() && stepMeta.isDrawn())
{
steps[nr] = stepMeta;
Point p = stepMeta.getLocation();
before[nr] = new Point(p.x, p.y);
stepMeta.setLocation(p.x, min);
after[nr] = new Point(p.x, min);
nr++;
}
}
spoon.addUndoPosition(steps, spoon.getTransMeta().getStepIndexes(steps), before, after);
redraw();
}
private void allignbottom()
{
if (spoon.getTransMeta().nrSelectedSteps() == 0) return;
StepMeta steps[] = new StepMeta[spoon.getTransMeta().nrSelectedSteps()];
Point before[] = new Point[spoon.getTransMeta().nrSelectedSteps()];
Point after[] = new Point[spoon.getTransMeta().nrSelectedSteps()];
int nr = 0;
int max = -99999;
// First look for the maximum y coordinate...
for (int i = 0; i < spoon.getTransMeta().nrSteps(); i++)
{
StepMeta stepMeta = spoon.getTransMeta().getStep(i);
if (stepMeta.isSelected() && stepMeta.isDrawn())
{
Point p = stepMeta.getLocation();
if (p.y > max) max = p.y;
}
}
// Then apply the coordinate...
for (int i = 0; i < spoon.getTransMeta().nrSteps(); i++)
{
StepMeta stepMeta = spoon.getTransMeta().getStep(i);
if (stepMeta.isSelected() && stepMeta.isDrawn())
{
steps[nr] = stepMeta;
Point p = stepMeta.getLocation();
before[nr] = new Point(p.x, p.y);
stepMeta.setLocation(p.x, max);
after[nr] = new Point(p.x, max);
nr++;
}
}
spoon.addUndoPosition(steps, spoon.getTransMeta().getStepIndexes(steps), before, after);
redraw();
}
private void distributehorizontal()
{
if (spoon.getTransMeta().nrSelectedSteps() == 0) return;
StepMeta steps[] = new StepMeta[spoon.getTransMeta().nrSelectedSteps()];
Point before[] = new Point[spoon.getTransMeta().nrSelectedSteps()];
Point after[] = new Point[spoon.getTransMeta().nrSelectedSteps()];
int min = 99999;
int max = -99999;
int sels = spoon.getTransMeta().nrSelectedSteps();
if (sels <= 1) return;
int order[] = new int[sels];
// First look for the minimum & maximum x coordinate...
int selnr = 0;
for (int i = 0; i < spoon.getTransMeta().nrSteps(); i++)
{
StepMeta stepMeta = spoon.getTransMeta().getStep(i);
if (stepMeta.isSelected() && stepMeta.isDrawn())
{
Point p = stepMeta.getLocation();
if (p.x < min) min = p.x;
if (p.x > max) max = p.x;
order[selnr] = i;
selnr++;
}
}
// Difficult to keep the steps in the correct order.
// If you just set the x-coordinates, you get special effects.
// Best is to keep the current order of things.
// First build an arraylist and store the order there.
// Then sort order[], based upon the coordinate of the step.
for (int i = 0; i < sels; i++)
{
for (int j = 0; j < sels - 1; j++)
{
Point p1 = spoon.getTransMeta().getStep(order[j]).getLocation();
Point p2 = spoon.getTransMeta().getStep(order[j + 1]).getLocation();
if (p1.x > p2.x) // swap
{
int dummy = order[j];
order[j] = order[j + 1];
order[j + 1] = dummy;
}
}
}
// The distance between two steps becomes.
int distance = (max - min) / (sels - 1);
for (int i = 0; i < sels; i++)
{
steps[i] = spoon.getTransMeta().getStep(order[i]);
Point p = steps[i].getLocation();
before[i] = new Point(p.x, p.y);
p.x = min + (i * distance);
after[i] = new Point(p.x, p.y);
}
// Undo!
spoon.addUndoPosition(steps, spoon.getTransMeta().getStepIndexes(steps), before, after);
redraw();
}
public void distributevertical()
{
if (spoon.getTransMeta().nrSelectedSteps() == 0) return;
StepMeta steps[] = new StepMeta[spoon.getTransMeta().nrSelectedSteps()];
Point before[] = new Point[spoon.getTransMeta().nrSelectedSteps()];
Point after[] = new Point[spoon.getTransMeta().nrSelectedSteps()];
int min = 99999;
int max = -99999;
int sels = spoon.getTransMeta().nrSelectedSteps();
if (sels <= 1) return;
int order[] = new int[sels];
// First look for the minimum & maximum y coordinate...
int selnr = 0;
for (int i = 0; i < spoon.getTransMeta().nrSteps(); i++)
{
StepMeta stepMeta = spoon.getTransMeta().getStep(i);
if (stepMeta.isSelected() && stepMeta.isDrawn())
{
Point p = stepMeta.getLocation();
if (p.y < min) min = p.y;
if (p.y > max) max = p.y;
order[selnr] = i;
selnr++;
}
}
// Difficult to keep the steps in the correct order.
// If you just set the x-coordinates, you get special effects.
// Best is to keep the current order of things.
// First build an arraylist and store the order there.
// Then sort order[], based upon the coordinate of the step.
for (int i = 0; i < sels; i++)
{
for (int j = 0; j < sels - 1; j++)
{
Point p1 = spoon.getTransMeta().getStep(order[j]).getLocation();
Point p2 = spoon.getTransMeta().getStep(order[j + 1]).getLocation();
if (p1.y > p2.y) // swap
{
int dummy = order[j];
order[j] = order[j + 1];
order[j + 1] = dummy;
}
}
}
// The distance between two steps becomes.
int distance = (max - min) / (sels - 1);
for (int i = 0; i < sels; i++)
{
steps[i] = spoon.getTransMeta().getStep(order[i]);
Point p = steps[i].getLocation();
before[i] = new Point(p.x, p.y);
p.y = min + (i * distance);
after[i] = new Point(p.x, p.y);
}
// Undo!
spoon.addUndoPosition(steps, spoon.getTransMeta().getStepIndexes(steps), before, after);
redraw();
}
private void detach(StepMeta stepMeta)
{
TransHopMeta hfrom = spoon.getTransMeta().findTransHopTo(stepMeta);
TransHopMeta hto = spoon.getTransMeta().findTransHopFrom(stepMeta);
if (hfrom != null && hto != null)
{
if (spoon.getTransMeta().findTransHop(hfrom.getFromStep(), hto.getToStep()) == null)
{
TransHopMeta hnew = new TransHopMeta(hfrom.getFromStep(), hto.getToStep());
spoon.getTransMeta().addTransHop(hnew);
spoon.addUndoNew(new TransHopMeta[] { hnew }, new int[] { spoon.getTransMeta().indexOfTransHop(hnew) });
spoon.refreshTree();
}
}
if (hfrom != null)
{
int fromidx = spoon.getTransMeta().indexOfTransHop(hfrom);
if (fromidx >= 0)
{
spoon.getTransMeta().removeTransHop(fromidx);
spoon.refreshTree();
}
}
if (hto != null)
{
int toidx = spoon.getTransMeta().indexOfTransHop(hto);
if (toidx >= 0)
{
spoon.getTransMeta().removeTransHop(toidx);
spoon.refreshTree();
}
}
spoon.refreshTree();
redraw();
}
private void drawRect(GC gc, Rectangle rect)
{
if (rect == null) return;
gc.setLineStyle(SWT.LINE_DASHDOT);
gc.setLineWidth(linewidth);
gc.setForeground(GUIResource.getInstance().getColorGray());
gc.drawRectangle(rect.x + offset.x, rect.y + offset.y, rect.width, rect.height);
gc.setLineStyle(SWT.LINE_SOLID);
}
// Preview the selected steps...
public void preview()
{
// Create a new transformation
TransMeta preview = new TransMeta();
// Copy the selected steps into it...
for (int i = 0; i < spoon.getTransMeta().nrSteps(); i++)
{
StepMeta stepMeta = spoon.getTransMeta().getStep(i);
if (stepMeta.isSelected())
{
preview.addStep(stepMeta);
}
}
// Copy the relevant TransHops into it...
for (int i = 0; i < spoon.getTransMeta().nrTransHops(); i++)
{
TransHopMeta hi = spoon.getTransMeta().getTransHop(i);
if (hi.isEnabled())
{
StepMeta fr = hi.getFromStep();
StepMeta to = hi.getToStep();
if (fr.isSelected() && to.isSelected())
{
preview.addTransHop(hi);
}
}
}
}
public void newProps()
{
GUIResource.getInstance().reload();
iconsize = spoon.props.getIconSize();
linewidth = spoon.props.getLineWidth();
}
public String toString()
{
return this.getClass().getName();
}
}
|
package com.kierdavis.ultracommand;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
public class UltraCommand extends JavaPlugin {
private Map<String, CustomCommand> commands;
private File commandsFile;
public void onEnable() {
commands = new HashMap<String, CustomCommand>();
commandsFile = new File(getDataFolder(), "commands.yml");
loadCustomCommands();
getLogger().info("Loaded " + Integer.toString(commands.size()) + " commands.");
getServer().getPluginManager().registerEvents(new PlayerListener(this), this);
}
public void onDisable() {
}
public CustomCommand getCustomCommand(String name) {
return commands.get(name.toLowerCase());
}
public void addCustomCommand(String name, CustomCommand cmd) {
commands.put(name.toLowerCase(), cmd);
}
public void removeCustomCommand(String name) {
commands.remove(name);
}
public void createCommandsFile() {
File parent = commandsFile.getParentFile();
try {
if (!parent.exists()) {
parent.mkdirs();
}
if (!commandsFile.exists()) {
boolean b = commandsFile.createNewFile();
if (b) {
getLogger().info("Created " + commandsFile.toString());
}
}
}
catch (IOException e) {
getLogger().warning("Could not create " + commandsFile.toString() + ": " + e.toString());
}
}
public void loadCustomCommands() {
if (!commandsFile.exists()) {
createCommandsFile();
return;
}
FileConfiguration commandsConfig = YamlConfiguration.loadConfiguration(commandsFile);
ConfigurationSection commandsSection = commandsConfig.getConfigurationSection("commands");
Iterator<String> keys = commandsSection.getKeys(false).iterator();
commands.clear();
while (keys.hasNext()) {
String cmdName = (String) keys.next();
ConfigurationSection commandSection = commandsSection.getConfigurationSection(cmdName);
CustomCommand cmd = new CustomCommand();
List<String> l;
int i;
l = commandSection.getStringList("text");
if (l != null && l.size() > 0) {
for (i = 0; i < l.size(); i++) {
cmd.addText(l.get(i));
}
}
l = commandSection.getStringList("chat");
if (l != null && l.size() > 0){
for (i = 0; i < l.size(); i++) {
cmd.addChat(l.get(i));
}
}
l = commandSection.getStringList("playerCommands");
if (l != null && l.size() > 0){
for (i = 0; i < l.size(); i++) {
cmd.addPlayerCommand(l.get(i));
}
}
l = commandSection.getStringList("consoleCommands");
if (l != null && l.size() > 0){
for (i = 0; i < l.size(); i++) {
cmd.addConsoleCommand(l.get(i));
}
}
addCustomCommand(cmdName, cmd);
}
}
}
|
package com.appspot.relaxe.expr;
import java.util.EnumSet;
public enum SQLKeyword implements Keyword {
SELECT,
FROM,
WHERE,
GROUP_BY,
HAVING,
ORDER_BY,
LIMIT,
OFFSET,
IN,
LIKE,
BETWEEN,
EXISTS,
AND,
OR,
NOT,
UNION,
EXCEPT,
INTERSECT,
INNER,
LEFT,
RIGHT,
OUTER,
FULL,
JOIN,
ON,
ALL,
DISTINCT,
AS,
INSERT,
INTO,
VALUES,
UPDATE,
DELETE,
SET,
NULL,
DEFAULT,
CREATE,
DROP,
ALTER,
ADD,
SCHEMA,
TABLE,
VIEW,
COLUMN,
TRUNCATE,
AUTHORIZATION,
CASCADE,
RESTRICT,
CURRENT_USER,
CURRENT_DATE,
CURRENT_TIME,
CURRENT_TIMESTAMP,
CHARACTER,
VARCHAR,
CLOB,
BIGINT,
BIT,
BLOB,
NUMERIC,
DECIMAL,
INTEGER,
SMALLINT,
FLOAT,
VARYING,
INT,
TINYINT,
DATE,
TIME,
TIMESTAMP,
CONSTRAINT,
ASC,
DESC,
IS,
GENERATED,
ALWAYS,
BY,
IDENTITY,
START,
WITH,
INCREMENT
;
private static EnumSet<SQLKeyword> keywords = EnumSet.allOf(SQLKeyword.class);
@Override
public void traverse(VisitContext vc, ElementVisitor v) {
v.start(vc, this);
v.end(this);
}
@Override
public String getTerminalSymbol() {
return super.toString().replace('_', ' ');
}
@Override
public boolean isOrdinary() {
return true;
}
public static boolean isKeyword(String s) {
s = s.trim().toUpperCase();
return keywords.contains(s);
}
}
|
package com.digero.maestro.view;
import info.clearthought.layout.TableLayout;
import info.clearthought.layout.TableLayoutConstants;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.prefs.Preferences;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.digero.common.midi.Note;
import com.digero.common.midi.SequencerEvent;
import com.digero.common.midi.SequencerListener;
import com.digero.common.midi.SequencerProperty;
import com.digero.common.midi.SequencerWrapper;
import com.digero.common.util.ExtensionFileFilter;
import com.digero.common.util.ICompileConstants;
import com.digero.common.util.IDisposable;
import com.digero.common.util.ParseException;
import com.digero.common.util.Util;
import com.digero.common.view.ColorTable;
import com.digero.common.view.LinkButton;
import com.digero.maestro.abc.AbcPart;
import com.digero.maestro.abc.AbcPartEvent;
import com.digero.maestro.abc.AbcPartListener;
import com.digero.maestro.abc.AbcPartProperty;
import com.digero.maestro.abc.DrumNoteMap;
import com.digero.maestro.midi.NoteEvent;
import com.digero.maestro.midi.NoteFilterSequencerWrapper;
import com.digero.maestro.midi.TrackInfo;
@SuppressWarnings("serial")
public class TrackPanel extends JPanel implements IDisposable, TableLayoutConstants, ICompileConstants {
private static final String DRUM_NOTE_MAP_DIR_PREF_KEY = "DrumNoteMap.directory";
// 0 1 2
// 1 | Drum save controls (optional) | |
static final int TITLE_COLUMN = 0;
static final int CONTROL_COLUMN = 1;
static final int NOTE_COLUMN = 2;
static final int TITLE_WIDTH = 164;
static final int CONTROL_WIDTH = 48;
private static final double[] LAYOUT_COLS = new double[] {
TITLE_WIDTH, CONTROL_WIDTH, FILL
};
private static final double[] LAYOUT_ROWS = new double[] {
48, PREFERRED
};
private final TrackInfo trackInfo;
private final NoteFilterSequencerWrapper seq;
private final SequencerWrapper abcSequencer;
private final AbcPart abcPart;
private JCheckBox checkBox;
private JSpinner transposeSpinner;
private JPanel drumSavePanel;
private TrackNoteGraph noteGraph;
private AbcPartListener abcListener;
private SequencerListener seqListener;
private boolean showDrumPanels;
private boolean wasDrumPart;
public TrackPanel(TrackInfo info, NoteFilterSequencerWrapper sequencer, AbcPart part, SequencerWrapper abcSequencer) {
super(new TableLayout(LAYOUT_COLS, LAYOUT_ROWS));
setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, ColorTable.PANEL_BORDER.get()));
this.trackInfo = info;
this.seq = sequencer;
this.abcPart = part;
this.abcSequencer = abcSequencer;
TableLayout tableLayout = (TableLayout) getLayout();
tableLayout.setHGap(4);
checkBox = new JCheckBox();
checkBox.setOpaque(false);
checkBox.setSelected(abcPart.isTrackEnabled(trackInfo.getTrackNumber()));
checkBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int track = trackInfo.getTrackNumber();
boolean enabled = checkBox.isSelected();
abcPart.setTrackEnabled(track, enabled);
if (MUTE_DISABLED_TRACKS)
seq.setTrackMute(track, !enabled);
}
});
noteGraph = new TrackNoteGraph(seq, trackInfo);
noteGraph.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3)
seq.setTrackSolo(trackInfo.getTrackNumber(), true);
}
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3)
seq.setTrackSolo(trackInfo.getTrackNumber(), false);
}
});
if (!trackInfo.isDrumTrack()) {
int currentTranspose = abcPart.getTrackTranspose(trackInfo.getTrackNumber());
transposeSpinner = new JSpinner(new TrackTransposeModel(currentTranspose, -48, 48, 12));
transposeSpinner.setToolTipText("Transpose this track by octaves (12 semitones)");
transposeSpinner.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
int track = trackInfo.getTrackNumber();
int value = (Integer) transposeSpinner.getValue();
if (value % 12 != 0) {
value = (abcPart.getTrackTranspose(track) / 12) * 12;
transposeSpinner.setValue(value);
}
else {
abcPart.setTrackTranspose(trackInfo.getTrackNumber(), value);
}
}
});
}
add(checkBox, TITLE_COLUMN + ", 0");
if (transposeSpinner != null)
add(transposeSpinner, CONTROL_COLUMN + ", 0, f, c");
add(noteGraph, NOTE_COLUMN + ", 0, " + NOTE_COLUMN + ", 1");
updateTitleText();
abcPart.addAbcListener(abcListener = new AbcPartListener() {
public void abcPartChanged(AbcPartEvent e) {
if (e.isNoteGraphRelated()) {
updateState();
noteGraph.repaint();
}
if (e.getProperty() == AbcPartProperty.INSTRUMENT || e.getProperty() == AbcPartProperty.TRACK_ENABLED)
updateColors();
}
});
seq.addChangeListener(seqListener = new SequencerListener() {
public void propertyChanged(SequencerEvent evt) {
if (evt.getProperty() == SequencerProperty.TRACK_ACTIVE) {
updateColors();
}
else if (evt.getProperty() == SequencerProperty.IS_RUNNING) {
noteGraph.repaint();
}
}
});
if (abcSequencer != null)
abcSequencer.addChangeListener(seqListener);
addPropertyChangeListener("enabled", new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
updateState();
}
});
updateState(true);
}
private void initDrumSavePanel() {
JLabel intro = new JLabel("Drum Map: ");
intro.setForeground(ColorTable.PANEL_TEXT_DISABLED.get());
LinkButton saveButton = new LinkButton("Export");
saveButton.setForeground(ColorTable.PANEL_LINK.get());
saveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveDrumMapping();
}
});
JLabel divider = new JLabel(" | ");
divider.setForeground(ColorTable.PANEL_TEXT_DISABLED.get());
LinkButton loadButton = new LinkButton("Import");
loadButton.setForeground(ColorTable.PANEL_LINK.get());
loadButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadDrumMapping();
}
});
drumSavePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 2, 0));
drumSavePanel.setBorder(BorderFactory.createEmptyBorder(0, 4, 4, 0));
drumSavePanel.setOpaque(false);
drumSavePanel.add(intro);
drumSavePanel.add(loadButton);
drumSavePanel.add(divider);
drumSavePanel.add(saveButton);
}
public TrackInfo getTrackInfo() {
return trackInfo;
}
private void updateState() {
updateState(false);
}
private void updateTitleText() {
final int ELLIPSIS_OFFSET = 28;
String title = trackInfo.getTrackNumber() + ". " + trackInfo.getName();
String instr = trackInfo.getInstrumentNames();
checkBox.setToolTipText("<html><b>" + title + "</b><br>" + instr + "</html>");
title = Util.ellipsis(title, TITLE_WIDTH - ELLIPSIS_OFFSET, checkBox.getFont().deriveFont(Font.BOLD));
instr = Util.ellipsis(instr, TITLE_WIDTH - ELLIPSIS_OFFSET, checkBox.getFont());
checkBox.setText("<html><b>" + title + "</b><br>" + instr + "</html>");
}
private void updateColors() {
int trackNumber = trackInfo.getTrackNumber();
boolean trackEnabled = abcPart.isTrackEnabled(trackNumber);
if (!seq.isTrackActive(trackNumber)) {
noteGraph.setNoteColor(ColorTable.NOTE_OFF);
noteGraph.setBadNoteColor(ColorTable.NOTE_BAD_OFF);
setBackground(ColorTable.GRAPH_BACKGROUND_OFF.get());
}
else if (trackEnabled || seq.getTrackSolo(trackNumber)) {
noteGraph.setNoteColor(ColorTable.NOTE_ENABLED);
noteGraph.setBadNoteColor(ColorTable.NOTE_BAD_ENABLED);
setBackground(ColorTable.GRAPH_BACKGROUND_ENABLED.get());
}
else {
boolean pseudoOff = (abcPart.isDrumPart() != trackInfo.isDrumTrack());
noteGraph.setNoteColor(pseudoOff ? ColorTable.NOTE_OFF : ColorTable.NOTE_DISABLED);
noteGraph.setBadNoteColor(pseudoOff ? ColorTable.NOTE_BAD_OFF : ColorTable.NOTE_BAD_DISABLED);
setBackground(ColorTable.GRAPH_BACKGROUND_DISABLED.get());
}
if (trackEnabled) {
checkBox.setForeground(ColorTable.PANEL_TEXT_ENABLED.get());
}
else {
boolean inputEnabled = abcPart.isDrumPart() == trackInfo.isDrumTrack();
checkBox.setForeground(inputEnabled ? ColorTable.PANEL_TEXT_DISABLED.get() : ColorTable.PANEL_TEXT_OFF
.get());
}
noteGraph.setOctaveLinesVisible(!trackInfo.isDrumTrack()
&& !(abcPart.getInstrument().isPercussion && abcPart.isTrackEnabled(trackInfo.getTrackNumber())));
}
private void updateState(boolean initDrumPanels) {
updateColors();
boolean trackEnabled = abcPart.isTrackEnabled(trackInfo.getTrackNumber());
checkBox.setSelected(trackEnabled);
boolean showDrumPanelsNew = abcPart.isDrumPart() && trackEnabled;
if (initDrumPanels || showDrumPanels != showDrumPanelsNew || wasDrumPart != abcPart.isDrumPart()) {
if (showDrumPanels != showDrumPanelsNew) {
noteGraph.repaint();
showDrumPanels = showDrumPanelsNew;
}
wasDrumPart = abcPart.isDrumPart();
for (int i = getComponentCount() - 1; i >= 0; --i) {
Component child = getComponent(i);
if (child instanceof DrumPanel) {
((DrumPanel) child).dispose();
remove(i);
}
}
if (drumSavePanel != null)
remove(drumSavePanel);
if (transposeSpinner != null)
transposeSpinner.setVisible(!abcPart.isDrumPart());
TableLayout layout = (TableLayout) getLayout();
if (showDrumPanels) {
if (drumSavePanel == null)
initDrumSavePanel();
add(drumSavePanel, TITLE_COLUMN + ", 1, l, c");
int row = LAYOUT_ROWS.length;
for (int noteId : trackInfo.getNotesInUse()) {
DrumPanel panel = new DrumPanel(trackInfo, seq, abcPart, noteId);
if (row <= layout.getNumRow())
layout.insertRow(row, PREFERRED);
add(panel, "0, " + row + ", 2, " + row);
}
}
updateTitleText();
revalidate();
}
}
private boolean saveDrumMapping() {
Preferences prefs = Preferences.userNodeForPackage(TrackPanel.class);
String dirPath = prefs.get(DRUM_NOTE_MAP_DIR_PREF_KEY, null);
File dir;
if (dirPath == null || !(dir = new File(dirPath)).isDirectory())
dir = Util.getLotroMusicPath(false /* create */);
JFileChooser fileChooser = new JFileChooser(dir);
fileChooser.setFileFilter(new ExtensionFileFilter("Drum Map", DrumNoteMap.FILE_SUFFIX));
File saveFile;
do {
if (fileChooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION)
return false;
saveFile = fileChooser.getSelectedFile();
if (!Util.stringEndsWithIgnoreCase(saveFile.getName(), "." + DrumNoteMap.FILE_SUFFIX)) {
saveFile = new File(saveFile.getParentFile(), saveFile.getName() + "." + DrumNoteMap.FILE_SUFFIX);
}
if (saveFile.exists()) {
int result = JOptionPane.showConfirmDialog(this, "File " + saveFile.getName()
+ " already exists. Overwrite?", "Confirm overwrite", JOptionPane.OK_CANCEL_OPTION);
if (result != JOptionPane.OK_OPTION)
continue;
}
} while (false);
try {
abcPart.getDrumMap(trackInfo.getTrackNumber()).save(saveFile);
}
catch (IOException e) {
JOptionPane.showMessageDialog(this, "Failed to save drum map:\n\n" + e.getMessage(),
"Failed to save drum map", JOptionPane.ERROR_MESSAGE);
return false;
}
prefs.put(DRUM_NOTE_MAP_DIR_PREF_KEY, fileChooser.getCurrentDirectory().getAbsolutePath());
return true;
}
private boolean loadDrumMapping() {
Preferences prefs = Preferences.userNodeForPackage(TrackPanel.class);
String dirPath = prefs.get(DRUM_NOTE_MAP_DIR_PREF_KEY, null);
File dir;
if (dirPath == null || !(dir = new File(dirPath)).isDirectory())
dir = Util.getLotroMusicPath(false /* create */);
JFileChooser fileChooser = new JFileChooser(dir);
fileChooser.setFileFilter(new ExtensionFileFilter("Drum Map", DrumNoteMap.FILE_SUFFIX));
if (fileChooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION)
return false;
File loadFile = fileChooser.getSelectedFile();
try {
abcPart.getDrumMap(trackInfo.getTrackNumber()).load(loadFile);
}
catch (IOException e) {
JOptionPane.showMessageDialog(this, "Failed to load drum map:\n\n" + e.getMessage(),
"Failed to load drum map", JOptionPane.ERROR_MESSAGE);
return false;
}
catch (ParseException e) {
JOptionPane.showMessageDialog(this, "Failed to load drum map:\n\n" + e.getMessage(),
"Failed to load drum map", JOptionPane.ERROR_MESSAGE);
return false;
}
prefs.put(DRUM_NOTE_MAP_DIR_PREF_KEY, fileChooser.getCurrentDirectory().getAbsolutePath());
return true;
}
public void dispose() {
abcPart.removeAbcListener(abcListener);
seq.removeChangeListener(seqListener);
if (abcSequencer != null)
abcSequencer.removeChangeListener(seqListener);
noteGraph.dispose();
}
private class TrackTransposeModel extends SpinnerNumberModel {
public TrackTransposeModel(int value, int minimum, int maximum, int stepSize) {
super(value, minimum, maximum, stepSize);
}
@Override
public void setValue(Object value) {
if (!(value instanceof Integer))
throw new IllegalArgumentException();
if ((Integer) value % 12 != 0)
throw new IllegalArgumentException();
super.setValue(value);
}
}
private class TrackNoteGraph extends NoteGraph {
public TrackNoteGraph(SequencerWrapper sequencer, TrackInfo trackInfo) {
super(sequencer, trackInfo, Note.C2.id - 12, Note.C5.id + 12);
}
@Override
protected int transposeNote(int noteId) {
if (!trackInfo.isDrumTrack()) {
noteId += abcPart.getTranspose(trackInfo.getTrackNumber());
}
return noteId;
}
@Override
protected boolean isNotePlayable(int noteId) {
if (abcPart.isDrumPart()) {
return abcPart.isDrumPlayable(trackInfo.getTrackNumber(), noteId);
}
else if (trackInfo.isDrumTrack() && !abcPart.isTrackEnabled(trackInfo.getTrackNumber())) {
return true;
}
else {
int minPlayable = abcPart.getInstrument().lowestPlayable.id;
int maxPlayable = abcPart.getInstrument().highestPlayable.id;
return (noteId >= minPlayable) && (noteId <= maxPlayable);
}
}
@Override
protected boolean isShowingNotesOn() {
if (sequencer.isRunning())
return sequencer.isTrackActive(trackInfo.getTrackNumber());
if (abcSequencer != null && abcSequencer.isRunning())
return abcPart.isTrackEnabled(trackInfo.getTrackNumber());
return false;
}
@Override
protected List<NoteEvent> getEvents() {
if (showDrumPanels)
return Collections.emptyList();
return super.getEvents();
}
}
}
|
package com.ecyrd.jspwiki;
import java.util.*;
import java.io.*;
import org.apache.log4j.*;
import com.ecyrd.jspwiki.filters.BasicPageFilter;
import com.ecyrd.jspwiki.attachment.*;
import com.ecyrd.jspwiki.providers.*;
/*
BUGS
- if a wikilink is added to a page, then removed, RefMan still thinks that
the page refers to the wikilink page. Hm.
- if a page is deleted, gets very confused.
*/
/*
A word about synchronizing:
I expect this object to be accessed in three situations:
- when a WikiEngine is created and it scans its wikipages
- when the WE saves a page
- when a JSP page accesses one of the WE's ReferenceManagers
to display a list of (un)referenced pages.
So, access to this class is fairly rare, and usually triggered by
user interaction. OTOH, the methods in this class use their storage
objects intensively (and, sorry to say, in an unoptimized manner =).
My deduction: using unsynchronized HashMaps etc and syncing methods
or code blocks is preferrable to using slow, synced storage objects.
We don't have iterative code here, so I'm going to use synced methods
for now.
Please contact me if you notice problems with ReferenceManager, and
especially with synchronization, or if you have suggestions about
syncing.
ebu@memecry.net
*/
/**
* Keeps track of wikipage references:
* <UL>
* <LI>What pages a given page refers to
* <LI>What pages refer to a given page
* </UL>
*
* This is a quick'n'dirty approach without any finesse in storage and
* searching algorithms; we trust java.util.*.
* <P>
* This class contains two HashMaps, m_refersTo and m_referredBy. The
* first is indexed by WikiPage names and contains a Collection of all
* WikiPages the page refers to. (Multiple references are not counted,
* naturally.) The second is indexed by WikiPage names and contains
* a Set of all pages that refer to the indexing page. (Notice -
* the keys of both Maps should be kept in sync.)
* <P>
* When a page is added or edited, its references are parsed, a Collection
* is received, and we crudely replace anything previous with this new
* Collection. We then check each referenced page name and make sure they
* know they are referred to by the new page.
* <P>
* Based on this information, we can perform non-optimal searches for
* e.g. unreferenced pages, top ten lists, etc.
* <P>
* The owning class must take responsibility of filling in any pre-existing
* information, probably by loading each and every WikiPage and calling this
* class to update the references when created.
*
* @author ebu@memecry.net
* @since 1.6.1
*/
public class ReferenceManager
extends BasicPageFilter
{
/** Maps page wikiname to a Collection of pages it refers to. The Collection
* must contain Strings. The Collection may contain names of non-existing
* pages.
*/
private Map m_refersTo;
/** Maps page wikiname to a Set of referring pages. The Set must
* contain Strings. Non-existing pages (a reference exists, but not a file
* for the page contents) may have an empty Set in m_referredBy.
*/
private Map m_referredBy;
/** The WikiEngine that owns this object. */
private WikiEngine m_engine;
private boolean m_matchEnglishPlurals = false;
private static Logger log = Logger.getLogger(ReferenceManager.class);
private static final String SERIALIZATION_FILE = "refmgr.ser";
/**
* Builds a new ReferenceManager.
*
* @param engine The WikiEngine to which this is meeting.
*/
public ReferenceManager( WikiEngine engine )
{
m_refersTo = new HashMap();
m_referredBy = new HashMap();
m_engine = engine;
m_matchEnglishPlurals = TextUtil.getBooleanProperty( engine.getWikiProperties(),
WikiEngine.PROP_MATCHPLURALS,
m_matchEnglishPlurals );
}
/**
* Does a full reference update.
*/
private void updatePageReferences( WikiPage page )
throws ProviderException
{
String content = m_engine.getPageManager().getPageText( page.getName(),
WikiPageProvider.LATEST_VERSION );
Collection links = m_engine.scanWikiLinks( page, content );
Collection attachments = m_engine.getAttachmentManager().listAttachments( page );
for( Iterator atti = attachments.iterator(); atti.hasNext(); )
{
links.add( ((Attachment)(atti.next())).getName() );
}
updateReferences( page.getName(), links );
}
/**
* Initializes the entire reference manager with the initial set of pages
* from the collection.
*
* @param pages A collection of all pages you want to be included in the reference
* count.
* @since 2.2
*/
public void initialize( Collection pages )
throws ProviderException
{
log.debug( "Initializing new ReferenceManager with "+pages.size()+" initial pages." );
long start = System.currentTimeMillis();
log.info( "Starting cross reference scan of WikiPages" );
// First, try to serialize old data from disk. If that fails,
// we'll go and update the entire reference lists (which'll take
// time)
try
{
long saved = unserializeFromDisk();
// Now we must check if any of the pages have been changed
// while we were in the electronic la-la-land, and update
// the references for them.
Iterator it = pages.iterator();
while( it.hasNext() )
{
WikiPage page = (WikiPage) it.next();
if( page instanceof Attachment )
{
// Skip attachments
}
else if( page.getLastModified().getTime() > saved )
{
updatePageReferences( page );
}
}
}
catch( Exception e )
{
log.info("Unable to unserialize old refmgr information, rebuilding database: "+e.getMessage());
buildKeyLists( pages );
// Scan the existing pages from disk and update references in the manager.
Iterator it = pages.iterator();
while( it.hasNext() )
{
WikiPage page = (WikiPage)it.next();
if( page instanceof Attachment )
{
// We cannot build a reference list from the contents
// of attachments, so we skip them.
}
else
{
updatePageReferences( page );
}
}
serializeToDisk();
}
log.info( "Cross reference scan done (" +
(System.currentTimeMillis()-start) +
" ms)" );
}
/**
* Reads the serialized data from the disk back to memory.
* Returns the date when the data was last written on disk
*/
private synchronized long unserializeFromDisk()
throws IOException,
ClassNotFoundException
{
ObjectInputStream in = null;
long saved = 0L;
try
{
long start = System.currentTimeMillis();
File f = new File( m_engine.getWorkDir(), SERIALIZATION_FILE );
in = new ObjectInputStream( new FileInputStream(f) );
saved = in.readLong();
m_refersTo = (Map) in.readObject();
m_referredBy = (Map) in.readObject();
in.close();
long finish = System.currentTimeMillis();
log.debug("Read serialized data successfully in "+(finish-start)+"ms");
}
finally
{
try {
if( in != null ) in.close();
} catch( IOException ex ) {}
}
return saved;
}
/**
* Serializes hashmaps to disk. The format is private, don't touch it.
*/
private synchronized void serializeToDisk()
{
ObjectOutputStream out = null;
try
{
long start = System.currentTimeMillis();
File f = new File( m_engine.getWorkDir(), SERIALIZATION_FILE );
out = new ObjectOutputStream( new FileOutputStream(f) );
out.writeLong( System.currentTimeMillis() ); // Timestamp
out.writeObject( m_refersTo );
out.writeObject( m_referredBy );
out.close();
long finish = System.currentTimeMillis();
log.debug("serialization done - took "+(finish-start)+"ms");
}
catch( IOException e )
{
log.error("Unable to serialize!");
try {
if( out != null ) out.close();
} catch( IOException ex ) {}
}
}
/**
* After the page has been saved, updates the reference lists.
*/
public void postSave( WikiContext context, String content )
{
WikiPage page = context.getPage();
updateReferences( page.getName(),
context.getEngine().scanWikiLinks( page, content ) );
serializeToDisk();
}
/**
* Updates the referred pages of a new or edited WikiPage. If a refersTo
* entry for this page already exists, it is removed and a new one is built
* from scratch. Also calls updateReferredBy() for each referenced page.
* <P>
* This is the method to call when a new page has been created and we
* want to a) set up its references and b) notify the referred pages
* of the references. Use this method during run-time.
*
* @param page Name of the page to update.
* @param references A Collection of Strings, each one pointing to a page this page references.
*/
public synchronized void updateReferences( String page, Collection references )
{
// Create a new entry in m_refersTo.
Collection oldRefTo = (Collection)m_refersTo.get( page );
m_refersTo.remove( page );
m_refersTo.put( page, references );
// We know the page exists, since it's making references somewhere.
// If an entry for it didn't exist previously in m_referredBy, make
// sure one is added now.
if( !m_referredBy.containsKey( page ) )
{
m_referredBy.put( page, new TreeSet() );
}
// Get all pages that used to be referred to by 'page' and
// remove that reference. (We don't want to try to figure out
// which particular references were removed...)
cleanReferredBy( page, oldRefTo, references );
// Notify all referred pages of their referinesshoodicity.
Iterator it = references.iterator();
while( it.hasNext() )
{
String referredPageName = (String)it.next();
updateReferredBy( referredPageName, page );
}
}
/**
* Returns the refers-to list. For debugging.
*/
protected Map getRefersTo()
{
return( m_refersTo );
}
/**
* Returns the referred-by list. For debugging.
*/
protected Map getReferredBy()
{
return( m_referredBy );
}
/**
* Cleans the 'referred by' list, removing references by 'referrer' to
* any other page. Called after 'referrer' is removed.
*/
private void cleanReferredBy( String referrer,
Collection oldReferred,
Collection newReferred )
{
// Two ways to go about this. One is to look up all pages previously
// referred by referrer and remove referrer from their lists, and let
// the update put them back in (except possibly removed ones).
// The other is to get the old referred to list, compare to the new,
// and tell the ones missing in the latter to remove referrer from
// their list. Hm. We'll just try the first for now. Need to come
// back and optimize this a bit.
if( oldReferred == null )
return;
Iterator it = oldReferred.iterator();
while( it.hasNext() )
{
String referredPage = (String)it.next();
Set oldRefBy = (Set)m_referredBy.get( referredPage );
if( oldRefBy != null )
{
oldRefBy.remove( referrer );
}
// If the page is referred to by no one AND it doesn't even
// exist, we might just as well forget about this entry.
// It will be added again elsewhere if new references appear.
if( ( ( oldRefBy == null ) || ( oldRefBy.isEmpty() ) ) &&
( m_engine.pageExists( referredPage ) == false ) )
{
m_referredBy.remove( referredPage );
}
}
}
/**
* When initially building a ReferenceManager from scratch, call this method
* BEFORE calling updateReferences() with a full list of existing page names.
* It builds the refersTo and referredBy key lists, thus enabling
* updateReferences() to function correctly.
* <P>
* This method should NEVER be called after initialization. It clears all mappings
* from the reference tables.
*
* @param pages a Collection containing WikiPage objects.
*/
private synchronized void buildKeyLists( Collection pages )
{
m_refersTo.clear();
m_referredBy.clear();
if( pages == null )
return;
Iterator it = pages.iterator();
try
{
while( it.hasNext() )
{
WikiPage page = (WikiPage)it.next();
// We add a non-null entry to referredBy to indicate the referred page exists
m_referredBy.put( page.getName(), new TreeSet() );
// Just add a key to refersTo; the keys need to be in sync with referredBy.
m_refersTo.put( page.getName(), null );
}
}
catch( ClassCastException e )
{
log.fatal( "Invalid collection entry in ReferenceManager.buildKeyLists().", e );
}
}
/**
* Marks the page as referred to by the referrer. If the page does not
* exist previously, nothing is done. (This means that some page, somewhere,
* has a link to a page that does not exist.)
* <P>
* This method is NOT synchronized. It should only be referred to from
* within a synchronized method, or it should be made synced if necessary.
*/
private void updateReferredBy( String page, String referrer )
{
// We're not really interested in first level self-references.
if( page.equals( referrer ) )
{
return;
}
Set referrers = (Set)m_referredBy.get( page );
// Even if 'page' has not been created yet, it can still be referenced.
// This requires we don't use m_referredBy keys when looking up missing
// pages, of course.
if(referrers == null)
{
referrers = new TreeSet();
m_referredBy.put( page, referrers );
}
referrers.add( referrer );
}
/**
* Finds all unreferenced pages. This requires a linear scan through
* m_referredBy to locate keys with null or empty values.
*/
public synchronized Collection findUnreferenced()
{
ArrayList unref = new ArrayList();
Set keys = m_referredBy.keySet();
Iterator it = keys.iterator();
while( it.hasNext() )
{
String key = (String) it.next();
//Set refs = (Set) m_referredBy.get( key );
Set refs = getReferenceList( m_referredBy, key );
if( refs == null || refs.isEmpty() )
{
unref.add( key );
}
}
return unref;
}
/**
* Finds all references to non-existant pages. This requires a linear
* scan through m_refersTo values; each value must have a corresponding
* key entry in the reference Maps, otherwise such a page has never
* been created.
* <P>
* Returns a Collection containing Strings of unreferenced page names.
* Each non-existant page name is shown only once - we don't return information
* on who referred to it.
*/
public synchronized Collection findUncreated()
{
TreeSet uncreated = new TreeSet();
// Go through m_refersTo values and check that m_refersTo has the corresponding keys.
// We want to reread the code to make sure our HashMaps are in sync...
Collection allReferences = m_refersTo.values();
Iterator it = allReferences.iterator();
while( it.hasNext() )
{
Collection refs = (Collection)it.next();
if( refs != null )
{
Iterator rit = refs.iterator();
while( rit.hasNext() )
{
String aReference = (String)rit.next();
if( m_engine.pageExists( aReference ) == false )
{
uncreated.add( aReference );
}
}
}
}
return uncreated;
}
/**
* Searches for the given page in the given Map.
*/
private Set getReferenceList( Map coll, String pagename )
{
Set refs = (Set)coll.get( pagename );
if( (refs == null || refs.size() == 0) && m_matchEnglishPlurals )
{
if( pagename.endsWith("s") )
{
refs = (Set)coll.get( pagename.substring(0,pagename.length()-1) );
}
else
{
refs = (Set)coll.get( pagename+"s" );
}
}
return refs;
}
/**
* Find all pages that refer to this page. Returns null if the page
* does not exist or is not referenced at all, otherwise returns a
* collection containing page names (String) that refer to this one.
*/
public synchronized Collection findReferrers( String pagename )
{
Set refs = getReferenceList( m_referredBy, pagename );
if( refs == null || refs.isEmpty() )
{
return null;
}
else
{
return refs;
}
}
}
|
package com.java.laiy.view;
import com.java.laiy.controller.Game;
import com.java.laiy.controller.GameController;
import com.java.laiy.model.Board;
import com.java.laiy.model.Figure;
import com.java.laiy.model.Player;
import com.java.laiy.model.exceptions.InvalidBoardSizeException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ConsoleMenuView {
private static final int START_CODE = 1;
private static final int LOAD_CODE = 2;
private static final int SETTINGS_CODE = 3;
private static final int EXIT_CODE = 4;
private static int BOARD_SIZE;
private static final int MIN_SIZE = 3;
public static void showMenuWithResult() {
System.out.println("++++ XO Magic ++++");
System.out.println(START_CODE + " - Play");
System.out.println(LOAD_CODE + " - Load");
System.out.println(SETTINGS_CODE + " - Set up and play");
System.out.println(EXIT_CODE + " - Exit");
System.out.print("> ");
try {
final Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case START_CODE:
System.out.println("A new game started");
defaultStart();
break;
case LOAD_CODE:
System.out.println("Loading...");
//TODO
break;
case SETTINGS_CODE:
customInput();
break;
case EXIT_CODE:
System.out.println("Exit");
break;
default:
System.out.println("Choice is incorrect, please try again");
showMenuWithResult();
break;
}
}
catch (final InputMismatchException e)
{
System.out.println("Please enter correct choice");
showMenuWithResult();
}
}
private static void defaultStart(){
final String gameName = "XO";
BOARD_SIZE = 3;
final String playerOneName = "PLAYER X";
final String playerTwoName = "PLAYER O";
customStart(BOARD_SIZE,playerOneName,playerTwoName, gameName);
}
private static void customInput() {
Scanner input = new Scanner(System.in);
final String gameName = "XO";
System.out.println("Enter player one name:");
String playerOneName = input.nextLine();
System.out.println("Enter player two name:");
String playerTwoName = input.nextLine();
final int boardSize = enterSize();
customStart(boardSize,playerOneName,playerTwoName, gameName);
}
private static int enterSize(){
Scanner input = new Scanner(System.in);
try {
System.out.println("Enter board size:");
BOARD_SIZE = input.nextInt();
if (BOARD_SIZE < MIN_SIZE){
throw new InvalidBoardSizeException();
}
}
catch (final InputMismatchException | InvalidBoardSizeException e){
System.out.println("Input is wrong, please enter correct integer greater than 3");
enterSize();
}
return BOARD_SIZE;
}
private static void customStart(final int BOARD_SIZE, final String playerOneName, final String playerTwoName, final String gameName){
final Board board = new Board(BOARD_SIZE);
final Player[] players = new Player[2];
players[0] = new Player(playerOneName, Figure.X);
players[1] = new Player(playerTwoName, Figure.O);
final GameController gameController = new GameController(gameName, players, board);
final ConsoleView consoleView = new ConsoleView(gameController);
final Game game = new Game(consoleView,gameController);
consoleView.showPlayers();
game.theGame();
}
}
|
package com.magneticbear.scala1;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
public class Favourites extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourites);
setupButtons();
show_events();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_favourites, menu);
return true;
}
public void setupButtons()
{
final Button rocker_events = (Button)findViewById(R.id.rocker_events);
final Button rocker_speakers = (Button)findViewById(R.id.rocker_speakers);
rocker_events.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
rocker_events.setBackgroundResource(R.drawable.fav_tab_left_down);
rocker_speakers.setBackgroundResource(R.drawable.fav_tab_right_up);
show_events();
}
});
rocker_speakers.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
rocker_events.setBackgroundResource(R.drawable.fav_tab_left_up);
rocker_speakers.setBackgroundResource(R.drawable.fav_tab_right_down);
show_speakers();
}
});
}
public void show_events()
{
UserData.load_or_create();
ArrayList<Struct_Event> local_event = (ArrayList)UserData.fav_events.clone();
Struct_Event_Adapter adapter = new Struct_Event_Adapter(getBaseContext(), R.id.struct_event_adapter_row_title, local_event);
((ListView)findViewById(R.id.favourites_list)).setAdapter(adapter);
}
public void show_speakers()
{
UserData.load_or_create();
ArrayList<Struct_Speaker> local_speaker = (ArrayList)UserData.fav_speakers.clone();
Struct_Speaker_Adapter adapter = new Struct_Speaker_Adapter(getBaseContext(), R.id.struct_speaker_adapter_row_title, local_speaker);
((ListView)findViewById(R.id.favourites_list)).setAdapter(adapter);
}
}
|
package com.opencms.launcher;
import com.opencms.template.*;
import com.opencms.file.*;
import com.opencms.core.*;
import java.util.*;
import java.io.*;
import javax.servlet.http.*;
abstract class A_CmsLauncher implements I_CmsLauncher, I_CmsLogChannels, I_CmsConstants {
/** Boolean for additional debug output control */
private static final boolean C_DEBUG = false;
/** Value of the filesystem counter, when the last template clear cache was done. */
private static long m_lastFsCounterTemplate = 0;
/** Value of the filesystem counter, when the last XML file clear cache was done. */
private static long m_lastFsCounterFile = 0;
/** The template cache that holds all cached templates */
protected static I_CmsTemplateCache m_templateCache = new CmsTemplateCache();
/**
* Utility method used by the launcher implementation to give control
* to the CanonicalRoot.
* The CanonicalRoot will call the master template and return a byte array of the
* generated output.
*
* @param cms CmsObject Object for accessing system resources.
* @param templateClass Class that should generate the output of the master template.
* @param masterTemplate CmsFile Object with masterTemplate for the output.
* @param parameters Hashtable with all parameters for the template class.
* @return byte array with the generated output or null if there were errors.
* @exception CmsException
*
*/
protected byte[] callCanonicalRoot(CmsObject cms, I_CmsTemplate templateClass, CmsFile masterTemplate, Hashtable parameters) throws CmsException {
try {
com.opencms.template.CmsRootTemplate root = (CmsRootTemplate)CmsTemplateClassManager.getClassInstance(cms, "com.opencms.template.CmsRootTemplate");
return root.getMasterTemplate(cms, templateClass, masterTemplate, m_templateCache, parameters);
} catch(Exception e) {
// There is no document we could show.
handleException(cms, e, "Received error while calling canonical root for requested file " + masterTemplate.getName() + ". ");
}
return null;
}
public void clearCache()
{
m_templateCache.clearCache();
}
/**
* Gets the name of the class in the form "[ClassName] "
* This can be used for error logging purposes.
* @return name of this class
*/
protected String getClassName() {
String name = getClass().getName();
return "[" + name.substring(name.lastIndexOf(".") + 1) + "] ";
}
/** Default constructor to create a new launcher */
/*public A_CmsLauncher() {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_DEBUG, getClassName() + "Initialized successfully.");
}
}*/
/**
* Gets the ID that indicates the type of the launcher.
* @return launcher ID
*/
public abstract int getLauncherId();
/**
* Gets a reference to the global template cache
* @return Template cache
*/
public static I_CmsTemplateCache getTemplateCache() {
return m_templateCache;
}
/**
* Calls the CmsClassManager to get an instance of the given template class.
* The returned object is checked to be an implementing class of the interface
* I_CmsTemplate.
* If the template cache of the template class is not yet setted, this will
* be done, too.
* @param cms CmsObject object for accessing system resources.
* @param classname Name of the requested template class.
* @return Instance of the template class.
* @exception CmsException.
*/
protected I_CmsTemplate getTemplateClass(CmsObject cms, String classname) throws CmsException {
if(C_DEBUG && A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_DEBUG, getClassName() + "Getting start template class " + classname + ". ");
}
Object o = CmsTemplateClassManager.getClassInstance(cms, classname);
// Check, if the loaded class really is a OpenCms template class.
// This is done be checking the implemented interface.
if(! (o instanceof I_CmsTemplate)) {
String errorMessage = "Class " + classname + " is no OpenCms template class.";
if(A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_CRITICAL, "[CmsTemplateClassManager] " + errorMessage);
}
throw new CmsException(errorMessage, CmsException.C_XML_NO_TEMPLATE_CLASS);
}
I_CmsTemplate cmsTemplate = (I_CmsTemplate)o;
if(!cmsTemplate.isTemplateCacheSet()) {
cmsTemplate.setTemplateCache(m_templateCache);
}
return cmsTemplate;
}
/**
* Utility method to handle any occurence of an execption.
* <P>
* If the Exception is NO CmsException (i.e. it was not detected previously)
* it will be written to the logfile.
* <P>
* If the current user is the anonymous user, no further execption will
* be thrown, but a server error will be sent
* (we want to prevent the user from seeing any exeptions).
* Otherwise a new Exception will be thrown.
*
* @param cms CmsObject Object for accessing system resources.
* @param e Exception that should be handled.
* @param errorText Error message that should be shown.
* @exception CmsException
*/
public void handleException(CmsObject cms, Exception e, String errorText) throws CmsException {
// Print out some error messages
if(A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + errorText);
A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + "--> Exception: "+ e);
A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + "--> Cannot create output for this file. Must send error. Sorry.");
}
// If the user is "Guest", we send an servlet error.
// Otherwise we try to throw an exception.
CmsRequestContext reqContext = cms.getRequestContext();
if((! C_DEBUG) && cms.anonymousUser().equals(reqContext.currentUser())) {
throw new CmsException(errorText, CmsException.C_SERVICE_UNAVAILABLE, e);
} else {
if(e instanceof CmsException) {
throw (CmsException)e;
} else {
throw new CmsException(errorText, CmsException.C_LAUNCH_ERROR, e);
}
}
}
/**
* Start method called by the OpenCms system to show a resource.
* <P>
* In this method initial values valid for all launchers can be set
* and the _clearcache parameter is checked.
* After this the abstract method launch(...) is called to
* invoke the customized part of the launcher.
*
* @param cms CmsObject Object for accessing system resources.
* @param file CmsFile Object with the selected resource to be shown.
* @param startTemplateClass Name of the template class to start with.
* @param openCms a instance of A_OpenCms for redirect-needs
* @exception CmsException
*/
public void initlaunch(CmsObject cms, CmsFile file, String startTemplateClass, A_OpenCms openCms) throws CmsException {
// First some debugging output.
if(C_DEBUG && A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + "Launcher started for " + file.getName());
}
// Check all values to be valid
String errorMessage = null;
if(file==null) {
errorMessage = "Got \"null\" CmsFile object. :-(";
}
if(cms==null) {
errorMessage = "Actual cms object missing";
}
if(errorMessage != null) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + errorMessage);
}
throw new CmsException(errorMessage, CmsException.C_LAUNCH_ERROR);
}
// Check the clearcache parameter
String clearcache = cms.getRequestContext().getRequest().getParameter("_clearcache");
long currentFsCounter = cms.getFileSystemChanges();
if((clearcache != null) && ("all".equals(clearcache) || "class".equals(clearcache))) {
CmsTemplateClassManager.clearCache();
}
if(((clearcache != null) && ("all".equals(clearcache) || "file".equals(clearcache)))
|| (currentFsCounter > m_lastFsCounterFile )) {
A_CmsXmlContent.clearFileCache();
m_lastFsCounterFile = currentFsCounter;
}
if(((clearcache != null) && ("all".equals(clearcache) || "template".equals(clearcache)))
|| (currentFsCounter > m_lastFsCounterTemplate )) {
m_templateCache.clearCache();
m_lastFsCounterTemplate = currentFsCounter;
}
launch(cms, file, startTemplateClass, openCms);
}
/**
* Unitary method to start generating the output.
* Every launcher has to implement this method.
* In it possibly the selected file will be analyzed, and the
* Canonical Root will be called with the appropriate
* template class, template file and parameters. At least the
* canonical root's output must be written to the HttpServletResponse.
*
* @param cms CmsObject Object for accessing system resources
* @param file CmsFile Object with the selected resource to be shown
* @param startTemplateClass Name of the template class to start with.
* @param openCms a instance of A_OpenCms for redirect-needs
* @exception CmsException
*/
protected abstract void launch(CmsObject cms, CmsFile file, String startTemplateClass, A_OpenCms openCms) throws CmsException;
/**
* Writes a given byte array to the HttpServletRespose output stream.
* @param result byte array that should be written.
* @param mimeType MIME type that should be set for the output.
* @exception CmsException
*/
protected void writeBytesToResponse(CmsObject cms, byte[] result)
throws CmsException {
int length;
try {
I_CmsResponse resp = cms.getRequestContext().getResponse();
if (!resp.isRedirected()){
OutputStream out = resp.getOutputStream();
resp.setContentLength(result.length);
out.write(result);
out.flush();
out.close();
}
} catch (IOException ioe) {
A_OpenCms.log(C_OPENCMS_INFO, getClassName() + "IO error while writing to response stream for " + cms.getRequestContext().getFileUri());
A_OpenCms.log(C_OPENCMS_INFO, getClassName() + ioe);
} catch(Exception e) {
String errorMessage = "Cannot write output to HTTP response stream";
handleException(cms, e, errorMessage);
}
}
}
|
package com.procom.filefly;
import java.io.File;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
/**
* The {@link android.app.Activity} that will launch in response to an
* ACTION_VIEW intent from the Android Beam API, copy the transferred
* file into the received subdirectory of the FileFly directory found
* on the root of the SD Card.
*
* @author Saurabh Sharma, Peter Piech
*
*/
public class ReceiveActivity extends FragmentActivity
{
private String mPath; // A File object containing the path to the transferred files
private Intent mIntent; // Incoming Intent
private String mFirstName;
private String mLastName;
private String mOriginalFileName;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receive);
mFirstName = new String();
mLastName = new String();
mOriginalFileName = new String();
handleViewIntent();
Toast.makeText(this, "Received file successfully..!", Toast.LENGTH_LONG).show(); // show the user this message
// TODO: copy transferred file into SDCard:/FileFly/received directory, and only then:
// TODO: add file record to internal SQLite database for use by DocumentListFragment
// TODO: initiate the MainActivity after above operations complete via an Intent with extra information
// TODO: in MainActivity, parse the extra information to mean that the app should just send an ACTION_VIEW intent to the system to open the file. This is so that the most recent activity of record is MainActivity and not ReceiveActivity.
// TODO: verify that after the appropriate application opens the file, the back button will bring the user to the MainActivity annd not ReceiveActivity
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* <Add Description Here Saurabh>
*
* @author Saurabh Sharma
*
*/
private void handleViewIntent()
{
// Get the Intent action
mIntent = getIntent();
String action = mIntent.getAction();
/*
* For ACTION_VIEW, the Activity is being asked to display data.
* Get the URI.
*/
if (TextUtils.equals(action, Intent.ACTION_VIEW)) {
// Get the URI from the Intent
Uri beamUri = mIntent.getData();
/*
* Test for the type of URI, by getting its scheme value
*/
if (TextUtils.equals(beamUri.getScheme(), "file")) {
mPath = handleFileUri(beamUri);
} else if (TextUtils.equals(beamUri.getScheme(), "content")) {
mPath = handleContentUri(beamUri);
} else {
// re-dispatch the intent to the system
startActivity(mIntent);
}
}
}
/**
* To get the directory path, get the path part of the URI, which contains all of the URI
* except the file: prefix. Create a File from the path part, then get the parent path of the File:
*
* @author Saurabh Sharma
*
*/
public String handleFileUri(Uri beamUri)
{
// Get the path part of the URI
String fileName = beamUri.getPath();
// parse out first/last name and original filename
grabNameFile(fileName);
// Create a File object for this filename (with original fileName????)
File copiedFile = new File(mOriginalFileName);
//File copiedFile = new File(fileName);
// Get a string containing the file's parent directory
return copiedFile.getAbsolutePath();
}
/**
* To parse out filename's first and last name attributes given
* an absolute path to the file
*
* @author Jacob Abramson
*/
// parses out first and last names and original filename
private void grabNameFile(String absPath) {
// parse filename from absolute path
String[] delimSlashes = absPath.split("/");
String fn = delimSlashes[delimSlashes.length - 1];
// split string based on underscores
String[] result = fn.split("_");
if (result.length < 3) {
//error, this means first/last name wasn't appended
return;
}
mFirstName = result[0];
mLastName = result[1];
mOriginalFileName = "";
// append original filename along with underscores if included
for (int i = 2; i < result.length; i++) {
mOriginalFileName += result[i];
if (i+1 < result.length) {
mOriginalFileName += "_";
}
}
}
/**
* To test the authority of the content URI and retrieve the the path and file name for the
* transferred file
*
* @author Saurabh Sharma
*
*/
public String handleContentUri(Uri beamUri) {
// Position of the filename in the query Cursor
int filenameIndex;
// File object for the filename
File copiedFile;
// The filename stored in MediaStore
String fileName;
// Test the authority of the URI
if (!TextUtils.equals(beamUri.getAuthority(), MediaStore.AUTHORITY)) {
/*
* As of now not including code to handle content URIs for other content providers
*/
return null;
// For a MediaStore content URI
} else {
// Get the column that contains the file name
String[] projection = { MediaStore.MediaColumns.DATA };
Cursor pathCursor =
getContentResolver().query(beamUri, projection,
null, null, null);
// Check for a valid cursor
if (pathCursor != null &&
pathCursor.moveToFirst()) {
// Get the column index in the Cursor
filenameIndex = pathCursor.getColumnIndex(
MediaStore.MediaColumns.DATA);
// Get the full file name including path
fileName = pathCursor.getString(filenameIndex);
// Create a File object for the filename
copiedFile = new File(fileName);
// Return the parent directory of the file
return new File(copiedFile.getParent()).toString();
} else {
// The query didn't work; return null
return null;
}
}
}
}
|
package com.redpois0n.gitj.ui;
import iconlib.IconUtils;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import com.redpois0n.git.Branch;
import com.redpois0n.git.Remote;
import com.redpois0n.git.Repository;
import com.redpois0n.git.Stash;
import com.redpois0n.git.Tag;
import com.redpois0n.gitj.Main;
@SuppressWarnings("serial")
public class ObjectsPanel extends JScrollPane {
private MainPanel panel;
private Repository repo;
private JTree tree;
private DefaultTreeModel treeModel;
private DefaultMutableTreeNode root;
public ObjectsPanel(MainFrame parent) {
tree = new JTree();
tree.setCellRenderer(new Renderer());
tree.setShowsRootHandles(true);
root = new DefaultMutableTreeNode("root");
treeModel = new DefaultTreeModel(root);
tree.setModel(treeModel);
tree.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
TreePath tp = tree.getPathForLocation(e.getX(), e.getY());
if (tp != null && tp.getLastPathComponent() != null) {
IconTreeNode node = (IconTreeNode) tp.getLastPathComponent();
if (node.getListener() != null) {
node.getListener().actionPerformed(new ActionEvent(node, 0, null));
}
}
}
});
setViewportView(tree);
}
public void reload(MainPanel panel, Repository repo) throws Exception {
this.panel = panel;
this.repo = repo;
root.removeAllChildren();
StashTreeNode stashNode = new StashTreeNode("Stashes", null);
treeModel.insertNodeInto(stashNode, root, 0);
for (Stash stash : repo.getStashes()) {
StashTreeNode node = new StashTreeNode(stash.getName(), stash);
treeModel.insertNodeInto(node, stashNode, 0);
}
TagTreeNode tagsNode = new TagTreeNode("Tags", null);
treeModel.insertNodeInto(tagsNode, root, 0);
for (Tag tag : repo.getTags()) {
TagTreeNode node = new TagTreeNode(tag.getTag(), tag);
treeModel.insertNodeInto(node, tagsNode, 0);
}
RemoteTreeNode remotesNode = new RemoteTreeNode("Remotes");
treeModel.insertNodeInto(remotesNode, root, 0);
for (Remote remote : repo.getRemotes()) {
RemoteTreeNode node = new RemoteTreeNode(remote.getName());
treeModel.insertNodeInto(node, remotesNode, 0);
}
BranchTreeNode branchNode = new BranchTreeNode("Branches", null);
treeModel.insertNodeInto(branchNode, root, 0);
for (Branch branch : repo.getBranches()) {
BranchTreeNode node = new BranchTreeNode(branch.getName(), branch);
treeModel.insertNodeInto(node, branchNode, 0);
}
treeModel.reload(root);
tree.setRootVisible(false);
}
public class Renderer extends DefaultTreeCellRenderer {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
JLabel label = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
if (value instanceof IconTreeNode) {
label.setIcon(((IconTreeNode) value).getIcon());
}
label.setFont(new Font(label.getFont().getName(), Font.PLAIN, label.getFont().getSize()));
try {
if (value instanceof BranchTreeNode) {
BranchTreeNode node = ((BranchTreeNode) value);
if (node.getBranch() != null && node.getBranch().equals(repo.getCurrentBranch())) {
label.setFont(new Font(label.getFont().getName(), Font.BOLD, label.getFont().getSize()));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return label;
}
}
public abstract class IconTreeNode extends DefaultMutableTreeNode {
private ImageIcon icon;
private ActionListener listener;
public IconTreeNode(String text, ImageIcon icon, ActionListener listener) {
super(text);
this.icon = icon;
this.listener = listener;
}
public IconTreeNode(String text, ImageIcon icon) {
this(text, icon, null);
}
public ImageIcon getIcon() {
return this.icon;
}
public ActionListener getListener() {
return this.listener;
}
}
public class TagTreeNode extends IconTreeNode {
public TagTreeNode(String text, final Tag tag) {
super(text, IconUtils.getIcon("tag-annotated"), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (tag != null) {
panel.getCommitPanel().setSelectedCommit(repo.getCommit(tag.getHash()));
}
}
});
}
}
public class BranchTreeNode extends IconTreeNode {
private Branch branch;
public BranchTreeNode(String text, final Branch branch) {
super(text, IconUtils.getIcon("branch"), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (branch != null) {
try {
repo.checkout(branch);
} catch (Exception e1) {
e1.printStackTrace();
Main.displayError(e1);
}
}
}
});
this.branch = branch;
}
public Branch getBranch() {
return this.branch;
}
}
public class RemoteTreeNode extends IconTreeNode {
public RemoteTreeNode(String text) {
super(text, IconUtils.getIcon("remote"));
}
}
public class StashTreeNode extends IconTreeNode {
private Stash stash;
public StashTreeNode(String text, final Stash stash) {
super(text, IconUtils.getIcon("stash"), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (stash != null) {
try {
} catch (Exception ex) {
ex.printStackTrace();
Main.displayError(ex);
}
}
}
});
this.stash = stash;
}
public Stash getStash() {
return this.stash;
}
}
}
|
package com.twinone.locker;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class ObserverService extends Service {
public static final String EXTRA_APPINFO = "com.twinone.locker.extraInfo";
public static final String TAG = "Observer";
public static final String PREF_FILE_PASSWD = "default";
public static final String PREF_KEY_PASSWD = "com.twinone.locker.pref.passwd";
public static final String PREF_DEF_PASSWD = "";
public static final String PREF_KEY_MESSAGE = "com.twinone.locker.pref.message";
/** File where locked apps are stored as {@link SharedPreferences} */
private static final String PREF_FILE_APPS = "locked_apps";
// private static final String PREF_KEY_APPS =
// "com.twinone.locker.pref.apps";
private static final String LOCKER_CLASS = LockActivity.class.getName();
private long DELAY = DELAY_POWERSAVE;
private static final long DELAY_PERFORMANCE = 70;
private static final long DELAY_FAST = 100;
private static final long DELAY_NORMAL = 150;
private static final long DELAY_SLOW = 200;
private static final long DELAY_POWERSAVE = 250;
private String mPassword;
private String lastApp = "";
private String lastClass = "";
private boolean mScreenOn = true;
private ActivityManager am;
private ScheduledExecutorService mExecutor;
BroadcastReceiver mScreenStatusReceiver;
/** In this map information about apps will be */
private HashSet<LockInfo> trackedApps;
@Override
public IBinder onBind(Intent i) {
return new LocalBinder();
}
public class LocalBinder extends Binder {
public ObserverService getInstance() {
return ObserverService.this;
}
}
@Override
public void onCreate() {
super.onCreate();
Log.w(TAG, "onCreate");
am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
mPassword = getPassword(this);
trackedApps = new HashSet<LockInfo>();
// // trackedApps.add(new LockInfo("com.whatsapp"));
// trackedApps.add(new LockInfo("com.twitter.android"));
// Set an empty notification
@SuppressWarnings("deprecation")
Notification n = new Notification(0, null, System.currentTimeMillis());
n.flags |= Notification.FLAG_NO_CLEAR;
startForeground(42, n);
// Start the monitoring
startScheduler();
mScreenStatusReceiver = new ScreenReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenStatusReceiver, filter);
// TODO Load applications from preferences
updateTrackedApps();
}
private void startScheduler() {
if (mExecutor == null) {
mExecutor = Executors.newSingleThreadScheduledExecutor();
mExecutor.scheduleWithFixedDelay(new PackageMonitor(), 0, DELAY,
TimeUnit.MILLISECONDS);
}
}
private void stopScheduler() {
if (mExecutor == null) {
mExecutor.shutdownNow();
mExecutor = null;
}
}
class ScreenReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.i("TAG", "Screen ON");
mScreenOn = true;
startScheduler();
// relockAll();
}
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.i("TAG", "Screen OFF");
mScreenOn = false;
stopScheduler();
relockAll();
}
}
};
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
/**
* Get password from SharedPreferences
*
* @param c
* @return The password current password or an empty string.
*/
public static final String getPassword(Context c) {
return c.getSharedPreferences(PREF_FILE_PASSWD, MODE_PRIVATE)
.getString(PREF_KEY_PASSWD, PREF_DEF_PASSWD);
}
/**
* Change the lock password and write it to disk
*
* @param c
* @param password
* @return True if success, false on failure
*/
public static final boolean setPassword(Context c, String password) {
SharedPreferences.Editor editor = c.getSharedPreferences(
PREF_FILE_PASSWD, MODE_PRIVATE).edit();
editor.putString(ObserverService.PREF_KEY_PASSWD, password);
return editor.commit();
}
public static final boolean setMessage(Context c, String value) {
SharedPreferences.Editor editor = c.getSharedPreferences(
PREF_FILE_PASSWD, MODE_PRIVATE).edit();
editor.putString(ObserverService.PREF_KEY_MESSAGE, value);
return editor.commit();
}
private class PackageMonitor extends Thread {
@Override
public void run() {
// Avoid battery drain when screen off.
ComponentName app = am.getRunningTasks(1).get(0).topActivity;
String appName = app.getPackageName();
String className = app.getClassName();
boolean appChanged = !appName.equals(lastApp);
boolean classChanged = !className.equals(lastClass);
if (classChanged || appChanged) {
Log.d(TAG, "" + appName + " " + className);
}
onObserve(appName, className);
lastClass = className;
lastApp = appName;
}
/**
* Called each time the monitor has observed a package in the front. The
* package can be the same as the previous.
*
* @param appName
* @param className
*/
private void onObserve(String appName, String className) {
// Log.v(TAG, "Package: " + appName);
// the app that's currently in front
LockInfo app = getLockInfoByPackageName(appName);
if (className.equals(LOCKER_CLASS)) {
// we don't want to show the locker if the locker is
// currently
// visible
return;
}
// Only if we're monitoring the app
if (app != null) {
// lock app if we should
if (app.locked) {
Log.v(TAG,
"Show locker for " + app.packageName
+ app.hashCode());
showLocker(app);
}
}
// lock all other apps because they're not in front anymore
relock(appName);
}
}
/**
* Locks ALL apps (Useful when screen is turned off)
*/
private void relockAll() {
for (LockInfo li : trackedApps) {
if (li.locked == false) {
Log.v(TAG, "relockAll() " + li.packageName);
li.locked = true;
}
}
}
/**
* Locks all apps except the one matching the provided string.
*
* @param appName
* The app that must NOT be locked.
*/
private void relock(String appName) {
for (LockInfo li : trackedApps) {
if (!li.packageName.equals(appName)) {
if (li.locked == false) {
Log.v(TAG, "relock() " + li.packageName);
li.locked = true;
}
}
}
}
private void printLockInfos() {
Log.d(TAG, "
for (LockInfo li : trackedApps) {
Log.v(TAG, li.locked + "\t" + li);
}
Log.d(TAG, "
}
@Override
public void onDestroy() {
super.onDestroy();
Log.w(TAG, "onDestroy");
// IMPORTANT
// The executor will happily run if it's not shutdown explicitly
stopScheduler();
am = null;
trackedApps = null;
unregisterReceiver(mScreenStatusReceiver);
}
private LockInfo getLockInfoByPackageName(String packageName) {
if (trackedApps == null)
Log.wtf(TAG, "lockList = null");
for (LockInfo li : trackedApps) {
if (li.packageName.equals(packageName)) {
return li;
}
}
return null;
}
// public void doLock(String appName) {
// LockInfo li = getLockInfoByPackageName(appName);
// if (li != null) {
// if (li.lock == false) {
// Log.i(TAG, "Locked in list " + li.packageName);
// li.lock = true;
// return;
// Log.w(TAG, "Not locked " + appName + ": not in list.");
public void doUnlock(String appName) {
Log.d(TAG, "doUnlock called");
LockInfo li = getLockInfoByPackageName(appName);
if (li != null) {
if (li.locked == true) {
Log.i(TAG, "Unlocked in list: " + li.packageName);
} else {
Log.w(TAG, "Tried to unlock " + li.hashCode()
+ " but was not locked");
printLockInfos();
}
li.locked = false;
return;
}
Log.w(TAG, "Not unlocked " + appName + ": not in list.");
}
/**
* Locks the current app
*/
private void showLocker(LockInfo lockInfo) {
if (mPassword.isEmpty()) {
Log.w(TAG, "Not showing lock for empty password:"
+ lockInfo.packageName);
return;
}
// Log.d(TAG, "Starting locker for " + lockInfo.packageName);
Intent intent = new Intent(ObserverService.this, LockActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
intent.putExtra(EXTRA_APPINFO, lockInfo);
startActivity(intent);
}
/**
*
* @param context
* @return A {@link Set} that is safe to edit and use.
*/
public static final Set<String> getTrackedApps(Context c) {
SharedPreferences sp = c.getSharedPreferences(PREF_FILE_APPS,
Context.MODE_PRIVATE);
Set<String> apps = new HashSet<String>(sp.getAll().keySet());
return apps;
}
/**
* Tracks or untracks an app
*
* @param packageName
* @param shouldTrack
* True if the new state will be tracking, false if not
*/
public final void setTracking(String packageName, boolean shouldTrack) {
SharedPreferences.Editor editor = getSharedPreferences(PREF_FILE_APPS,
Context.MODE_PRIVATE).edit();
if (shouldTrack) {
editor.putBoolean(packageName, true);
} else {
editor.remove(packageName);
}
boolean commited = editor.commit();
if (!commited) {
Log.w(TAG, "Not commited!");
}
updateTrackedApps();
}
// TODO
public final void updateTrackedApps() {
Set<String> apps = getTrackedApps(this);
trackedApps = new HashSet<LockInfo>();
for (String s : apps) {
trackedApps.add(new LockInfo(s));
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.