answer
stringlengths 17
10.2M
|
|---|
package gov.nih.nci.ncicb.cadsr.loader.persister;
import gov.nih.nci.ncicb.cadsr.domain.*;
import gov.nih.nci.ncicb.cadsr.loader.ElementsLists;
import org.apache.log4j.Logger;
import gov.nih.nci.ncicb.cadsr.loader.defaults.UMLDefaults;
import gov.nih.nci.ncicb.cadsr.loader.util.PropertyAccessor;
import gov.nih.nci.ncicb.cadsr.loader.util.StringUtil;
import java.util.*;
/**
*
* @author <a href="mailto:chris.ludet@oracle.com">Christophe Ludet</a>
*/
public class PackagePersister extends UMLPersister {
private static Logger logger = Logger.getLogger(PackagePersister.class.getName());
public PackagePersister() {
}
public void persist() {
ClassificationSchemeItem pkg = DomainObjectFactory.newClassificationSchemeItem();
List<ClassificationSchemeItem> packages = elements.getElements(pkg);
Map packageCsCsis = defaults.getPackageCsCsis();
if (packages != null) {
for (ListIterator<ClassificationSchemeItem> it = packages.listIterator(); it.hasNext();) {
pkg = it.next();
pkg.setAudit(defaults.getAudit());
pkg.setType(ClassificationSchemeItem.TYPE_UML_PACKAGE);
ClassificationSchemeItem subProject = DomainObjectFactory.newClassificationSchemeItem();
subProject.setLongName(defaults.getPackageDisplay(pkg.getLongName()));
subProject.setType(ClassificationSchemeItem.TYPE_UML_PROJECT);
// Verify is there is a sub project
if(!subProject.getLongName().equals(pkg.getLongName())) {
subProject.setAudit(defaults.getAudit());
// See if it already exist in DB
List l = classificationSchemeItemDAO.find(subProject);
if (l.size() == 0) { // not in DB, create it.
subProject.setId(classificationSchemeItemDAO.create(subProject));
} else {
subProject = (ClassificationSchemeItem) l.get(0);
}
} else {
}
// See if it already exist in DB
List l = classificationSchemeItemDAO.find(pkg);
if (l.size() == 0) { // not in DB, create it.
if(StringUtil.isEmpty(pkg.getPreferredDefinition()))
pkg.setPreferredDefinition("No Value Exists.");
pkg.setId(classificationSchemeItemDAO.create(pkg));
} else {
pkg = (ClassificationSchemeItem) l.get(0);
}
ClassSchemeClassSchemeItem subCsCsi = null;
if(subProject.getId() != null) {
subCsCsi = linkCsiToCs(subProject, defaults.getProjectCs(), null);
}
ClassSchemeClassSchemeItem packageCsCsi = linkCsiToCs(pkg, defaults.getProjectCs(), subCsCsi);
// Put CS_CSI in cache so OCs can use it
packageCsCsis.put(pkg.getLongName(), packageCsCsi);
}
}
}
private ClassSchemeClassSchemeItem linkCsiToCs(ClassificationSchemeItem csi, ClassificationScheme cs, ClassSchemeClassSchemeItem parent) {
List csCsis = cs.getCsCsis();
boolean found = false;
ClassSchemeClassSchemeItem newCsCsi = null;
if(csCsis != null && csCsis.size() > 0) {
for (ListIterator it = csCsis.listIterator(); it.hasNext();) {
ClassSchemeClassSchemeItem csCsi = (ClassSchemeClassSchemeItem) it.next();
if (csCsi.getCsi().getType().equals(csi.getType()) &&
csCsi.getCsi().getLongName().equals(csi.getLongName())) {
// There's already a CS_CSI.
// Does it have the same parent?
if(
((csCsi.getParent() == null)
&& (parent == null))
||
((csCsi.getParent() != null)
&& (parent != null)
&& (csCsi.getParent().getId() == parent.getId()))
)
{
newCsCsi = csCsi;
// if(parent != null)
// newCsCsi.setParent(parent);
found = true;
}
}
}
}
if (!found) {
logger.info(
PropertyAccessor
.getProperty("link.package.to.project", csi.getLongName()));
newCsCsi = DomainObjectFactory.newClassSchemeClassSchemeItem();
newCsCsi.setCs(cs);
newCsCsi.setCsi(csi);
newCsCsi.setLabel(csi.getLongName());
if(newCsCsi.getLabel().length() > 30)
newCsCsi.setLabel(
newCsCsi.getLabel().substring(0, 29));
newCsCsi.setAudit(defaults.getAudit());
if(parent != null) {
newCsCsi.setParent(parent);
}
newCsCsi.setId(classificationSchemeDAO
.addClassificationSchemeItem
(cs, newCsCsi));
defaults.refreshProjectCs();
logger.info(PropertyAccessor.getProperty("added.package"));
}
return newCsCsi;
}
}
|
package org.rstudio.studio.client.htmlpreview;
import org.rstudio.core.client.Size;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.common.satellite.SatelliteManager;
import org.rstudio.studio.client.htmlpreview.events.ShowHTMLPreviewEvent;
import org.rstudio.studio.client.htmlpreview.events.ShowHTMLPreviewHandler;
import com.google.inject.Inject;
import com.google.inject.Singleton;
@Singleton
public class HTMLPreview
{
@Inject
public HTMLPreview(EventBus eventBus,
final SatelliteManager satelliteManager)
{
eventBus.addHandler(ShowHTMLPreviewEvent.TYPE,
new ShowHTMLPreviewHandler() {
@Override
public void onShowHTMLPreview(ShowHTMLPreviewEvent event)
{
// open the window
satelliteManager.openSatellite(HTMLPreviewApplication.NAME,
event.getParams(),
new Size(850,1100));
}
});
}
}
|
package nl.b3p.viewer.stripes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.validation.Validate;
import nl.b3p.viewer.config.services.ArcIMSService;
import nl.b3p.viewer.config.services.WMSService;
import org.apache.commons.io.IOUtils;
/**
*
* @author Matthijs Laan
*/
@UrlBinding("/action/proxy/{mode}")
@StrictBinding
public class ProxyActionBean implements ActionBean {
private ActionBeanContext context;
@Validate
private String url;
@Validate
private String mode;
@Override
public ActionBeanContext getContext() {
return context;
}
@Override
public void setContext(ActionBeanContext context) {
this.context = context;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
@DefaultHandler
public Resolution proxy() throws Exception {
HttpServletRequest request = getContext().getRequest();
// Session must exist
HttpSession sess = request.getSession(false);
if(sess == null || url == null) {
return new ErrorResolution(HttpServletResponse.SC_FORBIDDEN, "Proxy requests forbidden");
}
// We don't do a host check because the user can add custom services
// using any URL. If the proxying viewer webapp is on a IP whitelist
// and an attacker knows the URL of the IP-whitelist protected service
// this may allow the attacker to request maps from that service if that
// service does not verify IP using the X-Forwarded-For header we send.
if(ArcIMSService.PROTOCOL.equals(mode)) {
return proxyArcIMS();
} else if(WMSService.PROTOCOL.equals(mode)){
return proxyWMS();
}else{
return new ErrorResolution(HttpServletResponse.SC_FORBIDDEN, "Proxy mode unacceptable");
}
}
// Not public, proxy() performs proxy checks!
private Resolution proxyArcIMS() throws Exception {
HttpServletRequest request = getContext().getRequest();
if(!"POST".equals(request.getMethod())) {
return new ErrorResolution(HttpServletResponse.SC_FORBIDDEN);
}
Map params = new HashMap(getContext().getRequest().getParameterMap());
// Only allow these parameters in proxy request
params.keySet().retainAll(Arrays.asList(
"ClientVersion",
"Encode",
"Form",
"ServiceName"
));
URL theUrl = new URL(url);
// Must not allow file / jar etc protocols, only HTTP:
String path = theUrl.getPath();
for(Map.Entry<String,String[]> param: (Set<Map.Entry<String,String[]>>)params.entrySet()) {
if(path.length() == theUrl.getPath().length()) {
path += "?";
} else {
path += "&";
}
path += URLEncoder.encode(param.getKey(), "UTF-8") + "=" + URLEncoder.encode(param.getValue()[0], "UTF-8");
}
theUrl = new URL("http", theUrl.getHost(), theUrl.getPort(), path);
// TODO logging for inspecting malicious proxy use
ByteArrayOutputStream post = new ByteArrayOutputStream();
IOUtils.copy(request.getInputStream(), post);
// This check makes some assumptions on how browsers serialize XML
// but all major browsers pass this check
if(!post.toString("US-ASCII").startsWith("<ARCXML version=\"1.1\"><REQUEST><GET_IMAGE")) {
return new ErrorResolution(HttpServletResponse.SC_FORBIDDEN);
}
final HttpURLConnection connection = (HttpURLConnection)theUrl.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setAllowUserInteraction(false);
connection.setRequestProperty("X-Forwarded-For", request.getRemoteAddr());
connection.connect();
try {
IOUtils.copy(new ByteArrayInputStream(post.toByteArray()), connection.getOutputStream());
} finally {
connection.getOutputStream().flush();
connection.getOutputStream().close();
}
return new StreamingResolution(connection.getContentType()) {
@Override
protected void stream(HttpServletResponse response) throws IOException {
try {
IOUtils.copy(connection.getInputStream(), response.getOutputStream());
} finally {
connection.disconnect();
}
}
};
}
private Resolution proxyWMS() throws IOException{
HttpServletRequest request = getContext().getRequest();
if(!"GET".equals(request.getMethod())) {
return new ErrorResolution(HttpServletResponse.SC_FORBIDDEN);
}
List<String> allowedParams = new ArrayList<String>();
allowedParams.add("VERSION");
allowedParams.add("SERVICE");
allowedParams.add("REQUEST");
allowedParams.add("UPDATESEQUENCE");
allowedParams.add("LAYERS");
allowedParams.add("LAYER");
allowedParams.add("STYLES");
allowedParams.add("SRS");
allowedParams.add("BBOX");
allowedParams.add("FORMAT");
allowedParams.add("WIDTH");
allowedParams.add("HEIGHT");
allowedParams.add("TRANSPARENT");
allowedParams.add("BGCOLOR");
allowedParams.add("EXCEPTIONS");
allowedParams.add("TIME");
allowedParams.add("ELEVATION");
allowedParams.add("QUERY_LAYERS");
allowedParams.add("X");
allowedParams.add("Y");
allowedParams.add("INFO_FORMAT");
allowedParams.add("FEATURE_COUNT");
allowedParams.add("SLD");
allowedParams.add("SLD_BODY");
//vendor
allowedParams.add("MAP");
URL theUrl = new URL(url);
String query = theUrl.getQuery();
//only WMS request param's allowed
String[] params = query.split("&");
StringBuilder sb = validateParams(params, allowedParams);
StringBuilder sb2 = validateParams(request.getParameterMap(),allowedParams);
sb.append(sb2);
int index = sb.charAt(0) == '&' ? 1 : 0;
String paramString = sb.substring(index);
theUrl = new URL("http",theUrl.getHost(),theUrl.getPort(),theUrl.getPath()+"?"+paramString);
//TODO: Check if response is a getFeatureInfo response.
final URLConnection connection = theUrl.openConnection();
return new StreamingResolution(connection.getContentType()) {
@Override
protected void stream(HttpServletResponse response) throws IOException {
IOUtils.copy(connection.getInputStream(), response.getOutputStream());
}
};
}
private StringBuilder validateParams (String [] params,List<String> allowedParams){
StringBuilder sb = new StringBuilder();
for (String param : params){
if (allowedParams.contains((param.split("=")[0]).toUpperCase())){
sb.append(param);
sb.append("&");
}
}
return sb;
}
private StringBuilder validateParams (Map<String,String[]> params,List<String> allowedParams){
StringBuilder sb = new StringBuilder();
for (String param : params.keySet()){
if (allowedParams.contains((param).toUpperCase())){
sb.append(param);
sb.append("=");
String[] paramValue = params.get(param);
for (int i = 0; i < paramValue.length; i++) {
String val = paramValue[i];
if(i > 0){
sb.append(",");
}
sb.append(val);
}
sb.append("&");
}
}
return sb;
}
}
|
package jp.satorufujiwara.http;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
public class Request {
private String url;
private String method;
private Map<String, String> headers;
private RequestBody body;
private RequestConvertTask<?> pendingTask;
Request(Builder builder) {
this.url = builder.url;
this.method = builder.method;
this.headers = builder.headers;
this.body = builder.body;
this.pendingTask = builder.task;
}
public String getUrl() {
return url;
}
public Map<String, String> getHeaders() {
return headers;
}
public String getMethod() {
return method;
}
public RequestBody getBody() {
return body;
}
void setBody(RequestBody body) {
this.body = body;
}
RequestConvertTask<?> getPendingTask() {
return pendingTask;
}
public static class Builder {
private final ConverterProvider converterProvider;
private String url;
private String method;
private Map<String, String> headers;
private RequestBody body;
private RequestConvertTask<?> task;
Builder(final ConverterProvider converterProvider) {
this.converterProvider = converterProvider;
method = "GET";
headers = new HashMap<>();
}
public Builder url(String url) {
this.url = url;
return this;
}
public Builder get() {
return method("GET", null);
}
public Builder post(RequestBody body) {
return method("POST", body);
}
public <T> Builder post(T body, Type type) {
return method("POST", body, type);
}
public Builder delete(RequestBody body) {
return method("DELETE", body);
}
public <T> Builder delete(T body, Type type) {
return method("DELETE", body, type);
}
public Builder put(RequestBody body) {
return method("PUT", body);
}
public <T> Builder put(T body, Type type) {
return method("PUT", body, type);
}
public Builder patch(RequestBody body) {
return method("PATCH", body);
}
public <T> Builder patch(T body, Type type) {
return method("PATCH", body, type);
}
public Builder addHeader(String name, String value) {
headers.put(name, value);
return this;
}
public Builder method(String method, RequestBody body) {
this.method = method;
this.body = body;
this.task = null;
return this;
}
public <T> Builder method(String method, T body, Type type) {
this.method = method;
this.body = null;
this.task = new RequestConvertTask<>(body, converterProvider.requestConverter(type));
return this;
}
public Request build() {
return new Request(this);
}
}
}
|
package org.xins.server;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.io.Writer;
import java.util.Iterator;
import org.xins.common.MandatoryArgumentChecker;
import org.xins.common.collections.PropertyReader;
import org.xins.common.xml.Element;
import org.xins.common.xml.ElementSerializer;
import org.xins.logdoc.ExceptionUtils;
import org.znerd.xmlenc.XMLEncoder;
import org.znerd.xmlenc.XMLOutputter;
/**
* Converter that can be used by calling conventions to generate responses
* which are compatible with the XINS standard calling convention.
*
* <p>The result output is always in the UTF-8 encoding.
*
* @version $Revision$ $Date$
* @author <a href="mailto:ernst@ernstdehaan.com">Ernst de Haan</a>
* @author <a href="mailto:anthony.goubard@orange-ftgroup.com">Anthony Goubard</a>
*
* @since XINS 1.5.0
*/
public final class CallResultOutputter {
// Class fields
/**
* The first output for each output conversion. Never <code>null</code>.
*/
private static final char[] DOCUMENT_PREFACE =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><result".toCharArray();
/**
* The output for the old-style calling convention in case success is true.
* Never <code>null</code>.
*/
private static final char[] SUCCESS_TRUE =
" success=\"true\">".toCharArray();
/**
* The output for the old-style calling convention in case success is
* false, just before the name of the first error code.
* Never <code>null</code>.
*/
private static final char[] SUCCESS_FALSE_PREFIX =
" success=\"false\" code=\"".toCharArray();
/**
* The output for the old-style calling convention in case success is
* false, just after the name of the first error code and before the name
* of the second.
* Never <code>null</code>.
*/
private static final char[] SUCCESS_FALSE_MIDDLE =
"\" errorcode=\"".toCharArray();
/**
* The output for the new-style calling convention in case success is
* false, just before the name of the error code.
* Never <code>null</code>.
*/
private static final char[] ERRORCODE_IS =
" errorcode=\"".toCharArray();
/**
* The output just before a parameter name. Never <code>null</code>.
*/
private static final char[] PARAM_PREFACE = "<param name=\"".toCharArray();
/**
* The output right after a parameter value. Never <code>null</code>.
*/
private static final char[] PARAM_SUFFIX = "</param>".toCharArray();
/**
* The final output for each output conversion. Never <code>null</code>.
*/
private static final char[] DOCUMENT_SUFFIX = "</result>".toCharArray();
/**
* An <code>XMLEncoder</code> for the UTF-8 encoding. Initialized by the
* class initialized and then never <code>null</code>.
*/
private static final XMLEncoder XML_ENCODER;
// Class functions
static {
try {
XML_ENCODER = XMLEncoder.getEncoder("UTF-8");
} catch (UnsupportedEncodingException exception) {
Error error = new Error();
ExceptionUtils.setCause(error, exception);
throw error;
}
}
public static void output(Writer out, FunctionResult result)
throws IllegalArgumentException, IOException {
output(out, result, false);
}
static void output(Writer out, FunctionResult result, boolean oldStyle)
throws IllegalArgumentException, IOException {
// Check preconditions
MandatoryArgumentChecker.check("out", out, "result", result);
// Output the declaration
out.write(DOCUMENT_PREFACE);
// Output the start of the <result> element
String code = result.getErrorCode();
if (oldStyle) {
if (code == null) {
out.write(SUCCESS_TRUE);
} else {
out.write(SUCCESS_FALSE_PREFIX);
out.write(code);
out.write(SUCCESS_FALSE_MIDDLE);
out.write(code);
out.write('"');
out.write('>');
}
} else {
if (code == null) {
out.write('>');
} else {
out.write(ERRORCODE_IS);
out.write(code);
out.write('"');
out.write('>');
}
}
// Write the output parameters, if any
PropertyReader params = result.getParameters();
if (params != null) {
Iterator names = params.getNames();
while (names.hasNext()) {
String n = (String) names.next();
if (n != null && n.length() > 0) {
String v = params.get(n);
if (v != null && v.length() > 0) {
out.write(PARAM_PREFACE);
XML_ENCODER.text(out, n, true);
out.write('"');
out.write('>');
XML_ENCODER.text(out, v, true);
out.write(PARAM_SUFFIX);
}
}
}
}
// Write the data element, if any
Element dataElement = result.getDataElement();
if (dataElement != null) {
ElementSerializer serializer = new ElementSerializer();
XMLOutputter xmlout = new XMLOutputter(out, "UTF-8");
serializer.output(xmlout, dataElement);
}
// End the root element <result>
out.write(DOCUMENT_SUFFIX);
}
// Constructors
/**
* Constructs a new <code>CallResultOutputter</code> object.
*/
private CallResultOutputter() {
// empty
}
}
|
package cn.wizzer.framework.base;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.lang.Strings;
import org.nutz.mvc.Mvcs;
public class Result {
private int code;
private String msg;
private Object data;
public Result() {
}
public static Result NEW() {
return new Result();
}
public Result addCode(int code) {
this.code = code;
return this;
}
public Result addMsg(String msg) {
this.msg = Strings.isBlank(msg) ? "" : Mvcs.getActionContext().getRequest() == null ? msg : Mvcs.getMessage(Mvcs.getActionContext().getRequest(), msg);
return this;
}
public Result addData(Object data) {
this.data = data;
return this;
}
public Result(int code, String msg, Object data) {
this.code = code;
if (Strings.isBlank(msg) || Mvcs.getActionContext() == null || Mvcs.getActionContext().getRequest() == null || Mvcs.getMessage(Mvcs.getActionContext().getRequest(), msg) == null) {
this.msg = "";
} else {
this.msg = Mvcs.getMessage(Mvcs.getActionContext().getRequest(), msg);
}
this.data = data;
}
public static Result success(String content) {
return new Result(0, content, null);
}
public static Result success(String content, Object data) {
return new Result(0, content, data);
}
public static Result error(int code, String content) {
return new Result(code, content, null);
}
public static Result error(String content) {
return new Result(1, content, null);
}
public static Result success() {
return new Result(0, "globals.result.success", null);
}
public static Result error() {
return new Result(1, "globals.result.error", null);
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
public Object getData() {
return data;
}
@Override
public String toString() {
return Json.toJson(this, JsonFormat.compact());
}
}
|
// Narya library - tools for developing networked games
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.presents.server.net;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import com.samskivert.util.*;
import com.threerings.io.FramingOutputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.presents.Log;
import com.threerings.presents.data.ConMgrStats;
import com.threerings.presents.net.AuthRequest;
import com.threerings.presents.net.AuthResponse;
import com.threerings.presents.net.DownstreamMessage;
import com.threerings.presents.server.Authenticator;
import com.threerings.presents.server.PresentsServer;
/**
* The connection manager manages the socket on which connections are
* received. It creates connection objects to manage each individual
* connection, but those connection objects interact closely with the
* connection manager because network I/O is done via a poll()-like
* mechanism rather than via threads.
*/
public class ConnectionManager extends LoopingThread
implements PresentsServer.Reporter
{
/**
* Constructs and initialized a connection manager (binding the socket
* on which it will listen for client connections).
*/
public ConnectionManager (int port)
throws IOException
{
_port = port;
_selector = SelectorProvider.provider().openSelector();
// create our stats record
_stats = new ConMgrStats();
_stats.init();
// register as a "state of server" reporter
PresentsServer.registerReporter(this);
}
/**
* Configures the connection manager with an entity that will be
* informed of the success or failure of the connection manager
* initialization process. <em>Note:</em> the callback methods will be
* called on the connection manager thread, so be careful not to do
* anything on those methods that will conflict with activities on the
* dobjmgr thread, etc.
*/
public void setStartupListener (ResultListener rl)
{
_startlist = rl;
}
/**
* Specifies the authenticator that should be used by the connection
* manager to authenticate logon requests.
*/
public void setAuthenticator (Authenticator author)
{
// say hello to our new authenticator
_author = author;
_author.setConnectionManager(this);
}
/**
* Returns the entity that is being used to authenticate connections.
*/
public Authenticator getAuthenticator ()
{
return _author;
}
/**
* Instructs us to execute the specified runnable when the connection
* manager thread exits. <em>Note:</em> this will be executed on the
* connection manager thread, so don't do anything dangerous. Only one
* action may be specified and it may be cleared by calling this
* method with null.
*/
public void setShutdownAction (Runnable onExit)
{
_onExit = onExit;
}
/**
* Returns our current runtime statistics. When the stats are fetched
* the counters are rolled to the next bucket. 60 buckets are tracked.
* <em>Note:</em> don't call this method <em>too</em> frequently (more
* often than once every few seconds or so) as it has to total things
* up and run a number of synchronized methods.
*/
public synchronized ConMgrStats getStats ()
{
// fill in our snapshot values
_stats.authQueueSize[_stats.current] = _authq.size();
_stats.deathQueueSize[_stats.current] = _deathq.size();
_stats.outQueueSize[_stats.current] = _outq.size();
if (_oflowqs.size() > 0) {
Iterator oqiter = _oflowqs.values().iterator();
while (oqiter.hasNext()) {
OverflowQueue oq = (OverflowQueue)oqiter.next();
_stats.overQueueSize[_stats.current] += oq.size();
}
}
_stats.increment();
return _stats;
}
/**
* Adds the specified connection observer to the observers list.
* Connection observers will be notified of connection-related
* events. An observer will not be added to the list twice.
*
* @see ConnectionObserver
*/
public void addConnectionObserver (ConnectionObserver observer)
{
synchronized (_observers) {
_observers.add(observer);
}
}
/**
* Removes the specified connection observer from the observers list.
*/
public void removeConnectionObserver (ConnectionObserver observer)
{
synchronized (_observers) {
_observers.remove(observer);
}
}
/**
* Queues a connection up to be closed on the conmgr thread.
*/
public void closeConnection (Connection conn)
{
_deathq.append(conn);
}
/**
* Called by the authenticator to indicate that a connection was
* successfully authenticated.
*/
public void connectionDidAuthenticate (Connection conn)
{
// slap this sucker onto the authenticated connections queue
_authq.append(conn);
}
// documentation inherited from interface PresentsServer.Reporter
public void appendReport (StringBuffer report, long now, long sinceLast)
{
long bytesIn, bytesOut, msgsIn, msgsOut;
synchronized (this) {
bytesIn = _bytesIn; _bytesIn = 0L;
bytesOut = _bytesOut; _bytesOut = 0L;
msgsIn = _msgsIn; _msgsIn = 0;
msgsOut = _msgsOut; _msgsOut = 0;
}
report.append("* presents.net.ConnectionManager:\n");
report.append("- Network input: ");
report.append(bytesIn).append(" bytes, ");
report.append(msgsIn).append(" msgs, ");
long avgIn = (msgsIn == 0) ? 0 : (bytesIn/msgsIn);
report.append(avgIn).append(" avg size, ");
report.append(bytesIn*1000/sinceLast).append(" bps\n");
report.append("- Network output: ");
report.append(bytesOut).append(" bytes, ");
report.append(msgsOut).append(" msgs, ");
long avgOut = (msgsOut == 0) ? 0 : (bytesOut/msgsOut);
report.append(avgOut).append(" avg size, ");
report.append(bytesOut*1000/sinceLast).append(" bps\n");
}
/**
* Notifies the connection observers of a connection event. Used
* internally.
*/
protected void notifyObservers (
int code, Connection conn, Object arg1, Object arg2)
{
synchronized (_observers) {
for (int i = 0; i < _observers.size(); i++) {
ConnectionObserver obs =
(ConnectionObserver)_observers.get(i);
switch (code) {
case CONNECTION_ESTABLISHED:
obs.connectionEstablished(conn, (AuthRequest)arg1,
(AuthResponse)arg2);
break;
case CONNECTION_FAILED:
obs.connectionFailed(conn, (IOException)arg1);
break;
case CONNECTION_CLOSED:
obs.connectionClosed(conn);
break;
default:
throw new RuntimeException("Invalid code supplied to " +
"notifyObservers: " + code);
}
}
}
}
// documentation inherited
protected void willStart ()
{
try {
// create our listening socket and add it to the select set
_listener = ServerSocketChannel.open();
_listener.configureBlocking(false);
InetSocketAddress isa = new InetSocketAddress(_port);
_listener.socket().bind(isa);
Log.info("Server listening on " + isa + ".");
// register our listening socket and map its select key to a
// net event handler that will accept new connections
SelectionKey lkey =
_listener.register(_selector, SelectionKey.OP_ACCEPT);
_handlers.put(lkey, new NetEventHandler() {
public int handleEvent (long when) {
acceptConnection();
// there's no easy way to measure bytes read when
// accepting a connection, so we claim nothing
return 0;
}
public boolean checkIdle (long now) {
return false; // we're never idle
}
});
} catch (IOException ioe) {
Log.warning("Failure listening to socket on port '" +_port + "'.");
Log.logStackTrace(ioe);
// notify our startup listener, if we have one
if (_startlist != null) {
_startlist.requestFailed(ioe);
}
return;
}
// we'll use this for sending messages to clients
_framer = new FramingOutputStream();
// notify our startup listener, if we have one
if (_startlist != null) {
_startlist.requestCompleted(null);
}
}
/**
* Performs the select loop. This is the body of the conmgr thread.
*/
protected void iterate ()
{
long iterStamp = System.currentTimeMillis();
// close any connections that have been queued up to die
Connection dconn;
while ((dconn = (Connection)_deathq.getNonBlocking()) != null) {
// it's possible that we caught an EOF trying to read from
// this connection even after it was queued up for death, so
// let's avoid trying to close it twice
if (!dconn.isClosed()) {
dconn.close();
}
}
// close connections that have had no network traffic for too long
Iterator hiter = _handlers.values().iterator();
while (hiter.hasNext()) {
NetEventHandler handler = (NetEventHandler)hiter.next();
if (handler.checkIdle(iterStamp)) {
// this will queue the connection up for closure on our
// next tick
closeConnection((Connection)handler);
}
}
// attempt to send any messages waiting on the overflow queues
if (_oflowqs.size() > 0) {
Iterator oqiter = _oflowqs.values().iterator();
while (oqiter.hasNext()) {
OverflowQueue oq = (OverflowQueue)oqiter.next();
try {
// try writing the messages in this overflow queue
if (oq.writeOverflowMessages(iterStamp)) {
// if they were all written, we can remove it
oqiter.remove();
Log.info("Flushed overflow queue " + oq + ".");
}
} catch (IOException ioe) {
oq.conn.handleFailure(ioe);
}
}
}
// send any messages that are waiting on the outgoing queue
Tuple tup;
while ((tup = (Tuple)_outq.getNonBlocking()) != null) {
Connection conn = (Connection)tup.left;
// if an overflow queue exists for this client, go ahead and
// slap the message on there because we can't send it until
// all other messages in their queue have gone out
OverflowQueue oqueue = (OverflowQueue)_oflowqs.get(conn);
if (oqueue != null) {
int size = oqueue.size();
if ((size > 500) && (size % 50 == 0)) {
Log.warning("Aiya, big overflow queue for " + conn +
" [size=" + size +
", adding=" + tup.right + "].");
}
oqueue.add(tup.right);
continue;
}
// otherwise write the message out to the client directly
writeMessage(conn, (byte[])tup.right, _oflowHandler);
}
// check for connections that have completed authentication
AuthingConnection conn;
while ((conn = (AuthingConnection)_authq.getNonBlocking()) != null) {
try {
// construct a new running connection to handle this
// connections network traffic from here on out
SelectionKey selkey = conn.getSelectionKey();
RunningConnection rconn = new RunningConnection(
this, selkey, conn.getChannel(), iterStamp);
// we need to keep using the same object input and output
// streams from the beginning of the session because they
// have contextual state that needs to be preserved
rconn.inheritStreams(conn);
// replace the mapping in the handlers table from the old
// connection with the new one
_handlers.put(selkey, rconn);
// and let our observers know about our new connection
notifyObservers(CONNECTION_ESTABLISHED, rconn,
conn.getAuthRequest(), conn.getAuthResponse());
} catch (IOException ioe) {
Log.warning("Failure upgrading authing connection to " +
"running connection.");
Log.logStackTrace(ioe);
}
}
Set ready = null;
try {
// check for incoming network events
// Log.debug("Selecting from " +
// StringUtil.toString(_selector.keys()) + " (" +
// SELECT_LOOP_TIME + ").");
int ecount = _selector.select(SELECT_LOOP_TIME);
ready = _selector.selectedKeys();
if (ecount == 0) {
if (ready.size() == 0) {
return;
} else {
Log.warning("select() returned no selected sockets, " +
"but there are " + ready.size() +
" in the ready set.");
}
}
} catch (IOException ioe) {
Log.warning("Failure select()ing [ioe=" + ioe + "].");
return;
} catch (RuntimeException re) {
// this block of code deals with a bug in the _selector that
// we observed on 2005-05-02, instead of looping indefinitely
// after things go pear-shaped, shut us down in an orderly
// fashion
Log.warning("Failure select()ing [re=" + re + "].");
Log.logStackTrace(re);
if (_runtimeExceptionCount++ >= 20) {
Log.warning("Too many errors, bailing.");
shutdown();
}
return;
}
// clear the runtime error count
_runtimeExceptionCount = 0;
// process those events
// Log.info("Ready set " + StringUtil.toString(ready) + ".");
Iterator siter = ready.iterator();
while (siter.hasNext()) {
SelectionKey selkey = (SelectionKey)siter.next();
NetEventHandler handler = null;
try {
handler = (NetEventHandler)_handlers.get(selkey);
if (handler == null) {
Log.warning("Received network event but have no " +
"registered handler [selkey=" + selkey + "].");
continue;
}
// Log.info("Got event [selkey=" + selkey +
// ", handler=" + handler + "].");
int got = handler.handleEvent(iterStamp);
if (got != 0) {
synchronized (this) {
_bytesIn += got;
_stats.bytesIn[_stats.current] += got;
// we know that the handlers only report having
// read bytes when they have a whole message, so
// we can count thusly
_msgsIn++;
_stats.msgsIn[_stats.current]++;
}
}
} catch (Exception e) {
Log.warning("Error processing network data: " + handler + ".");
Log.logStackTrace(e);
// if you freak out here, you go straight in the can
if (handler != null && handler instanceof Connection) {
closeConnection((Connection)handler);
}
}
}
ready.clear();
}
/**
* Writes a message out to a connection, passing the buck to the
* partial write handler if the entire message could not be written.
*
* @return true if the message was fully written, false if it was
* partially written (in which case the partial message handler will
* have been invoked).
*/
protected boolean writeMessage (
Connection conn, byte[] data, PartialWriteHandler pwh)
{
// if the connection to which this message is destined is closed,
// drop the message and move along quietly; this is perfectly
// have things to tell them; such is life in a fully asynchronous
// distributed system
if (conn.isClosed()) {
return true;
}
// sanity check the message size
if (data.length > 1024 * 1024) {
Log.warning("Refusing to write absurdly large message " +
"[conn=" + conn + ", size=" + data.length + "].");
return true;
}
// expand our output buffer if needed to accomodate this message
if (data.length > _outbuf.capacity()) {
// increase the buffer size in large increments
int ncapacity = Math.max(_outbuf.capacity() << 1, data.length);
Log.info("Expanding output buffer size [nsize=" + ncapacity + "].");
_outbuf = ByteBuffer.allocateDirect(ncapacity);
}
boolean fully = true;
try {
// Log.info("Writing " + data.length + " byte message to " +
// conn + ".");
// first copy the data into our "direct" output buffer
_outbuf.put(data);
_outbuf.flip();
// then write the data to the socket
int wrote = conn.getChannel().write(_outbuf);
noteWrite(1, wrote);
if (_outbuf.remaining() > 0) {
fully = false;
// Log.info("Partial write [conn=" + conn +
// ", msg=" + StringUtil.shortClassName(outmsg) +
// ", wrote=" + wrote +
// ", size=" + buffer.limit() + "].");
pwh.handlePartialWrite(conn, _outbuf);
// } else if (wrote > 10000) {
// Log.info("Big write [conn=" + conn +
// ", msg=" + StringUtil.shortClassName(outmsg) +
// ", wrote=" + wrote + "].");
}
} catch (IOException ioe) {
// instruct the connection to deal with its failure
conn.handleFailure(ioe);
} finally {
_outbuf.clear();
}
return fully;
}
/** Called by {@link #writeMessage} and friends when they write data
* over the network. */
protected final synchronized void noteWrite (int msgs, int bytes)
{
_msgsOut += msgs;
_bytesOut += bytes;
_stats.msgsOut[_stats.current] += msgs;
_stats.bytesOut[_stats.current] += bytes;
}
// documentation inherited
protected void handleIterateFailure (Exception e)
{
// log the exception
Log.warning("ConnectionManager.iterate() uncaught exception.");
Log.logStackTrace(e);
}
// documentation inherited
protected void didShutdown ()
{
Runnable onExit = _onExit;
if (onExit != null) {
Log.info("Connection Manager thread exited (running onExit).");
onExit.run();
} else {
Log.info("Connection Manager thread exited.");
}
}
/**
* Called by our net event handler when a new connection is ready to
* be accepted on our listening socket.
*/
protected void acceptConnection ()
{
SocketChannel channel = null;
try {
channel = _listener.accept();
if (channel == null) {
// in theory this shouldn't happen because we got an
// ACCEPT_READY event, but better safe than sorry
Log.info("Psych! Got ACCEPT_READY, but no connection.");
return;
}
if (!(channel instanceof SelectableChannel)) {
try {
Log.warning("Provided with un-selectable socket as " +
"result of accept(), can't cope " +
"[channel=" + channel + "].");
} catch (Error err) {
Log.warning("Un-selectable channel also couldn't " +
"be printed.");
}
// stick a fork in the socket
channel.socket().close();
return;
}
// Log.debug("Accepted connection " + channel + ".");
// create a new authing connection object to manage the
// authentication of this client connection and register it
// with our selection set
SelectableChannel selchan = (SelectableChannel)channel;
selchan.configureBlocking(false);
SelectionKey selkey = selchan.register(
_selector, SelectionKey.OP_READ);
_handlers.put(selkey, new AuthingConnection(this, selkey, channel));
return;
} catch (IOException ioe) {
Log.warning("Failure accepting new connection: " + ioe);
}
// make sure we don't leak a socket if something went awry
if (channel != null) {
try {
channel.socket().close();
} catch (IOException ioe) {
Log.warning("Failed closing aborted connection: " + ioe);
}
}
}
/**
* Called by a connection when it has a downstream message that needs
* to be delivered. <em>Note:</em> this method is called as a result
* of a call to {@link Connection#postMessage} which happens when
* forwarding an event to a client and at the completion of
* authentication, both of which <em>should</em> happen only on the
* distributed object thread.
*/
void postMessage (Connection conn, DownstreamMessage msg)
{
// sanity check
if (conn == null || msg == null) {
Log.warning("Bogosity.");
Thread.dumpStack();
} else {
// flatten this message using the connection's output stream
try {
ObjectOutputStream oout = conn.getObjectOutputStream(_framer);
oout.writeObject(msg);
oout.flush();
// now extract that data into a byte array
ByteBuffer buffer = _framer.frameAndReturnBuffer();
byte[] data = new byte[buffer.limit()];
buffer.get(data);
_framer.resetFrame();
// Log.info("Flattened " + msg + " into " +
// data.length + " bytes.");
// and slap both on the queue
_outq.append(new Tuple(conn, data));
} catch (Exception e) {
Log.warning("Failure flattening message [conn=" + conn +
", msg=" + msg + "]. Dropping.");
Log.logStackTrace(e);
}
}
}
/**
* Called by a connection if it experiences a network failure.
*/
void connectionFailed (Connection conn, IOException ioe)
{
// remove this connection from our mapping (it is automatically
// removed from the Selector when the socket is closed)
_handlers.remove(conn.getSelectionKey());
_oflowqs.remove(conn);
// let our observers know what's up
notifyObservers(CONNECTION_FAILED, conn, ioe, null);
}
/**
* Called by a connection when it discovers that it's closed.
*/
void connectionClosed (Connection conn)
{
// remove this connection from our mapping (it is automatically
// removed from the Selector when the socket is closed)
_handlers.remove(conn.getSelectionKey());
_oflowqs.remove(conn);
// let our observers know what's up
notifyObservers(CONNECTION_CLOSED, conn, null, null);
}
/** Used to handle partial writes in {@link #writeMessage}. */
protected static interface PartialWriteHandler
{
public void handlePartialWrite (Connection conn, ByteBuffer buffer);
}
/**
* Used to handle messages for a client whose network buffer has
* filled up because their outgoing network buffer has filled up. This
* can happen if the client receives many messages in rapid succession
* or if they receive very large messages or if they become
* unresponsive and stop acknowledging network packets sent by the
* server. We want to accomodate the first to circumstances and
* recognize the third as quickly as possible so that we can
* disconnect the client and propagate that information up to the
* higher levels so that further messages are not queued up for the
* unresponsive client.
*/
protected class OverflowQueue extends ArrayList
implements PartialWriteHandler
{
/** The connection for which we're managing overflow. */
public Connection conn;
/**
* Creates a new overflow queue for the supplied connection and
* with the supplied initial partial message.
*/
public OverflowQueue (Connection conn, ByteBuffer message)
{
this.conn = conn;
// set up our initial _partial buffer
handlePartialWrite(conn, message);
}
/**
* Called each time through the {@link ConnectionManager#iterate}
* loop, this attempts to send any remaining partial message and
* all subsequent messages in the overflow queue.
*
* @return true if all messages in this queue were successfully
* sent, false if there remains data to be sent on the next loop.
*
* @throws IOException if an error occurs writing data to the
* connection or if we have been unable to write any data to the
* connection for ten seconds.
*/
public boolean writeOverflowMessages (long iterStamp)
throws IOException
{
// write any partial message if we have one
if (_partial != null) {
// write all we can of our partial buffer
int wrote = conn.getChannel().write(_partial);
noteWrite(0, wrote);
if (_partial.remaining() == 0) {
_partial = null;
_partials++;
} else {
// Log.info("Still going [conn=" + conn +
// ", wrote=" + wrote +
// ", remain=" + _partial.remaining() + "].");
return false;
}
}
while (size() > 0) {
byte[] data = (byte[])remove(0);
// if any of these messages are partially written, we have
// to stop and wait for the next tick
_msgs++;
if (!writeMessage(conn, data, this)) {
return false;
}
}
return true;
}
// documentation inherited
public void handlePartialWrite (Connection conn, ByteBuffer buffer)
{
// set up our _partial buffer
_partial = ByteBuffer.allocateDirect(buffer.remaining());
_partial.put(buffer);
_partial.flip();
}
/**
* Returns a string representation of this instance.
*/
public String toString ()
{
return "[conn=" + conn + ", partials=" + _partials +
", msgs=" + _msgs + "]";
}
/** The remains of a message that was only partially written on
* its first attempt. */
protected ByteBuffer _partial;
/** A couple of counters. */
protected int _msgs, _partials;
}
protected int _port;
protected Authenticator _author;
protected Selector _selector;
protected ServerSocketChannel _listener;
protected ResultListener _startlist;
/** Counts consecutive runtime errors in select(). */
protected int _runtimeExceptionCount;
/** Maps selection keys to network event handlers. */
protected HashMap _handlers = new HashMap();
protected Queue _deathq = new Queue();
protected Queue _authq = new Queue();
protected Queue _outq = new Queue();
protected FramingOutputStream _framer;
protected ByteBuffer _outbuf = ByteBuffer.allocateDirect(64 * 1024);
protected HashMap _oflowqs = new HashMap();
protected ArrayList _observers = new ArrayList();
/** Bytes in and out in the last reporting period. */
protected long _bytesIn, _bytesOut;
/** Messages read and written in the last reporting period. */
protected int _msgsIn, _msgsOut;
/** Our current runtime stats. */
protected ConMgrStats _stats;
/** A runnable to execute when the connection manager thread exits. */
protected volatile Runnable _onExit;
/** Used to create an overflow queue on the first partial write. */
protected PartialWriteHandler _oflowHandler = new PartialWriteHandler() {
public void handlePartialWrite (Connection conn, ByteBuffer msgbuf) {
// if we couldn't write all the data for this message, we'll
// need to establish an overflow queue
Log.info("Starting overflow queue for " + conn + ".");
_oflowqs.put(conn, new OverflowQueue(conn, msgbuf));
}
};
/**
* How long we wait for network events before checking our running
* flag to see if we should still be running. We don't want to loop
* too tightly, but we need to make sure we don't sit around listening
* for incoming network events too long when there are outgoing
* messages in the queue.
*/
protected static final int SELECT_LOOP_TIME = 100;
// codes for notifyObservers()
protected static final int CONNECTION_ESTABLISHED = 0;
protected static final int CONNECTION_FAILED = 1;
protected static final int CONNECTION_CLOSED = 2;
}
|
package com.thinkbiganalytics.metadata.modeshape.generic;
import com.thinkbiganalytics.metadata.api.MetadataAccess;
import com.thinkbiganalytics.metadata.api.extension.ExtensibleEntity;
import com.thinkbiganalytics.metadata.api.extension.ExtensibleEntityProvider;
import com.thinkbiganalytics.metadata.api.extension.ExtensibleType;
import com.thinkbiganalytics.metadata.api.extension.ExtensibleTypeProvider;
import com.thinkbiganalytics.metadata.api.extension.FieldDescriptor;
import com.thinkbiganalytics.metadata.modeshape.ModeShapeEngineConfig;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import static org.assertj.core.api.Assertions.assertThat;
@SpringApplicationConfiguration(classes = { ModeShapeEngineConfig.class, JcrExtensibleProvidersTestConfig.class })
public class JcrExtensibleProvidersTest extends AbstractTestNGSpringContextTests {
@Inject
private ExtensibleTypeProvider typeProvider;
@Inject
private ExtensibleEntityProvider entityProvider;
@Inject
private MetadataAccess metadata;
@Test
public void testGetAllDefaultTypes() {
int size = metadata.commit(() -> {
List<ExtensibleType> types = typeProvider.getTypes();
return types.size();
});
// Feed + SLA + metric + Datasource + HiveTableDatasource = 5
assertThat(size).isEqualTo(7);
}
@Test(dependsOnMethods="testGetAllDefaultTypes")
public void testCreatePersonType() {
String typeName = metadata.commit(() -> {
ExtensibleType type = typeProvider.buildType("Person")
.field("name")
.type(FieldDescriptor.Type.STRING)
.displayName("Person name")
.description("The name of the person")
.required(true)
.add()
.addField("description", FieldDescriptor.Type.STRING)
.addField("age", FieldDescriptor.Type.LONG)
.build();
return type.getName();
});
assertThat(typeName).isNotNull().isEqualTo("Person");
}
@Test(dependsOnMethods="testCreatePersonType")
public void testCreateEmployeeType() {
String typeName = metadata.commit(() -> {
ExtensibleType person = typeProvider.getType("Person");
ExtensibleType emp = typeProvider.buildType("Employee")
.supertype(person)
.field("name")
.type(FieldDescriptor.Type.STRING)
.displayName("Person name")
.description("The name of the person")
.required(true)
.add()
.addField("description", FieldDescriptor.Type.STRING)
.addField("age", FieldDescriptor.Type.LONG)
.build();
return emp.getSupertype().getName();
});
assertThat(typeName).isNotNull().isEqualTo("Person");
}
@Test(dependsOnMethods="testCreatePersonType")
public void testGetPersonType() {
final ExtensibleType.ID id = metadata.commit(() -> {
ExtensibleType type = typeProvider.getType("Person");
return type.getId();
});
assertThat(id).isNotNull();
Map<String, FieldDescriptor.Type> fields = metadata.commit(() -> {
ExtensibleType type = typeProvider.getType("Person");
Map<String, FieldDescriptor.Type> map = new HashMap<>();
for (FieldDescriptor descr : type.getFieldDescriptors()) {
map.put(descr.getName(), descr.getType());
}
return map;
});
assertThat(fields).isNotNull();
assertThat(fields).containsEntry("name", FieldDescriptor.Type.STRING);
assertThat(fields).containsEntry("description", FieldDescriptor.Type.STRING);
assertThat(fields).containsEntry("age", FieldDescriptor.Type.LONG);
}
@Test(dependsOnMethods="testCreatePersonType")
public void testGetAllTypes() {
int size = metadata.commit(() -> {
List<ExtensibleType> types = typeProvider.getTypes();
return types.size();
});
// 5 + Person + Employee = 7
assertThat(size).isEqualTo(9);
}
@Test(dependsOnMethods="testCreatePersonType")
public void testCreateEntity() {
ExtensibleEntity.ID id = metadata.commit(() -> {
ExtensibleType type = typeProvider.getType("Person");
Map<String, Object> props = new HashMap<>();
props.put("name", "Bob");
props.put("description", "Silly");
props.put("age", 50);
ExtensibleEntity entity = entityProvider.createEntity(type, props);
return entity.getId();
});
assertThat(id).isNotNull();
}
@Test(dependsOnMethods="testCreatePersonType")
public void testGetEntity() {
String typeName = metadata.commit(() -> {
List<ExtensibleEntity> list = entityProvider.getEntities();
assertThat(list).isNotNull().hasSize(1);
ExtensibleEntity.ID id = list.get(0).getId();
ExtensibleEntity entity = entityProvider.getEntity(id);
assertThat(entity).isNotNull();
assertThat(entity.getProperty("name")).isEqualTo("Bob");
return entity.getTypeName();
});
assertThat(typeName).isEqualTo("Person");
}
}
|
package org.motechproject.scheduler.service.impl;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.motechproject.commons.sql.util.Drivers;
import org.motechproject.scheduler.constants.SchedulerConstants;
import org.motechproject.scheduler.contract.EventInfo;
import org.motechproject.scheduler.contract.JobBasicInfo;
import org.motechproject.scheduler.contract.JobDetailedInfo;
import org.motechproject.scheduler.contract.JobsSearchSettings;
import org.motechproject.scheduler.contract.RepeatingJobId;
import org.motechproject.scheduler.contract.RepeatingPeriodJobId;
import org.motechproject.scheduler.contract.RunOnceJobId;
import org.motechproject.scheduler.exception.MotechSchedulerJobRetrievalException;
import org.motechproject.scheduler.factory.MotechSchedulerFactoryBean;
import org.motechproject.scheduler.service.MotechSchedulerDatabaseService;
import org.quartz.CalendarIntervalTrigger;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.TriggerKey;
import org.quartz.TriggerUtils;
import org.quartz.impl.matchers.GroupMatcher;
import org.quartz.spi.OperableTrigger;
import org.quartz.utils.DBConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import static org.apache.commons.lang.StringUtils.isNotBlank;
/**
* Motech Scheduler Database Service implementation
*
* @see MotechSchedulerDatabaseService
*/
@Service("schedulerDatabaseService")
public class MotechSchedulerDatabaseServiceImpl implements MotechSchedulerDatabaseService {
private static final Logger LOGGER = LoggerFactory.getLogger(MotechSchedulerDatabaseServiceImpl.class);
private static final String DATE_FORMAT_PATTERN = "Y-MM-dd HH:mm:ss";
private static final String DATA_SOURCE = "org.quartz.jobStore.dataSource";
private static final String UI_DEFINED = "uiDefined";
private static final String START_TIME = "START_TIME";
private static final String END_TIME = "END_TIME";
private static final String TRIGGER_NAME = "TRIGGER_NAME";
private static final String TRIGGER_GROUP = "TRIGGER_GROUP";
private static final String TRIGGER_STATE = "TRIGGER_STATE";
private static final String TRIGGER_TYPE = "TRIGGER_TYPE";
private static final String WAITING = "WAITING";
private static final String TRIGGERS = "TRIGGERS";
private static final String JOB_DETAILS = "JOB_DETAILS";
private static final String JOB_DATA = "JOB_DATA";
private static final String OR = " OR ";
private static final String AND = " AND ";
@Autowired
private Properties sqlProperties;
private Scheduler scheduler;
@Autowired
private MotechSchedulerFactoryBean motechSchedulerFactoryBean;
@PostConstruct
public void init() {
scheduler = motechSchedulerFactoryBean.getQuartzScheduler();
}
@Override
public int countJobs(JobsSearchSettings jobsSearchSettings) throws MotechSchedulerJobRetrievalException {
String query = buildJobsCountSqlQuery(jobsSearchSettings);
int rowCount;
try {
rowCount = executeCountQuery(query);
LOGGER.debug("Executing {}", query);
return rowCount;
} catch (SQLException e) {
throw new MotechSchedulerJobRetrievalException("Jobs counting failed.", e);
}
}
@Override
public List<JobBasicInfo> getScheduledJobsBasicInfo(JobsSearchSettings jobsSearchSettings) throws MotechSchedulerJobRetrievalException {
List<JobBasicInfo> jobBasicInfos = new LinkedList<>();
if (!isNotBlank(jobsSearchSettings.getActivity()) || !isNotBlank(jobsSearchSettings.getStatus())) {
return jobBasicInfos;
}
String query = buildJobsBasicInfoSqlQuery(jobsSearchSettings);
LOGGER.debug("Executing {}", query);
List<String> columnNames = new LinkedList<>();
columnNames.add(TRIGGER_NAME);
columnNames.add(TRIGGER_GROUP);
columnNames.add(JOB_DATA);
List<List<Object>> objects;
try {
objects = executeQuery(query, columnNames);
for (List<Object> row : objects) {
JobKey jobKey = new JobKey(row.get(0).toString(), row.get(1).toString());
Trigger trigger = scheduler.getTriggersOfJob(jobKey).get(0);
String jobName = jobKey.getName();
String jobGroup = jobKey.getGroup();
String jobType = getJobType(jobKey);
String activity = getJobActivity(trigger);
String info = getJobInfo(trigger, jobType);
String status = getJobStatus(trigger.getKey());
String startDate = getStartDate(trigger);
String nextFireDate = "";
if (trigger.getNextFireTime() != null) {
nextFireDate = DateTimeFormat.forPattern(DATE_FORMAT_PATTERN).print(trigger.getNextFireTime().getTime());
}
String endDate = getEndDate(trigger, jobType);
boolean uiDefined = getUiDefined((byte[]) row.get(2));
jobBasicInfos.add(new JobBasicInfo(
activity,
status,
jobName,
jobGroup,
startDate,
nextFireDate,
endDate,
jobType,
info,
uiDefined
));
}
return jobBasicInfos;
} catch (SQLException | SchedulerException | ClassNotFoundException | IOException e) {
throw new MotechSchedulerJobRetrievalException("Retrieval of scheduled jobs failed.", e);
}
}
@Override
public JobDetailedInfo getScheduledJobDetailedInfo(JobBasicInfo jobBasicInfo) throws MotechSchedulerJobRetrievalException {
JobDetailedInfo jobDetailedInfo = new JobDetailedInfo();
List<EventInfo> eventInfos = new ArrayList<>();
try {
for (String groupName : scheduler.getJobGroupNames()) {
for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {
if (jobKey.getName().equals(jobBasicInfo.getName())) {
EventInfo eventInfo = new EventInfo();
String subject;
Map<String, Object> parameters = scheduler.getJobDetail(jobKey).getJobDataMap().getWrappedMap();
Map<String, Object> metadata = (HashMap) parameters.get(SchedulerConstants.EVENT_METADATA);
parameters.remove(SchedulerConstants.EVENT_METADATA);
parameters.putAll(metadata);
eventInfo.setParameters(parameters);
if (eventInfo.getParameters().containsKey(SchedulerConstants.EVENT_TYPE_KEY_NAME)) {
subject = eventInfo.getParameters().get(SchedulerConstants.EVENT_TYPE_KEY_NAME).toString();
eventInfo.getParameters().remove(SchedulerConstants.EVENT_TYPE_KEY_NAME);
} else {
subject = jobKey.getName().substring(0, jobKey.getName().indexOf('-'));
}
eventInfo.setSubject(subject);
eventInfos.add(eventInfo);
}
}
}
jobDetailedInfo.setEventInfoList(eventInfos);
return jobDetailedInfo;
} catch (SchedulerException e) {
throw new MotechSchedulerJobRetrievalException("Retrieval of detailed info for job " + jobBasicInfo.getName() + " failed.", e);
}
}
private List<List<Object>> executeQuery(String query, List<String> columns) throws SQLException {
List<List<Object>> rows = new LinkedList<>();
try (Connection conn = DBConnectionManager.getInstance().getConnection(sqlProperties.getProperty(DATA_SOURCE));
Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
List<Object> row = new LinkedList<>();
if (columns != null) {
for (String name : columns) {
row.add(rs.getObject(name));
}
}
rows.add(row);
}
}
return rows;
}
private int executeCountQuery(String query) throws SQLException {
int rowConut = 0;
try (Connection conn = DBConnectionManager.getInstance().getConnection(sqlProperties.getProperty(DATA_SOURCE));
Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery(query);
rs.next();
rowConut = rs.getInt(1);
}
return rowConut;
}
private void checkAndAddElement(StringBuilder sb, String element, boolean condition) {
if (condition) {
sb.append(element);
}
}
private String buildDateRangeFilter(JobsSearchSettings jobsSearchSettings) {
StringBuilder dateRangeSb = new StringBuilder();
boolean addAnd = false;
DateTime dateFrom;
DateTime dateTo;
if (StringUtils.isNotBlank(jobsSearchSettings.getTimeFrom())) {
dateFrom = DateTimeFormat.forPattern(DATE_FORMAT_PATTERN)
.parseDateTime(jobsSearchSettings.getTimeFrom());
dateRangeSb.append(getCorrectNameRepresentation(START_TIME)).append(" >= ").append(dateFrom.getMillis());
addAnd = true;
}
if (StringUtils.isNotBlank(jobsSearchSettings.getTimeTo())) {
dateTo = DateTimeFormat.forPattern(DATE_FORMAT_PATTERN)
.parseDateTime(jobsSearchSettings.getTimeTo());
checkAndAddElement(dateRangeSb, AND, addAnd);
dateRangeSb.append(getCorrectNameRepresentation(START_TIME)).append(" <= ").append(dateTo.getMillis());
}
return dateRangeSb.toString();
}
private String buildActivityFilter(JobsSearchSettings jobsSearchSettings) {
StringBuilder activitySb = new StringBuilder();
String[] activityElements = jobsSearchSettings.getActivity().split(",");
boolean addOr = false;
if (activityElements.length < 3) {
for(String element : activityElements) {
checkAndAddElement(activitySb, OR, addOr);
if (JobBasicInfo.ACTIVITY_NOTSTARTED.equals(element)) {
activitySb.append(getCorrectNameRepresentation(START_TIME)).append(" > ").append(DateTime.now().getMillis());
} else if (JobBasicInfo.ACTIVITY_FINISHED.equals(element)) {
activitySb.append(getCorrectNameRepresentation(END_TIME)).append(" < ").append(DateTime.now().getMillis())
.append(AND).append(getCorrectNameRepresentation(END_TIME)).append(" != 0");
} else {
activitySb.append(" (").append(getCorrectNameRepresentation(START_TIME)).append(" <= ")
.append(DateTime.now().getMillis()).append(" AND (")
.append(getCorrectNameRepresentation(END_TIME)).append(" >= ")
.append(DateTime.now().getMillis()).append(OR)
.append(getCorrectNameRepresentation(END_TIME)).append(" = 0))");
}
addOr = true;
}
}
return activitySb.toString();
}
private String buildStatusFilter(JobsSearchSettings jobsSearchSettings) {
StringBuilder statusSb = new StringBuilder();
String[] statusElements = jobsSearchSettings.getStatus().split(",");
boolean addOr = false; if (statusElements.length < 4) {
for(String element : statusElements) {
checkAndAddElement(statusSb, OR, addOr);
statusSb.append(getCorrectNameRepresentation(TRIGGER_STATE)).append(" = ");
if (Trigger.TriggerState.ERROR.toString().equals(element)) {
statusSb.append("\'").append(Trigger.TriggerState.ERROR.toString()).append("\'");
} else if (Trigger.TriggerState.BLOCKED.toString().equals(element)) {
statusSb.append("\'").append(Trigger.TriggerState.BLOCKED.toString()).append("\'");
} else if (Trigger.TriggerState.PAUSED.toString().equals(element)) {
statusSb.append("\'").append(Trigger.TriggerState.PAUSED.toString()).append("\'");
} else {
statusSb.append("\'").append(Trigger.TriggerState.NORMAL.toString()).append("\'");
statusSb.append(OR).append(getCorrectNameRepresentation(TRIGGER_STATE)).append(" = ");
statusSb.append("\'").append(Trigger.TriggerState.COMPLETE.toString()).append("\'");
statusSb.append(OR).append(getCorrectNameRepresentation(TRIGGER_STATE)).append(" = ");
statusSb.append("\'").append(WAITING).append("\'");
}
addOr = true;
}
}
return statusSb.toString();
}
private List<String> buildFilters(JobsSearchSettings jobsSearchSettings) {
List<String> filters = new ArrayList<>();
String dateRangeFilter = buildDateRangeFilter(jobsSearchSettings);
if (isNotBlank(dateRangeFilter)) {
filters.add(dateRangeFilter);
}
String activityFilter = buildActivityFilter(jobsSearchSettings);
if (isNotBlank(activityFilter)) {
filters.add(activityFilter);
}
String statusFilter = buildStatusFilter(jobsSearchSettings);
if (isNotBlank(statusFilter)) {
filters.add(statusFilter);
}
StringBuilder nameSb = new StringBuilder();
if (isNotBlank(jobsSearchSettings.getName())) {
nameSb.append(getCorrectNameRepresentation(TRIGGER_NAME)).append(" LIKE ").append("\'%")
.append(jobsSearchSettings.getName()).append("%\'");
filters.add(nameSb.toString());
}
return filters;
}
private String getCorrectNameRepresentation(String name) {
return sqlProperties.get("org.quartz.dataSource.motechDS.driver").equals(Drivers.MYSQL_DRIVER) ? name : "\"" + name.toLowerCase() + "\"";
}
private String buildWhereCondition(JobsSearchSettings jobsSearchSettings) {
List<String> filters = buildFilters(jobsSearchSettings);
StringBuilder sb = new StringBuilder();
boolean addAnd = false;
if (filters.size() > 0) {
sb.append(" WHERE ");
}
for (String filter : filters) {
if (filter.length() > 0) {
checkAndAddElement(sb, AND, addAnd);
sb.append("(").append(filter).append(")");
addAnd = true;
}
}
return sb.toString();
}
private String buildJobsBasicInfoSqlQuery(JobsSearchSettings jobsSearchSettings) {
StringBuilder sb = new StringBuilder("SELECT A.TRIGGER_NAME, A.TRIGGER_GROUP, B.JOB_DATA FROM ")
.append(getCorrectNameRepresentation(sqlProperties.get("org.quartz.jobStore.tablePrefix").toString() + TRIGGERS))
.append(" AS A JOIN ")
.append(getCorrectNameRepresentation(sqlProperties.get("org.quartz.jobStore.tablePrefix").toString() + JOB_DETAILS))
.append(" AS B")
.append(" ON A.TRIGGER_NAME = B.JOB_NAME AND A.TRIGGER_GROUP = B.JOB_GROUP")
.append(buildWhereCondition(jobsSearchSettings));
if (isNotBlank(jobsSearchSettings.getSortColumn()) && isNotBlank(jobsSearchSettings.getSortDirection())) {
sb.append(" ORDER BY ")
.append("A.")
.append(getCorrectNameRepresentation(getSortColumn(jobsSearchSettings.getSortColumn())))
.append(" ")
.append(jobsSearchSettings.getSortDirection().toUpperCase());
}
if (jobsSearchSettings.getRows() != null && jobsSearchSettings.getPage() != null) {
int offset = (jobsSearchSettings.getPage() == 0) ? 0 : (jobsSearchSettings.getPage() - 1) * jobsSearchSettings.getRows();
sb = sb.append(" LIMIT ").append(jobsSearchSettings.getRows()).append(" OFFSET ").append(offset);
}
return sb.toString();
}
private String buildJobsCountSqlQuery(JobsSearchSettings jobsSearchSettings) {
StringBuilder sb = new StringBuilder("SELECT COUNT(*) FROM ");
sb = sb.append(getCorrectNameRepresentation(sqlProperties.get("org.quartz.jobStore.tablePrefix").toString() + TRIGGERS));
sb = sb.append(buildWhereCondition(jobsSearchSettings));
return sb.toString();
}
private String getSortColumn(String column) {
String sortColumn;
if (column.equalsIgnoreCase("startDate")) {
sortColumn = START_TIME;
} else if (column.equalsIgnoreCase("endDate")) {
sortColumn = END_TIME;
} else if (column.equalsIgnoreCase("status")) {
sortColumn = TRIGGER_STATE;
} else if (column.equalsIgnoreCase("jobType")) {
sortColumn = TRIGGER_TYPE;
} else {
sortColumn = TRIGGER_NAME;
}
return sortColumn;
}
private String getJobInfo(Trigger trigger, String jobType) throws SchedulerException {
if (jobType.equals(JobBasicInfo.JOBTYPE_REPEATING)) {
Integer timesTriggered = 0;
String repeatMaxCount = "-";
if (trigger instanceof CalendarIntervalTrigger) {
CalendarIntervalTrigger calendarIntervalTrigger = (CalendarIntervalTrigger) trigger;
timesTriggered = calendarIntervalTrigger.getTimesTriggered();
} else if (trigger instanceof SimpleTrigger) {
SimpleTrigger simpleTrigger = (SimpleTrigger) trigger;
timesTriggered = simpleTrigger.getTimesTriggered();
}
if (trigger.getEndTime() != null) {
repeatMaxCount = Integer.toString(TriggerUtils.computeFireTimesBetween(
(OperableTrigger) trigger, null, trigger.getStartTime(), trigger.getEndTime()
).size() + timesTriggered);
}
return String.format("%d/%s", timesTriggered, repeatMaxCount);
} else if (jobType.equals(JobBasicInfo.JOBTYPE_CRON)) {
CronScheduleBuilder cronScheduleBuilder = (CronScheduleBuilder) trigger.getScheduleBuilder();
CronTrigger cronTrigger = (CronTrigger) cronScheduleBuilder.build();
return cronTrigger.getCronExpression();
} else {
return "-";
}
}
private String getJobType(JobKey jobKey) throws SchedulerException {
if (jobKey.getName().endsWith(RunOnceJobId.SUFFIX_RUNONCEJOBID)) {
return JobBasicInfo.JOBTYPE_RUNONCE;
} else if (jobKey.getName().endsWith(RepeatingJobId.SUFFIX_REPEATJOBID)) {
return JobBasicInfo.JOBTYPE_REPEATING;
} else if (jobKey.getName().endsWith(RepeatingPeriodJobId.SUFFIX_REPEATPERIODJOBID)) {
return JobBasicInfo.JOBTYPE_PERIOD;
} else {
return JobBasicInfo.JOBTYPE_CRON;
}
}
private String getStartDate(Trigger trigger) throws SchedulerException {
return DateTimeFormat.forPattern(DATE_FORMAT_PATTERN).print(trigger.getStartTime().getTime());
}
private String getEndDate(Trigger trigger, String jobType) throws SchedulerException {
DateTime endDateTime = new DateTime(trigger.getEndTime());
String startDate = getStartDate(trigger);
String endDate;
if (!endDateTime.isAfterNow()) {
if (jobType.equals(JobBasicInfo.JOBTYPE_RUNONCE)) {
endDate = startDate;
} else {
endDate = "-";
}
} else {
endDate = DateTimeFormat.forPattern(DATE_FORMAT_PATTERN).print(endDateTime);
}
return endDate;
}
private String getJobActivity(Trigger trigger) throws SchedulerException {
DateTime startDateTime = new DateTime(trigger.getStartTime());
DateTime endDateTime = new DateTime(trigger.getEndTime());
if (startDateTime.isAfterNow()) {
return JobBasicInfo.ACTIVITY_NOTSTARTED;
} else if (endDateTime.isBeforeNow()) {
return JobBasicInfo.ACTIVITY_FINISHED;
} else {
return JobBasicInfo.ACTIVITY_ACTIVE;
}
}
private String getJobStatus(TriggerKey triggerKey) throws SchedulerException {
Trigger.TriggerState currentTriggerState = scheduler.getTriggerState(triggerKey);
if (currentTriggerState == Trigger.TriggerState.ERROR) {
return JobBasicInfo.STATUS_ERROR;
} else if (currentTriggerState == Trigger.TriggerState.BLOCKED) {
return JobBasicInfo.STATUS_BLOCKED;
} else if (currentTriggerState == Trigger.TriggerState.PAUSED) {
return JobBasicInfo.STATUS_PAUSED;
} else {
return JobBasicInfo.STATUS_OK;
}
}
private boolean getUiDefined(byte[] bytes) throws IOException, ClassNotFoundException {
try (InputStream is = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(is)) {
JobDataMap jobDataMap = (JobDataMap) ois.readObject();
return isUiDefined(jobDataMap);
}
}
private boolean isUiDefined(JobDataMap jobDataMap) {
return jobDataMap.get(SchedulerConstants.EVENT_METADATA) != null && (Boolean) ((Map<String, Object>) jobDataMap.get(SchedulerConstants.EVENT_METADATA)).get(UI_DEFINED);
}
}
|
package org.apache.velocity.runtime.resource;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;
import org.apache.velocity.Template;
import org.apache.velocity.runtime.Runtime;
import org.apache.velocity.runtime.configuration.Configuration;
import org.apache.velocity.runtime.resource.ResourceFactory;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;
import org.apache.velocity.runtime.resource.loader.ResourceLoaderFactory;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.ParseErrorException;
/**
* Class to manage the text resource for the Velocity
* Runtime.
*
* @author <a href="mailto:jvanzyl@periapt.com">Jason van Zyl</a>
* @version $Id: ResourceManager.java,v 1.11 2001/03/03 20:49:40 jvanzyl Exp $
*/
public class ResourceManager
{
/**
* A template resources.
*/
public static final int RESOURCE_TEMPLATE = 1;
/**
* A static content resource.
*/
public static final int RESOURCE_CONTENT = 2;
/**
* Hashtable used to store templates that have been
* processed. Our simple caching mechanism.
*/
private static Hashtable globalCache = new Hashtable();
/**
* The List of templateLoaders that the Runtime will
* use to locate the InputStream source of a template.
*/
private static ArrayList resourceLoaders = new ArrayList();
/**
* This is a list of the template stream source
* initializers, basically properties for a particular
* template stream source. The order in this list
* reflects numbering of the properties i.e.
* template.loader.1.<property> = <value>
* template.loader.2.<property> = <value>
*/
private static ArrayList sourceInitializerList = new ArrayList();
/**
* This is a map of public name of the template
* stream source to it's initializer. This is so
* that clients of velocity can set properties of
* a template source stream with its public name.
* So for example, a client could set the
* File.resource.path property and this would
* change the resource.path property for the
* file template stream source.
*/
private static Hashtable sourceInitializerMap = new Hashtable();
/**
* Each loader needs a configuration object for
* its initialization, this flags keeps track of whether
* or not the configuration objects have been created
* for the resource loaders.
*/
private static boolean resourceLoaderInitializersActive = false;
/**
* Initialize the ResourceManager. It is assumed
* that assembleSourceInitializers() has been
* called before this is run.
*/
public static void initialize() throws Exception
{
ResourceLoader resourceLoader;
assembleResourceLoaderInitializers();
for (int i = 0; i < sourceInitializerList.size(); i++)
{
Configuration configuration = (Configuration) sourceInitializerList.get(i);
String loaderClass = configuration.getString("class");
resourceLoader = ResourceLoaderFactory.getLoader(loaderClass);
resourceLoader.commonInit(configuration);
resourceLoader.init(configuration);
resourceLoaders.add(resourceLoader);
}
}
/**
* This will produce a List of Hashtables, each
* hashtable contains the intialization info for
* a particular resource loader. This Hastable
* will be passed in when initializing the
* the template loader.
*/
private static void assembleResourceLoaderInitializers()
{
if (resourceLoaderInitializersActive)
{
return;
}
for (int i = 1; i < 10; i++)
{
String loaderID = "resource.loader." + new Integer(i).toString();
/*
* Create a resources class specifically for
* the loader if we have a valid subset of
* resources. VelocityResources.subset(prefix)
* will return null if we do not have a valid
* subset of resources.
*/
if (Runtime.getConfiguration().subset(loaderID) == null)
{
continue;
}
Configuration loaderConfiguration = new Configuration(
Runtime.getConfiguration().subset(loaderID));
/*
* Add resources to the list of resource loader
* initializers.
*/
sourceInitializerList.add(loaderConfiguration);
/*
* Make a Map of the public names for the sources
* to the sources property identifier so that external
* clients can set source properties. For example:
* File.resource.path would get translated into
* template.loader.1.resource.path and the translated
* name would be used to set the property.
*/
sourceInitializerMap.put(
loaderConfiguration.getString("public.name").toLowerCase(),
loaderConfiguration);
}
}
/**
* Gets the named resource. Returned class type corresponds to specified type
* (i.e. <code>Template</code> to <code>RESOURCE_TEMPLATE</code>).
*
* @param resourceName The name of the resource to retrieve.
* @param resourceType The type of resource (<code>RESOURCE_TEMPLATE</code>,
* <code>RESOURCE_CONTENT</code>, etc.).
* @return Resource with the template parsed and ready.
* @throws ResourceNotFoundException if template not found
* from any available source.
* @throws ParseErrorException if template cannot be parsed due
* to syntax (or other) error.
* @throws Exception if a problem in parse
*/
public static Resource getResource(String resourceName, int resourceType)
throws ResourceNotFoundException, ParseErrorException, Exception
{
Resource resource = null;
ResourceLoader resourceLoader = null;
/*
* Check to see if the resource was placed in the cache.
* If it was placed in the cache then we will use
* the cached version of the resource. If not we
* will load it.
*/
if (globalCache.containsKey(resourceName))
{
resource = (Resource) globalCache.get(resourceName);
/*
* The resource knows whether it needs to be checked
* or not, and the resource's loader can check to
* see if the source has been modified. If both
* these conditions are true then we must reload
* the input stream and parse it to make a new
* AST for the resource.
*/
if ( resource.requiresChecking() )
{
/*
* touch() the resource to reset the counters
*/
resource.touch();
if( resource.isSourceModified() )
{
try
{
/*
* read in the fresh stream and parse
*/
resource.process();
/*
* now set the modification info and reset
* the modification check counters
*/
resource.setLastModified(
resourceLoader.getLastModified( resource ));
}
catch( ResourceNotFoundException rnfe )
{
Runtime.error("ResourceManager.getResource() exception: " + rnfe);
throw rnfe;
}
catch( ParseErrorException pee )
{
Runtime.error("ResourceManager.getResource() exception: " + pee);
throw pee;
}
catch( Exception eee )
{
Runtime.error("ResourceManager.getResource() exception: " + eee);
throw eee;
}
}
}
return resource;
}
else
{
/*
* it's not in the cache
*/
try
{
resource = ResourceFactory.getResource(resourceName, resourceType);
resource.setName(resourceName);
/*
* Now we have to try to find the appropriate
* loader for this resource. We have to cycle through
* the list of available resource loaders and see
* which one gives us a stream that we can use to
* make a resource with.
*/
//! Bug this is being run more then once!
for (int i = 0; i < resourceLoaders.size(); i++)
{
resourceLoader = (ResourceLoader) resourceLoaders.get(i);
resource.setResourceLoader(resourceLoader);
Runtime.info("Attempting to find " + resourceName +
" with " + resourceLoader.getClassName());
if (resource.process())
break;
}
/*
* Return null if we can't find a resource.
*/
if (resource.getData() == null)
throw new ResourceNotFoundException("Can't find " + resourceName + "!");
resource.setLastModified(resourceLoader.getLastModified(resource));
resource.setModificationCheckInterval(
resourceLoader.getModificationCheckInterval());
resource.touch();
/*
* Place the resource in the cache if the resource
* loader says to.
*/
if (resourceLoader.isCachingOn())
globalCache.put(resourceName, resource);
}
catch( ParseErrorException pee )
{
Runtime.error("ResourceManager.getResource() parse exception: " + pee);
throw pee;
}
catch( Exception ee )
{
Runtime.error("ResourceManager.getResource() exception: " + ee);
throw ee;
}
}
return resource;
}
/**
* Allow clients of Velocity to set a template stream
* source property before the template source streams
* are initialized. This would for example allow clients
* to set the template path that would be used by the
* file template stream source. Right now these properties
* have to be set before the template stream source is
* initialized. Maybe we should allow these properties
* to be changed on the fly.
*
* It is assumed that the initializers have been
* assembled.
*/
public static void setSourceProperty(String key, String value)
{
if (resourceLoaderInitializersActive == false)
{
assembleResourceLoaderInitializers();
}
String publicName = key.substring(0, key.indexOf("."));
String property = key.substring(key.indexOf(".") + 1);
Configuration loaderConfiguration = (Configuration)
sourceInitializerMap.get(publicName.toLowerCase());
loaderConfiguration.setProperty(property, value);
}
}
|
package com.intellij.diagnostic;
import com.intellij.CommonBundle;
import com.intellij.errorreport.ErrorReportSender;
import com.intellij.errorreport.bean.ErrorBean;
import com.intellij.errorreport.bean.NotifierBean;
import com.intellij.errorreport.error.InternalEAPException;
import com.intellij.errorreport.error.NewBuildException;
import com.intellij.errorreport.error.NoSuchEAPUserException;
import com.intellij.errorreport.error.ThreadClosedException;
import com.intellij.errorreport.itn.ITNProxy;
import com.intellij.ide.BrowserUtil;
import com.intellij.idea.IdeaLogger;
import com.intellij.openapi.diagnostic.ErrorReportSubmitter;
import com.intellij.openapi.diagnostic.IdeaLoggingEvent;
import com.intellij.openapi.diagnostic.SubmittedReportInfo;
import com.intellij.openapi.ui.Messages;
import com.intellij.util.net.IOExceptionDialog;
import org.jetbrains.annotations.NonNls;
import java.awt.*;
import java.io.IOException;
public class ITNReporter extends ErrorReportSubmitter {
private static int previousExceptionThreadId = 0;
private static boolean wasException = false;
@NonNls private static final String URL_HEADER = "http:
public String getReportActionText() {
return DiagnosticBundle.message("error.report.to.jetbrains.action");
}
public SubmittedReportInfo submit(IdeaLoggingEvent[] events, Component parentComponent) {
return sendError(events[0], parentComponent);
}
/**
* @noinspection ThrowablePrintStackTrace
*/
private static SubmittedReportInfo sendError(IdeaLoggingEvent event, Component parentComponent) {
NotifierBean notifierBean = new NotifierBean();
ErrorBean errorBean = new ErrorBean();
errorBean.autoInit();
errorBean.setLastAction(IdeaLogger.ourLastActionId);
int threadId = 0;
SubmittedReportInfo.SubmissionStatus submissionStatus = SubmittedReportInfo.SubmissionStatus.FAILED;
do {
// prepare
try {
ErrorReportSender sender = ErrorReportSender.getInstance();
sender.prepareError(event.getThrowable());
EAPSendErrorDialog dlg = new EAPSendErrorDialog();
dlg.show();
boolean anonymousLogin = false;
@NonNls String itnLogin = ErrorReportConfigurable.getInstance().ITN_LOGIN;
@NonNls String itnPassword = ErrorReportConfigurable.getInstance().getPlainItnPassword();
if (itnLogin.trim().length() == 0 && itnPassword.trim().length() == 0) {
anonymousLogin = true;
itnLogin = "idea_anonymous";
itnPassword = "guest";
}
notifierBean.setItnLogin(itnLogin);
notifierBean.setItnPassword(itnPassword);
String description = dlg.getErrorDescription();
String message = event.getMessage();
errorBean.setDescription((description.length() > 0 ? "User description: " + description + "\n" : "")+
(message != null ? "Error message: " + message + "\n" : ""));
if (dlg.isShouldSend()) {
threadId = sender.sendError(notifierBean, errorBean);
if (previousExceptionThreadId != 0) {
ITNProxy.postNewComment(ErrorReportConfigurable.getInstance().ITN_LOGIN,
ErrorReportConfigurable.getInstance().getPlainItnPassword(),
threadId, "Previous exception is: " +
URL_HEADER +
previousExceptionThreadId);
}
previousExceptionThreadId = threadId;
if (wasException) {
ITNProxy.postNewComment(ErrorReportConfigurable.getInstance().ITN_LOGIN,
ErrorReportConfigurable.getInstance().getPlainItnPassword(),
threadId, "There was at least one exception before this one.");
}
wasException = true;
submissionStatus = SubmittedReportInfo.SubmissionStatus.NEW_ISSUE;
Messages.showInfoMessage(parentComponent,
DiagnosticBundle.message("error.report.confirmation"),
ReportMessages.ERROR_REPORT);
break;
}
else {
break;
}
}
catch (NoSuchEAPUserException e) {
if (Messages.showYesNoDialog(parentComponent, DiagnosticBundle.message("error.report.authentication.failed"),
ReportMessages.ERROR_REPORT, Messages.getErrorIcon()) != 0) {
break;
}
}
catch (InternalEAPException e) {
if (Messages.showYesNoDialog(parentComponent, DiagnosticBundle.message("error.report.posting.failed"),
ReportMessages.ERROR_REPORT, Messages.getErrorIcon()) != 0) {
break;
}
}
catch (IOException e) {
if (!IOExceptionDialog.showErrorDialog(e, DiagnosticBundle.message("error.report.exception.title"),
DiagnosticBundle.message("error.report.failure.message"))) {
break;
}
}
catch (NewBuildException e) {
Messages.showMessageDialog(parentComponent,
DiagnosticBundle.message("error.report.new.eap.build.message", e.getMessage()), CommonBundle.getWarningTitle(),
Messages.getWarningIcon());
break;
}
catch (ThreadClosedException e) {
submissionStatus = SubmittedReportInfo.SubmissionStatus.DUPLICATE;
threadId = e.getThreadId();
if (Messages.showYesNoDialog(parentComponent,
DiagnosticBundle.message("error.report.already.closed.message", e.getMessage()),
ReportMessages.ERROR_REPORT, Messages.getQuestionIcon()) == 0) {
try {
BrowserUtil.launchBrowser(URL_HEADER + threadId);
}
catch (IllegalThreadStateException ex) {
// it's OK
// browser is not exited
}
}
break;
}
catch (Exception e) {
if (Messages.showYesNoDialog(parentComponent, DiagnosticBundle.message("error.report.sending.failure"),
ReportMessages.ERROR_REPORT, Messages.getErrorIcon()) != 0) {
break;
}
}
}
while (true);
return new SubmittedReportInfo(submissionStatus != SubmittedReportInfo.SubmissionStatus.FAILED ? URL_HEADER + threadId : null,
String.valueOf(threadId),
submissionStatus);
}
}
|
package org.vrjuggler.vrjconfig.customeditors.intersense;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Dimension;
import java.awt.Container;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import javax.swing.tree.*;
import org.vrjuggler.jccl.config.*;
import org.vrjuggler.jccl.editors.*;
import org.jdom.*;
public class IntersensePanel extends JPanel implements CustomEditor
{
/** Panel which contains all general Intersense information. */
private JPanel mDeviceInfoPanel = new JPanel();
private JPanel mTopSectionPanel = new JPanel();
private GridLayout mInfoPanelLayout = new GridLayout();
private JLabel mPortLbl = new JLabel();
private PropertyEditorPanel mPortEditor = null;
private JLabel mDriverLbl = new JLabel();
private PropertyEditorPanel mDriverEditor = null;
private JLabel mISenseIconLbl = new JLabel();
/** ConfigElement for this Intersense device. */
private ConfigElement mConfigElement = null;
/** ConfigContext associated with this Intersense device. */
private ConfigContext mConfigContext = null;
/** Table that displays all stations for this Intersense device. */
private JTable mStationsTable = new StationTable();
private JPanel mStationsPanel = null;
private JPanel mProxyPanel = new JPanel();
/** Toolbar for controling ProxyTree. */
private JToolBar mToolbar = new JToolBar();
private JScrollPane mProxyTreeScrollPane = new JScrollPane();
/** Representation of proxies pointing at this device. */
private ProxyTree mProxyTree = new ProxyTree();
/** The model that contains all information about this Intersense device. */
private IntersenseModel mModel = null;
private JButton mCreateBtn = new JButton();
private JButton mRemoveBtn = new JButton();
private JButton mAttachBtn = new JButton();
private JButton mDisconnectBtn = new JButton();
private JButton mVisualizeBtn = new JButton("3D Visualization");
/**
* Constructor.
*/
public IntersensePanel()
{
// Register ourselves with the CustomEditorRegistry.
CustomEditorRegistry.registerEditor("intersense_api", IntersensePanel.class);
mStationsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// Change the ProxyTree when we select a station.
mStationsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent e)
{
//Ignore extra messages.
if (e.getValueIsAdjusting()) return;
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
if (!lsm.isSelectionEmpty())
{
int selectedRow = lsm.getMinSelectionIndex();
Object value = mStationsTable.getModel().getValueAt(selectedRow, 0);
StationModel station_model = (StationModel)value;
mProxyTree.setModel(station_model.getProxyModel());
mProxyTree.expandAll(true);
}
}
});
try
{
jbInit();
}
catch(Exception e)
{
e.printStackTrace();
}
// Try to get icons for the toolbar buttons
try
{
ClassLoader loader = getClass().getClassLoader();
mCreateBtn.setIcon(new ImageIcon(loader.getResource("org/vrjuggler/vrjconfig/customeditors/intersense/images/Add16.gif")));
mRemoveBtn.setIcon(new ImageIcon(loader.getResource("org/vrjuggler/vrjconfig/customeditors/intersense/images/Delete16.gif")));
mAttachBtn.setIcon(new ImageIcon(loader.getResource("org/vrjuggler/vrjconfig/customeditors/intersense/images/Import16.gif")));
mDisconnectBtn.setIcon(new ImageIcon(loader.getResource("org/vrjuggler/vrjconfig/customeditors/intersense/images/Export16.gif")));
mISenseIconLbl.setIcon(new ImageIcon(loader.getResource("org/vrjuggler/vrjconfig/customeditors/intersense/images/IS_logo.gif")));
}
catch (Exception e)
{
// Ack! No icons. Use text labels instead
mCreateBtn.setText("New");
mRemoveBtn.setText("Delete");
mAttachBtn.setText("Attach");
mDisconnectBtn.setText("Disconnect");
System.out.println(e);
e.printStackTrace();
}
}
/**
* Specify the ConfigContext and ConfigElement for this Intersense device.
*/
public void setConfig(ConfigContext ctx, ConfigElement elm)
{
mConfigContext = ctx;
mConfigElement = elm;
if(null == mConfigContext)
{
System.out.println("ERROR: You must set the ConfigContext before you set the ConfigElement.");
}
IntersenseModel isense_model = new IntersenseModel(mConfigElement, mConfigContext);
setModel(isense_model);
init();
}
/**
* Specify the IntersenseModel that this panel should display.
*/
public void setModel(IntersenseModel model)
{
mModel = model;
// Create a model to use in the station table.
StationTableModelAdaptor stations_model = new StationTableModelAdaptor(mModel);
mStationsTable.setModel(stations_model);
// Force the ProxyTree to display information about the first station by default.
// TODO: Make it display nothing by default.
List station_models = mModel.getStationModels();
if (station_models.size() > 0)
{
StationModel station_model = (StationModel)station_models.get(0);
mProxyTree.setModel((DefaultTreeModel)station_model.getProxyModel());
mProxyTree.expandAll(true);
}
}
/**
* Get the panel for this CustomEditor.
*/
public Container getPanel()
{
return this;
}
/**
* Return the title of this CustomEditor.
*/
public String getTitle()
{
return("Intersense Editor");
}
public ActionListener getHelpActionListener()
{
return null;
}
public void editorClosing()
{
}
/**
* Initialize the GUI created with JBuilder.
*/
private void jbInit() throws Exception
{
// Make sure that the table's panel does not grow
// any larger than the preferred size.
mStationsPanel = new JPanel()
{
public Dimension getMaximumSize()
{
return getPreferredSize();
}
};
mCreateBtn.setToolTipText("Create New Proxy");
mCreateBtn.setActionCommand("create");
mCreateBtn.setFocusPainted(false);
mRemoveBtn.setToolTipText("Remove Proxy");
mRemoveBtn.setActionCommand("remove");
mRemoveBtn.setFocusPainted(false);
mAttachBtn.setToolTipText("Attach Existing Proxy");
mAttachBtn.setActionCommand("attach");
mAttachBtn.setFocusPainted(false);
mDisconnectBtn.setToolTipText("Disconnect Proxy");
mDisconnectBtn.setActionCommand("disconnect");
mDisconnectBtn.setFocusPainted(false);
mCreateBtn.addActionListener(mProxyTree);
mRemoveBtn.addActionListener(mProxyTree);
mAttachBtn.addActionListener(mProxyTree);
mDisconnectBtn.addActionListener(mProxyTree);
mToolbar.add(mCreateBtn, null);
mToolbar.add(mRemoveBtn, null);
mToolbar.add(mAttachBtn, null);
mToolbar.add(mDisconnectBtn, null);
ImageIcon wand = new ImageIcon("/home/users/aronb/JavaTesting/Intersense/wand1.jpg");
this.setLayout(new BorderLayout());
mPortLbl.setText("Port:");
mDriverLbl.setText("Driver:");
mStationsTable.setBackground(UIManager.getColor("Menu"));
mInfoPanelLayout.setColumns(2);
mInfoPanelLayout.setRows(3);
mTopSectionPanel.setLayout(new BoxLayout(mTopSectionPanel, BoxLayout.X_AXIS));
mTopSectionPanel.add(mISenseIconLbl);
mTopSectionPanel.add(Box.createHorizontalGlue());
mTopSectionPanel.add(mDeviceInfoPanel);
try
{
ClassLoader loader = getClass().getClassLoader();
String class_name = "org.vrjuggler.vrjconfig.commoneditors.positionaldeviceeditor.PositionalDeviceEditor";
final Class jogl_editor_class = loader.loadClass(class_name);
mTopSectionPanel.add(mVisualizeBtn);
mVisualizeBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
try
{
CustomEditor pos_editor = (CustomEditor)jogl_editor_class.newInstance();
JDialog dlg = new JDialog(
(Frame)SwingUtilities.getAncestorOfClass(Frame.class, IntersensePanel.this),
"3D Visualization", true);
pos_editor.setConfig(mConfigContext, mConfigElement);
dlg.getContentPane().add((JPanel)pos_editor);
dlg.pack();
dlg.setVisible(true);
//frame.setSize(750, 750);
//frame.show();
}
catch(InstantiationException e)
{
System.out.println(e);
e.printStackTrace();
}
catch(IllegalAccessException e)
{
System.out.println(e);
e.printStackTrace();
}
}
});
}
catch(ClassNotFoundException e)
{
System.out.println("*** Could not find the PositionalDeviceEditor, JOGL must not be availible. ***");
}
this.add(mTopSectionPanel, BorderLayout.NORTH);
Border raisedbevel = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
TitledBorder title = BorderFactory.createTitledBorder(raisedbevel, "Intersense Stations");
title.setTitlePosition(TitledBorder.TOP);
mStationsPanel.setBorder(title);
mStationsPanel.setLayout(new BorderLayout());
mStationsPanel.add(mStationsTable, BorderLayout.NORTH);
Box dumb = Box.createHorizontalBox();
Box ver = Box.createVerticalBox();
//dumb.setLayout(new FlowLayout());
this.add(dumb, BorderLayout.CENTER);
ver.add(mStationsPanel);
ver.add(Box.createVerticalGlue());
dumb.add(ver, BorderLayout.WEST);
mProxyPanel.setLayout(new BorderLayout());
mProxyPanel.add(mProxyTreeScrollPane, BorderLayout.CENTER);
mProxyPanel.add(mToolbar, BorderLayout.NORTH);
Border lowered = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
TitledBorder proxy_title = BorderFactory.createTitledBorder(lowered, "Station Proxies");
proxy_title.setTitlePosition(TitledBorder.TOP);
mProxyPanel.setBorder(proxy_title);
dumb.add(mProxyPanel, BorderLayout.EAST);
mProxyTreeScrollPane.getViewport().add(mProxyTree, null);
mProxyTreeScrollPane.setBorder(BorderFactory.createLoweredBevelBorder());
}
public void init()
{
// Get handle to broker
mBroker = new ConfigBrokerProxy();
ConfigDefinition cfg_def = mConfigElement.getDefinition();
mPortEditor = new PropertyEditorPanel(mConfigContext, mConfigElement.getProperty("port", 0),
cfg_def.getPropertyDefinition("port"),
mConfigElement, 0, getBackground());
mDriverEditor = new PropertyEditorPanel(mConfigContext, mConfigElement.getProperty("driver", 0),
cfg_def.getPropertyDefinition("driver"),
mConfigElement, 0, getBackground());
mDeviceInfoPanel.setLayout(mInfoPanelLayout);
mDeviceInfoPanel.add(mDriverLbl, null);
mDeviceInfoPanel.add(mDriverEditor, null);
mDeviceInfoPanel.add(mPortLbl, null);
mDeviceInfoPanel.add(mPortEditor, null);
}
/** Reference to the ConfigBroker used in this object. */
private ConfigBroker mBroker = null;
/**
* Gets a handle to the configuration broker.
*/
private ConfigBroker getBroker()
{
if (mBroker == null)
{
synchronized (this)
{
if (mBroker == null)
{
mBroker = new ConfigBrokerProxy();
}
}
}
return mBroker;
}
/**
* Return a list of all ConfigElements that have the given ConfigDefinition and derived definitions.
*/
protected java.util.List getElementsWithDefinitionAndDerived(String token)
{
java.util.List result = new ArrayList();
java.util.List elts = getBroker().getElements(mConfigContext);
// First get all for this type.
result.addAll(ConfigUtilities.getElementsWithDefinition(elts, token));
// Then get for all derived types.
ConfigDefinitionRepository repos = getBroker().getRepository();
java.util.List sub_defs = repos.getSubDefinitions(token);
for(Iterator itr = sub_defs.iterator() ; itr.hasNext() ; )
{
java.util.List elements = ConfigUtilities.getElementsWithDefinition(elts, (String)itr.next());
result.addAll(elements);
}
return result;
}
}
|
package data;
import java.sql.*;
import entidades.*;
import utils.ApplicationException;
public class DataPersonaje {
public DataPersonaje(){
}
public void add(Personaje p){
ResultSet rs=null;
PreparedStatement stmt=null;
|
package org.nd4j.linalg.cpu.nativecpu.ops;
import lombok.Data;
import lombok.Getter;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.indexer.LongIndexer;
import org.nd4j.autodiff.functions.DifferentialFunction;
import org.nd4j.autodiff.samediff.serde.FlatBuffersMapper;
import org.nd4j.common.base.Preconditions;
import org.nd4j.common.config.ND4JEnvironmentVars;
import org.nd4j.graph.OpType;
import org.nd4j.linalg.api.buffer.*;
import org.nd4j.linalg.api.environment.Nd4jEnvironment;
import org.nd4j.linalg.api.memory.pointers.PagedPointer;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ndarray.INDArrayStatistics;
import org.nd4j.linalg.api.ops.*;
import org.nd4j.linalg.api.ops.aggregates.Aggregate;
import org.nd4j.linalg.api.ops.aggregates.Batch;
import org.nd4j.linalg.api.ops.executioner.DefaultOpExecutioner;
import org.nd4j.linalg.api.ops.executioner.OpStatus;
import org.nd4j.linalg.api.ops.impl.scatter.ScatterUpdate;
import org.nd4j.linalg.api.ops.impl.summarystats.Variance;
import org.nd4j.linalg.api.ops.impl.transforms.any.IsMax;
import org.nd4j.linalg.api.ops.performance.PerformanceTracker;
import org.nd4j.linalg.api.ops.random.BaseRandomOp;
import org.nd4j.linalg.api.rng.Random;
import org.nd4j.linalg.api.shape.LongShapeDescriptor;
import org.nd4j.linalg.api.shape.Shape;
import org.nd4j.linalg.api.shape.TadPack;
import org.nd4j.linalg.api.shape.options.ArrayOptionsHelper;
import org.nd4j.linalg.api.shape.options.ArrayType;
import org.nd4j.linalg.cache.ConstantHandler;
import org.nd4j.linalg.cache.TADManager;
import org.nd4j.linalg.cpu.nativecpu.CpuTADManager;
import org.nd4j.linalg.cpu.nativecpu.buffer.BaseCpuDataBuffer;
import org.nd4j.linalg.cpu.nativecpu.buffer.LongBuffer;
import org.nd4j.linalg.cpu.nativecpu.buffer.Utf8Buffer;
import org.nd4j.linalg.cpu.nativecpu.rng.CpuNativeRandom;
import org.nd4j.linalg.exception.ND4JIllegalArgumentException;
import org.nd4j.linalg.exception.ND4JIllegalStateException;
import org.nd4j.linalg.exception.ND4JOpProfilerException;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.api.memory.MemcpyDirection;
import org.nd4j.common.primitives.AtomicBoolean;
import org.nd4j.common.primitives.Optional;
import org.nd4j.common.primitives.Pair;
import org.nd4j.common.util.ArrayUtil;
import org.nd4j.nativeblas.*;
import java.util.*;
@Slf4j
public class NativeOpExecutioner extends DefaultOpExecutioner {
private NativeOps loop = NativeOpsHolder.getInstance().getDeviceNativeOps();
private ConstantHandler constantHandler = Nd4j.getConstantHandler();
@Getter
private CpuTADManager tadManager = new CpuTADManager();
//thread locals for custom op inputs and outputs to prevent allocations
//every time exec(CustomOp) is called
private ThreadLocal<Map<Integer,PointerPointer>> inputShapes = new ThreadLocal<>();
private ThreadLocal<Map<Integer,PointerPointer>> inputBuffers = new ThreadLocal<>();
private ThreadLocal<Map<Integer,PointerPointer>> outputShapes = new ThreadLocal<>();
private ThreadLocal<Map<Integer,PointerPointer>> outputBuffers = new ThreadLocal<>();
private ThreadLocal<Map<Integer,LongPointer>> iArgsPointer = new ThreadLocal<>();
private ThreadLocal<Map<Integer,DoublePointer>> tArgsPointer = new ThreadLocal<>();
private ThreadLocal<Map<Integer,BooleanPointer>> bArgsPointer = new ThreadLocal<>();
private ThreadLocal<Map<Integer,ShortPointer>> halfArgsPointer = new ThreadLocal<>();
protected Map<String, CustomOpDescriptor> customOps = null;
protected ThreadLocal<PointerPointer> extraz = new ThreadLocal<>();
protected AtomicBoolean experimentalMode = new AtomicBoolean(false);
protected Map<String, Boolean> mklOverrides = new HashMap<>();
/**
* Instead of allocating new memory chunks for each batch invocation, we reuse them on thread/opNum basis
* Since for NativeOpExecutioner all executions are synchronous
*/
private ThreadLocal<Map<Integer, Pointer>> batchPointers = new ThreadLocal<>();
private ThreadLocal<Map<Integer, AggregateMemoryBlock>> memoryBlocks = new ThreadLocal<>();
public NativeOpExecutioner() {
tadManager.init(loop, constantHandler);
experimentalMode.set(loop.isExperimentalEnabled());
// filling vars for possible overrides
val env = System.getenv(ND4JEnvironmentVars.ND4J_MKL_FALLBACK);
if (env != null) {
// in this case we just disable mkl-dnn globally
if (env.equalsIgnoreCase("true")) {
Nd4jCpu.Environment.getInstance().setUseONEDNN(false);
} else {
val split = env.toLowerCase().split(",");
for (val name:split) {
mklOverrides.put(name, new Boolean(true));
}
}
}
}
@Override
public INDArray exec(Op op) {
return exec(op, null);
}
@Override
public INDArray exec(Op op, OpContext opContext) {
checkForCompression(op);
if (op instanceof ScalarOp) {
ScalarOp s = (ScalarOp) op;
exec(s, opContext);
} else if (op instanceof TransformOp) {
TransformOp t = (TransformOp) op;
exec(t, opContext);
} else if (op instanceof ReduceOp) {
ReduceOp ac = (ReduceOp) op;
exec(ac, opContext);
} else if (op instanceof IndexAccumulation) {
IndexAccumulation iac = (IndexAccumulation) op;
exec(iac, opContext); //Currently using DefaultOpExecutioner
} else if (op instanceof BroadcastOp) {
BroadcastOp broadcastOp = (BroadcastOp) op;
exec(broadcastOp, opContext);
} else if (op instanceof RandomOp) {
RandomOp rngOp = (RandomOp) op;
exec(rngOp, opContext, Nd4j.getRandom());
}
return op.z();
}
@Override
public INDArray exec(IndexAccumulation op) {
return exec(op, null);
}
public INDArray exec(IndexAccumulation op, OpContext oc) {
checkForCompression(op);
INDArray x = getX(op, oc);
INDArray z = getZ(op, oc);
if (extraz.get() == null)
extraz.set(new PointerPointer(32));
val dimension = Shape.normalizeAxis(x.rank(), op.dimensions().toIntVector());
if (x.isEmpty()) {
for (val d:dimension) {
Preconditions.checkArgument(x.shape()[d] != 0, "IndexReduce can't be issued along axis with 0 in shape");
}
}
boolean keepDims = op.isKeepDims();
long[] retShape = Shape.reductionShape(x, dimension, true, keepDims);
if(z == null || x == z) {
val ret = Nd4j.createUninitialized(DataType.LONG, retShape);
setZ(ret, op, oc);
z = ret;
} else if(!Arrays.equals(retShape, z.shape())){
throw new IllegalStateException("Z array shape does not match expected return type for op " + op
+ ": expected shape " + Arrays.toString(retShape) + ", z.shape()=" + Arrays.toString(z.shape()));
}
op.validateDataTypes();
Pointer dimensionAddress = constantHandler.getConstantBuffer(dimension, DataType.INT).addressPointer();
Pair<DataBuffer, DataBuffer> tadBuffers = tadManager.getTADOnlyShapeInfo(x, dimension);
Pointer hostTadShapeInfo = tadBuffers.getFirst().addressPointer();
DataBuffer offsets = tadBuffers.getSecond();
Pointer hostTadOffsets = offsets == null ? null : offsets.addressPointer();
PointerPointer dummy = extraz.get().put(hostTadShapeInfo, hostTadOffsets);
long st = profilingConfigurableHookIn(op, tadBuffers.getFirst());
val xb = ((BaseCpuDataBuffer) x.data()).getOpaqueDataBuffer();
val zb = ((BaseCpuDataBuffer) z.data()).getOpaqueDataBuffer();
if (z.isScalar()) {
loop.execIndexReduceScalar(dummy, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, x.dataType()),
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null);
} else {
loop.execIndexReduce(dummy, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, x.dataType()),
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
((BaseCpuDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(), (LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(), null);
}
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
profilingConfigurableHookOut(op, oc, st);
return getZ(op, oc);
}
@Override
public INDArray exec(Variance op) {
return exec((ReduceOp) op);
}
@Override
public INDArray exec(ReduceOp op) {
return exec(op, null);
}
public INDArray exec(ReduceOp op, OpContext oc) {
INDArray x = getX(op, oc);
INDArray y = getY(op, oc);
INDArray z = getZ(op, oc);
Preconditions.checkNotNull(x, "Op.x() cannot be null: Was null for op %s", op);
op.validateDataTypes(oc);
if(op instanceof BaseReduceOp && ((BaseReduceOp)op).isEmptyReduce()){
//Edge case for TF import compatibility: [x,y].reduce(empty) = [x,y]
//Note that "empty" axis is NOT the same as length 0, as in INDArray.sum(new int[0]), which means "all dimensions"
if(z != null){
Preconditions.checkState(x.equalShapes(z), "For empty reductions, result (z) array must have same shape as x shape." +
" Got: x=%ndShape, z=%ndShape", x, z);
z.assign(x);
return z;
} else {
setZ(x.dup(), op, oc);
return z;
}
}
// FIXME: this should be moved down to C++ on per-op basis
val dimension = Shape.normalizeAxis(x.rank(), op.dimensions() != null ? op.dimensions().toIntVector() : null);
// reduce to scalar case, ReduceBool ops require special treatment
if (op instanceof BaseReduceBoolOp && x.isEmpty() && (dimension == null || (dimension.length == 1 && dimension[0] == Integer.MAX_VALUE))) {
if (z == null) {
setZ(Nd4j.scalar(((BaseReduceBoolOp) op).emptyValue()), op, oc);
} else {
z.assign(((BaseReduceBoolOp) op).emptyValue());
}
return z;
}
//validateDataType(Nd4j.dataType(), op);
if (extraz.get() == null)
extraz.set(new PointerPointer(32));
boolean keepDims = op.isKeepDims();
long[] retShape = Shape.reductionShape(x, dimension, true, keepDims);
if (x.isVector() && x.length() == ArrayUtil.prod(retShape) && ArrayUtil.prodLong(retShape) > 1 && y == null)
return op.noOp();
/**
* This is the result array.
* We create it only if we hadn't provided it before
*/
INDArray ret;
if (z == null || z == x) {
if (op.isComplexAccumulation()) {
long xT = x.tensorsAlongDimension(dimension);
long yT = y.tensorsAlongDimension(dimension);
ret = Nd4j.create(op.resultType(), new long[]{xT, yT});
} else {
if (y != null) {
//2 options here: either pairwise, equal sizes - OR every X TAD vs. entirety of Y
if(x.length() == y.length()) {
//Pairwise
if (x.tensorsAlongDimension(dimension) != y.tensorsAlongDimension(dimension)) {
throw new ND4JIllegalStateException("Number of TADs along dimension don't match: (x shape = " +
Arrays.toString(x.shape()) + ", y shape = " + Arrays.toString(y.shape()) +
", dimension = " + Arrays.toString(dimension) + ")");
}
//reduce ops can have second inputs as axes
} else if(!(op instanceof ReduceOp)) {
//Every X TAD vs. entirety of Y
val xTADSize = x.length() / x.tensorsAlongDimension(dimension);
if (xTADSize != y.length()) {
throw new ND4JIllegalStateException("Size of TADs along dimension don't match for pairwise execution:" +
" (x TAD size = " + xTADSize + ", y size = " + y.length());
}
}
}
DataType dt = oc != null ? op.resultType(oc) : op.resultType();
ret = Nd4j.create(dt, retShape);
}
setZ(ret, op, oc);
z = ret;
} else {
// compare length
long shapeProduct = (retShape.length == 0 ? 1 : ArrayUtil.prodLong(retShape));
if (!op.isComplexAccumulation() && z.length() != shapeProduct) {
if(!(x.isEmpty() && op.isKeepDims())){
//Empty reductions are special case: [1,0].sum(0,1,keep=true) -> shape [1,1]
throw new ND4JIllegalStateException("Shape of target array for reduction [" + Arrays.toString(z.shape()) + "] doesn't match expected [" + Arrays.toString(retShape) + "]");
}
}
else if (op.isComplexAccumulation()) {
long xT = x.tensorsAlongDimension(dimension);
long yT = y.tensorsAlongDimension(dimension);
if (z.length() != xT * yT)
throw new ND4JIllegalStateException("Shape of target array for reduction [" + Arrays.toString(z.shape()) + "] doesn't match expected [" + (xT * yT) + "]");
}
ret = z;
}
//log.info("X dtype: {}; Z dtype: {}", x.dataType(), z.dataType());
/**
* Returns the {@link Shape#createShapeInformation(int[], int[], int, int, char)}
* and the associated offsets for each {@link INDArray#tensorAlongDimension(int, int...)}
* The first item is the shape information. The second one is the offsets.
*/
Pair<DataBuffer, DataBuffer> tadBuffers = x.isEmpty() ? Pair.<DataBuffer, DataBuffer>makePair(x.data(), null): tadManager.getTADOnlyShapeInfo(x, dimension);
Pair<DataBuffer, DataBuffer> yTadBuffers = null;
long st = profilingConfigurableHookIn(op, tadBuffers.getFirst());
/**
* Note because dimension arrays don't change,
* we use an {@link ConstantHandler} which knows how to reserve memory
* for immutable buffers for the dimensions.
* This gives us a pointer which is passed around in libnd4j.
*/
Pointer dimensionAddress = constantHandler.getConstantBuffer(dimension, DataType.INT).addressPointer();
val xb = ((BaseCpuDataBuffer) x.data()).getOpaqueDataBuffer();
val zb = ((BaseCpuDataBuffer) z.data()).getOpaqueDataBuffer();
if (op instanceof Variance) {
if (ret.isScalar()) {
loop.execSummaryStatsScalar(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, z.dataType()),
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
((Variance) op).isBiasCorrected());
} else {
Variance var = (Variance) op;
try {
loop.execSummaryStatsTad(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, z.dataType()),
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
((BaseCpuDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(), (LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(), null,
var.isBiasCorrected(), null, null);
} catch (Throwable t){
String str = opInfoString(op, Optional.of(dimension));
throw new RuntimeException("Native AccumulationOp execution (double) failed: " + str, t);
}
}
}
//pairwise reduction like similarity of two arrays
else if (y != null && op.getOpType() == Op.Type.REDUCE3) {
val yb = ((BaseCpuDataBuffer) y.data()).getOpaqueDataBuffer();
if (op.isComplexAccumulation()) {
try {
loop.execReduce3All(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, z.dataType()),
yb, (LongPointer) y.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
((BaseCpuDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(), (LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(), null,
(LongPointer) tadBuffers.getFirst().addressPointer(), new LongPointerWrapper(tadBuffers.getSecond().addressPointer()),
(LongPointer) yTadBuffers.getFirst().addressPointer(), new LongPointerWrapper(yTadBuffers.getSecond().addressPointer())
);
} catch (Throwable t){
String str = opInfoString(op, Optional.of(dimension));
throw new RuntimeException("Native AccumulationOp execution (double) failed: " + str, t);
}
} else if (ret.isScalar()) {
loop.execReduce3Scalar(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, z.dataType()),
yb, (LongPointer) y.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) ret.shapeInfoDataBuffer().addressPointer(), null);
} else {
try {
loop.execReduce3Tad(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, z.dataType()),
yb, (LongPointer) y.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
((BaseCpuDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(), (LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(), null,
null, null, null, null);
} catch (Throwable t){
String str = opInfoString(op, Optional.of(dimension));
throw new RuntimeException("Native AccumulationOp execution (double) failed: " + str, t);
}
}
} else {
if (ret.isScalar()) {
switch (op.getOpType()) {
case REDUCE_FLOAT:
loop.execReduceFloat(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, z.dataType()),
zb, (LongPointer) ret.shapeInfoDataBuffer().addressPointer(), null);
break;
case REDUCE_BOOL:
loop.execReduceBool(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, x.dataType()),
zb, (LongPointer) ret.shapeInfoDataBuffer().addressPointer(), null);
break;
case REDUCE_SAME:
loop.execReduceSame(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, x.dataType()),
zb, (LongPointer) ret.shapeInfoDataBuffer().addressPointer(), null);
break;
case REDUCE_LONG:
loop.execReduceLong(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, x.dataType()),
zb, (LongPointer) ret.shapeInfoDataBuffer().addressPointer(), null);
break;
default:
throw new UnsupportedOperationException("Unsupported op used in reduce: "+ op.getOpType());
}
} else {
switch (op.getOpType()) {
case REDUCE_FLOAT:
loop.execReduceFloat2(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, z.dataType()),
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
((BaseCpuDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(), (LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(), null);
break;
case REDUCE_LONG:
loop.execReduceLong2(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, x.dataType()),
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
((BaseCpuDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(),
(LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(), null);
break;
case REDUCE_SAME:
loop.execReduceSame2(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, z.dataType()),
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
((BaseCpuDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(),
(LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(), null);
break;
case REDUCE_BOOL:
loop.execReduceBool2(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, x.dataType()),
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
((BaseCpuDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(),
(LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(), null);
break;
default:
throw new UnsupportedOperationException("Unsupported op used in reduce: "+ op.getOpType());
}
}
}
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
return getZ(op, oc);
}
/**
* ScalarOp execution
* @param op Op to execute
*/
private void invokeScalarAlongDimension(ScalarOp op) {
invokeScalarAlongDimension(op, null);
}
private void invokeScalarAlongDimension(ScalarOp op, OpContext oc) {
INDArray x = getX(op, oc);
INDArray y = getY(op, oc);
INDArray z = getZ(op, oc);
val dimension = op.dimensions().toIntVector();
//dimension = Shape.normalizeAxis(op.x().rank(), dimension);
// do tad magic
/**
* Returns the {@link Shape#createShapeInformation(int[], int[], int, int, char)}
* and the associated offsets for each {@link INDArray#tensorAlongDimension(int, int...)}
* The first item is the shape information. The second one is the offsets.
*/
Pair<DataBuffer, DataBuffer> tadBuffers = tadManager.getTADOnlyShapeInfo(op.x(), dimension);
Pointer hostTadShapeInfo = tadBuffers.getFirst().addressPointer();
Pointer hostTadOffsets = tadBuffers.getSecond().addressPointer();
Pointer devTadShapeInfoZ = null;
Pointer devTadOffsetsZ = null;
/**
* Returns the {@link Shape#createShapeInformation(int[], int[], int, int, char)}
* and the associated offsets for each {@link INDArray#tensorAlongDimension(int, int...)}
* The first item is the shape information. The second one is the offsets.
*
* Note that this is the *result* TAD information. An op is always input (x) and output (z)
* for result.
* This is for assigning the result to of the operation along
* the proper dimension.
*/
Pair<DataBuffer, DataBuffer> tadBuffersZ = tadManager.getTADOnlyShapeInfo(op.z(), dimension);
devTadShapeInfoZ = tadBuffersZ.getFirst().addressPointer();
devTadOffsetsZ = tadBuffersZ.getSecond().addressPointer();
if (extraz.get() == null)
extraz.set(new PointerPointer(32));
val xb = ((BaseCpuDataBuffer) x.data()).getOpaqueDataBuffer();
val yb = ((BaseCpuDataBuffer) y.data()).getOpaqueDataBuffer();
val zb = ((BaseCpuDataBuffer) z.data()).getOpaqueDataBuffer();
switch (op.getOpType()) {
case SCALAR:
loop.execScalarTad(null, op.opNum(),
xb, (LongPointer) op.x().shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) op.z().shapeInfoDataBuffer().addressPointer(), null,
yb, (LongPointer) y.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, op.z().dataType()),
((BaseCpuDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(), (LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(),null,
(LongPointer) hostTadShapeInfo, (LongPointer) hostTadOffsets,
(LongPointer) devTadShapeInfoZ, (LongPointer) devTadOffsetsZ);
break;
case SCALAR_BOOL:
loop.execScalarBoolTad(null, op.opNum(),
xb, (LongPointer) op.x().shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) op.z().shapeInfoDataBuffer().addressPointer(), null,
yb, (LongPointer) op.y().shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, op.z().dataType()),
((BaseCpuDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(), (LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(), null,
(LongPointer) hostTadShapeInfo, (LongPointer) hostTadOffsets,
(LongPointer) devTadShapeInfoZ, (LongPointer) devTadOffsetsZ);
break;
default:
throw new UnsupportedOperationException();
}
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
}
public INDArray exec(ScalarOp op){
return exec(op, null);
}
public INDArray exec(ScalarOp op, OpContext oc) {
long st = profilingConfigurableHookIn(op);
//validateDataType(Nd4j.dataType(), op);
if((oc != null && oc.getOutputArray(0) == null) || getZ(op, oc) == null){
switch (op.getOpType()) {
case SCALAR:
setZ(getX(op, oc).ulike(), op, oc);
// op.setZ(op.x().ulike());
break;
case SCALAR_BOOL:
// op.setZ(Nd4j.createUninitialized(DataType.BOOL, op.x().shape()));
setZ(Nd4j.createUninitialized(DataType.BOOL, getX(op, oc).shape()), op, oc);
break;
default:
throw new ND4JIllegalStateException("Unknown op type: [" + op.getOpType() +"]");
}
}
// if (op.x().length() != op.z().length())
if (op.dimensions() != null) {
invokeScalarAlongDimension(op);
return getZ(op, oc);
}
val x = ((BaseCpuDataBuffer) getX(op, oc).data()).getOpaqueDataBuffer();
val scalar = ((BaseCpuDataBuffer) op.scalar().data()).getOpaqueDataBuffer();
val z = ((BaseCpuDataBuffer) getZ(op, oc).data()).getOpaqueDataBuffer();
switch (op.getOpType()) {
case SCALAR:
loop.execScalar(null,
op.opNum(),
x, (LongPointer) getX(op, oc).shapeInfoDataBuffer().addressPointer(), null,
z, (LongPointer) getZ(op, oc).shapeInfoDataBuffer().addressPointer(), null,
scalar, (LongPointer) op.scalar().shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, getZ(op, oc).dataType()));
break;
case SCALAR_BOOL:
loop.execScalarBool(null,
op.opNum(),
x, (LongPointer) getX(op, oc).shapeInfoDataBuffer().addressPointer(), null,
z, (LongPointer) getZ(op, oc).shapeInfoDataBuffer().addressPointer(), null,
scalar, (LongPointer) op.scalar().shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, getX(op, oc).dataType()));
break;
default:
throw new ND4JIllegalStateException("Unknown op type: [" + op.getOpType() +"]");
}
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
profilingConfigurableHookOut(op, oc, st);
return getZ(op, oc);
}
private Pointer getPointerForExtraArgs(Op op, DataType type) {
if (op.extraArgs() != null) {
val eadb = op.extraArgsDataBuff(type);
if (eadb != null)
return eadb.addressPointer();
else
return null;
}
return null;
}
private void exec(TransformOp op) {
exec(op, null);
}
private void exec(TransformOp op, OpContext oc) {
INDArray x = getX(op, oc);
INDArray y = getY(op, oc);
INDArray z = getZ(op, oc);
long st = 0;
// validateDataType(Nd4j.dataType(), op);
if (extraz.get() == null)
extraz.set(new PointerPointer(32));
PointerPointer dummy = extraz.get();
// Pow operations might be special
if (op.opNum() == 31) {
if (y != null && y.isScalar()) {
// op.setY(Nd4j.valueArrayOf(op.x().shape(), op.y().getDouble(0)));
setY(Nd4j.valueArrayOf(x.shape(), y.getDouble(0)), op, oc);
}
}
/**
* This is the {@link IsMax}
* operation.
*
* @see {@link Op#extraArgs()}
* for what an extra argument is in an op.
*
* The extra argument in the op here is the {@link IsMax#IsMax(INDArray, int...)}
* dimension to do the ismax along
*/
if (op.opName().equalsIgnoreCase("ismax") && op.extraArgs() != null && op.extraArgs().length > 0) {
int[] dimension = new int[(int) op.extraArgs()[0]];
for (int i = 0; i < dimension.length; i++) {
dimension[i] = (int) op.extraArgs()[i + 1];
}
/**
* Returns the {@link Shape#createShapeInformation(int[], int[], int, int, char)}
* and the associated offsets for each {@link INDArray#tensorAlongDimension(int, int...)}
* The first item is the shape information. The second one is the offsets.
*/
Pair<DataBuffer, DataBuffer> tadBuffers = tadManager.getTADOnlyShapeInfo(op.z(), dimension);
Pointer tad = tadBuffers.getFirst().addressPointer();
DataBuffer offsets = tadBuffers.getSecond();
Pointer off = offsets == null ? null : offsets.addressPointer();
dummy.put(0, tad);
dummy.put(1, off);
st = profilingConfigurableHookIn(op, tadBuffers.getFirst());
} else
st = profilingConfigurableHookIn(op);
if (y != null) {
if (z == null) {
setZ(Nd4j.create(op.resultType(), x.shape()), op, oc);
z = getZ(op, oc);
}
op.validateDataTypes(oc, experimentalMode.get());
//log.info("X type: {}; Y type: {}; Z type: {}; OpNum: {}", op.x().dataType(), op.y().dataType(), op.z().dataType(), op.opNum());
val xb = ((BaseCpuDataBuffer) x.data()).getOpaqueDataBuffer();
val yb = ((BaseCpuDataBuffer) y.data()).getOpaqueDataBuffer();
val zb = ((BaseCpuDataBuffer) z.data()).getOpaqueDataBuffer();
switch (op.getOpType()) {
case TRANSFORM_ANY:
case TRANSFORM_FLOAT:
case TRANSFORM_STRICT:
case TRANSFORM_SAME:
if (!experimentalMode.get())
Preconditions.checkArgument(x.dataType() == y.dataType() || y.dataType() == DataType.BOOL,
"Op.X and Op.Y must have the same data type, but got %s vs. %s", x.dataType(), y.dataType());
loop.execPairwiseTransform(dummy, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
yb, (LongPointer) y.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, z.dataType()));
break;
case TRANSFORM_BOOL:
loop.execTransformBool(dummy, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, x.dataType()));
break;
case PAIRWISE_BOOL:
loop.execPairwiseTransformBool(dummy, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
yb, (LongPointer) y.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, x.dataType()));
break;
}
} else {
if (z == null) {
setZ(Nd4j.createUninitialized((oc != null ? op.resultType(oc) : op.resultType()), x.shape()), op, oc);
z = getZ(op, oc);
}
op.validateDataTypes(oc, experimentalMode.get());
val xb = ((BaseCpuDataBuffer) x.data()).getOpaqueDataBuffer();
val zb = ((BaseCpuDataBuffer) z.data()).getOpaqueDataBuffer();
switch (op.getOpType()) {
case TRANSFORM_FLOAT: {
val xtraz = getPointerForExtraArgs(op, z.dataType());
loop.execTransformFloat(dummy, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(),
null, xtraz);
break;
}
case TRANSFORM_STRICT: {
val xtraz = getPointerForExtraArgs(op, z.dataType());
loop.execTransformStrict(dummy, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
xtraz);
break;
}
case TRANSFORM_SAME: {
val xtraz = getPointerForExtraArgs(op, z.dataType());
loop.execTransformSame(dummy, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
xtraz);
break;
}
case TRANSFORM_ANY: {
val xtraz = getPointerForExtraArgs(op, x.dataType());
val opNum = op.opNum();
loop.execTransformAny(dummy, opNum,
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
xtraz);
break;
}
case TRANSFORM_BOOL: {
val xtraz = getPointerForExtraArgs(op, x.dataType());
val opNum = op.opNum();
loop.execTransformBool(dummy, opNum,
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
xtraz);
break;
}
default:
throw new UnsupportedOperationException("Unknown transform type: [" + op.getOpType() + "]");
}
}
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
profilingConfigurableHookOut(op, oc, st);
}
public INDArray exec(BroadcastOp op) {
return exec(op, null);
}
public INDArray exec(BroadcastOp op, OpContext oc) {
INDArray x = getX(op, oc);
INDArray y = getY(op, oc);
INDArray z = getZ(op, oc);
long st = profilingConfigurableHookIn(op);
op.validateDataTypes(experimentalMode.get());
val dimension = op.dimensions().toIntVector();
/**
* Returns the {@link Shape#createShapeInformation(int[], int[], int, int, char)}
* and the associated offsets for each {@link INDArray#tensorAlongDimension(int, int...)}
* The first item is the shape information. The second one is the offsets.
*/
Pair<DataBuffer, DataBuffer> tadBuffers = tadManager.getTADOnlyShapeInfo(x, dimension);
Pointer hostTadShapeInfo = tadBuffers.getFirst().addressPointer();
Pointer hostTadOffsets = tadBuffers.getSecond().addressPointer();
Pointer devTadShapeInfoZ = null;
Pointer devTadOffsetsZ = null;
// if (!Arrays.equals(x.shape(),z.shape()) || !Arrays.equals(x.stride(),z.stride()) || x.ordering() != z.ordering()) {
// that's the place where we're going to have second TAD in place
Pair<DataBuffer, DataBuffer> tadBuffersZ = tadManager.getTADOnlyShapeInfo(z, dimension);
devTadShapeInfoZ = tadBuffersZ.getFirst().addressPointer();
devTadOffsetsZ = tadBuffersZ.getSecond().addressPointer();
if (extraz.get() == null)
extraz.set(new PointerPointer(32));
PointerPointer dummy = extraz.get().put(hostTadShapeInfo, hostTadOffsets, devTadShapeInfoZ, devTadOffsetsZ);
Pointer dimensionAddress = constantHandler.getConstantBuffer(dimension, DataType.INT).addressPointer();
val xb = ((BaseCpuDataBuffer) x.data()).getOpaqueDataBuffer();
val yb = ((BaseCpuDataBuffer) y.data()).getOpaqueDataBuffer();
val zb = ((BaseCpuDataBuffer) z.data()).getOpaqueDataBuffer();
switch (op.getOpType()) {
case BROADCAST:
loop.execBroadcast(dummy, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
yb, (LongPointer) y.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
((BaseCpuDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(), (LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(), null);
break;
case BROADCAST_BOOL:
loop.execBroadcastBool(dummy, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
yb, (LongPointer) y.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
null,
((BaseCpuDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(), (LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(), null);
break;
default:
throw new UnsupportedOperationException("Unknown operation type: [" + op.getOpType() + "]");
}
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
return z;
}
protected <T extends Aggregate> Pointer getPointer(Batch<T> batch) {
if (batchPointers.get() == null)
batchPointers.set(new HashMap<Integer, Pointer>());
if (!batchPointers.get().containsKey(batch.opNum())) {
val pointer = new IntPointer(batch.getSample().getRequiredBatchMemorySize() / 4 );
batchPointers.get().put(batch.opNum(), pointer);
return pointer;
}
return batchPointers.get().get(batch.opNum());
}
/**
* This method executes previously built batch
*
* @param batch
*/
@Override
public <T extends Aggregate> void exec(Batch<T> batch) {
//profilingHookIn(batch);
IntPointer pointer = (IntPointer) getPointer(batch);
int maxTypes = 5;
int maxIntArrays = batch.getSample().maxIntArrays();
int maxArraySize = batch.getSample().maxIntArraySize();
int indexPos = maxTypes * Batch.getBatchLimit();
int intArraysPos = indexPos + (batch.getSample().maxIndexArguments() * Batch.getBatchLimit());
int realPos = (intArraysPos + (maxIntArrays * maxArraySize * Batch.getBatchLimit()))
/ (Nd4j.dataType() == DataType.DOUBLE ? 2 : 1);
int argsPos = (realPos + ((batch.getSample().maxRealArguments() * Batch.getBatchLimit())))
/ (Nd4j.dataType() == DataType.DOUBLE ? 1 : 2);
int shapesPos = argsPos + (batch.getSample().maxArguments() * Batch.getBatchLimit());
DataType dataType = null;
for (int i = 0; i < batch.getNumAggregates(); i++) {
T op = batch.getAggregates().get(i);
if (i == 0)
dataType = op.getArguments().get(0).dataType();
// put num arguments
int idx = i * maxTypes;
pointer.put(idx, op.getArguments().size());
pointer.put(idx + 1, op.getShapes().size());
pointer.put(idx + 2, op.getIndexingArguments().size());
pointer.put(idx + 3, op.getRealArguments().size());
pointer.put(idx + 4, op.getIntArrayArguments().size());
// putting indexing arguments
for (int e = 0; e < op.getIndexingArguments().size(); e++) {
idx = indexPos + i * batch.getSample().maxIndexArguments();
pointer.put(idx + e, op.getIndexingArguments().get(e));
}
// putting intArray values
int bsize = maxIntArrays * maxArraySize;
for (int e = 0; e < op.getIntArrayArguments().size(); e++) {
int step = (i * bsize) + (e * maxArraySize);
if (op.getIntArrayArguments().get(e) != null)
for (int x = 0; x < op.getIntArrayArguments().get(e).length; x++) {
idx = intArraysPos + step + x;
pointer.put(idx, op.getIntArrayArguments().get(e)[x]);
}
}
// TODO: variable datatype should be handled here
// putting real arguments
switch (dataType){
case FLOAT:
FloatPointer fPtr = new FloatPointer(pointer);
for (int e = 0; e < op.getRealArguments().size(); e++) {
idx = realPos + i * op.maxRealArguments();
fPtr.put(idx + e, op.getRealArguments().get(e).floatValue());
}
break;
case DOUBLE:
DoublePointer dPtr = new DoublePointer(pointer);
for (int e = 0; e < op.getRealArguments().size(); e++) {
idx = realPos + (i * op.maxRealArguments());
dPtr.put(idx + e, op.getRealArguments().get(e).doubleValue());
}
break;
default:
throw new ND4JIllegalArgumentException("Only FLOAT and DOUBLE datatypes are supported");
}
if (extraz.get() == null)
extraz.set(new PointerPointer(32));
// putting arguments pointers
PointerPointer ptrPtr = new PointerPointer(pointer);//extraz.get().put(pointer);
for (int e = 0; e < op.getArguments().size(); e++) {
idx = argsPos + i * batch.getSample().maxArguments();
if (op.getArguments().get(e) != null) {
ptrPtr.put(idx + e, op.getArguments().get(e).data().addressPointer());
}
}
// putting shape pointers
for (int e = 0; e < op.getShapes().size(); e++) {
idx = shapesPos + i * batch.getSample().maxShapes();
if (op.getShapes().get(e) != null)
ptrPtr.put(idx + e, op.getShapes().get(e).addressPointer());
}
}
loop.execAggregateBatch(null, batch.getNumAggregates(), batch.opNum(),
batch.getSample().maxArguments(), batch.getSample().maxShapes(),
batch.getSample().maxIntArrays(), batch.getSample().maxIntArraySize(),
batch.getSample().maxIndexArguments(), batch.getSample().maxRealArguments(), pointer, FlatBuffersMapper.getDataTypeAsByte(dataType));
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
}
/**
* This method takes arbitrary
* sized list of {@link Aggregate},
* and packs them into batches
* Note here that this is mainly used for random number generation
* for {@link RandomOp} and things like {@link org.nd4j.linalg.api.rng.distribution.Distribution}
* @param batch the list of {@link Aggregate} to
* execute upon
*/
@Override
public void exec(List<Aggregate> batch) {
if (batch.size() == 0)
return;
List<Batch<Aggregate>> batches = Batch.getBatches(batch);
for (Batch<Aggregate> single : batches) {
this.exec(single);
}
}
/**
* This method takes arbitrary
* sized list of {@link Aggregate},
* and packs them into batches
* Note here that this is mainly used for random number generation
* for {@link RandomOp} and things like {@link org.nd4j.linalg.api.rng.distribution.Distribution}
* @param op the list of {@link Aggregate} to
* execute upon
*/
@Override
public void exec(Aggregate op) {
// long st = profilingHookIn(op);
if (memoryBlocks.get() == null)
memoryBlocks.set(new HashMap<Integer, AggregateMemoryBlock>());
if (memoryBlocks.get().get(op.opNum()) == null)
memoryBlocks.get().put(op.opNum(), new AggregateMemoryBlock(op));
AggregateMemoryBlock block = memoryBlocks.get().get(op.opNum());
int numArguments = op.getArguments().size();
int numIndexArguments = op.getIndexingArguments().size();
int numRealArguments = op.getRealArguments().size();
int numShapes = op.getShapes().size();
int numIntArrays = op.getIntArrayArguments().size();
PointerPointer arguments = block.getArgumentsPointer(); //new PointerPointer(numArguments);
List<IntPointer> pointers = new ArrayList<>();
PointerPointer intArrays = block.getArraysPointer(); //new PointerPointer(numIntArrays);
val dataType = op.getArguments().get(0).dataType();
for (int x = 0; x < numArguments; x++) {
arguments.put(x, op.getArguments().get(x) == null ? null
: op.getArguments().get(x).data().addressPointer());
}
PointerPointer shapes = block.getShapesPointer(); //new PointerPointer(numShapes);
for (int x = 0; x < numShapes; x++) {
if (op.getShapes().get(x).dataType() != DataType.LONG)
throw new RuntimeException("ShapeBuffers should have LONG data opType");
shapes.put(x, op.getShapes().get(x) == null ? null : op.getShapes().get(x).addressPointer());
}
//int[] indexes = new int[numIndexArguments];
IntPointer pointer = block.getIndexingPointer();
for (int x = 0; x < numIndexArguments; x++) {
pointer.put(x, op.getIndexingArguments().get(x));
}
//IntPointer pointer = new IntPointer(indexes);
double[] reals = new double[numRealArguments];
for (int x = 0; x < numRealArguments; x++) {
//reals[x] = op.getRealArguments().get(x).doubleValue();
switch (dataType) {
case FLOAT:
((FloatPointer) block.getRealArgumentsPointer()).put(x, op.getRealArguments().get(x).floatValue());
break;
case DOUBLE:
((DoublePointer) block.getRealArgumentsPointer()).put(x, op.getRealArguments().get(x).doubleValue());
break;
default:
throw new ND4JIllegalArgumentException("Only FLOAT and DOUBLE datatypes are supported");
}
}
for (int x = 0; x < numIntArrays; x++) {
IntPointer intPtr = block.getIntArrays().get(x); //new IntPointer(op.getIntArrayArguments().get(x));
intPtr.put(op.getIntArrayArguments().get(x), 0, op.getIntArrayArguments().get(x).length);
intArrays.put(x, intPtr);
pointers.add(intPtr);
}
//INDArray realsBuffer = Nd4j.create(reals);
loop.execAggregate(null, op.opNum(), arguments, numArguments, shapes, numShapes, pointer,
numIndexArguments, intArrays, numIntArrays, block.getRealArgumentsPointer(),
numRealArguments, FlatBuffersMapper.getDataTypeAsByte(dataType));
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
}
/**
* This method return set of key/value and
* key/key/value objects,
* describing current environment
*
* @return
*/
@Override
public Properties getEnvironmentInformation() {
Properties properties = super.getEnvironmentInformation();
properties.put(Nd4jEnvironment.BACKEND_KEY, "CPU");
properties.put(Nd4jEnvironment.OMP_THREADS_KEY, loop.ompGetMaxThreads());
properties.put(Nd4jEnvironment.BLAS_THREADS_KEY, Nd4j.factory().blas().getMaxThreads());
properties.put(Nd4jEnvironment.BLAS_VENDOR_KEY, (Nd4j.factory().blas()).getBlasVendor().toString());
properties.put(Nd4jEnvironment.HOST_FREE_MEMORY_KEY, Pointer.maxBytes() - Pointer.totalBytes());
// fill bandwidth information
/*
Note: Environment information is logged as part of ND4J initialization... but PerformanceTracker required
ND4J init to be completed before it can be initialized. Hence we can get a null PerformanceTracker when
OpExecutioner.printEnvironmentInformation() is called as part of ND4J class initialization - even
though PerformanceTracker.getInstance() refers to a static final field (as it may not yet be initialized)
*/
if(PerformanceTracker.getInstance() != null) {
properties.put(Nd4jEnvironment.MEMORY_BANDWIDTH_KEY, PerformanceTracker.getInstance().getCurrentBandwidth());
}
return properties;
}
/**
* This method executes specified RandomOp using default RNG available via Nd4j.getRandom()
*
* @param op
*/
@Override
public INDArray exec(RandomOp op) {
return exec(op, Nd4j.getRandom());
}
/**
* This method executes specific
* RandomOp against specified RNG
*
* @param op
* @param rng
*/
@Override
public INDArray exec(RandomOp op, Random rng) {
return exec(op, null, rng);
}
public INDArray exec(RandomOp op, OpContext oc, Random rng) {
INDArray x = getX(op, oc);
INDArray y = getY(op, oc);
INDArray z = getZ(op, oc);
if(op instanceof BaseRandomOp && ((BaseRandomOp)op).isTripleArgRngOp() && z != null && x == null && y == null){
//Ugly hack to ensure the triple arg call occurs
//See GaussianDistribution.setZ etc
x = z;
y = z;
}
if (!(rng instanceof CpuNativeRandom))
throw new IllegalStateException(
"You should use one of NativeRandom classes for NativeOperations execution. Op class: " + op.getClass().getName());
long st = profilingConfigurableHookIn(op);
//validateDataType(Nd4j.dataType(), op);
Preconditions.checkArgument(z.isR(), "Op.Z must have one of floating point types");
val xb = x == null ? null : ((BaseCpuDataBuffer) x.data()).getOpaqueDataBuffer();
val yb = y == null ? null : ((BaseCpuDataBuffer) y.data()).getOpaqueDataBuffer();
val zb = z == null ? null : ((BaseCpuDataBuffer) z.data()).getOpaqueDataBuffer();
if (x != null && y != null && z != null) {
DataBuffer dataBuffer = op.extraArgsDataBuff(z.dataType());
// triple arg call
loop.execRandom3(null, op.opNum(), rng.getStatePointer(), // rng state ptr
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
yb, (LongPointer) y.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
dataBuffer != null ? dataBuffer.addressPointer() : null);
} else if (x != null && z != null) {
DataBuffer dataBuffer = op.extraArgsDataBuff(z.dataType());
//double arg call
loop.execRandom2(null, op.opNum(), rng.getStatePointer(), // rng state ptr
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
dataBuffer != null ? dataBuffer.addressPointer() : null);
} else {
// single arg call
loop.execRandom(null, op.opNum(), rng.getStatePointer(), // rng state ptr
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
op.extraArgsDataBuff(z.dataType()).addressPointer());
}
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
profilingConfigurableHookOut(op, oc, st);
return z;
}
@Override
public TADManager getTADManager() {
return tadManager;
}
/**
* This class holds memory chunks required for single specific Aggregate op.
* Can be used together with ThreadLocal variables
*/
@Data
private static class AggregateMemoryBlock {
private List<IntPointer> intArrays = new ArrayList<>();
private IntPointer indexingPointer;
private Pointer realArgumentsPointer;
private PointerPointer shapesPointer;
private PointerPointer argumentsPointer;
private PointerPointer arraysPointer;
private final int opNum;
private AggregateMemoryBlock(@NonNull Aggregate op) {
opNum = op.opNum();
// creating IntArrays
for (int i = 0; i < op.maxIntArrays(); i++) {
intArrays.add(new IntPointer(op.maxIntArraySize()));
}
// allocating chunk for IndexingArguments
indexingPointer = new IntPointer(op.maxIndexArguments());
// allocating chunk for RealArguments
realArgumentsPointer = Nd4j.dataType() == DataType.DOUBLE ? new DoublePointer(op.maxRealArguments())
: new FloatPointer(op.maxRealArguments());
// allocating chunk for shapesPointer
shapesPointer = new PointerPointer(op.maxShapes());
// allocating chunk for argumentsPointer
argumentsPointer = new PointerPointer(op.maxArguments());
// chunk for intArrays
arraysPointer = new PointerPointer(op.maxIntArrays());
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
AggregateMemoryBlock that = (AggregateMemoryBlock) o;
return opNum == that.opNum;
}
@Override
public int hashCode() {
return opNum;
}
}
@Override
public synchronized Map<String, CustomOpDescriptor> getCustomOperations() {
if (customOps == null) {
String list = loop.getAllCustomOps();
if (list == null || list.isEmpty()) {
log.warn("No customs ops available!");
customOps = Collections.emptyMap();
return customOps;
}
val map = new HashMap<String, CustomOpDescriptor>();
String[] split = list.split(";");
for (String op : split) {
if (op == null || op.isEmpty())
continue;
String[] another = op.split(":");
CustomOpDescriptor descriptor = CustomOpDescriptor.builder()
.hash(Long.valueOf(another[1]))
.numInputs(Integer.valueOf(another[2]))
.numOutputs(Integer.valueOf(another[3]))
.allowsInplace(Integer.valueOf(another[4]) == 1)
.numTArgs(Integer.valueOf(another[5]))
.numIArgs(Integer.valueOf(another[6]))
.build();
map.put(another[0], descriptor);
}
customOps = Collections.unmodifiableMap(map);
}
return customOps;
}
private PointerPointer getPointerPointerFrom(ThreadLocal<Map<Integer,PointerPointer>> map,int numArguments) {
if(map.get() == null) {
Map<Integer,PointerPointer> store = new HashMap<>();
store.put(numArguments,new PointerPointer(numArguments));
map.set(store);
return map.get().get(numArguments);
}
else if (map.get().get(numArguments) == null) {
PointerPointer pointerPointer = new PointerPointer(numArguments);
map.get().put(numArguments,pointerPointer);
return pointerPointer;
}
return map.get().get(numArguments);
}
private ShortPointer getShortPointerFrom(ThreadLocal<Map<Integer,ShortPointer>> map,int numArguments) {
if(map.get() == null) {
Map<Integer,ShortPointer> store = new HashMap<>();
store.put(numArguments,new ShortPointer(numArguments));
map.set(store);
return map.get().get(numArguments);
}
else if (map.get().get(numArguments) == null) {
ShortPointer pointerPointer = new ShortPointer(numArguments);
map.get().put(numArguments,pointerPointer);
return pointerPointer;
}
return map.get().get(numArguments);
}
private LongPointer getLongPointerFrom(ThreadLocal<Map<Integer,LongPointer>> map,int numArguments) {
if(map.get() == null) {
Map<Integer,LongPointer> store = new HashMap<>();
store.put(numArguments,new LongPointer(numArguments));
map.set(store);
return map.get().get(numArguments);
}
else if (map.get().get(numArguments) == null) {
val pointerPointer = new LongPointer(numArguments);
map.get().put(numArguments,pointerPointer);
return pointerPointer;
}
return map.get().get(numArguments);
}
private DoublePointer getDoublePointerFrom(ThreadLocal<Map<Integer,DoublePointer>> map,int numArguments) {
if(map.get() == null) {
Map<Integer,DoublePointer> store = new HashMap<>();
store.put(numArguments,new DoublePointer(numArguments));
map.set(store);
return map.get().get(numArguments);
}
else if (map.get().get(numArguments) == null) {
DoublePointer pointerPointer = new DoublePointer(numArguments);
map.get().put(numArguments,pointerPointer);
return pointerPointer;
}
return map.get().get(numArguments);
}
private BooleanPointer getBooleanPointerFrom(ThreadLocal<Map<Integer,BooleanPointer>> map,int numArguments) {
if(map.get() == null) {
Map<Integer,BooleanPointer> store = new HashMap<>();
store.put(numArguments,new BooleanPointer(numArguments));
map.set(store);
return map.get().get(numArguments);
}
else if (map.get().get(numArguments) == null) {
val pointerPointer = new BooleanPointer(numArguments);
map.get().put(numArguments,pointerPointer);
return pointerPointer;
}
return map.get().get(numArguments);
}
private PointerPointer getInputShapes(int numArguments) {
return getPointerPointerFrom(inputShapes,numArguments);
}
private PointerPointer getInputBuffers(int numArguments) {
return getPointerPointerFrom(inputBuffers,numArguments);
}
private PointerPointer getOutputShapes(int numArguments) {
return getPointerPointerFrom(outputShapes,numArguments);
}
private PointerPointer getOutputBuffers(int numArguments) {
return getPointerPointerFrom(outputBuffers,numArguments);
}
/**
* This method executes given CustomOp
*
* PLEASE NOTE: You're responsible for input/output validation
* @param op Operation to execute
*/
@Override
public INDArray[] exec(@NonNull CustomOp op) {
DifferentialFunction differentialFunction = (DifferentialFunction) op;
String ownName = differentialFunction.getOwnName();
boolean shapeOverride = false;
if (op.numOutputArguments() == 0 && !op.isInplaceCall()) {
try {
val list = this.calculateOutputShape(op);
if (list.isEmpty())
throw new ND4JIllegalStateException("Op name " + op.opName() + " failed to calculate output shape and data types.");
for (LongShapeDescriptor shape : list)
op.addOutputArgument(Nd4j.create(shape, false));
shapeOverride = true;
} catch (ND4JIllegalStateException e){
throw e;
} catch (Exception e) {
throw new ND4JIllegalStateException("Op name " + op.opName() + " - no output arrays were provided and calculateOutputShape failed to execute", e);
//throw new RuntimeException(e);
}
}
val name = op.opName();
try (val context = buildContext()) {
// optionally skip shape validation on op execution
if (shapeOverride)
context.shapeFunctionOverride(true);
context.markInplace(op.isInplaceCall());
// transferring rng state
context.setRngStates(Nd4j.getRandom().rootState(), Nd4j.getRandom().nodeState());
//transferring input/output arrays
context.setInputArrays(op.inputArguments());
context.setOutputArrays(op.outputArguments());
// transferring static args
context.setBArguments(op.bArgs());
context.setIArguments(op.iArgs());
context.setTArguments(op.tArgs());
context.setDArguments(op.dArgs());
val result = exec(op, context);
val states = context.getRngStates();
// check if input & output needs update
for (val in:op.inputArguments()) {
if (!in.isEmpty())
((BaseCpuDataBuffer) in.data()).actualizePointerAndIndexer();
}
for (val out:op.outputArguments()) {
if (!out.isEmpty())
((BaseCpuDataBuffer) out.data()).actualizePointerAndIndexer();
}
// pulling states back
Nd4j.getRandom().setStates(states.getFirst(), states.getSecond());
return result;
} catch (ND4JOpProfilerException e){
throw e;
} catch (Exception e) {
throw new RuntimeException("Op [" + name + "] execution failed", e);
}
}
protected LongShapeDescriptor getShapeFromPointer(LongPointer ptr) {
val rank = (int) ptr.get(0);
val shape = new long[rank * 2 + 4];
for (int i = 0; i < shape.length; i++) {
shape[i] = ptr.get(i);
}
//val extras = ptr.get(Shape.shapeInfoLength(rank) - 3);
val t = ArrayOptionsHelper.arrayType(shape);
return LongShapeDescriptor.fromShape(Shape.shape(shape), Shape.stride(shape), Shape.elementWiseStride(shape), Shape.order(shape), ArrayOptionsHelper.dataType(shape), t == ArrayType.EMPTY);
}
@Override
public List<LongShapeDescriptor> calculateOutputShape(@NonNull CustomOp op) {
return calculateOutputShape(op, null);
}
@Override
public List<LongShapeDescriptor> calculateOutputShape(@NonNull CustomOp op, OpContext opContext) {
DifferentialFunction func = (DifferentialFunction) op;
String opName = func.getOwnName();
val lc = op.opName().toLowerCase();
val hash = op.opHash();
val result = new ArrayList<LongShapeDescriptor>();
int nIn = opContext != null ? opContext.numInputArguments() : op.numInputArguments();
if(nIn == 0 && op.getDescriptor().getNumInputs() >= 1) {
if(log.isTraceEnabled()){
log.trace("Could not calculate output shape for op {}: number of input args was 0",
op.getClass().getName());
}
return Collections.emptyList();
}
val inputBuffers = new PointerPointer<>(nIn);
val inputShapes = new PointerPointer<>(nIn);
val inputArgs = opContext != null && opContext.getInputArrays() != null && !opContext.getInputArrays().isEmpty()
? opContext.getInputArrays() : op.inputArguments();
int cnt= 0;
for (val in: inputArgs) {
if (!in.isEmpty())
inputBuffers.put(cnt, in.data().addressPointer());
inputShapes.put(cnt++, in.shapeInfoDataBuffer().addressPointer());
}
int nIArgs = opContext != null ? opContext.numIArguments() : op.numIArguments();
val iArgs = nIArgs > 0 ? new LongPointer(nIArgs) : null;
cnt = 0;
if(opContext != null){
for (val i: opContext.getIArguments())
iArgs.put(cnt++, i);
} else {
for (val i: op.iArgs())
iArgs.put(cnt++, i);
}
int nTArgs = opContext != null ? opContext.numTArguments() : op.numTArguments();
val tArgs = nTArgs > 0 ? new DoublePointer(nTArgs) : null;
int nBArgs = opContext != null ? opContext.numBArguments() : op.numBArguments();
val bArgs = nBArgs > 0 ? new BooleanPointer(nBArgs) : null;
int nDArgs = opContext != null ? opContext.numDArguments() : op.numDArguments();
val dArgs = nDArgs > 0 ? new IntPointer(nDArgs) : null;
cnt = 0;
if(opContext != null) {
for (val b: opContext.getBArguments())
bArgs.put(cnt++, b);
} else {
for (val b: op.bArgs())
bArgs.put(cnt++, b);
}
cnt = 0;
if(opContext != null) {
for (val b: opContext.getTArguments())
tArgs.put(cnt++, b);
} else {
for (val b: op.tArgs())
tArgs.put(cnt++, b);
}
cnt = 0;
if(opContext != null) {
for (val b: opContext.getDArguments())
dArgs.put(cnt++, b.toInt());
} else {
for (val b: op.dArgs())
dArgs.put(cnt++, b.toInt());
}
OpaqueShapeList ptrptr;
try {
ptrptr = loop.calculateOutputShapes2(null,
hash, inputBuffers, inputShapes, nIn, tArgs,
nTArgs, iArgs, nIArgs, bArgs, nBArgs, dArgs, nDArgs);
if (loop.lastErrorCode() != 0) {
DifferentialFunction differentialFunction = (DifferentialFunction) op;
if(opContext != null)
throw new RuntimeException("Op " + op.opName() + " with name " + differentialFunction.getOwnName() + " failed to execute." + " Here is the error from c++: " + loop.lastErrorMessage());
else {
throw new RuntimeException("Op " + op.opName() + " with name " + differentialFunction.getOwnName() + " failed to execute. Here is the error from c++: " + loop.lastErrorMessage());
}
}
} catch (Throwable t) {
StringBuilder sb = new StringBuilder();
sb.append("Inputs: [(");
for( int i = 0; i < inputArgs.size(); i++) {
if(i > 0)
sb.append("), (");
sb.append(Shape.shapeToStringShort(inputArgs.get(i)));
}
sb.append(")]");
if(op instanceof DifferentialFunction && ((DifferentialFunction)op).getSameDiff() != null) {
appendSameDiffInfo(sb, (DifferentialFunction) op);
}
int nOut = opContext != null ? opContext.numOutputArguments() : op.numOutputArguments();
log.error("Failed to calculate output shapes for op {}. Attempted to execute with {} inputs, {} outputs, " +
"{} targs, {} iargs, {} bargs and {} dargs. {} - Please see above message (printed out from c++) for a possible cause of error.",
op.opName(), nIn, nOut, nTArgs, nIArgs, nBArgs, nDArgs, sb.toString());
throw t;
}
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
if (ptrptr == null)
throw new RuntimeException();
for (int e = 0; e < loop.getShapeListSize(ptrptr); e++ )
result.add(getShapeFromPointer(new PagedPointer(loop.getShape(ptrptr, e)).asLongPointer()));
loop.deleteShapeList(ptrptr);
if(log.isTraceEnabled()) {
String[] arr = new String[result.size()];
for( int i = 0; i < result.size(); i++) {
arr[i] = result.get(i).toString();
}
DifferentialFunction differentialFunction = (DifferentialFunction) op;
log.trace("Calculated output shapes for op of name {} and type {} - {}",differentialFunction.getOwnName(), op.getClass().getName(), Arrays.toString(arr));
}
return result;
}
@Override
public void enableDebugMode(boolean reallyEnable) {
debug.set(reallyEnable);
loop.enableDebugMode(reallyEnable);
}
@Override
public void enableVerboseMode(boolean reallyEnable) {
verbose.set(reallyEnable);
loop.enableVerboseMode(reallyEnable);
}
@Override
public void registerGraph(long id, Pointer graph) {
loop.registerGraph(null, id, graph);
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
}
@Override
public Map<String, INDArray> executeGraph(long id, @NonNull Map<String, INDArray> map, @NonNull Map<String, Integer> reverseMap) {
val ptrBuffers = new PointerPointer(map.size());
val ptrShapes = new PointerPointer(map.size());
val ptrIndices = new IntPointer(map.size());
int cnt = 0;
val keySet = new ArrayList<String>(map.keySet());
for (val key: keySet) {
val array = map.get(key);
ptrBuffers.put(cnt, array.data().addressPointer());
ptrShapes.put(cnt, array.shapeInfoDataBuffer().addressPointer());
ptrIndices.put(cnt, reverseMap.get(key));
cnt++;
}
val newMap = new LinkedHashMap<String, INDArray>();
OpaqueVariablesSet result = loop.executeStoredGraph(null, id, ptrBuffers, ptrShapes, ptrIndices, map.size());
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
OpStatus status = OpStatus.byNumber(loop.getVariablesSetStatus(result));
if (status != OpStatus.ND4J_STATUS_OK)
throw new ND4JIllegalStateException("Op execution failed: " + status);
for (int e = 0; e < loop.getVariablesSetSize(result); e++) {
OpaqueVariable var = loop.getVariable(result, e);
int nodeId = loop.getVariableId(var);
int index = loop.getVariableIndex(var);
LongPointer shapeInfo = loop.getVariableShape(var);
Pointer buffer = loop.getVariableBuffer(var);
val rank = (int) shapeInfo.get(0);
val jshape = new long[rank * 2 + 4];
for (int i = 0; i < jshape.length; i++) {
jshape[i] = shapeInfo.get(i);
}
val shapeOf = Shape.shapeOf(jshape);
val stridesOf = Shape.stridesOf(jshape);
val order = Shape.order(jshape);
val array = Nd4j.create(shapeOf, stridesOf, 0, order);
val perfX = PerformanceTracker.getInstance().helperStartTransaction();
Pointer.memcpy(array.data().addressPointer(), buffer, Shape.lengthOf(shapeOf) * Nd4j.sizeOfDataType(array.dataType()));
PerformanceTracker.getInstance().helperRegisterTransaction(0, perfX, Shape.lengthOf(shapeOf) * Nd4j.sizeOfDataType(array.dataType()), MemcpyDirection.HOST_TO_HOST);
//newMap.put(keySet.get(nodeId), array);
String nodeName = loop.getVariableName(var);
newMap.put(nodeName, array);
}
loop.deleteVariablesSet(result);
return newMap;
}
@Override
public void forgetGraph(long id) {
loop.unregisterGraph(null, id);
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
}
/**
* This method allows to set desired number of elements per thread, for performance optimization purposes.
* I.e. if array contains 2048 elements, and threshold is set to 1024, 2 threads will be used for given op execution.
* <p>
* Default value: 1024
*
* @param threshold
*/
@Override
public void setElementsThreshold(int threshold) {
loop.setElementThreshold(threshold);
}
/**
* This method allows to set desired number of sub-arrays per thread, for performance optimization purposes.
* I.e. if matrix has shape of 64 x 128, and threshold is set to 8, each thread will be processing 8 sub-arrays (sure, if you have 8 core cpu).
* If your cpu has, say, 4, cores, only 4 threads will be spawned, and each will process 16 sub-arrays
* <p>
* Default value: 8
*
* @param threshold
*/
@Override
public void setTadThreshold(int threshold) {
loop.setTADThreshold(threshold);
}
@Override
public String getString(DataBuffer buffer, long index) {
Preconditions.checkArgument(buffer instanceof Utf8Buffer, "Expected Utf8Buffer");
val addr = ((LongIndexer) buffer.indexer()).get(index);
val ptr = new PagedPointer(addr);
val str = new Nd4jCpu.utf8string(ptr);
return str._buffer().capacity(str._length()).getString();
}
@Override
public ExecutionerType type() {
return ExecutionerType.NATIVE_CPU;
}
@Override
public boolean isExperimentalMode() {
return experimentalMode.get();
}
@Override
public void scatterUpdate(ScatterUpdate.UpdateOp op, @NonNull INDArray array, @NonNull INDArray indices, @NonNull INDArray updates, @NonNull int[] axis) {
val tadX = tadManager.getTADOnlyShapeInfo(array, axis);
val tadY = tadManager.getTADOnlyShapeInfo(updates, axis);
if (tadY.getSecond().length() != indices.length())
throw new IllegalStateException("Number of updates doesn't match number of indices. Bad dimensions used?");
loop.scatterUpdate(null, op.ordinal(), (int) indices.length(),
array.data().addressPointer(), (LongPointer) tadX.getFirst().addressPointer(), (LongPointer) tadX.getSecond().addressPointer(), null, null, null,
updates.data().addressPointer(), (LongPointer) tadY.getFirst().addressPointer(), (LongPointer) tadY.getSecond().addressPointer(), null, null, null,
indices.data().addressPointer(), (LongPointer) indices.shapeInfoDataBuffer().addressPointer(), null, null);
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
}
@Override
public OpContext buildContext() {
return new CpuOpContext();
}
@Override
public INDArray[] exec(CustomOp op, @NonNull OpContext context) {
long st = profilingConfigurableHookIn(op, context);
boolean mklOverride = false;
try {
if (Nd4jCpu.Environment.getInstance().isUseONEDNN()) {
val opName = op.opName();
val state = mklOverrides.get(op);
if (state != null && state == true) {
mklOverride = true;
Nd4jCpu.Environment.getInstance().setUseONEDNN(true);
}
}
val status = loop.execCustomOp2(null, op.opHash(), context.contextPointer());
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
if (status != 0) {
DifferentialFunction differentialFunction = (DifferentialFunction) op;
throw new RuntimeException("Op with name " + differentialFunction.getOwnName() + " and op type [" + op.opName() + "] execution failed");
}
if (context.getOutputArrays().isEmpty())
return new INDArray[0];
else
return context.getOutputArrays().toArray(new INDArray[context.getOutputArrays().size()]);
} catch (Exception e) {
val sb = new StringBuilder();
sb.append("Inputs: [(");
int nIn = (context.getInputArrays() == null ? 0 : context.getInputArrays().size());
for (int i = 0; i < nIn; i++) {
if (i > 0)
sb.append("), (");
sb.append(Shape.shapeToStringShort(context.getInputArrays().get(i)));
}
sb.append(")]. Outputs: [(");
int nOut = (context.getOutputArrays() == null ? 0 : context.getOutputArrays().size());
for (int i = 0; i < nOut; i++) {
if (i > 0)
sb.append("), (");
sb.append(Shape.shapeToStringShort(context.getOutputArrays().get(i)));
}
sb.append(")]. tArgs: ");
int nT = (context.getTArguments() == null ? 0 : context.getTArguments().size());
if (nT > 0) {
sb.append(context.getTArguments());
} else {
sb.append("-");
}
sb.append(". iArgs: ");
int nI = (context.getIArguments() == null ? 0 : context.getIArguments().size());
if (nI > 0) {
sb.append(context.getIArguments());
} else {
sb.append("-");
}
sb.append(". bArgs: ");
int nB = (context.getBArguments() == null ? 0 : context.getBArguments().size());
if (nB > 0) {
sb.append(context.getBArguments());
} else {
sb.append("-");
}
if (op instanceof DifferentialFunction) {
String n = ((DifferentialFunction) op).getOwnName();
if (n != null && !n.equals(op.opName())) {
sb.append(". Op own name: \"").append(n).append("\"");
}
}
if(op instanceof DifferentialFunction && ((DifferentialFunction)op).getSameDiff() != null){
appendSameDiffInfo(sb, (DifferentialFunction) op);
}
log.error("Failed to execute op " + op.opName() + ". Attempted to execute with " +
nIn + " inputs, " +
nOut + " outputs, " +
nT + " targs," +
nB + " bargs and " +
nI + " iargs. " +
sb.toString() +
" - Please see above message (printed out from c++) for a possible cause of error.");
throw e;
} finally {
if (mklOverride)
Nd4jCpu.Environment.getInstance().setUseONEDNN(true);
profilingConfigurableHookOut(op, context, st);
}
}
@Override
public INDArrayStatistics inspectArray(INDArray array) {
val debugInfo = new Nd4jCpu.DebugInfo();
loop.inspectArray(null, array.data().addressPointer(), (LongPointer) array.shapeInfoDataBuffer().addressPointer(), null, null, debugInfo);
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
return INDArrayStatistics.builder()
.minValue(debugInfo._minValue())
.maxValue(debugInfo._maxValue())
.meanValue(debugInfo._meanValue())
.stdDevValue(debugInfo._stdDevValue())
.countInf(debugInfo._infCount())
.countNaN(debugInfo._nanCount())
.countNegative(debugInfo._negativeCount())
.countPositive(debugInfo._positiveCount())
.countZero(debugInfo._zeroCount())
.build();
}
@Override
public DataBuffer createShapeInfo(long[] shape, long[] stride, long elementWiseStride, char order, DataType dtype, boolean empty) {
val dbf = loop.shapeBuffer(shape.length, new LongPointer(shape), new LongPointer(stride), dtype.toInt(), order, elementWiseStride, empty);
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
val result = new LongBuffer(loop.getConstantShapeBufferPrimary(dbf), Shape.shapeInfoLength(shape.length));
loop.deleteConstantShapeBuffer(dbf);
return result;
}
@Override
public DataBuffer createShapeInfo(long[] shape, long[] stride, long elementWiseStride, char order, DataType dtype, long extras) {
OpaqueConstantShapeBuffer dbf = loop.shapeBufferEx(shape.length, new LongPointer(shape), new LongPointer(stride), dtype.toInt(), order, elementWiseStride, extras);
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
val result = new LongBuffer(loop.getConstantShapeBufferPrimary(dbf), Shape.shapeInfoLength(shape.length));
loop.deleteConstantShapeBuffer(dbf);
return result;
}
@Override
public TadPack tadShapeInfoAndOffsets(INDArray array, int[] dimension) {
OpaqueTadPack pack = loop.tadOnlyShapeInfo((LongPointer) array.shapeInfoDataBuffer().addressPointer(), new IntPointer(dimension), dimension.length);
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
val tadShape = new LongBuffer(loop.getPrimaryShapeInfo(pack), loop.getShapeInfoLength(pack));
val tadOffsets = new LongBuffer(loop.getPrimaryOffsets(pack), loop.getNumberOfTads(pack));
loop.deleteTadPack(pack);
return new TadPack(tadShape, tadOffsets);
}
protected void appendSameDiffInfo(StringBuilder sb, DifferentialFunction df){
String[] inNames = df.argNames();
String[] outNames = df.outputVariablesNames();
if(inNames != null){
sb.append(". Input var names: ").append(Arrays.toString(inNames));
}
if(outNames != null){
sb.append(". Output var names: ").append(Arrays.toString(outNames));
}
}
}
|
package org.helioviewer.jhv.camera;
import java.util.ArrayList;
import java.util.Date;
import org.helioviewer.base.datetime.ImmutableDateTime;
import org.helioviewer.base.math.GL3DQuatd;
import org.helioviewer.base.math.GL3DVec3d;
import org.helioviewer.base.physics.Astronomy;
import org.helioviewer.base.physics.Constants;
import org.helioviewer.jhv.display.Displayer;
import org.helioviewer.jhv.display.TimeListener;
import org.helioviewer.jhv.gui.ImageViewerGui;
import org.helioviewer.jhv.layers.LayersListener;
import org.helioviewer.jhv.renderable.RenderableCamera;
import org.helioviewer.viewmodel.view.AbstractView;
public class GL3DFollowObjectCamera extends GL3DSolarRotationTrackingTrackballCamera implements GL3DPositionLoadingListener, LayersListener, TimeListener {
private final ArrayList<GL3DFollowObjectCameraListener> followObjectCameraListeners = new ArrayList<GL3DFollowObjectCameraListener>();
private final GL3DPositionLoading positionLoading;
private double currentL = 0.;
private double currentB = 0.;
private double currentDistance = Constants.SunMeanDistanceToEarth / Constants.SunRadius;
private Date cameraDate;
private boolean interpolation;
public GL3DFollowObjectCamera() {
super();
positionLoading = new GL3DPositionLoading();
positionLoading.addListener(this);
Displayer.getLayersModel().addLayersListener(this);
this.timeChanged(Displayer.getLastUpdatedTimestamp());
}
@Override
public void reset() {
super.reset();
}
@Override
public void activate(GL3DCamera precedingCamera) {
super.activate(precedingCamera);
this.activeLayerChanged(Displayer.getLayersModel().getActiveView());
this.timeChanged(Displayer.getLastUpdatedTimestamp());
Displayer.addFirstTimeListener(this);
}
@Override
public void deactivate() {
super.deactivate();
Displayer.removeTimeListener(this);
}
@Override
public String getName() {
return "Follow object camera";
}
@Override
public void timeChanged(Date date) {
if (date != null && this.positionLoading.isLoaded() && !this.getTrackingMode()) {
long currentCameraTime, dateTime = date.getTime();
if (interpolation) {
// Active layer times
AbstractView view = Displayer.getLayersModel().getActiveView();
long t1 = Displayer.getLayersModel().getStartDate(view).getTime().getTime();
long t2 = Displayer.getLayersModel().getEndDate(view).getTime().getTime();
//Camera times
long t3 = this.positionLoading.getBeginDate().getTime();
long t4 = this.positionLoading.getEndDate().getTime();
if (t4 != t3) {
currentCameraTime = (long) ((t3 + 1. * (t4 - t3) * (dateTime - t1) / (t2 - t1)));
} else {
currentCameraTime = t4;
}
} else {
currentCameraTime = dateTime;
}
cameraDate = new Date(currentCameraTime);
RenderableCamera renderableCamera = ImageViewerGui.getRenderableCamera();
if (renderableCamera != null) {
renderableCamera.setTimeString(cameraDate);
ImageViewerGui.getRenderableContainer().fireTimeUpdated(renderableCamera);
}
GL3DVec3d position = this.positionLoading.getInterpolatedPosition(currentCameraTime);
if (position != null) {
currentL = position.y;
currentB = -position.z;
currentDistance = position.x;
updateRotation(date);
}
}
}
private void updateRotation(Date date) {
if (this.positionLoading.isLoaded()) {
double currentRotation = (-currentL + Astronomy.getL0Radians(date)) % (Math.PI * 2.0);
GL3DQuatd newRotation = GL3DQuatd.createRotation(-currentB, GL3DVec3d.XAxis);
newRotation.rotate(GL3DQuatd.createRotation(currentRotation, GL3DVec3d.YAxis));
this.setLocalRotation(newRotation);
this.setZTranslation(-currentDistance);
this.updateCameraTransformation();
}
}
public void addFollowObjectCameraListener(GL3DFollowObjectCameraListener listener) {
this.followObjectCameraListeners.add(listener);
}
public void removeFollowObjectCameraListener(GL3DFollowObjectCameraListener listener) {
this.followObjectCameraListeners.remove(listener);
}
@Override
public void fireNewLoaded(String state) {
for (GL3DFollowObjectCameraListener listener : followObjectCameraListeners) {
listener.fireLoaded(state);
}
Displayer.render();
}
public void setBeginDate(Date date, boolean applyChanges) {
this.positionLoading.setBeginDate(date, applyChanges);
}
public void setEndDate(Date date, boolean applyChanges) {
this.positionLoading.setEndDate(date, applyChanges);
}
public void setObservingObject(String object, boolean applyChanges) {
this.positionLoading.setObserver(object, applyChanges);
}
public void setInterpolation(boolean interpolation) {
this.interpolation = interpolation;
}
@Override
public void layerAdded(int idx) {
}
@Override
public void layerRemoved(int oldIdx) {
}
@Override
public void activeLayerChanged(AbstractView view) {
if (!interpolation) {
ImmutableDateTime date;
date = Displayer.getLayersModel().getStartDate(view);
if (date != null) {
positionLoading.setBeginDate(date.getTime(), true);
}
date = Displayer.getLayersModel().getEndDate(view);
if (date != null) {
positionLoading.setEndDate(date.getTime(), true);
}
}
}
public Date getBeginTime() {
return this.positionLoading.getBeginDate();
}
public Date getEndTime() {
return this.positionLoading.getEndDate();
}
}
|
package org.optaplanner.core.impl.localsearch.decider.acceptor.greatdeluge;
import org.optaplanner.core.api.score.Score;
import org.optaplanner.core.impl.localsearch.decider.acceptor.AbstractAcceptor;
import org.optaplanner.core.impl.localsearch.scope.LocalSearchMoveScope;
import org.optaplanner.core.impl.localsearch.scope.LocalSearchPhaseScope;
import org.optaplanner.core.impl.localsearch.scope.LocalSearchStepScope;
import org.optaplanner.core.impl.score.ScoreUtils;
public class GreatDelugeAcceptor extends AbstractAcceptor {
private Score initialLevel = null;
private Double rainSpeed = null;
private Double rainSpeedRatio = null;
private int levelsLength = -1;
private double[] initialLevelScoreLevels;
private double[] initialLevelScoreLevelsNegative;
private double[] levelScoreLevels;
private double levelMinimum = 0;
private final double THRESHOLD = .0000001;
// Good value to come out from
private final double DEFAULTRAINSPEEDRATIO = 0.99999995;
public void setInitialLevels(Score initialLevel) { this.initialLevel = initialLevel; }
public void setRainSpeed(Double rainSpeed) { this.rainSpeed = rainSpeed; }
public void setRainSpeedRatio(Double rainSpeedRatio) {this.rainSpeedRatio = rainSpeedRatio; }
public void phaseStarted(LocalSearchPhaseScope phaseScope) {
super.phaseStarted(phaseScope);
if (initialLevel != null) {
for (double initialLevelLevel : ScoreUtils.extractLevelDoubles(initialLevel)) {
if (initialLevelLevel < 0.0) {
throw new IllegalArgumentException("The initial level (" + initialLevel
+ ") cannot have negative level (" + initialLevelLevel + ").");
}
}
initialLevelScoreLevels = ScoreUtils.extractLevelDoubles(initialLevel);
levelScoreLevels = initialLevelScoreLevels;
} else {
initialLevelScoreLevelsNegative = ScoreUtils.extractLevelDoubles(phaseScope.getBestScore());
logger.info(phaseScope.getBestScore().toShortString());
levelScoreLevels = initialLevelScoreLevelsNegative;
for (int i = 0; i < levelScoreLevels.length; i++) {
if (Math.abs(levelScoreLevels[i]) < THRESHOLD) {
logger.info(Double.toString(levelScoreLevels[i]));
continue;
}
levelScoreLevels[i] = -levelScoreLevels[i]+5;
logger.info(Double.toString(levelScoreLevels[i]));
}
}
levelsLength = levelScoreLevels.length;
}
public void phaseEnded(LocalSearchPhaseScope phaseScope) {
super.phaseEnded(phaseScope);
initialLevelScoreLevels = null;
levelScoreLevels = null;
levelsLength = -1;
}
@Override
public boolean isAccepted(LocalSearchMoveScope moveScope) {
Score moveScore = moveScope.getScore();
double[] moveScoreLevels = ScoreUtils.extractLevelDoubles(moveScore);
for (int i = 0; i < levelsLength; i++) {
double moveScoreLevel = moveScoreLevels[i];
double levelScoreLevel = levelScoreLevels[i];
if (moveScoreLevel > -levelScoreLevel) {
return true;
} else if (Math.abs(moveScoreLevel + levelScoreLevel) < THRESHOLD) {
if (i == levelsLength -1) {
return true;
}
continue;
} else {
return false;
}
}
return true;
}
// change water level at the beginning of the step
public void stepStarted(LocalSearchStepScope stepScope) {
super.stepEnded(stepScope);
for (int i = 0; i < levelsLength; i++) {
if (rainSpeed != null) {
levelScoreLevels[i] = levelScoreLevels[i] - rainSpeed;
} else if (rainSpeedRatio != null) {
levelScoreLevels[i] = levelScoreLevels[i] * rainSpeedRatio;
} else {
levelScoreLevels[i] = levelScoreLevels[i] * DEFAULTRAINSPEEDRATIO;
}
if (levelScoreLevels[i] < levelMinimum) {
levelScoreLevels[i] = levelMinimum;
}
}
}
}
|
package org.jasig.portal;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Map;
import org.jasig.portal.car.CarResources;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.oreilly.servlet.multipart.Part;
/**
* A set of runtime data accessible by a channel.
*
* @author <a href="mailto:pkharchenko@unicon.net">Peter Kharchenko</a>
* @version $Revision$
*/
public class ChannelRuntimeData extends Hashtable implements Cloneable {
private static final Log log = LogFactory.getLog(ChannelRuntimeData.class);
private BrowserInfo binfo=null;
private Locale[] locales = null;
private UPFileSpec channelUPFile;
private String baseActionURL = null;
private String httpRequestMethod=null;
private String remoteAddress=null;
private String keywords=null;
private boolean renderingAsRoot=false;
private boolean targeted = false;
private static final String TRADITIONAL_MEDIA_BASE = "media/";
public static final String CAR_BASE = "/CAR_BASE";
public static final String WEB_APP_BASE = null;
/**
* Default empty constructor
*/
public ChannelRuntimeData() {
super();
channelUPFile = new UPFileSpec();
}
/**
* Create a new instance of ourself
* Used by the CError channel
* @return crd the cloned ChannelRuntimeData object
*/
public Object clone() {
ChannelRuntimeData crd = new ChannelRuntimeData();
crd.binfo = binfo;
crd.locales = locales;
crd.channelUPFile = channelUPFile;
crd.baseActionURL = baseActionURL;
crd.httpRequestMethod = httpRequestMethod;
crd.keywords = keywords;
crd.renderingAsRoot = renderingAsRoot;
crd.targeted = targeted;
crd.putAll(this);
return crd;
}
/**
* Set a UPFileSpec which will be used to produce
* baseActionURL and workerActionURL.
* @param upfs the UPFileSpec
*/
public void setUPFile(UPFileSpec upfs) {
channelUPFile = upfs;
}
/**
* Get the UPFileSpec
* @return channelUPFile the UPFileSpec
*/
public UPFileSpec getUPFile() {
return this.channelUPFile;
}
/**
* Set the HTTP Request method.
*
* @param method a <code>String</code> value
*/
public void setHttpRequestMethod(String method) {
this.httpRequestMethod=method;
}
/**
* Get HTTP request method (i.e. GET, POST)
*
* @return a <code>String</code> value
*/
public String getHttpRequestMethod() {
return this.httpRequestMethod;
}
/**
* Sets the base action URL. This was added back in for the benefit
* of web services. Not sure if it is going to stay this way.
* @param baseActionURL the base action URL
*/
public void setBaseActionURL(String baseActionURL) {
this.baseActionURL = baseActionURL;
}
/**
* Sets whether or not the channel is rendering as the root of the layout.
* @param rar <code>true</code> if channel is rendering as the root, otherwise <code>false</code>
*/
public void setRenderingAsRoot(boolean rar) {
renderingAsRoot = rar;
}
/**
* Sets whether or not the channel is currently targeted. A channel is targeted
* if an incoming request specifies the channel's subscribe ID as the targeted node ID.
* @param targeted <code>true</code> if channel is targeted, otherwise <code>false</code>
*/
public void setTargeted(boolean targeted) {
this.targeted = targeted;
}
/**
* Setter method for browser info object.
*
* @param bi a browser info associated with the current request
*/
public void setBrowserInfo(BrowserInfo bi) {
this.binfo = bi;
}
/**
* Provides information about a user-agent associated with the current request/response.
*
* @return a <code>BrowserInfo</code> object ecapsulating various user-agent information.
*/
public BrowserInfo getBrowserInfo() {
return binfo;
}
/**
* Setter method for array of locales. A channel should
* make an effort to render itself according to the
* order of the locales in this array.
* @param locales an ordered list of locales
*/
public void setLocales(Locale[] locales) {
this.locales = locales;
}
/**
* Accessor method for ordered set of locales.
* @return locales an ordered list of locales
*/
public Locale[] getLocales() {
return locales;
}
/**
* A convenience method for setting a whole set of parameters at once.
* The values in the Map must be object arrays. If (name, value[]) is in
* the Map, then a future call to getParameter(name) will return value[0].
* @param params a <code>Map</code> of parameter names to parameter value arrays.
*/
public void setParameters(Map params) {
this.putAll(params); // copy a Map
}
/**
* A convenience method for setting a whole set of parameters at once.
* The Map should contain name-value pairs. The name should be a String
* and the value should be either a String or a Part.
* If (name, value) is in the Map then a future call to getParameter(name)
* will return value.
* @param params a <code>Map</code> of parameter names to parameter value arrays.
*/
public void setParametersSingleValued(Map params) {
if (params != null) {
java.util.Iterator iter = params.keySet().iterator();
while (iter.hasNext()) {
String key = (String)iter.next();
Object value = params.get(key);
if (value instanceof String)
setParameter(key, (String)value);
else if (value instanceof Part)
setParameter(key, (Part)value);
}
}
}
/**
* Sets multi-valued parameter.
*
* @param pName parameter name
* @param values an array of parameter values
* @return an array of parameter values
*/
public String[] setParameterValues(String pName, String[] values) {
return (String[])super.put(pName, values);
}
/**
* Establish a parameter name-value pair.
*
* @param pName parameter name
* @param value parameter value
*/
public void setParameter(String pName, String value) {
String[] valueArray = new String[1];
valueArray[0] = value;
super.put(pName, valueArray);
}
public com.oreilly.servlet.multipart.Part[] setParameterValues(String pName, com.oreilly.servlet.multipart.Part[] values) {
return (com.oreilly.servlet.multipart.Part[])super.put(pName, values);
}
public synchronized void setParameter(String key, Part value) {
Part[] valueArray = new Part[1];
valueArray[0] = value;
super.put(key, valueArray);
}
/**
* Returns a baseActionURL - parameters of a request coming in on the baseActionURL
* will be placed into the ChannelRuntimeData object for channel's use.
*
* @return a value of URL to which parameter sequences should be appended.
*/
public String getBaseActionURL() {
return this.getBaseActionURL(false);
}
/**
* Returns a baseActionURL - parameters of a request coming in on the baseActionURL
* will be placed into the ChannelRuntimeData object for channel's use.
*
* @param idempotent a <code>boolean</code> value specifying if a given URL should be idepotent.
* @return a value of URL to which parameter sequences should be appended.
*/
public String getBaseActionURL(boolean idempotent) {
// If the base action URL was explicitly set, use it
// peterk: we should probably introduce idepotent version of this one as well, at some point
if (baseActionURL != null) {
return baseActionURL;
}
String url=null;
try {
if(idempotent) {
UPFileSpec upfs=new UPFileSpec(channelUPFile);
upfs.setTagId(PortalSessionManager.IDEMPOTENT_URL_TAG);
url=upfs.getUPFile();
} else {
url=channelUPFile.getUPFile();
}
} catch (Exception e) {
log.error("ChannelRuntimeData::getBaseActionURL() : unable to construct a base action URL!");
}
return url;
}
/**
* Returns an idempotent URL that includes a single query parameter that
* targets a channel for focus mode by functional name. Additional
* query parameters appended will be passed to the focused channel via
* the channel's ChannelRuntimeData object.
*
* @return a value of URL including a single query parameter.
* @since 2.5.1
*/
public String getFnameActionURL(String fname) {
String url=null;
try {
UPFileSpec upfs=new UPFileSpec(channelUPFile);
upfs.setTagId(PortalSessionManager.IDEMPOTENT_URL_TAG);
url=upfs.getUPFile();
url = url + "?" + Constants.FNAME_PARAM + "=" + fname;
} catch (Exception e) {
log.error("Unable to construct a fname action URL!", e);
}
return url;
}
/**
* Returns the URL to invoke one of the workers specified in PortalSessionManager.
* Typically the channel that is invoked with the worker will have to implement an
* interface specific for that worker.
* @param worker - Worker string must be a UPFileSpec.xxx value.
* @return URL to invoke the worker.
*/
public String getBaseWorkerURL(String worker) {
// todo: propagate the exception
String url=null;
try {
url=getBaseWorkerURL(worker,false);
} catch (Exception e) {
log.error("ChannelRuntimeData::getBaseWorkerURL() : unable to construct a worker action URL for a worker \""+worker+"\".");
}
return url;
}
/**
Returns a media base appropriate for web-visible resources used by and
deployed with the passed in object. If the class of the passed in
object was loaded from a CAR then a URL appropriate for accessing
images in CARs is returned. Otherwise, a URL to the base media
in the web application's document root is returned.
*/
public String getBaseMediaURL( Object aChannelObject )
throws PortalException
{
return getBaseMediaURL( aChannelObject.getClass() );
}
/**
Returns a media base appropriate for web-visible resources used by and
deployed with the passed in class. If the class of the passed in
object was loaded from a CAR then a URL appropriate for accessing
images in CARs is returned. Otherwise, a URL to the base media
in the web application's document root is returned.
*/
public String getBaseMediaURL( Class aChannelClass )
throws PortalException
{
if (aChannelClass == null)
return TRADITIONAL_MEDIA_BASE;
if (aChannelClass == CarResources.class)
return createBaseCarMediaURL();
if ( aChannelClass.getClassLoader() ==
CarResources.getInstance().getClassLoader() )
return createBaseCarMediaURL();
return TRADITIONAL_MEDIA_BASE;
}
/**
Returns a media base appropriate for the resource path passed in. The
resource path is the path to the resource within its channel archive.
(See org.jasig.portal.car.CarResources class for more information.)
If the passed in resourcePath matches that of a resource loaded from
CARs then this method returns a URL appropriate to obtain CAR
deployed, web-visible resources. Otherwise it returns a URL to the
traditional media path under the uPortal web application's document
root.
*/
public String getBaseMediaURL( String resourcePath )
throws PortalException
{
if ( resourcePath == null || resourcePath.equals(WEB_APP_BASE))
return TRADITIONAL_MEDIA_BASE;
if ( resourcePath.equals(CAR_BASE))
return createBaseCarMediaURL();
if ( CarResources.getInstance().containsResource( resourcePath ) )
return createBaseCarMediaURL();
return TRADITIONAL_MEDIA_BASE;
}
/**
* Creates the CAR media base URL.
*/
private String createBaseCarMediaURL() throws PortalException {
String url = getBaseWorkerURL( CarResources.CAR_WORKER_ID, true );
return url.concat( "?" + CarResources.CAR_RESOURCE_PARM + "=" );
}
/**
* Returns the URL to invoke one of the workers specified in PortalSessionManager.
* Typically the channel that is invoked with the worker will have to implement an
* interface specific for that worker.
* @param worker - Worker string must be a UPFileSpec.xxx value.
* @param idempotent a <code>boolean</code> value sepcifying if a URL should be idempotent
* @return URL to invoke the worker.
* @exception PortalException if an error occurs
*/
public String getBaseWorkerURL(String worker, boolean idempotent) throws PortalException {
String url=null;
UPFileSpec upfs=new UPFileSpec(channelUPFile);
upfs.setMethod(UPFileSpec.WORKER_METHOD);
upfs.setMethodNodeId(worker);
if(idempotent) {
upfs.setTagId(PortalSessionManager.IDEMPOTENT_URL_TAG);
}
url=upfs.getUPFile();
return url;
}
/**
* Tells whether or not the channel is rendering as the root of the layout.
* @return <code>true</code> if channel is rendering as the root, otherwise <code>false</code>
*/
public boolean isRenderingAsRoot() {
return renderingAsRoot;
}
/**
* Tells whether or not the channel is currently targeted. A channel is targeted
* if an incoming request specifies the channel's subscribe ID as the targeted node ID.
* @return <code>true</code> if channel is targeted, otherwise <code>false</code>
*/
public boolean isTargeted() {
return targeted;
}
/**
* Get a parameter value. If the parameter has multiple values, only the first value is returned.
*
* @param pName parameter name
* @return parameter value
*/
public String getParameter(String pName) {
String[] value_array = this.getParameterValues(pName);
if ((value_array != null) && (value_array.length > 0))
return value_array[0];
else
return null;
}
/**
* Obtain an <code>Object</code> parameter value. If the parameter has multiple values, only the first value is returned.
*
* @param pName parameter name
* @return parameter value
*/
public Object getObjectParameter(String pName) {
Object[] value_array = this.getObjectParameterValues(pName);
if ((value_array != null) && (value_array.length > 0)) {
return value_array[0];
} else {
return null;
}
}
/**
* Obtain all values for a given parameter.
*
* @param pName parameter name
* @return an array of parameter string values
*/
public String[] getParameterValues(String pName) {
Object[] pars = (Object[])super.get(pName);
if (pars instanceof String[]) {
return (String[])pars;
} else {
return null;
}
}
/**
* Obtain all values for a given parameter as <code>Object</code>s.
*
* @param pName parameter name
* @return a vector of parameter <code>Object[]</code> values
*/
public Object[] getObjectParameterValues(String pName) {
return (Object[])super.get(pName);
}
/**
* Get an enumeration of parameter names.
*
* @return an <code>Enumeration</code> of parameter names.
*/
public Enumeration getParameterNames() {
return (Enumeration)super.keys();
}
/**
* Get the parameters as a Map
* @return a Map of parameter name-value pairs
*/
public Map getParameters() {
Map params = new java.util.HashMap(this.size());
Enumeration e = this.getParameterNames();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
String value = this.getParameter(name);
params.put(name, value);
}
return params;
}
/**
* Sets the keywords
* @param keywords a String of keywords
*/
public void setKeywords(String keywords) {
this.keywords = keywords;
}
/**
* Returns the keywords
* @return a String of keywords, null if there were none
*/
public String getKeywords() {
return keywords;
}
/**
* @return the remote address
*/
public String getRemoteAddress() {
return remoteAddress;
}
/**
* @param string
*/
public void setRemoteAddress(String string) {
remoteAddress = string;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("ChannelRuntimeData: map=[").append(super.toString()).append("]");
sb.append(" browserInfo = [").append(this.binfo).append("] ");
sb.append(" locales = [").append(this.locales).append("] ");
sb.append(" channelUPFile = [").append(this.channelUPFile).append("] ");
sb.append(" baseActionURL = [").append(this.baseActionURL).append("] ");
sb.append(" httpRequestMethod = [").append(this.httpRequestMethod).append("] ");
sb.append(" remoteAddress = [").append(this.remoteAddress).append("] ");
sb.append(" keywords = [").append(this.keywords).append("] ");
sb.append(" renderingAsRoot = [").append(this.renderingAsRoot).append("] ");
sb.append(" targeted = [").append(this.targeted).append("]");
return sb.toString();
}
}
|
package org.jfree.chart.title;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.jfree.chart.block.AbstractBlock;
import org.jfree.chart.block.Block;
import org.jfree.chart.block.LengthConstraintType;
import org.jfree.chart.block.RectangleConstraint;
import org.jfree.chart.util.GradientPaintTransformer;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.PaintUtilities;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.chart.util.RectangleAnchor;
import org.jfree.chart.util.SerialUtilities;
import org.jfree.chart.util.ShapeUtilities;
import org.jfree.chart.util.Size2D;
import org.jfree.chart.util.StandardGradientPaintTransformer;
/**
* The graphical item within a legend item.
*/
public class LegendGraphic extends AbstractBlock
implements Block, PublicCloneable {
/**
* A flag that controls whether or not the shape is visible - see also
* lineVisible.
*/
private boolean shapeVisible;
/**
* The shape to display. To allow for accurate positioning, the center
* of the shape should be at (0, 0).
*/
private transient Shape shape;
/**
* Defines the location within the block to which the shape will be aligned.
*/
private RectangleAnchor shapeLocation;
/**
* Defines the point on the shape's bounding rectangle that will be
* aligned to the drawing location when the shape is rendered.
*/
private RectangleAnchor shapeAnchor;
/** A flag that controls whether or not the shape is filled. */
private boolean shapeFilled;
/** The fill paint for the shape. */
private transient Paint fillPaint;
/**
* The fill paint transformer (used if the fillPaint is an instance of
* GradientPaint).
*
* @since 1.0.4
*/
private GradientPaintTransformer fillPaintTransformer;
/** A flag that controls whether or not the shape outline is visible. */
private boolean shapeOutlineVisible;
/** The outline paint for the shape. */
private transient Paint outlinePaint;
/** The outline stroke for the shape. */
private transient Stroke outlineStroke;
/**
* A flag that controls whether or not the line is visible - see also
* shapeVisible.
*/
private boolean lineVisible;
/** The line. */
private transient Shape line;
/** The line stroke. */
private transient Stroke lineStroke;
/** The line paint. */
private transient Paint linePaint;
/**
* Creates a new legend graphic.
*
* @param shape the shape (<code>null</code> not permitted).
* @param fillPaint the fill paint (<code>null</code> not permitted).
*/
public LegendGraphic(Shape shape, Paint fillPaint) {
if (shape == null) {
throw new IllegalArgumentException("Null 'shape' argument.");
}
if (fillPaint == null) {
throw new IllegalArgumentException("Null 'fillPaint' argument.");
}
this.shapeVisible = true;
this.shape = shape;
this.shapeAnchor = RectangleAnchor.CENTER;
this.shapeLocation = RectangleAnchor.CENTER;
this.shapeFilled = true;
this.fillPaint = fillPaint;
this.fillPaintTransformer = new StandardGradientPaintTransformer();
setPadding(2.0, 2.0, 2.0, 2.0);
}
/**
* Returns a flag that controls whether or not the shape
* is visible.
*
* @return A boolean.
*
* @see #setShapeVisible(boolean)
*/
public boolean isShapeVisible() {
return this.shapeVisible;
}
/**
* Sets a flag that controls whether or not the shape is
* visible.
*
* @param visible the flag.
*
* @see #isShapeVisible()
*/
public void setShapeVisible(boolean visible) {
this.shapeVisible = visible;
}
/**
* Returns the shape.
*
* @return The shape.
*
* @see #setShape(Shape)
*/
public Shape getShape() {
return this.shape;
}
/**
* Sets the shape.
*
* @param shape the shape.
*
* @see #getShape()
*/
public void setShape(Shape shape) {
this.shape = shape;
}
/**
* Returns a flag that controls whether or not the shapes
* are filled.
*
* @return A boolean.
*
* @see #setShapeFilled(boolean)
*/
public boolean isShapeFilled() {
return this.shapeFilled;
}
/**
* Sets a flag that controls whether or not the shape is
* filled.
*
* @param filled the flag.
*
* @see #isShapeFilled()
*/
public void setShapeFilled(boolean filled) {
this.shapeFilled = filled;
}
/**
* Returns the paint used to fill the shape.
*
* @return The fill paint.
*
* @see #setFillPaint(Paint)
*/
public Paint getFillPaint() {
return this.fillPaint;
}
/**
* Sets the paint used to fill the shape.
*
* @param paint the paint.
*
* @see #getFillPaint()
*/
public void setFillPaint(Paint paint) {
this.fillPaint = paint;
}
/**
* Returns the transformer used when the fill paint is an instance of
* <code>GradientPaint</code>.
*
* @return The transformer (never <code>null</code>).
*
* @since 1.0.4.
*
* @see #setFillPaintTransformer(GradientPaintTransformer)
*/
public GradientPaintTransformer getFillPaintTransformer() {
return this.fillPaintTransformer;
}
/**
* Sets the transformer used when the fill paint is an instance of
* <code>GradientPaint</code>.
*
* @param transformer the transformer (<code>null</code> not permitted).
*
* @since 1.0.4
*
* @see #getFillPaintTransformer()
*/
public void setFillPaintTransformer(GradientPaintTransformer transformer) {
if (transformer == null) {
throw new IllegalArgumentException("Null 'transformer' argument.");
}
this.fillPaintTransformer = transformer;
}
/**
* Returns a flag that controls whether the shape outline is visible.
*
* @return A boolean.
*
* @see #setShapeOutlineVisible(boolean)
*/
public boolean isShapeOutlineVisible() {
return this.shapeOutlineVisible;
}
/**
* Sets a flag that controls whether or not the shape outline
* is visible.
*
* @param visible the flag.
*
* @see #isShapeOutlineVisible()
*/
public void setShapeOutlineVisible(boolean visible) {
this.shapeOutlineVisible = visible;
}
/**
* Returns the outline paint.
*
* @return The paint.
*
* @see #setOutlinePaint(Paint)
*/
public Paint getOutlinePaint() {
return this.outlinePaint;
}
/**
* Sets the outline paint.
*
* @param paint the paint.
*
* @see #getOutlinePaint()
*/
public void setOutlinePaint(Paint paint) {
this.outlinePaint = paint;
}
/**
* Returns the outline stroke.
*
* @return The stroke.
*
* @see #setOutlineStroke(Stroke)
*/
public Stroke getOutlineStroke() {
return this.outlineStroke;
}
/**
* Sets the outline stroke.
*
* @param stroke the stroke.
*
* @see #getOutlineStroke()
*/
public void setOutlineStroke(Stroke stroke) {
this.outlineStroke = stroke;
}
/**
* Returns the shape anchor.
*
* @return The shape anchor.
*
* @see #getShapeAnchor()
*/
public RectangleAnchor getShapeAnchor() {
return this.shapeAnchor;
}
/**
* Sets the shape anchor. This defines a point on the shapes bounding
* rectangle that will be used to align the shape to a location.
*
* @param anchor the anchor (<code>null</code> not permitted).
*
* @see #setShapeAnchor(RectangleAnchor)
*/
public void setShapeAnchor(RectangleAnchor anchor) {
if (anchor == null) {
throw new IllegalArgumentException("Null 'anchor' argument.");
}
this.shapeAnchor = anchor;
}
/**
* Returns the shape location.
*
* @return The shape location.
*
* @see #setShapeLocation(RectangleAnchor)
*/
public RectangleAnchor getShapeLocation() {
return this.shapeLocation;
}
/**
* Sets the shape location. This defines a point within the drawing
* area that will be used to align the shape to.
*
* @param location the location (<code>null</code> not permitted).
*
* @see #getShapeLocation()
*/
public void setShapeLocation(RectangleAnchor location) {
if (location == null) {
throw new IllegalArgumentException("Null 'location' argument.");
}
this.shapeLocation = location;
}
/**
* Returns the flag that controls whether or not the line is visible.
*
* @return A boolean.
*
* @see #setLineVisible(boolean)
*/
public boolean isLineVisible() {
return this.lineVisible;
}
/**
* Sets the flag that controls whether or not the line is visible.
*
* @param visible the flag.
*
* @see #isLineVisible()
*/
public void setLineVisible(boolean visible) {
this.lineVisible = visible;
}
/**
* Returns the line centered about (0, 0).
*
* @return The line.
*
* @see #setLine(Shape)
*/
public Shape getLine() {
return this.line;
}
/**
* Sets the line. A Shape is used here, because then you can use Line2D,
* GeneralPath or any other Shape to represent the line.
*
* @param line the line.
*
* @see #getLine()
*/
public void setLine(Shape line) {
this.line = line;
}
/**
* Returns the line paint.
*
* @return The paint.
*
* @see #setLinePaint(Paint)
*/
public Paint getLinePaint() {
return this.linePaint;
}
/**
* Sets the line paint.
*
* @param paint the paint.
*
* @see #getLinePaint()
*/
public void setLinePaint(Paint paint) {
this.linePaint = paint;
}
/**
* Returns the line stroke.
*
* @return The stroke.
*
* @see #setLineStroke(Stroke)
*/
public Stroke getLineStroke() {
return this.lineStroke;
}
/**
* Sets the line stroke.
*
* @param stroke the stroke.
*
* @see #getLineStroke()
*/
public void setLineStroke(Stroke stroke) {
this.lineStroke = stroke;
}
/**
* Arranges the contents of the block, within the given constraints, and
* returns the block size.
*
* @param g2 the graphics device.
* @param constraint the constraint (<code>null</code> not permitted).
*
* @return The block size (in Java2D units, never <code>null</code>).
*/
public Size2D arrange(Graphics2D g2, RectangleConstraint constraint) {
RectangleConstraint contentConstraint = toContentConstraint(constraint);
LengthConstraintType w = contentConstraint.getWidthConstraintType();
LengthConstraintType h = contentConstraint.getHeightConstraintType();
Size2D contentSize = null;
if (w == LengthConstraintType.NONE) {
if (h == LengthConstraintType.NONE) {
contentSize = arrangeNN(g2);
}
else if (h == LengthConstraintType.RANGE) {
throw new RuntimeException("Not yet implemented.");
}
else if (h == LengthConstraintType.FIXED) {
throw new RuntimeException("Not yet implemented.");
}
}
else if (w == LengthConstraintType.RANGE) {
if (h == LengthConstraintType.NONE) {
throw new RuntimeException("Not yet implemented.");
}
else if (h == LengthConstraintType.RANGE) {
throw new RuntimeException("Not yet implemented.");
}
else if (h == LengthConstraintType.FIXED) {
throw new RuntimeException("Not yet implemented.");
}
}
else if (w == LengthConstraintType.FIXED) {
if (h == LengthConstraintType.NONE) {
throw new RuntimeException("Not yet implemented.");
}
else if (h == LengthConstraintType.RANGE) {
throw new RuntimeException("Not yet implemented.");
}
else if (h == LengthConstraintType.FIXED) {
contentSize = new Size2D(
contentConstraint.getWidth(),
contentConstraint.getHeight()
);
}
}
return new Size2D(
calculateTotalWidth(contentSize.getWidth()),
calculateTotalHeight(contentSize.getHeight())
);
}
/**
* Performs the layout with no constraint, so the content size is
* determined by the bounds of the shape and/or line drawn to represent
* the series.
*
* @param g2 the graphics device.
*
* @return The content size.
*/
protected Size2D arrangeNN(Graphics2D g2) {
Rectangle2D contentSize = new Rectangle2D.Double();
if (this.line != null) {
contentSize.setRect(this.line.getBounds2D());
}
if (this.shape != null) {
contentSize = contentSize.createUnion(this.shape.getBounds2D());
}
return new Size2D(contentSize.getWidth(), contentSize.getHeight());
}
/**
* Draws the graphic item within the specified area.
*
* @param g2 the graphics device.
* @param area the area.
*/
public void draw(Graphics2D g2, Rectangle2D area) {
area = trimMargin(area);
drawBorder(g2, area);
area = trimBorder(area);
area = trimPadding(area);
if (this.lineVisible) {
Point2D location = RectangleAnchor.coordinates(area,
this.shapeLocation);
Shape aLine = ShapeUtilities.createTranslatedShape(getLine(),
this.shapeAnchor, location.getX(), location.getY());
g2.setPaint(this.linePaint);
g2.setStroke(this.lineStroke);
g2.draw(aLine);
}
if (this.shapeVisible) {
Point2D location = RectangleAnchor.coordinates(area,
this.shapeLocation);
Shape s = ShapeUtilities.createTranslatedShape(this.shape,
this.shapeAnchor, location.getX(), location.getY());
if (this.shapeFilled) {
Paint p = this.fillPaint;
if (p instanceof GradientPaint) {
GradientPaint gp = (GradientPaint) this.fillPaint;
p = this.fillPaintTransformer.transform(gp, s);
}
g2.setPaint(p);
g2.fill(s);
}
if (this.shapeOutlineVisible) {
g2.setPaint(this.outlinePaint);
g2.setStroke(this.outlineStroke);
g2.draw(s);
}
}
}
/**
* Draws the block within the specified area.
*
* @param g2 the graphics device.
* @param area the area.
* @param params ignored (<code>null</code> permitted).
*
* @return Always <code>null</code>.
*/
public Object draw(Graphics2D g2, Rectangle2D area, Object params) {
draw(g2, area);
return null;
}
/**
* Tests this <code>LegendGraphic</code> instance for equality with an
* arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (!(obj instanceof LegendGraphic)) {
return false;
}
LegendGraphic that = (LegendGraphic) obj;
if (this.shapeVisible != that.shapeVisible) {
return false;
}
if (!ShapeUtilities.equal(this.shape, that.shape)) {
return false;
}
if (this.shapeFilled != that.shapeFilled) {
return false;
}
if (!PaintUtilities.equal(this.fillPaint, that.fillPaint)) {
return false;
}
if (!ObjectUtilities.equal(this.fillPaintTransformer,
that.fillPaintTransformer)) {
return false;
}
if (this.shapeOutlineVisible != that.shapeOutlineVisible) {
return false;
}
if (!PaintUtilities.equal(this.outlinePaint, that.outlinePaint)) {
return false;
}
if (!ObjectUtilities.equal(this.outlineStroke, that.outlineStroke)) {
return false;
}
if (this.shapeAnchor != that.shapeAnchor) {
return false;
}
if (this.shapeLocation != that.shapeLocation) {
return false;
}
if (this.lineVisible != that.lineVisible) {
return false;
}
if (!ShapeUtilities.equal(this.line, that.line)) {
return false;
}
if (!PaintUtilities.equal(this.linePaint, that.linePaint)) {
return false;
}
if (!ObjectUtilities.equal(this.lineStroke, that.lineStroke)) {
return false;
}
return super.equals(obj);
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
public int hashCode() {
int result = 193;
result = 37 * result + ObjectUtilities.hashCode(this.fillPaint);
// FIXME: use other fields too
return result;
}
/**
* Returns a clone of this <code>LegendGraphic</code> instance.
*
* @return A clone of this <code>LegendGraphic</code> instance.
*
* @throws CloneNotSupportedException if there is a problem cloning.
*/
public Object clone() throws CloneNotSupportedException {
LegendGraphic clone = (LegendGraphic) super.clone();
clone.shape = ShapeUtilities.clone(this.shape);
clone.line = ShapeUtilities.clone(this.line);
return clone;
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writeShape(this.shape, stream);
SerialUtilities.writePaint(this.fillPaint, stream);
SerialUtilities.writePaint(this.outlinePaint, stream);
SerialUtilities.writeStroke(this.outlineStroke, stream);
SerialUtilities.writeShape(this.line, stream);
SerialUtilities.writePaint(this.linePaint, stream);
SerialUtilities.writeStroke(this.lineStroke, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.shape = SerialUtilities.readShape(stream);
this.fillPaint = SerialUtilities.readPaint(stream);
this.outlinePaint = SerialUtilities.readPaint(stream);
this.outlineStroke = SerialUtilities.readStroke(stream);
this.line = SerialUtilities.readShape(stream);
this.linePaint = SerialUtilities.readPaint(stream);
this.lineStroke = SerialUtilities.readStroke(stream);
}
}
|
package com.opengamma.master.historicaltimeseries.impl;
import java.text.MessageFormat;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TransferQueue;
import java.util.concurrent.atomic.AtomicInteger;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.apache.commons.lang.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.threeten.bp.LocalDate;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.id.ExternalId;
import com.opengamma.id.ExternalIdBundle;
import com.opengamma.id.ExternalIdWithDates;
import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesResolutionResult;
import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesResolver;
import com.opengamma.master.historicaltimeseries.ManageableHistoricalTimeSeriesInfo;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.ehcache.EHCacheUtils;
import com.opengamma.util.tuple.Triple;
/**
* A <code>HistoricalTimeSeriesResolver</code> that tries to find the distribution spec in a cache. If it doesn't find it, it will delegate to an underlying <code>HistoricalTimeSeriesResolver</code>.
*/
public class EHCachingHistoricalTimeSeriesResolver implements HistoricalTimeSeriesResolver {
private static final Logger s_logger = LoggerFactory.getLogger(EHCachingHistoricalTimeSeriesResolver.class);
private final class ThreadLocalWorker {
private final TransferQueue<ThreadLocalWorker> _waiting = new LinkedTransferQueue<ThreadLocalWorker>();
private ExternalIdBundle _identifierBundle;
private LocalDate _identifierValidityDate;
private String _dataSource;
private String _dataProvider;
private String _dataField;
private String _resolutionKey;
private boolean _haveResult;
private HistoricalTimeSeriesResolutionResult _result;
private RuntimeException _error;
public void init(final ExternalIdBundle identifierBundle, final LocalDate identifierValidityDate, final String dataSource, final String dataProvider, final String dataField,
final String resolutionKey) {
_identifierBundle = identifierBundle;
_identifierValidityDate = identifierValidityDate;
_dataSource = dataSource;
_dataProvider = dataProvider;
_dataField = dataField;
_resolutionKey = resolutionKey;
}
// Caller must hold the monitor
public void setResult(final HistoricalTimeSeriesResolutionResult result) {
ThreadLocalWorker waiting = _waiting.poll();
if (waiting != null) {
do {
waiting._haveResult = true;
waiting._result = result;
waiting = _waiting.poll();
} while (waiting != null);
notifyAll();
}
}
// Caller must hold the monitor
public void setError(final RuntimeException error) {
ThreadLocalWorker waiting = _waiting.poll();
if (waiting != null) {
do {
waiting._haveResult = true;
waiting._error = error;
waiting = _waiting.poll();
} while (waiting != null);
notifyAll();
}
}
// Caller must hold the monitor on the delegate
public HistoricalTimeSeriesResolutionResult getResult(ThreadLocalWorker delegate) {
_haveResult = false;
delegate._waiting.add(this);
while (!_haveResult) {
try {
delegate.wait();
} catch (InterruptedException e) {
throw new OpenGammaRuntimeException("Interrupted", e);
}
}
final RuntimeException e = _error;
if (e != null) {
_error = null;
throw e;
}
HistoricalTimeSeriesResolutionResult result = _result;
_result = null;
return result;
}
@Override
public boolean equals(final Object o) {
ThreadLocalWorker other = (ThreadLocalWorker) o;
return ObjectUtils.equals(_identifierBundle, other._identifierBundle)
&& ObjectUtils.equals(_identifierValidityDate, other._identifierValidityDate)
&& ObjectUtils.equals(_dataSource, other._dataSource)
&& ObjectUtils.equals(_dataProvider, other._dataProvider)
&& ObjectUtils.equals(_dataField, other._dataField)
&& ObjectUtils.equals(_resolutionKey, other._resolutionKey);
}
@Override
public int hashCode() {
int hc = ObjectUtils.hashCode(_identifierBundle);
hc += (hc << 4) + ObjectUtils.hashCode(_identifierValidityDate);
hc += (hc << 4) + ObjectUtils.hashCode(_dataSource);
hc += (hc << 4) + ObjectUtils.hashCode(_dataProvider);
hc += (hc << 4) + ObjectUtils.hashCode(_dataField);
hc += (hc << 4) + ObjectUtils.hashCode(_resolutionKey);
return hc;
}
}
private static final String SEPARATOR = "~";
/**
* Cache key format for hts resolution.
*/
private static final String HISTORICAL_TIME_SERIES_RESOLUTION_CACHE_FORMAT = "htsResolution.{0}";
/**
* Default cache key format arg.
*/
private static final String HISTORICAL_TIME_SERIES_RESOLUTION_CACHE_DEFAULT_ARG = "DEFAULT";
private final HistoricalTimeSeriesResolver _underlying;
/**
* The cache manager.
*/
private final CacheManager _cacheManager;
/**
* The reference data cache.
*/
private final Cache _cache;
private static final int OPTIMISTIC_ON = 1;
private static final int OPTIMISTIC_AUTO = 2;
private volatile int _optimisticFieldResolution = OPTIMISTIC_ON | OPTIMISTIC_AUTO;
private final AtomicInteger _optimisticFieldMetric1 = new AtomicInteger();
private final AtomicInteger _optimisticFieldMetric2 = new AtomicInteger();
private final ThreadLocal<ThreadLocalWorker> _worker = new ThreadLocal<ThreadLocalWorker>() {
@Override
protected ThreadLocalWorker initialValue() {
return new ThreadLocalWorker();
}
};
private final ConcurrentMap<ThreadLocalWorker, ThreadLocalWorker> _workers = new ConcurrentHashMap<ThreadLocalWorker, ThreadLocalWorker>();
// TODO: Do we need optimistic identifier resolution? E.g. are there graphs with large number of currency identifiers as their targets and nothing in HTS for them?
public EHCachingHistoricalTimeSeriesResolver(final HistoricalTimeSeriesResolver underlying, final CacheManager cacheManager) {
this(underlying, cacheManager, HISTORICAL_TIME_SERIES_RESOLUTION_CACHE_DEFAULT_ARG);
}
public EHCachingHistoricalTimeSeriesResolver(final HistoricalTimeSeriesResolver underlying, final CacheManager cacheManager, String cacheName) {
ArgumentChecker.notNull(underlying, "Underlying HistoricalTimeSeriesResolver");
ArgumentChecker.notNull(cacheManager, "cacheManager");
ArgumentChecker.notNull(cacheName, "cacheName");
_underlying = underlying;
_cacheManager = cacheManager;
String combinedCacheName = MessageFormat.format(HISTORICAL_TIME_SERIES_RESOLUTION_CACHE_FORMAT, cacheName);
EHCacheUtils.addCache(cacheManager, combinedCacheName);
_cache = EHCacheUtils.getCacheFromManager(cacheManager, combinedCacheName);
}
public CacheManager getCacheManager() {
return _cacheManager;
}
/**
* Sets whether to assume the time series is likely to exist or not. Optimistic resolution will always go to the underlying immediately. Pessimistic resolution will cache source/provider/field
* combinations that are known to exist or not exist and check these first to avoid hitting the underlying so heavily. If the resolutions will mostly succeed, use an optimistic mode. If the
* resolutions will mostly fail, use a pessimistic mode.
*
* @param optimisticResolution the mode to set
*/
public void setOptimisticFieldResolution(final boolean optimisticResolution) {
if (optimisticResolution) {
_optimisticFieldResolution |= OPTIMISTIC_ON;
} else {
_optimisticFieldResolution &= ~OPTIMISTIC_ON;
}
}
public boolean isOptimisticFieldResolution() {
return (_optimisticFieldResolution & OPTIMISTIC_ON) != 0;
}
/**
* Turns the automatic setting of the optimistic field resolution flag on/off.
*
* @param auto true to use the automatic setting algorithm, false to disable - call {@link #setOptimisticFieldResolution} to set a mode
*/
public void setAutomaticFieldResolutionOptimisation(final boolean auto) {
if (auto) {
_optimisticFieldResolution |= OPTIMISTIC_AUTO;
} else {
_optimisticFieldResolution &= ~OPTIMISTIC_AUTO;
}
}
public boolean isAutomaticFieldResolutionOptimisation() {
return (_optimisticFieldResolution & OPTIMISTIC_AUTO) != 0;
}
private void updateAutoFieldResolutionOptimisation() {
if (_optimisticFieldMetric2.incrementAndGet() == 1000) {
_optimisticFieldMetric2.set(0);
final int cmp = _optimisticFieldMetric1.getAndSet(0);
if (cmp < -500) {
boolean opt = !isOptimisticFieldResolution();
s_logger.info("Switching to {} field resolution ({})", opt ? "optimistic" : "pessimistic", cmp);
setOptimisticFieldResolution(opt);
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Staying with {} field resolution ({})", isOptimisticFieldResolution() ? "optimistic" : "pessimistic", cmp);
}
}
}
}
private boolean verifyInDatabase(final String dataSource, final String dataProvider, final String dataField) {
final Triple<String, String, String> key = Triple.of(dataSource, dataProvider, dataField);
if (_underlying.resolve(null, null, dataSource, dataProvider, dataField, null) != null) {
// There is something in the database
s_logger.debug("Verified {} in database", key);
_cache.put(new Element(key, Boolean.TRUE));
return true;
} else {
// There is nothing in the database for this combination
s_logger.debug("Verified {} absent from database", key);
_cache.put(new Element(key, null));
if (isAutomaticFieldResolutionOptimisation()) {
updateAutoFieldResolutionOptimisation();
}
return false;
}
}
protected HistoricalTimeSeriesResolutionResult resolveImpl(final ThreadLocalWorker worker, final ExternalIdBundle identifierBundle, final LocalDate identifierValidityDate,
final String dataSource, final String dataProvider, final String dataField, final String resolutionKey) {
boolean knownPresent = false;
Element e;
if ((identifierBundle != null) && isOptimisticFieldResolution()) {
knownPresent = true;
} else {
e = _cache.get(Triple.of(dataSource, dataProvider, dataField));
if (e != null) {
if (e.getObjectValue() == null) {
// We've already checked and there are NO time series with this source/provider/field combo
if (isAutomaticFieldResolutionOptimisation()) {
_optimisticFieldMetric1.incrementAndGet();
updateAutoFieldResolutionOptimisation();
}
return null;
} else {
// We know there's at least one time-series
knownPresent = true;
if (isAutomaticFieldResolutionOptimisation()) {
_optimisticFieldMetric1.decrementAndGet();
updateAutoFieldResolutionOptimisation();
}
}
} else {
s_logger.debug("No lookup information for {}", dataField);
}
}
if (identifierBundle == null) {
if (knownPresent || verifyInDatabase(dataSource, dataProvider, dataField)) {
return new HistoricalTimeSeriesResolutionResult(null);
} else {
return null;
}
}
HistoricalTimeSeriesResolutionResult resolveResult;
for (ExternalId id : identifierBundle) {
String key = id.toString() + SEPARATOR +
dataField + SEPARATOR +
(dataSource != null ? dataSource : "") + SEPARATOR +
(dataProvider != null ? dataProvider : "") + SEPARATOR +
resolutionKey;
e = _cache.get(key);
HistoricalTimeSeriesResolutionCacheItem cacheItem = e != null ? (HistoricalTimeSeriesResolutionCacheItem) e.getObjectValue() : null;
if (cacheItem != null) {
boolean isInvalid = cacheItem.isInvalid(identifierValidityDate);
resolveResult = !isInvalid ? cacheItem.get(identifierValidityDate) : null;
if (isInvalid || resolveResult != null) {
if (isAutomaticFieldResolutionOptimisation()) {
if (isOptimisticFieldResolution()) {
if (resolveResult != null) {
_optimisticFieldMetric1.incrementAndGet();
} else {
_optimisticFieldMetric1.decrementAndGet();
}
}
updateAutoFieldResolutionOptimisation();
}
return resolveResult;
}
}
}
if (!knownPresent) {
if (!verifyInDatabase(dataSource, dataProvider, dataField)) {
return null;
}
}
resolveResult = _underlying.resolve(identifierBundle, identifierValidityDate, dataSource, dataProvider, dataField, resolutionKey);
if (resolveResult != null) {
ManageableHistoricalTimeSeriesInfo info = resolveResult.getHistoricalTimeSeriesInfo();
for (ExternalIdWithDates id : info.getExternalIdBundle()) {
if (id.isValidOn(identifierValidityDate)) {
String key = id.getExternalId().toString() + SEPARATOR +
dataField + SEPARATOR +
info.getDataSource() + SEPARATOR +
info.getDataProvider() + SEPARATOR +
resolutionKey;
addResultToCache(key, id, resolveResult);
key = id.getExternalId().toString() + SEPARATOR +
dataField + SEPARATOR +
SEPARATOR +
info.getDataProvider() + SEPARATOR +
resolutionKey;
addResultToCache(key, id, resolveResult);
key = id.getExternalId().toString() + SEPARATOR +
dataField + SEPARATOR +
info.getDataSource() + SEPARATOR +
SEPARATOR +
resolutionKey;
addResultToCache(key, id, resolveResult);
key = id.getExternalId().toString() + SEPARATOR +
dataField + SEPARATOR +
SEPARATOR +
SEPARATOR +
resolutionKey;
addResultToCache(key, id, resolveResult);
}
}
if (isAutomaticFieldResolutionOptimisation()) {
if (isOptimisticFieldResolution()) {
_optimisticFieldMetric1.incrementAndGet();
}
updateAutoFieldResolutionOptimisation();
}
} else {
// PLAT-2633: Record resolution failures (misses) in the cache as well
for (ExternalId id : identifierBundle) {
String key = id.toString() + SEPARATOR +
dataField + SEPARATOR +
(dataSource != null ? dataSource : "") + SEPARATOR +
(dataProvider != null ? dataProvider : "") + SEPARATOR +
resolutionKey;
addInvalidDateToCache(key, identifierValidityDate, id);
}
if (isAutomaticFieldResolutionOptimisation()) {
if (isOptimisticFieldResolution()) {
_optimisticFieldMetric1.decrementAndGet();
}
updateAutoFieldResolutionOptimisation();
}
}
return resolveResult;
}
private void addResultToCache(String key, ExternalIdWithDates externalIdWithDates, HistoricalTimeSeriesResolutionResult result) {
Element cacheElement = _cache.get(key);
if (cacheElement == null) {
HistoricalTimeSeriesResolutionCacheItem cacheItem = new HistoricalTimeSeriesResolutionCacheItem(externalIdWithDates.getExternalId());
cacheElement = new Element(key, cacheItem);
Element existingCacheElement = _cache.putIfAbsent(cacheElement);
if (existingCacheElement != null) {
cacheElement = existingCacheElement;
}
}
HistoricalTimeSeriesResolutionCacheItem cacheItem = (HistoricalTimeSeriesResolutionCacheItem) cacheElement.getObjectValue();
cacheItem.put(externalIdWithDates, result);
}
private void addInvalidDateToCache(String key, LocalDate identifierValidityDate, ExternalId externalId) {
Element cacheElement = _cache.get(key);
if (cacheElement == null) {
HistoricalTimeSeriesResolutionCacheItem cacheItem = new HistoricalTimeSeriesResolutionCacheItem(externalId);
cacheElement = new Element(key, cacheItem);
Element existingCacheElement = _cache.putIfAbsent(cacheElement);
if (existingCacheElement != null) {
cacheElement = existingCacheElement;
}
}
HistoricalTimeSeriesResolutionCacheItem cacheItem = (HistoricalTimeSeriesResolutionCacheItem) cacheElement.getObjectValue();
cacheItem.putInvalid(identifierValidityDate);
}
/**
* Call this at the end of a unit test run to clear the state of EHCache. It should not be part of a generic lifecycle method.
*/
protected void shutdown() {
_cacheManager.removeCache(_cache.getName());
}
// HistoricalTimeSeriesResolver
@Override
public HistoricalTimeSeriesResolutionResult resolve(final ExternalIdBundle identifierBundle, final LocalDate identifierValidityDate,
final String dataSource, final String dataProvider, final String dataField, final String resolutionKey) {
final HistoricalTimeSeriesResolutionResult result;
ThreadLocalWorker worker = _worker.get();
worker.init(identifierBundle, identifierValidityDate, dataSource, dataProvider, dataField, resolutionKey);
do {
final ThreadLocalWorker delegate = _workers.putIfAbsent(worker, worker);
if (delegate == null) {
break;
} else {
synchronized (delegate) {
if (_workers.get(worker) == delegate) {
return worker.getResult(delegate);
}
}
}
} while (true);
try {
result = resolveImpl(worker, identifierBundle, identifierValidityDate, dataSource, dataProvider, dataField, resolutionKey);
synchronized (worker) {
worker.setResult(result);
_workers.remove(worker);
}
} catch (Throwable t) {
RuntimeException e;
if (t instanceof RuntimeException) {
e = (RuntimeException) t;
} else {
e = new OpenGammaRuntimeException("Checked exception", t);
}
synchronized (worker) {
worker.setError(e);
_workers.remove(worker);
}
throw e;
}
return result;
}
}
|
package org.jivesoftware.smack;
import org.xmlpull.v1.*;
import java.util.*;
import java.util.List;
import java.io.ObjectInputStream;
import java.io.ByteArrayInputStream;
import java.beans.PropertyDescriptor;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.provider.*;
/**
* Listens for XML traffic from the XMPP server and parses it into packet objects.
* The packet reader also manages all packet listeners and collectors.<p>
*
* @see PacketCollector
* @see PacketListener
* @author Matt Tucker
*/
class PacketReader {
/**
* Namespace used to store packet properties.
*/
private static final String PROPERTIES_NAMESPACE =
"http:
private Thread readerThread;
private Thread listenerThread;
private XMPPConnection connection;
private XmlPullParser parser;
private boolean done = false;
protected List collectors = new ArrayList();
private List listeners = new ArrayList();
protected List connectionListeners = new ArrayList();
private String connectionID = null;
private Object connectionIDLock = new Object();
protected PacketReader(XMPPConnection connection) {
this.connection = connection;
readerThread = new Thread() {
public void run() {
parsePackets();
}
};
readerThread.setName("Smack Packet Reader");
readerThread.setDaemon(true);
listenerThread = new Thread() {
public void run() {
processListeners();
}
};
listenerThread.setName("Smack Listener Processor");
listenerThread.setDaemon(true);
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance(
"org.xmlpull.mxp1.MXParserFactory", null);
factory.setNamespaceAware(true);
parser = factory.newPullParser();
parser.setInput(connection.reader);
}
catch (XmlPullParserException xppe) {
xppe.printStackTrace();
}
}
/**
* Creates a new packet collector for this reader. A packet filter determines
* which packets will be accumulated by the collector.
*
* @param packetFilter the packet filter to use.
* @return a new packet collector.
*/
public PacketCollector createPacketCollector(PacketFilter packetFilter) {
PacketCollector packetCollector = new PacketCollector(this, packetFilter);
return packetCollector;
}
/**
* Registers a packet listener with this reader. A packet filter determines
* which packets will be delivered to the listener.
*
* @param packetListener the packet listener to notify of new packets.
* @param packetFilter the packet filter to use.
*/
public void addPacketListener(PacketListener packetListener, PacketFilter packetFilter) {
ListenerWrapper wrapper = new ListenerWrapper(this, packetListener,
packetFilter);
synchronized (listeners) {
listeners.add(wrapper);
}
}
/**
* Removes a packet listener.
*
* @param packetListener the packet listener to remove.
*/
public void removePacketListener(PacketListener packetListener) {
synchronized (listeners) {
for (int i=0; i<listeners.size(); i++) {
ListenerWrapper wrapper = (ListenerWrapper)listeners.get(i);
if (wrapper != null && wrapper.packetListener.equals(packetListener)) {
listeners.set(i, null);
}
}
}
}
/**
* Starts the packet reader thread and returns once a connection to the server
* has been established. A connection will be attempted for a maximum of five
* seconds. An XMPPException will be thrown if the connection fails.
*
* @throws XMPPException if the server fails to send an opening stream back
* for more than five seconds.
*/
public void startup() throws XMPPException {
readerThread.start();
listenerThread.start();
// Wait for stream tag before returing. We'll wait a maximum of five seconds before
// giving up and throwing an error.
try {
synchronized(connectionIDLock) {
connectionIDLock.wait(5000);
}
}
catch (InterruptedException ie) { }
if (connectionID == null) {
throw new XMPPException("Connection failed. No response from server.");
}
else {
connection.connectionID = connectionID;
}
}
/**
* Shuts the packet reader down.
*/
public void shutdown() {
// Notify connection listeners of the connection closing if done hasn't already been set.
if (!done) {
synchronized (connectionListeners) {
for (Iterator i=connectionListeners.iterator(); i.hasNext(); ) {
ConnectionListener listener = (ConnectionListener)i.next();
listener.connectionClosed();
}
}
}
done = true;
}
/**
* Sends out a notification that there was an error with the connection
* and closes the connection.
*
* @param e the exception that causes the connection close event.
*/
void notifyConnectionError(Exception e) {
done = true;
connection.close();
// Notify connection listeners of the error.
synchronized (connectionListeners) {
for (Iterator i=connectionListeners.iterator(); i.hasNext(); ) {
ConnectionListener listener = (ConnectionListener)i.next();
listener.connectionClosedOnError(e);
}
}
}
/**
* Process listeners.
*/
private void processListeners() {
boolean processedPacket = false;
while (!done) {
synchronized (listeners) {
if (listeners.size() > 0) {
for (int i=listeners.size()-1; i>=0; i
if (listeners.get(i) == null) {
listeners.remove(i);
}
}
}
}
processedPacket = false;
int size = listeners.size();
for (int i=0; i<size; i++) {
ListenerWrapper wrapper = (ListenerWrapper)listeners.get(i);
if (wrapper != null) {
processedPacket = processedPacket || wrapper.notifyListener();
}
}
if (!processedPacket) {
try {
Thread.sleep(100);
}
catch (InterruptedException ie) { }
}
}
}
/**
* Parse top-level packets in order to process them further.
*/
private void parsePackets() {
try {
int eventType = parser.getEventType();
do {
if (eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals("message")) {
processPacket(parseMessage(parser));
}
else if (parser.getName().equals("iq")) {
processPacket(parseIQ(parser));
}
else if (parser.getName().equals("presence")) {
processPacket(parsePresence(parser));
}
// We found an opening stream. Record information about it, then notify
// the connectionID lock so that the packet reader startup can finish.
else if (parser.getName().equals("stream")) {
// Ensure the correct jabber:client namespace is being used.
if ("jabber:client".equals(parser.getNamespace(null))) {
// Get the connection id.
for (int i=0; i<parser.getAttributeCount(); i++) {
if (parser.getAttributeName(i).equals("id")) {
// Save the connectionID and notify that we've gotten it.
connectionID = parser.getAttributeValue(i);
synchronized(connectionIDLock) {
connectionIDLock.notifyAll();
}
}
else if (parser.getAttributeName(i).equals("from")) {
// Use the server name that the server says that it is.
connection.host = parser.getAttributeValue(i);
}
}
}
}
}
else if (eventType == XmlPullParser.END_TAG) {
if (parser.getName().equals("stream")) {
// Close the connection.
connection.close();
}
}
eventType = parser.next();
} while (!done && eventType != XmlPullParser.END_DOCUMENT);
}
catch (Exception e) {
if (!done) {
// Close the connection and notify connection listeners of the
// error.
notifyConnectionError(e);
}
}
}
/**
* Processes a packet after it's been fully parsed by looping through the installed
* packet collectors and listeners and letting them examine the packet to see if
* they are a match with the filter.
*
* @param packet the packet to process.
*/
private void processPacket(Packet packet) {
if (packet == null) {
return;
}
// Remove all null values from the collectors list.
synchronized (collectors) {
for (int i=collectors.size()-1; i>=0; i
if (collectors.get(i) == null) {
collectors.remove(i);
}
}
}
// Loop through all collectors and notify the appropriate ones.
int size = collectors.size();
for (int i=0; i<size; i++) {
PacketCollector collector = (PacketCollector)collectors.get(i);
if (collector != null) {
// Have the collector process the packet to see if it wants to handle it.
collector.processPacket(packet);
}
}
}
/**
* Parses an IQ packet.
*
* @param parser the XML parser, positioned at the start of an IQ packet.
* @return an IQ object.
* @throws Exception if an exception occurs while parsing the packet.
*/
private IQ parseIQ(XmlPullParser parser) throws Exception {
IQ iqPacket = null;
String id = parser.getAttributeValue("", "id");
String to = parser.getAttributeValue("", "to");
String from = parser.getAttributeValue("", "from");
IQ.Type type = IQ.Type.fromString(parser.getAttributeValue("", "type"));
XMPPError error = null;
boolean done = false;
while (!done) {
int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG) {
String elementName = parser.getName();
String namespace = parser.getNamespace();
if (elementName.equals("error")) {
error = parseError(parser);
}
else if (elementName.equals("query") && namespace.equals("jabber:iq:auth")) {
iqPacket = parseAuthentication(parser);
}
else if (elementName.equals("query") && namespace.equals("jabber:iq:roster")) {
iqPacket = parseRoster(parser);
}
else if (elementName.equals("query") && namespace.equals("jabber:iq:register")) {
iqPacket = parseRegistration(parser);
}
// Otherwise, see if there is a registered provider for
// this element name and namespace.
else {
Object provider = ProviderManager.getIQProvider(elementName, namespace);
if (provider != null) {
if (provider instanceof IQProvider) {
iqPacket = ((IQProvider)provider).parseIQ(parser);
}
else if (provider instanceof Class) {
iqPacket = (IQ)parseWithIntrospection(elementName,
(Class)provider, parser);
}
}
}
}
else if (eventType == XmlPullParser.END_TAG) {
if (parser.getName().equals("iq")) {
done = true;
}
}
}
// Decide what to do when an IQ packet was not understood
if (iqPacket == null) {
if (IQ.Type.GET == type || IQ.Type.SET == type ) {
// If the IQ stanza is of type "get" or "set" containing a child element
// qualified by a namespace it does not understand, then answer an IQ of
// type "error" with code 501 ("feature-not-implemented")
iqPacket = new IQ() {
public String getChildElementXML() {
return null;
}
};
iqPacket.setPacketID(id);
iqPacket.setTo(from);
iqPacket.setFrom(to);
iqPacket.setType(IQ.Type.ERROR);
iqPacket.setError(new XMPPError(501, "feature-not-implemented"));
connection.sendPacket(iqPacket);
return null;
}
else {
// If an IQ packet wasn't created above, create an empty IQ packet.
iqPacket = new IQ() {
public String getChildElementXML() {
return null;
}
};
}
}
// Set basic values on the iq packet.
iqPacket.setPacketID(id);
iqPacket.setTo(to);
iqPacket.setFrom(from);
iqPacket.setType(type);
iqPacket.setError(error);
return iqPacket;
}
private Authentication parseAuthentication(XmlPullParser parser) throws Exception {
Authentication authentication = new Authentication();
boolean done = false;
while (!done) {
int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals("username")) {
authentication.setUsername(parser.nextText());
}
else if (parser.getName().equals("password")) {
authentication.setPassword(parser.nextText());
}
else if (parser.getName().equals("digest")) {
authentication.setDigest(parser.nextText());
}
else if (parser.getName().equals("resource")) {
authentication.setResource(parser.nextText());
}
}
else if (eventType == XmlPullParser.END_TAG) {
if (parser.getName().equals("query")) {
done = true;
}
}
}
return authentication;
}
private RosterPacket parseRoster(XmlPullParser parser) throws Exception {
RosterPacket roster = new RosterPacket();
boolean done = false;
RosterPacket.Item item = null;
while (!done) {
int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals("item")) {
String jid = parser.getAttributeValue("", "jid");
String name = parser.getAttributeValue("", "name");
// Create packet.
item = new RosterPacket.Item(jid, name);
// Set status.
String ask = parser.getAttributeValue("", "ask");
RosterPacket.ItemStatus status = RosterPacket.ItemStatus.fromString(ask);
item.setItemStatus(status);
// Set type.
String subscription = parser.getAttributeValue("", "subscription");
RosterPacket.ItemType type = RosterPacket.ItemType.fromString(subscription);
item.setItemType(type);
}
if (parser.getName().equals("group")) {
String groupName = parser.nextText();
item.addGroupName(groupName);
}
}
else if (eventType == XmlPullParser.END_TAG) {
if (parser.getName().equals("item")) {
roster.addRosterItem(item);
}
if (parser.getName().equals("query")) {
done = true;
}
}
}
return roster;
}
private Registration parseRegistration(XmlPullParser parser) throws Exception {
Registration registration = new Registration();
Map fields = null;
boolean done = false;
while (!done) {
int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals("username")) {
registration.setUsername(parser.nextText());
}
else if (parser.getName().equals("password")) {
registration.setPassword(parser.nextText());
}
// Else if any other element that's in the jabber:iq:register namespace,
// attempt to parse it if it's in the form <name>value</name>.
else if (parser.getNamespace().equals("jabber:iq:register")) {
String name = parser.getName();
if (parser.next() == XmlPullParser.TEXT) {
String value = parser.getText();
// Ignore instructions, but anything else should be added to the map.
if (!name.equals("instructions")) {
if (fields == null) {
fields = new HashMap();
}
fields.put(name, value);
}
else {
registration.setInstructions(value);
}
}
}
}
else if (eventType == XmlPullParser.END_TAG) {
if (parser.getName().equals("query")) {
done = true;
}
}
}
registration.setAttributes(fields);
return registration;
}
private Object parseWithIntrospection(String elementName,
Class objectClass, XmlPullParser parser) throws Exception
{
boolean done = false;
Object object = objectClass.newInstance();
while (!done) {
int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG) {
String name = parser.getName();
String stringValue = parser.nextText();
PropertyDescriptor descriptor = new PropertyDescriptor(name, objectClass);
// Load the class type of the property.
Class propertyType = descriptor.getPropertyType();
// Get the value of the property by converting it from a
// String to the correct object type.
Object value = decode(propertyType, stringValue);
// Set the value of the bean.
descriptor.getWriteMethod().invoke(object, new Object[] { value });
}
else if (eventType == XmlPullParser.END_TAG) {
if (parser.getName().equals(elementName)) {
done = true;
}
}
}
return object;
}
/**
* Decodes a String into an object of the specified type. If the object
* type is not supported, null will be returned.
*
* @param type the type of the property.
* @param value the encode String value to decode.
* @return the String value decoded into the specified type.
*/
private static Object decode(Class type, String value) throws Exception {
if (type.getName().equals("java.lang.String")) {
return value;
}
if (type.getName().equals("boolean")) {
return Boolean.valueOf(value);
}
if (type.getName().equals("int")) {
return Integer.valueOf(value);
}
if (type.getName().equals("long")) {
return Long.valueOf(value);
}
if (type.getName().equals("float")) {
return Float.valueOf(value);
}
if (type.getName().equals("double")) {
return Double.valueOf(value);
}
if (type.getName().equals("java.lang.Class")) {
return Class.forName(value);
}
return null;
}
/**
* Parses error sub-packets.
*
* @param parser the XML parser.
* @return an error sub-packet.
* @throws Exception if an exception occurs while parsing the packet.
*/
private XMPPError parseError(XmlPullParser parser) throws Exception {
String errorCode = null;
String message = null;
for (int i=0; i<parser.getAttributeCount(); i++) {
if (parser.getAttributeName(i).equals("code")) {
errorCode = parser.getAttributeValue("", "code");
}
}
// Get the error text in a safe way since we are not sure about the error message format
try {
message = parser.nextText();
}
catch (XmlPullParserException ex) {}
while (true) {
if (parser.getEventType() == XmlPullParser.END_TAG && parser.getName().equals("error")) {
break;
}
parser.next();
}
return new XMPPError(Integer.parseInt(errorCode), message);
}
/**
* Parses a message packet.
*
* @param parser the XML parser, positioned at the start of a message packet.
* @return a Message packet.
* @throws Exception if an exception occurs while parsing the packet.
*/
private Packet parseMessage(XmlPullParser parser) throws Exception {
Message message = new Message();
message.setTo(parser.getAttributeValue("", "to"));
message.setFrom(parser.getAttributeValue("", "from"));
message.setType(Message.Type.fromString(parser.getAttributeValue("", "type")));
// Parse sub-elements. We include extra logic to make sure the values
// are only read once. This is because it's possible for the names to appear
// in arbitrary sub-elements.
boolean done = false;
String subject = null;
String body = null;
String thread = null;
Map properties = null;
while (!done) {
int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG) {
String elementName = parser.getName();
String namespace = parser.getNamespace();
if (elementName.equals("subject")) {
if (subject == null) {
subject = parser.nextText();
}
}
else if (elementName.equals("body")) {
if (body == null) {
body = parser.nextText();
}
}
else if (elementName.equals("thread")) {
if (thread == null) {
thread = parser.nextText();
}
}
else if (elementName.equals("error")) {
message.setError(parseError(parser));
}
else if (elementName.equals("properties") &&
namespace.equals(PROPERTIES_NAMESPACE))
{
properties = parseProperties(parser);
}
// Otherwise, it must be a packet extension.
else {
message.addExtension(parsePacketExtension(elementName, namespace, parser));
}
}
else if (eventType == XmlPullParser.END_TAG) {
if (parser.getName().equals("message")) {
done = true;
}
}
}
message.setSubject(subject);
message.setBody(body);
message.setThread(thread);
// Set packet properties.
if (properties != null) {
for (Iterator i=properties.keySet().iterator(); i.hasNext(); ) {
String name = (String)i.next();
message.setProperty(name, properties.get(name));
}
}
return message;
}
/**
* Parses a presence packet.
*
* @param parser the XML parser, positioned at the start of a presence packet.
* @return a Presence packet.
* @throws Exception if an exception occurs while parsing the packet.
*/
private Presence parsePresence(XmlPullParser parser) throws Exception {
Presence.Type type = Presence.Type.fromString(parser.getAttributeValue("", "type"));
Presence presence = new Presence(type);
presence.setTo(parser.getAttributeValue("", "to"));
presence.setFrom(parser.getAttributeValue("", "from"));
presence.setPacketID(parser.getAttributeValue("", "id"));
// Parse sub-elements
boolean done = false;
while (!done) {
int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG) {
String elementName = parser.getName();
String namespace = parser.getNamespace();
if (elementName.equals("status")) {
presence.setStatus(parser.nextText());
}
else if (elementName.equals("priority")) {
try {
int priority = Integer.parseInt(parser.nextText());
presence.setPriority(priority);
}
catch (NumberFormatException nfe) { }
}
else if (elementName.equals("show")) {
presence.setMode(Presence.Mode.fromString(parser.nextText()));
}
else if (elementName.equals("error")) {
presence.setError(parseError(parser));
}
else if (elementName.equals("properties") &&
namespace.equals(PROPERTIES_NAMESPACE))
{
Map properties = parseProperties(parser);
// Set packet properties.
for (Iterator i=properties.keySet().iterator(); i.hasNext(); ) {
String name = (String)i.next();
presence.setProperty(name, properties.get(name));
}
}
// Otherwise, it must be a packet extension.
else {
presence.addExtension(parsePacketExtension(elementName, namespace, parser));
}
}
else if (eventType == XmlPullParser.END_TAG) {
if (parser.getName().equals("presence")) {
done = true;
}
}
}
return presence;
}
/**
* Parses a packet extension sub-packet.
*
* @param elementName the XML element name of the packet extension.
* @param namespace the XML namespace of the packet extension.
* @param parser the XML parser, positioned at the starting element of the extension.
* @return a PacketExtension.
* @throws Exception if a parsing error occurs.
*/
private PacketExtension parsePacketExtension(String elementName, String namespace, XmlPullParser parser)
throws Exception
{
// See if a provider is registered to handle the extension.
Object provider = ProviderManager.getExtensionProvider(elementName, namespace);
if (provider != null) {
if (provider instanceof PacketExtensionProvider) {
return ((PacketExtensionProvider)provider).parseExtension(parser);
}
else if (provider instanceof Class) {
return (PacketExtension)parseWithIntrospection(
elementName, (Class)provider, parser);
}
}
// No providers registered, so use a default extension.
DefaultPacketExtension extension = new DefaultPacketExtension(elementName, namespace);
boolean done = false;
while (!done) {
int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG) {
String name = parser.getName();
// If an empty element, set the value with the empty string.
if (parser.isEmptyElementTag()) {
extension.setValue(name,"");
}
// Otherwise, get the the element text.
else {
eventType = parser.next();
if (eventType == XmlPullParser.TEXT) {
String value = parser.getText();
extension.setValue(name, value);
}
}
}
else if (eventType == XmlPullParser.END_TAG) {
if (parser.getName().equals(elementName)) {
done = true;
}
}
}
return extension;
}
/**
* Parse a properties sub-packet. If any errors occur while de-serializing Java object
* properties, an exception will be printed and not thrown since a thrown
* exception will shut down the entire connection. ClassCastExceptions will occur
* when both the sender and receiver of the packet don't have identical versions
* of the same class.
*
* @param parser the XML parser, positioned at the start of a properties sub-packet.
* @return a map of the properties.
* @throws Exception if an error occurs while parsing the properties.
*/
private Map parseProperties(XmlPullParser parser) throws Exception {
Map properties = new HashMap();
while (true) {
int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG && parser.getName().equals("property")) {
// Advance to name element.
parser.next();
String name = parser.nextText();
parser.next();
String type = parser.getAttributeValue("", "type");
String valueText = parser.nextText();
Object value = null;
if ("integer".equals(type)) {
value = new Integer(valueText);
}
else if ("long".equals(type)) {
value = new Long(valueText);
}
else if ("float".equals(type)) {
value = new Float(valueText);
}
else if ("double".equals(type)) {
value = new Double(valueText);
}
else if ("boolean".equals(type)) {
value = new Boolean(valueText);
}
else if ("string".equals(type)) {
value = valueText;
}
else if ("java-object".equals(type)) {
try {
byte [] bytes = StringUtils.decodeBase64(valueText);
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
value = in.readObject();
}
catch (Exception e) {
e.printStackTrace();
}
}
if (name != null && value != null) {
properties.put(name, value);
}
}
else if (eventType == XmlPullParser.END_TAG) {
if (parser.getName().equals("properties")) {
break;
}
}
}
return properties;
}
/**
* A wrapper class to associate a packet collector with a listener.
*/
private static class ListenerWrapper {
private PacketListener packetListener;
private PacketCollector packetCollector;
public ListenerWrapper(PacketReader packetReader, PacketListener packetListener,
PacketFilter packetFilter)
{
this.packetListener = packetListener;
this.packetCollector = new PacketCollector(packetReader, packetFilter);
}
public boolean equals(Object object) {
if (object == null) {
return false;
}
if (object instanceof ListenerWrapper) {
return ((ListenerWrapper)object).packetListener.equals(this.packetListener);
}
else if (object instanceof PacketListener) {
return object.equals(this.packetListener);
}
return false;
}
public boolean notifyListener() {
Packet packet = packetCollector.pollResult();
if (packet != null) {
packetListener.processPacket(packet);
return true;
}
else {
return false;
}
}
public void cancel() {
packetCollector.cancel();
packetCollector = null;
packetListener = null;
}
}
}
|
package com.google.refine.expr.functions.strings;
import java.util.Properties;
import org.json.JSONException;
import org.json.JSONWriter;
import com.google.gdata.util.common.base.CharMatcher;
import com.google.refine.grel.Function;
public class Trim implements Function {
@Override
public Object call(Properties bindings, Object[] args) {
if (args.length == 1) {
Object s1 = args[0];
if (s1 != null && s1 instanceof String) {
return CharMatcher.WHITESPACE.trimFrom((String) s1);
}
}
return null;
}
@Override
public void write(JSONWriter writer, Properties options)
throws JSONException {
writer.object();
writer.key("description"); writer.value("Returns copy of the string, with leading and trailing whitespace omitted.");
writer.key("params"); writer.value("string s");
writer.key("returns"); writer.value("string");
writer.endObject();
}
}
|
//Prevayler(TM) - The Free-Software Prevalence Layer.
//Contributions: Aleksey Aristov, Carlos Villela, Justin Sampson.
package org.prevayler;
import java.io.IOException;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.prevayler.foundation.monitor.Monitor;
import org.prevayler.foundation.monitor.SimpleMonitor;
import org.prevayler.foundation.network.OldNetworkImpl;
import org.prevayler.foundation.serialization.JavaSerializer;
import org.prevayler.foundation.serialization.Serializer;
import org.prevayler.foundation.serialization.XStreamSerializer;
import org.prevayler.implementation.PrevaylerDirectory;
import org.prevayler.implementation.PrevaylerImpl;
import org.prevayler.implementation.clock.MachineClock;
import org.prevayler.implementation.journal.Journal;
import org.prevayler.implementation.journal.PersistentJournal;
import org.prevayler.implementation.journal.TransientJournal;
import org.prevayler.implementation.publishing.CentralPublisher;
import org.prevayler.implementation.publishing.TransactionPublisher;
import org.prevayler.implementation.replication.ClientPublisher;
import org.prevayler.implementation.replication.ServerListener;
import org.prevayler.implementation.snapshot.GenericSnapshotManager;
import org.prevayler.implementation.snapshot.NullSnapshotManager;
public class PrevaylerFactory<P>{
private P _prevalentSystem;
private Clock _clock;
private boolean _transactionDeepCopyMode = true;
private boolean _transientMode;
private String _prevalenceDirectory;
private NullSnapshotManager<P> _nullSnapshotManager;
private long _journalSizeThreshold;
private long _journalAgeThreshold;
private boolean _journalDiskSync = true;
private int _serverPort = -1;
private String _remoteServerIpAddress;
private int _remoteServerPort;
public static final int DEFAULT_REPLICATION_PORT = 8756;
private Monitor _monitor;
private Serializer _journalSerializer;
private String _journalSuffix;
private Map _snapshotSerializers = new HashMap();
private String _primarySnapshotSuffix;
/**
* <i>Example:</i>
* <br><code>
* <br>PrevaylerFactory<MyObjectToPersist> f = new PrevaylerFactory<MyObjectToPersist>();
* <br></code>
* <br>Use if you want access to any configuration options not available via the static method short-cuts.
*/
public PrevaylerFactory(){}
/** Creates a Prevayler that will use the given prevalenceBase directory to read and write its .snapshot and .journal files, using standard Java serialization/deserialization. This requires that the Prevalent System and all Transaction implementations used by the Prevayler are Java-Serializable.
* <br>
* <br><i>Example:</i>
* <br><code>
* <br><i>//Your object:</i>
* <br>MyObjectToPersist newPrevalentSystem = new MyObjectToPersist();
* <br>String prevalenceBase = "myDirectory";
* <br><b>Prevayler<MyObjectToPersist> prevayler = PrevaylerFactory.createPrevayler(newPrevalentSystem, prevalenceBase);</b>
* <br></code>
* @param newPrevalentSystem The newly started, "empty" prevalent system that will be used as a starting point for every system startup, until the first snapshot is taken.
* @param prevalenceBase The directory where the .snapshot files and .journal files will be read and written.
*/
public static <P> Prevayler<P> createPrevayler(P newPrevalentSystem, String prevalenceBase) throws Exception {
PrevaylerFactory<P> factory = new PrevaylerFactory<P>();
factory.configurePrevalentSystem(newPrevalentSystem);
factory.configurePrevalenceDirectory(prevalenceBase);
return factory.create();
}
/** Creates a Prevayler that will use a directory called "PrevalenceBase" under the current directory to read and write its .snapshot and .journal files, using standard Java serialization/deserialization. This requires that the Prevalent System and all Transaction implementations used by the Prevayler are Java-Serializable.
* @param newPrevalentSystem The newly started, "empty" prevalent system that will be used as a starting point for every system startup, until the first snapshot is taken.
* @see #createPrevayler(Serializable, String)
*/
public static <P> Prevayler<P> createPrevayler(P newPrevalentSystem) throws Exception {
return createPrevayler(newPrevalentSystem, "PrevalenceBase");
}
/** Creates a Prevayler that will execute Transactions WITHOUT writing them to disk. Snapshots will work as "checkpoints" for the system, therefore. This is useful for stand-alone applications that have a "Save" button, for example. The Prevayler will use standard Java serialization/deserialization for reading and writing its .snapshot files, which requires that the Prevalent System is Java-Serializable.
* @param newPrevalentSystem The newly started, "empty" prevalent system that will be used as a starting point for every system startup, until the first snapshot is taken.
* @param snapshotDirectory The directory where the .snapshot files will be read and written.
* @see #createPrevayler(Serializable, String)
*/
public static <P> Prevayler<P> createCheckpointPrevayler(P newPrevalentSystem, String snapshotDirectory) {
PrevaylerFactory<P> factory = new PrevaylerFactory<P>();
factory.configurePrevalentSystem(newPrevalentSystem);
factory.configurePrevalenceDirectory(snapshotDirectory);
factory.configureTransientMode(true);
try {
return factory.create();
} catch (Exception e) {
e.printStackTrace(); //Transient Prevayler creation should not fail.
return null;
}
}
/** Creates a Prevayler that will execute Transactions WITHOUT writing them to disk. This is useful for running automated tests or demos MUCH faster than with a regular Prevayler.
*
* Attempts to take snapshots on this transient Prevayler will throw an IOException.
* @param newPrevalentSystem The newly started, "empty" prevalent system.
* @see #createCheckpointPrevayler(Serializable, String)
*/
public static <P> Prevayler<P> createTransientPrevayler(P newPrevalentSystem) {
PrevaylerFactory<P> factory = new PrevaylerFactory<P>();
factory.configurePrevalentSystem(newPrevalentSystem);
factory.configureNullSnapshotManager(new NullSnapshotManager<P>(newPrevalentSystem, "Transient Prevaylers are unable to take snapshots."));
factory.configureTransientMode(true);
try {
return factory.create();
} catch (Exception e) {
e.printStackTrace(); //Transient Prevayler creation should not fail.
return null;
}
}
/** @deprecated Use createCheckpointPrevayler() instead of this method. Deprecated since Prevayler2.00.001.
*/
public static <P> Prevayler<P> createTransientPrevayler(P newPrevalentSystem, String snapshotDirectory) {
return createCheckpointPrevayler(newPrevalentSystem, snapshotDirectory);
}
private Clock clock() {
return _clock != null ? _clock : new MachineClock();
}
public void configurePrevalentSystem(P newPrevalentSystem) {
_prevalentSystem = newPrevalentSystem;
}
/** Configures the directory where the created Prevayler will read and write its .journal and .snapshot files. The default is a directory called "PrevalenceBase" under the current directory.
* @param prevalenceDirectory Will be ignored for the .snapshot files if a SnapshotManager is configured.
*/
public void configurePrevalenceDirectory(String prevalenceDirectory) {
_prevalenceDirectory = prevalenceDirectory;
}
/**
* Configures whether deep copies of transactions are executed instead of the transactions themselves, upon calling ".execute" on the created Prevayler. The default is <code>true</code>.
*
* @param transactionDeepCopyMode
* <br>
* <br>If <code>false</code>, references passed in to transactions are used naturally, as they are during ordinary Java method calls, allowing their underlying objects to be changed inside transactions. However, any unrecoverable changes to the prevalent system and unrecoverable uses of reference equality inside transactions will not fail fast as they would upon recovery.
* <br>
* <br>If <code>true</code> (default), a deep copy of the transaction is executed each time. This allows any unrecoverable changes to the prevalent system and unrecoverable uses of reference equality inside transactions to fail fast as they would upon recovery. However, it only allows changes to deep copies of the objects passed in, not the original objects.
*
*/
public void configureTransactionDeepCopy(boolean transactionDeepCopyMode){
_transactionDeepCopyMode = transactionDeepCopyMode;
}
/** Configures the Clock that will be used by the created Prevayler. The Clock interface can be implemented by the application if it requires Prevayler to use a special time source other than the machine clock (default).
*/
public void configureClock(Clock clock) {
_clock = clock;
}
/**
* Assigns a monitor object to receive notifications from Prevayler. This is useful for logging or sending eMails to system administrators, for example. If this method is not called or if null is passed as a parameter, a SimpleMonitor will be used to log notification on System.err.
*
* @param monitor the Monitor implementation to use.
* @see org.prevayler.foundation.monitor.SimpleMonitor
*/
public void configureMonitor(Monitor monitor) {
_monitor = monitor;
}
public void configureTransientMode(boolean transientMode) {
_transientMode = transientMode;
}
/** Reserved for future implementation.
*/
public void configureReplicationClient(String remoteServerIpAddress, int remoteServerPort) {
_remoteServerIpAddress = remoteServerIpAddress;
_remoteServerPort = remoteServerPort;
}
/** Reserved for future implementation.
*/
public void configureReplicationServer(int port) {
_serverPort = port;
}
private void configureNullSnapshotManager(NullSnapshotManager<P> snapshotManager) {
_nullSnapshotManager = snapshotManager;
}
/**
* Configures the size (in bytes) of the journal file. When the current journal exceeds this size, a new journal is created.
*/
public void configureJournalFileSizeThreshold(long sizeInBytes) {
_journalSizeThreshold = sizeInBytes;
}
/**
* Sets the age (in milliseconds) of the journal file. When the current journal expires, a new journal is created.
*/
public void configureJournalFileAgeThreshold(long ageInMilliseconds) {
_journalAgeThreshold = ageInMilliseconds;
}
/**
* Configures whether the journal will sync writes to disk. The default is <code>true</code>.
*
* @param journalDiskSync
* <br>
* <br>If <code>false</code>, transactions may execute without necessarily being written to the
* physical disk. Transactions are still flushed to the operating system before being
* executed, but FileDescriptor.sync() is never called. This increases transaction
* throughput dramatically, but allows transactions to be lost if the system
* does not shut down cleanly. Calling {@link Prevayler#close()} will close the
* underlying journal file and therefore cause all transactions to be written to
* disk.
* <br>
* <br>If <code>true</code> (default), every transaction is forced to be written to the
* physical disk before it is executed (using {@link java.io.FileDescriptor#sync()}).
* (Many transactions may be written at once, but no transaction will be executed
* before it is written to disk.)
*
*/
public void configureJournalDiskSync(boolean journalDiskSync) {
_journalDiskSync = journalDiskSync;
}
public void configureJournalSerializer(JavaSerializer serializer) {
configureJournalSerializer("journal", serializer);
}
public void configureJournalSerializer(XStreamSerializer serializer) {
configureJournalSerializer("xstreamjournal", serializer);
}
public void configureJournalSerializer(String suffix, Serializer serializer) {
PrevaylerDirectory.checkValidJournalSuffix(suffix);
if (_journalSerializer != null) {
throw new IllegalStateException("Read the javadoc to this method.");
}
_journalSerializer = serializer;
_journalSuffix = suffix;
}
public void configureSnapshotSerializer(JavaSerializer serializer) {
configureSnapshotSerializer("snapshot", serializer);
}
public void configureSnapshotSerializer(XStreamSerializer serializer) {
configureSnapshotSerializer("xstreamsnapshot", serializer);
}
/**
* Configure a serialization strategy for snapshots. This may be called any number of times with
* different suffixes to configure different strategies for reading existing snapshots. The first
* call to this method establishes the <i>primary</i> strategy, which will be used for writing
* snapshots as well as for deep-copying the prevalent system whenever necessary.
*/
public void configureSnapshotSerializer(String suffix, Serializer serializer) {
PrevaylerDirectory.checkValidSnapshotSuffix(suffix);
_snapshotSerializers.put(suffix, serializer);
if (_primarySnapshotSuffix == null) {
_primarySnapshotSuffix = suffix;
}
}
/** Returns a Prevayler created according to what was defined by calls to the configuration methods above.
* @throws IOException If there is trouble creating the Prevalence Base directory or reading a .journal or .snapshot file.
* @throws ClassNotFoundException If a class of a serialized Object is not found when reading a .journal or .snapshot file.
*/
public Prevayler<P> create() throws Exception {
GenericSnapshotManager<P> snapshotManager = snapshotManager();
TransactionPublisher publisher = publisher(snapshotManager);
if (_serverPort != -1) new ServerListener(publisher, new OldNetworkImpl(), _serverPort);
return new PrevaylerImpl<P>(snapshotManager, publisher, journalSerializer(), _transactionDeepCopyMode);
}
private String prevalenceDirectory() {
return _prevalenceDirectory != null ? _prevalenceDirectory : "Prevalence";
}
private P prevalentSystem() {
if (_prevalentSystem == null) throw new IllegalStateException("The prevalent system must be configured.");
return _prevalentSystem;
}
private TransactionPublisher publisher(GenericSnapshotManager<P> snapshotManager) throws IOException {
if (_remoteServerIpAddress != null) return new ClientPublisher(new OldNetworkImpl(), _remoteServerIpAddress, _remoteServerPort);
return new CentralPublisher(clock(), journal());
}
private Journal journal() throws IOException {
if (_transientMode) {
return (Journal) new TransientJournal();
} else {
PrevaylerDirectory directory = new PrevaylerDirectory(prevalenceDirectory());
return new PersistentJournal(directory, _journalSizeThreshold, _journalAgeThreshold, _journalDiskSync, journalSuffix(), monitor());
}
}
private Serializer journalSerializer() {
if (_journalSerializer != null) return _journalSerializer;
return new JavaSerializer();
}
private String journalSuffix() {
return _journalSuffix != null ? _journalSuffix : "journal";
}
private GenericSnapshotManager<P> snapshotManager() throws Exception {
if (_nullSnapshotManager != null)
return _nullSnapshotManager;
PrevaylerDirectory directory = new PrevaylerDirectory(prevalenceDirectory());
if (!_snapshotSerializers.isEmpty())
return new GenericSnapshotManager<P>(_snapshotSerializers, _primarySnapshotSuffix, prevalentSystem(), directory, journalSerializer());
String snapshotSuffix = "snapshot";
JavaSerializer snapshotSerializer = new JavaSerializer();
return new GenericSnapshotManager<P>(Collections.singletonMap(snapshotSuffix, snapshotSerializer), snapshotSuffix, prevalentSystem(), directory, journalSerializer());
}
private Monitor monitor() {
return _monitor != null ? _monitor : new SimpleMonitor(System.err);
}
}
|
package ac.at.tuwien.infosys.fakeload;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
public final class ImmutableFakeLoad extends AbstractFakeLoad {
private final long duration;
private final TimeUnit unit;
private final int repetitions;
private final int cpuLoad;
private final long memoryLoad;
private final long diskIOLoad;
private final long netIOLoad;
private final List<FakeLoad> loads;
private ImmutableFakeLoad(long duration, TimeUnit unit, int repetitions,
int cpuLoad, long memoryLoad, long diskIOLoad, long netIOLoad,
List<FakeLoad> loads) {
this.duration = duration;
this.unit = unit;
this.repetitions = repetitions;
this.cpuLoad = cpuLoad;
this.memoryLoad = memoryLoad;
this.diskIOLoad = diskIOLoad;
this.netIOLoad = netIOLoad;
this.loads = Collections.unmodifiableList(loads);
}
ImmutableFakeLoad() {
this(0L, TimeUnit.MILLISECONDS, 0,
0, 0L, 0L, 0L, new ArrayList<>());
}
ImmutableFakeLoad(long duration, TimeUnit unit) {
this(duration, unit, 0,
0, 0L, 0L, 0L, new ArrayList<>());
}
@Override
public FakeLoad lasting(long duration, TimeUnit unit) {
return new ImmutableFakeLoad(duration, unit, repetitions, cpuLoad, memoryLoad, diskIOLoad, netIOLoad, loads);
}
@Override
public FakeLoad repeat(int noOfRepetitions) {
return null;
}
@Override
public FakeLoad withCpuLoad(int cpuLoad) {
return new ImmutableFakeLoad(duration, unit, repetitions, cpuLoad, memoryLoad, diskIOLoad, netIOLoad, loads);
}
@Override
public FakeLoad withMemoryLoad(long amount, MemoryUnit unit) {
long memoryLoad = amount * unit.toBytes();
return new ImmutableFakeLoad(duration, this.unit, repetitions, cpuLoad, memoryLoad, diskIOLoad, netIOLoad, loads);
}
@Override
public FakeLoad withDiskIOLoad(long diskIOLoad) {
return new ImmutableFakeLoad(duration, this.unit, repetitions, cpuLoad, memoryLoad, diskIOLoad, netIOLoad, loads);
}
@Override
public FakeLoad withNetIOLoad(long netIOLoad) {
return new ImmutableFakeLoad(duration, this.unit, repetitions, cpuLoad, memoryLoad, diskIOLoad, netIOLoad, loads);
}
@Override
public FakeLoad addLoad(FakeLoad load) {
// add load
List<FakeLoad> newLoads;
if (this.loads.size() > 0) {
newLoads = this.loads.subList(0, this.loads.size()-1);
} else {
newLoads = new ArrayList<>();
}
newLoads.add(load);
return new ImmutableFakeLoad(duration, unit, repetitions, cpuLoad, memoryLoad, diskIOLoad, netIOLoad, newLoads);
}
@Override
public FakeLoad addLoads(Collection<FakeLoad> loads) {
List<FakeLoad> newLoads;
if (this.loads.size() > 0) {
newLoads = this.loads.subList(0, this.loads.size()-1);
} else {
newLoads = new ArrayList<>();
}
newLoads.addAll(loads);
return new ImmutableFakeLoad(duration, unit, repetitions, cpuLoad, memoryLoad, diskIOLoad, netIOLoad, newLoads);
}
@Override
public Collection<FakeLoad> getLoads() {
return loads;
}
@Override
public int getCpuLoad() {
return cpuLoad;
}
@Override
public long getMemoryLoad() {
return memoryLoad;
}
@Override
public long getDiskIOLoad() {
return diskIOLoad;
}
@Override
public long getNetIOLoad() {
return netIOLoad;
}
@Override
public long getDuration() {
return duration;
}
@Override
public TimeUnit getTimeUnit() {
return unit;
}
@Override
public boolean contains(FakeLoad load) {
if (this.equals(load)) {
return true;
}
// check if pattern is contained in child patterns
for (FakeLoad l : this.getLoads()) {
return l.contains(load);
}
// if not found anywhere return false
return false;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ImmutableFakeLoad that = (ImmutableFakeLoad) o;
if (duration != that.duration) return false;
if (repetitions != that.repetitions) return false;
if (cpuLoad != that.cpuLoad) return false;
if (memoryLoad != that.memoryLoad) return false;
if (diskIOLoad != that.diskIOLoad) return false;
if (netIOLoad != that.netIOLoad) return false;
if (unit != that.unit) return false;
return loads.equals(that.loads);
}
@Override
public int hashCode() {
int result = (int) (duration ^ (duration >>> 32));
result = 31 * result + (unit != null ? unit.hashCode() : 0);
result = 31 * result + repetitions;
result = 31 * result + cpuLoad;
result = 31 * result + (int) (memoryLoad ^ (memoryLoad >>> 32));
result = 31 * result + (int) (diskIOLoad ^ (diskIOLoad >>> 32));
result = 31 * result + (int) (netIOLoad ^ (netIOLoad >>> 32));
result = 31 * result + loads.hashCode();
return result;
}
@Override
public String toString() {
return "ImmutableFakeLoad{" +
"duration=" + duration +
", unit=" + unit +
", repetitions=" + repetitions +
", cpuLoad=" + cpuLoad +
", memoryLoad=" + memoryLoad +
", diskIOLoad=" + diskIOLoad +
", netIOLoad=" + netIOLoad +
", loads=" + loads +
'}';
}
}
|
package oap.metrics;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;
import oap.testng.AbstractTest;
import org.influxdb.dto.Point;
import org.joda.time.DateTimeUtils;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.joining;
import static oap.testng.Asserts.assertString;
public class InfluxDBReporterTest extends AbstractTest {
private MockInfluxDB influxDB;
private MetricRegistry registry;
@BeforeMethod
@Override
public void beforeMethod() throws Exception {
super.beforeMethod();
influxDB = new MockInfluxDB();
registry = new MetricRegistry();
DateTimeUtils.setCurrentMillisFixed( 1454055727921L );
}
@Test
public void testReport_aggregates() throws Exception {
final InfluxDBReporter reporter = createReporter( influxDB, registry, asList( "test.*", "test2.test2.*" ) );
registry.counter( "test.name1" ).inc();
registry.counter( "test.name2" ).inc( 2 );
registry.register( "test2.test2.g1", ( Gauge ) () -> 10 );
registry.register( "test2.test2.g2", ( Gauge ) () -> 10 );
registry.histogram( "test.h1" ).update( 10 );
registry.histogram( "test.h2" ).update( 20 );
registry.meter( "test2.test2.m1" ).mark();
registry.meter( "test2.test2.m2" ).mark();
registry.timer( "test.t1" ).update( 10, TimeUnit.DAYS );
registry.timer( "test.t2" ).update( 10, TimeUnit.HOURS );
reporter.report(
registry.getGauges(),
registry.getCounters(),
registry.getHistograms(),
registry.getMeters(),
registry.getTimers()
);
assertString( getPoints() ).contains(
"test", "t1=10.0", "g1=10i", "h1=10.0", "h1_75th=10.0", "name1=1i,name2=2i",
"t1=10.0", "t2=0.416666666666666", "h2_stddev=0.0", "m2=0.0" );
}
public InfluxDBReporter createReporter( MockInfluxDB influxDB, MetricRegistry registry, List<String> aggregates ) {
return new InfluxDBReporter(
influxDB,
"database",
emptyMap(),
registry,
"name",
new ReporterFilter( emptyList(), emptyList() ),
aggregates,
TimeUnit.DAYS,
TimeUnit.DAYS,
false
);
}
@Test
public void testAggregatesWithTags() {
final InfluxDBReporter reporter = createReporter( influxDB, registry, singletonList( "test.*" ) );
registry.counter( "test.name1,b=10,v=20" ).inc();
registry.counter( "test.name2,b=10,v=20" ).inc( 2 );
reporter.report(
registry.getGauges(),
registry.getCounters(),
registry.getHistograms(),
registry.getMeters(),
registry.getTimers()
);
assertString( getPoints() ).isEqualTo( "test,b=10,v=20 name1=1i,name2=2i 1454055727921000000" );
}
public String getPoints() {
return influxDB.writes.stream().map( Point::lineProtocol ).collect( joining( "\n" ) );
}
}
|
package cruise.umple.compiler;
import java.util.*;
import org.junit.*;
public class RequirementTest
{
ArrayList<Requirement> allTestRequirements;
@Before
public void setUp()
{
allTestRequirements = new ArrayList<Requirement>();
}
@Test
public void constructor()
{
Requirement c = new Requirement("R01","blah2","");
Assert.assertEquals("blah2",c.getStatement());
}
@Test
public void format_null()
{
String output = Requirement.format("Slashes",allTestRequirements);
Assert.assertEquals(null,output);
}
@Test
public void format_oneRequirement()
{
allTestRequirements.add(new Requirement("R01","a",""));
String output = Requirement.format("Slashes",allTestRequirements);
Assert.assertEquals("// R01: a",output);
}
@Test
public void format_multipleRequirements()
{
allTestRequirements.add(new Requirement("R01","a",""));
allTestRequirements.add(new Requirement("R02","a2",""));
String output = Requirement.format("Slashes",allTestRequirements);
Assert.assertEquals("// R01: a\n// R02: a2",output);
}
}
|
package mil.darpa.nxcore;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.BZip2Codec;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
/**
* MapReduce class used to split the NXCore Windows output running on Linux.
*
* @author Matt Parker (matthew.parker@l-3com.com)
*
*/
public class SplitFiles {
/**
* Spilt the file data into the four separate data types.
*/
public static class SplitFilesMapper extends Mapper<LongWritable, Text, Text, Text>{
public static final int RECORD_TYPE = 0;
public static final int RECORD = 1;
@Override
protected void map( LongWritable key, Text value, Context context ) throws IOException, InterruptedException {
//Go from 20140101.XA.nvc.txt.bz2 -> 20140101
String filekey = ((FileSplit) context.getInputSplit()).getPath().getName().substring(0,8);
//Split record type, record
String[] components = value.toString().split(",",1);
//Segment data by file.
Text filesplit = new Text( filekey + "-" + components[RECORD_TYPE] );
context.write( filesplit, new Text(components[RECORD]) );
}
}
/**
* Aggregate records into files by day and record type.
*/
public static class SplitFilesReducer extends Reducer<Text,Text,NullWritable,Text> {
public static final int RECORD_TYPE = 1;
public static final int RECORD_DATE = 0;
MultipleOutputs<NullWritable,Text> mos;
@Override
protected void setup(Context context) throws IOException, InterruptedException {
super.setup(context);
mos = new MultipleOutputs<NullWritable,Text>(context);
}
@Override
protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
String[] components = key.toString().split("-",1);
String year = components[RECORD_DATE].substring(0,4);
String month = components[RECORD_DATE].substring(4,6);
StringBuffer outfile = new StringBuffer();
outfile.append("/")
.append( components[RECORD_TYPE] )
.append("/")
.append( year )
.append("/")
.append( month )
.append("/")
.append( components[RECORD_DATE]); //date
for ( Text value : values ){
mos.write( NullWritable.get(), value, outfile.toString() );
}
}
@Override
protected void cleanup(Context context) throws IOException, InterruptedException {
super.cleanup(context);
mos.close();
}
}
/**
* Set the MapReduce job configuration.
*
* @param args
* @throws Exception
*/
public static void main( String[] args ) throws Exception {
Configuration conf = new Configuration();
GenericOptionsParser optionParser = new GenericOptionsParser(conf, args);
String[] remainingArgs = optionParser.getRemainingArgs();
if (!(remainingArgs.length != 3)) {
System.err.println("Usage: SplitFiles <in> <out>");
System.exit(0);
}
Job job = Job.getInstance(conf,"split-nxcore-files");
job.setJarByClass(SplitFiles.class);
job.setMapperClass(SplitFiles.SplitFilesMapper.class);
job.setReducerClass(SplitFiles.SplitFilesReducer.class);
job.setOutputKeyClass(LongWritable.class);
job.setOutputValueClass(Text.class);
List<String> otherArgs = new ArrayList<String>();
for (int i=0; i < remainingArgs.length; ++i) {
otherArgs.add(remainingArgs[i]);
}
FileInputFormat.addInputPath(job, new Path( otherArgs.get(0) ));
FileOutputFormat.setOutputPath(job, new Path( otherArgs.get(1) ));
TextOutputFormat.setCompressOutput(job, true);
TextOutputFormat.setOutputCompressorClass(job, BZip2Codec.class );
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
|
package ag.ifpb.sct.ws.site.resource.json;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.restlet.ext.fileupload.RestletFileUpload;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.StreamRepresentation;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;
public class ImageResource extends ServerResource {
private String calculateName(byte[] bytefile){
try{
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] byteresume = digest.digest(bytefile);
BigInteger integer = new BigInteger(1, byteresume);
return integer.toString(16);
}
catch (NoSuchAlgorithmException e) {
return String.valueOf(System.currentTimeMillis());
}
}
@Post
public JsonRepresentation upload(StreamRepresentation representation){
JSONResult result = new JSONResult();
try {
File repository = new File("/tmp");
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(5000, repository);
RestletFileUpload upload = new RestletFileUpload(fileItemFactory);
List<FileItem> list = upload.parseRepresentation(representation);
int listsize = list.size();
JSONArray a = new JSONArray();
for (int i = 0; i < listsize; i++){
FileItem fi = list.get(i);
String name = calculateName(fi.get());
File file = new File("/tmp/" + name + ".png");
a.put(i, file.getAbsoluteFile());
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(fi.get());
fileOutputStream.flush();
fileOutputStream.close();
}
result.setData(a);
result.setSuccess(true);
}
catch (IOException | FileUploadException | JSONException e) {
result.setSuccess(false);
result.setMessage(e.getMessage());
e.printStackTrace();
}
return new JsonRepresentation(result.asJSON());
}
}
|
package org.openoffice.configuration;
import org.xml.sax.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
import java.util.*;
import java.io.*;
import com.jclark.xsl.sax.Driver;
/**
* Title: XMLDefaultGenerator<p>
* Description: Tool for generating configuration default data<p>
*/
public class XMLDefaultGenerator {
public static final String FILE_EXT = ".xml";
protected String packageName = null;
protected String componentName = null;
protected String categoryName = null;
protected String transformationFile = null;
/**
* construct the generator by validation of the source file
*/
public XMLDefaultGenerator(String sourceFile) throws Exception
{
// set the driver for xt
System.setProperty("com.jclark.xsl.sax.parser", "org.apache.xerces.parsers.SAXParser");
evaluateSchema(sourceFile);
}
public String getComponentName() {return componentName;}
public String getPackageName() {return packageName;}
public String getCategoryName() {return categoryName;}
/**
* construct the generator by validation of the source file
*/
protected void evaluateSchema(String schemaFile) throws Exception
{
try
{
SAXParserFactory factory = SAXParserFactory.newInstance();
// factory.setValidating(true);
// Parse the input
SAXParser saxParser = factory.newSAXParser();
Inspector inspector = new Inspector();
saxParser.parse( new File(new File(schemaFile).getAbsolutePath()).toURL().toString(), inspector );
// get the necessary information for generation
packageName = inspector.packageName;
componentName = inspector.componentName;
categoryName = inspector.categoryName;
transformationFile = inspector.transformationFile;
}
catch (SAXParseException spe) {
// Error generated by the parser
System.out.println ("\n** Parsing error"
+ ", line " + spe.getLineNumber ()
+ ", uri " + spe.getSystemId ());
System.out.println(" " + spe.getMessage() );
throw spe;
}
catch (SAXException sxe) {
// Error generated by this application
// (or a parser-initialization error)
Exception x = sxe;
if (sxe.getException() != null)
x = sxe.getException();
x.printStackTrace();
throw sxe;
}
catch (IOException ioe) {
// I/O error
ioe.printStackTrace();
throw ioe;
}
catch (Exception pce) {
// Parser with specified options can't be built
pce.printStackTrace();
throw pce;
}
}
/**
* creating the destination file name
*/
public String getTargetName(String aRoot, String aKind) throws Exception
{
String aRelPath = packageName.replace('.', File.separatorChar);
// create the instance directory
File aFile = new File(aRoot + File.separatorChar + aKind + File.separatorChar +
aRelPath + File.separatorChar + componentName + FILE_EXT);
return aFile.getPath();
}
/**
* generating the target document
*/
public void generate(String argv [], boolean asTemplate) throws Exception
{
// add the necessary transformation parameters
{
String[] args = new String[argv.length + 1];
for (int i = 0; i < argv.length; i++)
args[i] = argv[i];
args[1] = argv[1] + File.separator + transformationFile;
// handle the path parameter for the source
args[3] = "path=" + Generator.getAbsolutePath(argv[3]);
args[argv.length] = "pathSeparator=" + File.pathSeparator;
argv = args;
}
try
{
// make sure that all directories exist
File path = new File(argv[2]).getParentFile();
path.mkdirs();
String[] args = null;
// templates need a new argument, which is used for
// as parameter for the xsl translation
if (asTemplate)
{
args = new String[argv.length + 1];
for (int i = 0; i < argv.length; i++)
args[i] = argv[i];
args[argv.length] = "templates=true";
}
else
args = argv;
Driver.main(args);
}
catch (Exception e)
{
e.printStackTrace();
throw e;
}
}
/**
* generating the instance document
*/
protected void generateInstanceFile(String argv []) throws Exception
{
argv[2] = getTargetName(argv[2], "instance");
generate(argv, false);
}
/**
* generating the template document
*/
protected void generateTemplateFile(String argv []) throws Exception
{
argv[2] = getTargetName(argv[2], "template");
generate(argv, true);
}
public static void main (String argv [])
{
if (argv.length < 4) {
System.err.println ("Usage: cmd <filename> <xsldir> <outdir> <include-path> [transformation parameters]");
System.err.println ("<filename>: Configuration description file");
System.err.println ("<xsldir>: Directory where to locate the transformation files used");
System.err.println ("<outdir>: Directory where to generate the output files");
System.err.println ("<include-path>: Path where to find imported configuration files");
System.exit (1);
}
try
{
XMLDefaultGenerator generator = new XMLDefaultGenerator(argv [0]);
String[] args = new String[argv.length + 1];
for (int i = 0; i < argv.length; i++)
args[i] = argv[i];
String url = new File(argv[2] + File.separator + "template")
.getAbsoluteFile().toURL().toString();
args[argv.length] = "templateURL=" + url;
// create the instance file
generator.generateInstanceFile((String[])args.clone());
// create the template file
generator.generateTemplateFile((String[])args.clone());
}
catch (Exception pce) {
// Parser with specified options can't be built
pce.printStackTrace();
System.exit (1);
}
}
}
|
package hudson.maven;
import static hudson.Util.*;
import static hudson.model.ItemGroupMixIn.loadChildren;
import hudson.CopyOnWrite;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Functions;
import hudson.Indenter;
import hudson.Plugin;
import hudson.Util;
import hudson.maven.local_repo.DefaultLocalRepositoryLocator;
import hudson.maven.local_repo.LocalRepositoryLocator;
import hudson.maven.local_repo.PerJobLocalRepositoryLocator;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.BuildableItemWithBuildWrappers;
import hudson.model.DependencyGraph;
import hudson.model.Descriptor;
import hudson.model.Descriptor.FormException;
import hudson.model.Executor;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.Job;
import hudson.model.Queue;
import hudson.model.Queue.Task;
import hudson.model.ResourceActivity;
import hudson.model.Result;
import hudson.model.SCMedItem;
import hudson.model.Saveable;
import hudson.model.TaskListener;
import hudson.model.TopLevelItem;
import hudson.mvn.DefaultGlobalSettingsProvider;
import hudson.mvn.DefaultSettingsProvider;
import hudson.mvn.FilePathSettingsProvider;
import hudson.mvn.GlobalSettingsProvider;
import hudson.mvn.GlobalSettingsProviderDescriptor;
import hudson.mvn.SettingsProvider;
import hudson.mvn.SettingsProviderDescriptor;
import hudson.search.CollectionSearchIndex;
import hudson.search.SearchIndexBuilder;
import hudson.tasks.BuildStep;
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildWrappers;
import hudson.tasks.Builder;
import hudson.tasks.Fingerprinter;
import hudson.tasks.Mailer;
import hudson.tasks.Maven;
import hudson.tasks.Maven.MavenInstallation;
import hudson.tasks.Publisher;
import hudson.tasks.JavadocArchiver;
import hudson.tasks.junit.JUnitResultArchiver;
import hudson.util.CopyOnWriteMap;
import hudson.util.DescribableList;
import hudson.util.FormValidation;
import hudson.util.Function1;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Stack;
import javax.servlet.ServletException;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.maven.model.building.ModelBuildingRequest;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
/**
* Group of {@link MavenModule}s.
*
* <p>
* This corresponds to the group of Maven POMs that constitute a single
* tree of projects. This group serves as the grouping of those related
* modules.
*
* @author Kohsuke Kawaguchi
*/
public class MavenModuleSet extends AbstractMavenProject<MavenModuleSet,MavenModuleSetBuild> implements TopLevelItem, ItemGroup<MavenModule>, SCMedItem, Saveable, BuildableItemWithBuildWrappers {
/**
* All {@link MavenModule}s, keyed by their {@link MavenModule#getModuleName()} module name}s.
*/
transient /*final*/ Map<ModuleName,MavenModule> modules = new CopyOnWriteMap.Tree<ModuleName,MavenModule>();
/**
* Topologically sorted list of modules. This only includes live modules,
* since archived ones usually don't have consistent history.
*/
@CopyOnWrite
transient List<MavenModule> sortedActiveModules;
/**
* Name of the top-level module. Null until the root module is determined.
*/
private ModuleName rootModule;
private String rootPOM;
private String goals;
/**
* @deprecated as of 1.481
* Subsumed by {@link #settings}, maps to {@link FilePathSettingsProvider}
*/
private transient String alternateSettings;
/**
* Default goals specified in POM. Can be null.
*/
private String defaultGoals;
/**
* Identifies {@link MavenInstallation} to be used.
* Null to indicate 'default' maven.
*/
private String mavenName;
/**
* Equivalent of CLI <tt>MAVEN_OPTS</tt>. Can be null.
*/
private String mavenOpts;
/**
* If true, the build will be aggregator style, meaning
* all the modules are executed in a single Maven invocation, as in CLI.
* False otherwise, meaning each module is built separately and possibly in parallel.
*
* @since 1.133
*/
private boolean aggregatorStyleBuild = true;
/**
* If true, and if aggregatorStyleBuild is false and we are using Maven 2.1 or later, the build will
* check the changeset before building, and if there are changes, only those modules which have changes
* or those modules which failed or were unstable in the previous build will be built directly, using
* Maven's make-like reactor mode. Any modules depending on the directly built modules will also be built,
* but that's controlled by Maven.
*
* @since 1.318
*/
private boolean incrementalBuild = false;
/**
* If true, the build will use its own local Maven repository
* via "-Dmaven.repo.local=...".
* <p>
* This would consume additional disk space, but provides isolation with other builds on the same machine,
* such as mixing SNAPSHOTS. Maven also doesn't try to coordinate the concurrent access to Maven repositories
* from multiple Maven process, so this helps there too.
*
* @since 1.223
* @deprecated as of 1.448
* Subsumed by {@link #localRepository}. false maps to {@link DefaultLocalRepositoryLocator},
* and true maps to {@link PerJobLocalRepositoryLocator}
*/
private transient Boolean usePrivateRepository;
/**
* Encapsulates where to run the local repository.
*
* If null, inherited from the global configuration.
*
* @since 1.448
*/
private LocalRepositoryLocator localRepository = null;
/**
* If true, the build will send a failure e-mail for each failing maven module.
* Defaults to <code>true</code> to simulate old behavior.
* <p>
* see JENKINS-5695.
*/
private Boolean perModuleEmail = Boolean.TRUE;
/**
* If true, do not automatically schedule a build when one of the project dependencies is built.
* <p>
* See HUDSON-1714.
*/
private boolean ignoreUpstremChanges = false;
/**
* If true, do not archive artifacts to the master.
*/
private boolean archivingDisabled = false;
/**
* parameter for pom parsing by default <code>false</code> to be faster
* @since 1.394
*/
private boolean resolveDependencies = false;
/**
* parameter for pom parsing by default <code>false</code> to be faster
* @since 1.394
*/
private boolean processPlugins = false;
/**
* parameter for validation level during pom parsing by default the one corresponding
* to the maven version used (2 or 3)
* @since 1.394
*/
private int mavenValidationLevel = -1;
/**
* Inform jenkins this build don't use UI code and can run without access to graphical environment. Could be used
* later to select a headless-slave from a pool, but first introduced for JENKINS-9785
*/
private boolean runHeadless = false;
/**
* @since 1.426
* @deprecated since 1.484 settings are provided by {@link #settings}
*/
private String settingConfigId;
/**
* @since 1.426
* @deprecated since 1.484 settings are provided by {@link #globalSettings}
*/
private String globalSettingConfigId;
/**
* used temporary during maven build to store file path
* @since 1.426
* @deprecated since 1.484 settings are provided by {@link #globalSettings}
*/
protected transient String globalSettingConfigPath;
/**
* @since 1.481
*/
private SettingsProvider settings = new DefaultSettingsProvider();
/**
* @since 1.481
*/
private GlobalSettingsProvider globalSettings = new DefaultGlobalSettingsProvider();
public Object readResolve() {
// backward compatibility
Plugin plugin = null;
if(StringUtils.isNotBlank(this.settingConfigId) || StringUtils.isNotBlank(this.globalSettingConfigId)) {
plugin = Jenkins.getInstance().getPlugin("config-file-provider");
if(plugin == null || !plugin.getWrapper().isEnabled()){
System.err.println("ERROR: 'config-file-provider' is not installed or disabled, therefore the config cant be fully loaded!!");
}
}
if (this.alternateSettings != null) {
this.settings = new FilePathSettingsProvider(alternateSettings);
this.alternateSettings = null;
} else if (plugin != null && StringUtils.isNotBlank(this.settingConfigId)) {
try {
Class<? extends SettingsProvider> legacySettings = plugin.getWrapper().classLoader.loadClass("org.jenkinsci.plugins.configfiles.maven.MvnSettingsProvider").asSubclass(SettingsProvider.class);
SettingsProvider newInstance = legacySettings.newInstance();
PropertyUtils.setProperty(newInstance, "settingsConfigId", this.settingConfigId);
this.settings = newInstance;
this.settingConfigId = null;
} catch (Exception e) {
// The PluginUpdateMonitor is also informing the admin about the update
System.err.println("ERROR: Please update the 'config-file-provider' plugin, the current version is not supported anymore! (settingConfigId="+settingConfigId+")");
e.printStackTrace();
}
}
if (plugin != null && StringUtils.isNotBlank(this.globalSettingConfigId)) {
try {
Class<? extends GlobalSettingsProvider> legacySettings = plugin.getWrapper().classLoader.loadClass("org.jenkinsci.plugins.configfiles.maven.MvnGlobalSettingsProvider").asSubclass(GlobalSettingsProvider.class);
GlobalSettingsProvider newInstance = legacySettings.newInstance();
PropertyUtils.setProperty(newInstance, "settingsConfigId", this.globalSettingConfigId);
this.globalSettings = newInstance;
this.globalSettingConfigId = null;
} catch (Exception e) {
// The PluginUpdateMonitor is also informing the admin about the update
System.err.println("ERROR: Please update the 'config-file-provider' plugin, the current version is not supported anymore! (globalSettingConfigId="+globalSettingConfigId+")");
e.printStackTrace();
}
}
return this;
}
/**
* Reporters configured at {@link MavenModuleSet} level. Applies to all {@link MavenModule} builds.
*/
private DescribableList<MavenReporter,Descriptor<MavenReporter>> reporters =
new DescribableList<MavenReporter,Descriptor<MavenReporter>>(this);
/**
* List of active {@link Publisher}s configured for this project.
* @since 1.176
*/
private DescribableList<Publisher,Descriptor<Publisher>> publishers =
new DescribableList<Publisher,Descriptor<Publisher>>(this);
/**
* List of active {@link BuildWrapper}s configured for this project.
* @since 1.212
*/
private DescribableList<BuildWrapper,Descriptor<BuildWrapper>> buildWrappers =
new DescribableList<BuildWrapper, Descriptor<BuildWrapper>>(this);
/**
* List of active {@link Builder}s configured for this project.
*/
private DescribableList<Builder,Descriptor<Builder>> prebuilders =
new DescribableList<Builder,Descriptor<Builder>>(this);
private DescribableList<Builder,Descriptor<Builder>> postbuilders =
new DescribableList<Builder,Descriptor<Builder>>(this);
private Result runPostStepsIfResult;
/**
* @deprecated
* Use {@link #MavenModuleSet(ItemGroup, String)}
*/
public MavenModuleSet(String name) {
this(Jenkins.getInstance(),name);
}
public MavenModuleSet(ItemGroup parent, String name) {
super(parent,name);
}
/**
* Builders that are run before the main Maven execution.
*
* @since 1.433
*/
public DescribableList<Builder,Descriptor<Builder>> getPrebuilders() {
return prebuilders;
}
/**
* Builders that are run after the main Maven execution.
*
* @since 1.433
*/
public DescribableList<Builder,Descriptor<Builder>> getPostbuilders() {
return postbuilders;
}
/**
* {@link #postbuilders} are run if the result is better or equal to this threshold.
*
* @return
* never null
* @since 1.433
*/
public Result getRunPostStepsIfResult() {
return Functions.defaulted(runPostStepsIfResult,Result.FAILURE);
}
public void setRunPostStepsIfResult(Result v) {
this.runPostStepsIfResult = Functions.defaulted(v,Result.FAILURE);
}
public String getUrlChildPrefix() {
// seemingly redundant "./" is used to make sure that ':' is not interpreted as the scheme identifier
return ".";
}
public Collection<MavenModule> getItems() {
return modules.values();
}
@Exported
public Collection<MavenModule> getModules() {
return getItems();
}
public MavenModule getItem(String name) {
return modules.get(ModuleName.fromString(name));
}
public MavenModule getModule(String name) {
return getItem(name);
}
@Override // to make this accessible from MavenModuleSetBuild
protected void updateTransientActions() {
super.updateTransientActions();
}
protected List<Action> createTransientActions() {
List<Action> r = super.createTransientActions();
// Fix for ISSUE-1149
for (MavenModule module: modules.values()) {
module.updateTransientActions();
}
if(publishers!=null) // this method can be loaded from within the onLoad method, where this might be null
for (BuildStep step : publishers)
r.addAll(step.getProjectActions(this));
if (buildWrappers!=null)
for (BuildWrapper step : buildWrappers)
r.addAll(step.getProjectActions(this));
return r;
}
protected void addTransientActionsFromBuild(MavenModuleSetBuild build, List<Action> collection, Set<Class> added) {
if(build==null) return;
for (Action a : build.getActions())
if(a instanceof MavenAggregatedReport)
if(added.add(a.getClass()))
collection.add(((MavenAggregatedReport)a).getProjectAction(this));
List<MavenReporter> list = build.projectActionReporters;
if(list==null) return;
for (MavenReporter step : list) {
if(!added.add(step.getClass())) continue; // already added
Action a = step.getAggregatedProjectAction(this);
if(a!=null)
collection.add(a);
}
}
/**
* Called by {@link MavenModule#doDoDelete(StaplerRequest, StaplerResponse)}.
* Real deletion is done by the caller, and this method only adjusts the
* data structure the parent maintains.
*/
/*package*/ void onModuleDeleted(MavenModule module) {
modules.remove(module.getModuleName());
}
/**
* Returns true if there's any disabled module.
*/
public boolean hasDisabledModule() {
for (MavenModule m : modules.values()) {
if(m.isDisabled())
return true;
}
return false;
}
/**
* Possibly empty list of all disabled modules (if disabled==true)
* or all enabeld modules (if disabled==false)
*/
public List<MavenModule> getDisabledModules(boolean disabled) {
if(!disabled && sortedActiveModules!=null)
return sortedActiveModules;
List<MavenModule> r = new ArrayList<MavenModule>();
for (MavenModule m : modules.values()) {
if(m.isDisabled()==disabled)
r.add(m);
}
return r;
}
public Indenter<MavenModule> createIndenter() {
return new Indenter<MavenModule>() {
protected int getNestLevel(MavenModule job) {
return job.nestLevel;
}
};
}
public boolean isIncrementalBuild() {
return incrementalBuild;
}
public boolean isAggregatorStyleBuild() {
return aggregatorStyleBuild;
}
/**
* @deprecated as of 1.448
* Use {@link #getLocalRepository()}
*/
public boolean usesPrivateRepository() {
return !(getLocalRepository() instanceof DefaultLocalRepositoryLocator);
}
public boolean isPerModuleEmail() {
return perModuleEmail;
}
public boolean ignoreUpstremChanges() {
return ignoreUpstremChanges;
}
public boolean runHeadless() {
return runHeadless;
}
public boolean isArchivingDisabled() {
return archivingDisabled;
}
public void setIncrementalBuild(boolean incrementalBuild) {
this.incrementalBuild = incrementalBuild;
}
public void setAggregatorStyleBuild(boolean aggregatorStyleBuild) {
this.aggregatorStyleBuild = aggregatorStyleBuild;
}
/**
* @deprecated as of 1.448.
* Use {@link #setLocalRepository(LocalRepositoryLocator)} instead
*/
public void setUsePrivateRepository(boolean usePrivateRepository) {
setLocalRepository(usePrivateRepository?new PerJobLocalRepositoryLocator() : new DefaultLocalRepositoryLocator());
}
/**
* @return
* never null
*/
public LocalRepositoryLocator getLocalRepository() {
return localRepository!=null ? localRepository : getDescriptor().getLocalRepository();
}
/**
* Undefaulted locally configured value with taking inheritance from the global configuration into account.
*/
public LocalRepositoryLocator getExplicitLocalRepository() {
return localRepository;
}
public void setLocalRepository(LocalRepositoryLocator localRepository) {
this.localRepository = localRepository;
}
public void setIgnoreUpstremChanges(boolean ignoreUpstremChanges) {
this.ignoreUpstremChanges = ignoreUpstremChanges;
}
public void setRunHeadless(boolean runHeadless) {
this.runHeadless = runHeadless;
}
public void setIsArchivingDisabled(boolean archivingDisabled) {
this.archivingDisabled = archivingDisabled;
}
public boolean isResolveDependencies()
{
return resolveDependencies;
}
public void setResolveDependencies( boolean resolveDependencies ) {
this.resolveDependencies = resolveDependencies;
}
public boolean isProcessPlugins() {
return processPlugins;
}
public void setProcessPlugins( boolean processPlugins ) {
this.processPlugins = processPlugins;
}
public int getMavenValidationLevel() {
return mavenValidationLevel;
}
/**
* @since 1.481
*/
public SettingsProvider getSettings() {
return settings != null ? settings : new DefaultSettingsProvider();
}
/**
* @since 1.481
*/
public GlobalSettingsProvider getGlobalSettings() {
return globalSettings != null ? globalSettings : new DefaultGlobalSettingsProvider();
}
/**
* List of active {@link MavenReporter}s that should be applied to all module builds.
*/
public DescribableList<MavenReporter, Descriptor<MavenReporter>> getReporters() {
return reporters;
}
/**
* List of active {@link Publisher}s. Can be empty but never null.
*/
public DescribableList<Publisher, Descriptor<Publisher>> getPublishers() {
return publishers;
}
@Override
public DescribableList<Publisher, Descriptor<Publisher>> getPublishersList() {
return publishers;
}
public DescribableList<BuildWrapper, Descriptor<BuildWrapper>> getBuildWrappersList() {
return buildWrappers;
}
/**
* List of active {@link BuildWrapper}s. Can be empty but never null.
*
* @deprecated as of 1.335
* Use {@link #getBuildWrappersList()} to be consistent with other subtypes of {@link AbstractProject}.
*/
public DescribableList<BuildWrapper, Descriptor<BuildWrapper>> getBuildWrappers() {
return buildWrappers;
}
public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
if(ModuleName.isValid(token))
return getModule(token);
return super.getDynamic(token,req,rsp);
}
public File getRootDirFor(MavenModule child) {
return new File(getModulesDir(),child.getModuleName().toFileSystemName());
}
public void onRenamed(MavenModule item, String oldName, String newName) throws IOException {
throw new UnsupportedOperationException();
}
public void onDeleted(MavenModule item) throws IOException {
// noop
}
public Collection<Job> getAllJobs() {
Set<Job> jobs = new HashSet<Job>(getItems());
jobs.add(this);
return jobs;
}
@Override
protected Class<MavenModuleSetBuild> getBuildClass() {
return MavenModuleSetBuild.class;
}
@Override
protected SearchIndexBuilder makeSearchIndex() {
return super.makeSearchIndex()
.add(new CollectionSearchIndex<MavenModule>() {// for computers
protected MavenModule get(String key) {
for (MavenModule m : modules.values()) {
if(m.getDisplayName().equals(key))
return m;
}
return null;
}
protected Collection<MavenModule> all() {
return modules.values();
}
protected String getName(MavenModule o) {
return o.getName();
}
});
}
@Override
public boolean isFingerprintConfigured() {
return true;
}
public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
modules = Collections.emptyMap(); // needed during load
super.onLoad(parent, name);
modules = loadChildren(this, getModulesDir(),new Function1<ModuleName,MavenModule>() {
public ModuleName call(MavenModule module) {
return module.getModuleName();
}
});
// update the transient nest level field.
MavenModule root = getRootModule();
if(root!=null && root.getChildren()!=null) {
List<MavenModule> sortedList = new ArrayList<MavenModule>();
Stack<MavenModule> q = new Stack<MavenModule>();
root.nestLevel = 0;
q.push(root);
while(!q.isEmpty()) {
MavenModule p = q.pop();
sortedList.add(p);
List<MavenModule> children = p.getChildren();
if(children!=null) {
for (MavenModule m : children)
m.nestLevel = p.nestLevel+1;
for( int i=children.size()-1; i>=0; i--) // add them in the reverse order
q.push(children.get(i));
}
}
this.sortedActiveModules = sortedList;
} else {
this.sortedActiveModules = getDisabledModules(false);
}
if(reporters==null){
reporters = new DescribableList<MavenReporter, Descriptor<MavenReporter>>(this);
}
reporters.setOwner(this);
if(publishers==null){
publishers = new DescribableList<Publisher,Descriptor<Publisher>>(this);
}
publishers.setOwner(this);
if(buildWrappers==null){
buildWrappers = new DescribableList<BuildWrapper, Descriptor<BuildWrapper>>(this);
}
buildWrappers.setOwner(this);
if(prebuilders==null){
prebuilders = new DescribableList<Builder,Descriptor<Builder>>(this);
}
prebuilders.setOwner(this);
if(postbuilders==null){
postbuilders = new DescribableList<Builder,Descriptor<Builder>>(this);
}
postbuilders.setOwner(this);
if(perModuleEmail == null){
perModuleEmail = Boolean.TRUE;
}
if (Boolean.TRUE.equals(usePrivateRepository)) {
this.localRepository = new PerJobLocalRepositoryLocator();
usePrivateRepository = null;
}
updateTransientActions();
}
private File getModulesDir() {
return new File(getRootDir(),"modules");
}
/**
* To make it easy to grasp relationship among modules
* and the module set, we'll align the build numbers of
* all the modules.
*
* <p>
* This method is invoked from {@link Executor#run()},
* and because of the mutual exclusion among {@link MavenModuleSetBuild}
* and {@link MavenBuild}, we can safely touch all the modules.
*/
public synchronized int assignBuildNumber() throws IOException {
// determine the next value
updateNextBuildNumber();
return super.assignBuildNumber();
}
public void logRotate() throws IOException, InterruptedException {
super.logRotate();
// perform the log rotation of modules
for (MavenModule m : modules.values())
m.logRotate();
}
/**
* The next build of {@link MavenModuleSet} must have
* the build number newer than any of the current module build.
*/
/*package*/ void updateNextBuildNumber() throws IOException {
int next = this.nextBuildNumber;
for (MavenModule m : modules.values())
next = Math.max(next,m.getNextBuildNumber());
if(this.nextBuildNumber!=next) {
this.nextBuildNumber=next;
this.saveNextBuildNumber();
}
}
protected void buildDependencyGraph(DependencyGraph graph) {
// the modules are already rebuild by DependencyGraph#init !
// Collection<MavenModule> modules = getModules();
// for (MavenModule m : modules) {
// m.buildDependencyGraph(graph);
publishers.buildDependencyGraph(this,graph);
buildWrappers.buildDependencyGraph(this,graph);
prebuilders.buildDependencyGraph(this,graph);
postbuilders.buildDependencyGraph(this,graph);
}
public MavenModule getRootModule() {
if(rootModule==null) return null;
return modules.get(rootModule);
}
public MavenInstallation inferMavenInstallation() {
return getMaven();
}
@Override
protected Set<ResourceActivity> getResourceActivities() {
final Set<ResourceActivity> activities = new HashSet<ResourceActivity>();
activities.addAll(super.getResourceActivities());
activities.addAll(Util.filter(publishers, ResourceActivity.class));
activities.addAll(Util.filter(buildWrappers, ResourceActivity.class));
activities.addAll(Util.filter(prebuilders, ResourceActivity.class));
activities.addAll(Util.filter(postbuilders, ResourceActivity.class));
return activities;
}
/**
*
* @deprecated for backward comp only
* @return
*/
public String getRootPOM(){
return getRootPOM( null );
}
/**
* Gets the location of top-level <tt>pom.xml</tt> relative to the workspace root.
* @since 1.466
*/
public String getRootPOM(EnvVars env) {
if (rootPOM == null) return "pom.xml";
// JENKINS-13822
if (env == null) return rootPOM;
return env.expand(rootPOM);
}
public void setRootPOM(String rootPOM) {
this.rootPOM = rootPOM;
}
public AbstractProject<?,?> asProject() {
return this;
}
/**
* Gets the list of goals to execute.
*/
public String getGoals() {
if(goals==null) {
if(defaultGoals!=null) return defaultGoals;
return "install";
}
return goals;
}
public void setGoals(String goals) {
this.goals = goals;
}
private boolean checkMavenOption(String shortForm, String longForm) {
for (String t : Util.tokenize(getGoals())) {
if(t.equals(shortForm) || t.equals(longForm))
return true;
}
return false;
}
private List<String> getMavenArgument(String shortForm, String longForm) {
List<String> args = new ArrayList<String>();
boolean switchFound=false;
for (String t : Util.tokenize(getGoals())) {
if(switchFound) {
args.add(t);
switchFound = false;
}
else
if(t.equals(shortForm) || t.equals(longForm))
switchFound=true;
else
if(t.startsWith(shortForm)) {
args.add(t.substring(shortForm.length()));
}
else
if(t.startsWith(longForm)) {
args.add(t.substring(longForm.length()));
}
}
return args;
}
/**
* Gets the workspace-relative path to an alternative Maven settings.xml file.
* @deprecated as of 1.481
*/
public String getAlternateSettings() {
return alternateSettings;
}
/**
* Sets the workspace-relative path to an alternative Maven settings.xml file.
* @deprecated as of 1.481
*/
public void setAlternateSettings(String alternateSettings) throws IOException {
this.alternateSettings = alternateSettings;
}
/**
* If the list of configured goals contain the "-P" option,
* return the configured profiles. Otherwise null.
*/
public String getProfiles() {
return Util.join(getMavenArgument("-P","--activate-profiles"),",");
}
/**
* Gets the system properties explicitly set in the Maven command line (the "-D" option.)
*/
public Properties getMavenProperties() {
Properties props = new Properties();
for (String arg : getMavenArgument("-D","--define")) {
int idx = arg.indexOf('=');
if(idx<0) props.put(arg,"true");
else props.put(arg.substring(0,idx),arg.substring(idx+1));
}
return props;
}
/**
* Check for "-N" or "--non-recursive" in the Maven goals/options.
*/
public boolean isNonRecursive() {
return checkMavenOption("-N", "--non-recursive");
}
/**
* Possibly null, whitespace-separated (including TAB, NL, etc) VM options
* to be used to launch Maven process.
*
* If mavenOpts is null or empty, we'll return the globally-defined MAVEN_OPTS.
*
* <p>
* This method returns a configured value as-is, which can include variabl references.
* At runtime, use {@link AbstractMavenBuild#getMavenOpts(TaskListener, EnvVars)} to obtain
* a fully resolved value.
*/
public String getMavenOpts() {
if ((mavenOpts!=null) && (mavenOpts.trim().length()>0)) {
return mavenOpts.replaceAll("[\t\r\n]+"," ");
}
else {
String globalOpts = DESCRIPTOR.getGlobalMavenOpts();
if (globalOpts!=null) {
return globalOpts.replaceAll("[\t\r\n]+"," ");
}
else {
return globalOpts;
}
}
}
/**
* Set mavenOpts.
*/
public void setMavenOpts(String mavenOpts) {
this.mavenOpts = mavenOpts;
}
/**
* Gets the Maven to invoke.
* If null, we pick any random Maven installation.
*/
public MavenInstallation getMaven() {
for( MavenInstallation i : DESCRIPTOR.getMavenDescriptor().getInstallations() ) {
if(mavenName==null || i.getName().equals(mavenName))
return i;
}
return null;
}
public void setMaven(String mavenName) {
this.mavenName = mavenName;
}
/**
* Returns the {@link MavenModule}s that are in the queue.
*/
public List<Queue.Item> getQueueItems() {
return filter(Arrays.asList(Jenkins.getInstance().getQueue().getItems()));
}
/**
* Returns the {@link MavenModule}s that are in the queue.
*/
public List<Queue.Item> getApproximateQueueItemsQuickly() {
return filter(Jenkins.getInstance().getQueue().getApproximateItemsQuickly());
}
private List<Queue.Item> filter(Collection<Queue.Item> base) {
List<Queue.Item> r = new ArrayList<Queue.Item>();
for( Queue.Item item : base) {
Task t = item.task;
if((t instanceof MavenModule && ((MavenModule)t).getParent()==this) || t ==this)
r.add(item);
}
return r;
}
/**
* Gets the list of goals specified by the user,
* without taking inheritance and POM default goals
* into account.
*
* <p>
* This is only used to present the UI screen, and in
* all the other cases {@link #getGoals()} should be used.
*/
public String getUserConfiguredGoals() {
return goals;
}
/*package*/ void reconfigure(PomInfo rootPom) throws IOException {
if(this.rootModule!=null && this.rootModule.equals(rootPom.name))
return; // no change
this.rootModule = rootPom.name;
this.defaultGoals = rootPom.defaultGoal;
save();
}
// Web methods
protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
super.submit(req,rsp);
JSONObject json = req.getSubmittedForm();
rootPOM = Util.fixEmpty(req.getParameter("rootPOM").trim());
if(rootPOM!=null && rootPOM.equals("pom.xml")) rootPOM=null; // normalization
goals = Util.fixEmpty(req.getParameter("goals").trim());
mavenOpts = Util.fixEmpty(req.getParameter("mavenOpts").trim());
settings = SettingsProvider.parseSettingsProvider(req);
globalSettings = GlobalSettingsProvider.parseSettingsProvider(req);
mavenName = req.getParameter("maven_version");
aggregatorStyleBuild = !req.hasParameter("maven.perModuleBuild");
if (json.optBoolean("usePrivateRepository"))
localRepository = req.bindJSON(LocalRepositoryLocator.class,json.getJSONObject("explicitLocalRepository"));
else
localRepository = null;
perModuleEmail = req.hasParameter("maven.perModuleEmail");
ignoreUpstremChanges = !json.has("triggerByDependency");
runHeadless = req.hasParameter("maven.runHeadless");
incrementalBuild = req.hasParameter("maven.incrementalBuild");
archivingDisabled = req.hasParameter("maven.archivingDisabled");
resolveDependencies = req.hasParameter( "maven.resolveDependencies" );
processPlugins = req.hasParameter( "maven.processPlugins" );
mavenValidationLevel = NumberUtils.toInt( req.getParameter( "maven.validationLevel" ), -1 );
reporters.rebuild(req,json,MavenReporters.getConfigurableList());
publishers.rebuildHetero(req, json, Publisher.all(), "publisher");
buildWrappers.rebuild(req,json,BuildWrappers.getFor(this));
runPostStepsIfResult = Result.fromString(req.getParameter( "post-steps.runIfResult"));
prebuilders.rebuildHetero(req,json, Builder.all(), "prebuilder");
postbuilders.rebuildHetero(req,json, Builder.all(), "postbuilder");
}
/**
* Delete all disabled modules.
*/
public HttpResponse doDoDeleteAllDisabledModules() throws IOException, InterruptedException {
checkPermission(DELETE);
for( MavenModule m : getDisabledModules(true))
m.delete();
return HttpResponses.redirectToDot();
}
/**
* Check the location of the POM, alternate settings file, etc - any file.
*/
public FormValidation doCheckFileInWorkspace(@QueryParameter String value) throws IOException, ServletException {
MavenModuleSetBuild lb = getLastBuild();
if (lb!=null) {
FilePath ws = lb.getModuleRoot();
if(ws!=null)
return ws.validateRelativePath(value,true,true);
}
return FormValidation.ok();
}
public DescriptorImpl getDescriptor() {
return DESCRIPTOR;
}
@Extension(ordinal=900)
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
public static final class DescriptorImpl extends AbstractProjectDescriptor {
/**
* Globally-defined MAVEN_OPTS.
*/
private String globalMavenOpts;
/**
* @since 1.394
*/
private Map<String, Integer> mavenValidationLevels = new LinkedHashMap<String, Integer>();
/**
* @since 1.448
*/
private LocalRepositoryLocator localRepository = new DefaultLocalRepositoryLocator();
public DescriptorImpl() {
super();
load();
mavenValidationLevels.put( "DEFAULT", -1 );
mavenValidationLevels.put( "LEVEL_MINIMAL", ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL );
mavenValidationLevels.put( "LEVEL_MAVEN_2_0", ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0 );
mavenValidationLevels.put( "LEVEL_MAVEN_3_0", ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0 );
mavenValidationLevels.put( "LEVEL_MAVEN_3_1", ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_1 );
mavenValidationLevels.put( "LEVEL_STRICT", ModelBuildingRequest.VALIDATION_LEVEL_STRICT );
}
public List<SettingsProviderDescriptor> getSettingsProviders() {
return Jenkins.getInstance().getDescriptorList(SettingsProvider.class);
}
public List<GlobalSettingsProviderDescriptor> getGlobalSettingsProviders() {
return Jenkins.getInstance().getDescriptorList(GlobalSettingsProvider.class);
}
public String getGlobalMavenOpts() {
return globalMavenOpts;
}
public void setGlobalMavenOpts(String globalMavenOpts) {
this.globalMavenOpts = globalMavenOpts;
save();
}
/**
* @return never null.
*/
public LocalRepositoryLocator getLocalRepository() {
return localRepository!=null ? localRepository : new DefaultLocalRepositoryLocator();
}
public void setLocalRepository(LocalRepositoryLocator localRepository) {
this.localRepository = localRepository;
save();
}
public String getDisplayName() {
return Messages.MavenModuleSet_DiplayName();
}
public MavenModuleSet newInstance(ItemGroup parent, String name) {
return new MavenModuleSet(parent,name);
}
public Maven.DescriptorImpl getMavenDescriptor() {
return Jenkins.getInstance().getDescriptorByType(Maven.DescriptorImpl.class);
}
/**
* @since 1.394
* @return
*/
public Map<String, Integer> getMavenValidationLevels() {
return mavenValidationLevels;
}
@Override
public boolean configure( StaplerRequest req, JSONObject o ) {
globalMavenOpts = Util.fixEmptyAndTrim(o.getString("globalMavenOpts"));
localRepository = req.bindJSON(LocalRepositoryLocator.class,o.getJSONObject("localRepository"));
save();
return true;
}
@Override
public boolean isApplicable(Descriptor descriptor) {
return !NOT_APPLICABLE_TYPES.contains(descriptor.clazz);
}
private static final Set<Class> NOT_APPLICABLE_TYPES = new HashSet<Class>(Arrays.asList(
Fingerprinter.class, // this kicks in automatically
JavadocArchiver.class, // this kicks in automatically
Mailer.class, // for historical reasons, Maven uses MavenMailer
JUnitResultArchiver.class // done by SurefireArchiver
));
}
}
|
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
public class Image implements Serializable {
public final static Integer DISABLED = 0;
public final static Integer ENABLED = 1;
public final static String MODULE = "module";
public final static String SERVER = "server";
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
private String path;
private String displayName;
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
private Integer status;
private String imageType;
private String managerName;
private String prefixEnv;
private Integer prefixId;
@JsonIgnore
@OneToMany(mappedBy = "image")
private List<Module> modules;
@JsonIgnore
@OneToMany(mappedBy = "image")
private List<Server> servers;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public List<Module> getModules() {
return modules;
}
public void setModules(List<Module> modules) {
this.modules = modules;
}
public List<Server> getServers() {
return servers;
}
public void setServers(List<Server> servers) {
this.servers = servers;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getImageType() {
return imageType;
}
public void setImageType(String imageType) {
this.imageType = imageType;
}
public String getManagerName() {
return managerName;
}
public void setManagerName(String managerName) {
this.managerName = managerName;
}
@Override
public String toString() {
return "Image [id=" + id + ", name=" + name + ", path=" + path + ", status=" + status + ", imageType="
+ imageType + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Image other = (Image) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public String getPrefixEnv() {
return prefixEnv;
}
public void setPrefixEnv(String prefixEnv) {
this.prefixEnv = prefixEnv;
}
// do not remove prefixId use for splitting server by nature
public Integer getPrefixId() {
return prefixEnv.hashCode();
}
}
|
package alien4cloud.paas.cloudify3.service;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.xml.bind.DatatypeConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import alien4cloud.paas.cloudify3.model.CloudifyLifeCycle;
import alien4cloud.paas.cloudify3.model.Event;
import alien4cloud.paas.cloudify3.model.EventAlienPersistent;
import alien4cloud.paas.cloudify3.model.EventAlienWorkflow;
import alien4cloud.paas.cloudify3.model.EventAlienWorkflowStarted;
import alien4cloud.paas.cloudify3.model.EventType;
import alien4cloud.paas.cloudify3.model.NodeInstance;
import alien4cloud.paas.cloudify3.model.Workflow;
import alien4cloud.paas.cloudify3.restclient.DeploymentEventClient;
import alien4cloud.paas.cloudify3.restclient.NodeInstanceClient;
import alien4cloud.paas.model.AbstractMonitorEvent;
import alien4cloud.paas.model.DeploymentStatus;
import alien4cloud.paas.model.PaaSDeploymentStatusMonitorEvent;
import alien4cloud.paas.model.PaaSInstancePersistentResourceMonitorEvent;
import alien4cloud.paas.model.PaaSInstanceStateMonitorEvent;
import alien4cloud.paas.model.PaaSTopologyDeploymentContext;
import alien4cloud.paas.model.PaaSWorkflowMonitorEvent;
import alien4cloud.paas.model.PaaSWorkflowStepMonitorEvent;
import alien4cloud.utils.MapUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
/**
* Handle cloudify 3 events request
*/
@Component("cloudify-event-service")
@Slf4j
public class EventService {
@Resource
private DeploymentEventClient eventClient;
@Resource
private NodeInstanceClient nodeInstanceClient;
@Resource
private StatusService statusService;
/**
* Hold last event ids
*/
private Set<String> lastEvents;
private long lastRequestedTimestamp;
@Resource
private ScalableComputeReplacementService scalableComputeReplacementService;
// TODO : May manage in a better manner this kind of state
private Map<String, String> paaSDeploymentIdToAlienDeploymentIdMapping = Maps.newConcurrentMap();
private Map<String, String> alienDeploymentIdToPaaSDeploymentIdMapping = Maps.newConcurrentMap();
public void init(Map<String, PaaSTopologyDeploymentContext> activeDeploymentContexts) {
for (Map.Entry<String, PaaSTopologyDeploymentContext> activeDeploymentContextEntry : activeDeploymentContexts.entrySet()) {
paaSDeploymentIdToAlienDeploymentIdMapping.put(activeDeploymentContextEntry.getKey(), activeDeploymentContextEntry.getValue().getDeploymentId());
alienDeploymentIdToPaaSDeploymentIdMapping.put(activeDeploymentContextEntry.getValue().getDeploymentId(), activeDeploymentContextEntry.getKey());
}
}
/**
* This queue is used for internal events
*/
private List<AbstractMonitorEvent> internalProviderEventsQueue = Lists.newLinkedList();
private static final long delay = 2 * 1000L;
public synchronized ListenableFuture<AbstractMonitorEvent[]> getEventsSince(final Date lastTimestamp, int batchSize) {
// TODO Workaround as cloudify 3 seems do not respect appearance order of event based on timestamp
if (lastEvents != null) {
lastTimestamp.setTime(lastTimestamp.getTime() - delay);
} else {
lastEvents = Sets.newConcurrentHashSet();
}
// Process internal events
final ListenableFuture<AbstractMonitorEvent[]> internalEvents = processInternalQueue(batchSize);
if (internalEvents != null) {
// Deliver internal events first, next time when Alien poll, we'll deliver cloudify events
return internalEvents;
}
// Try to get events from cloudify
ListenableFuture<Event[]> eventsFuture;
// If the request is on the same timestamp then iterate from the last event size
// TODO It's like a queue consumption and it's really ugly
if (lastRequestedTimestamp == lastTimestamp.getTime()) {
eventsFuture = eventClient.asyncGetBatch(null, lastTimestamp, lastEvents.size(), batchSize);
} else {
eventsFuture = eventClient.asyncGetBatch(null, lastTimestamp, 0, batchSize);
}
lastRequestedTimestamp = lastTimestamp.getTime();
Function<Event[], AbstractMonitorEvent[]> cloudify3ToAlienEventsAdapter = new Function<Event[], AbstractMonitorEvent[]>() {
@Override
public AbstractMonitorEvent[] apply(Event[] cloudifyEvents) {
// Convert cloudify events to alien events
List<Event> eventsAfterFiltering = Lists.newArrayList();
for (Event cloudifyEvent : cloudifyEvents) {
if (!lastEvents.contains(cloudifyEvent.getId())) {
eventsAfterFiltering.add(cloudifyEvent);
} else if (log.isDebugEnabled()) {
log.debug("Filtering event " + cloudifyEvent.getId() + ", last events size " + lastEvents.size());
}
}
if (lastRequestedTimestamp != lastTimestamp.getTime()) {
// Only clear last events if the last requested timestamp has changed
lastEvents.clear();
}
for (Event cloudifyEvent : cloudifyEvents) {
lastEvents.add(cloudifyEvent.getId());
}
List<AbstractMonitorEvent> alienEvents = toAlienEvents(eventsAfterFiltering);
return alienEvents.toArray(new AbstractMonitorEvent[alienEvents.size()]);
}
};
ListenableFuture<AbstractMonitorEvent[]> alienEventsFuture = Futures.transform(eventsFuture, cloudify3ToAlienEventsAdapter);
// Add a callback to deliver deployment status events
Futures.addCallback(alienEventsFuture, new FutureCallback<AbstractMonitorEvent[]>() {
@Override
public void onSuccess(AbstractMonitorEvent[] result) {
for (final AbstractMonitorEvent event : result) {
if (event instanceof PaaSDeploymentStatusMonitorEvent) {
if (log.isDebugEnabled()) {
log.debug("Send event {} to Alien", event);
}
final DeploymentStatus deploymentStatus = ((PaaSDeploymentStatusMonitorEvent) event).getDeploymentStatus();
final String paaSDeploymentId = alienDeploymentIdToPaaSDeploymentIdMapping.get(event.getDeploymentId());
statusService.registerDeploymentEvent(paaSDeploymentId, deploymentStatus);
if (DeploymentStatus.DEPLOYED.equals(deploymentStatus)) {
log.info("Deployment {} has finished successfully", paaSDeploymentId);
} else if (DeploymentStatus.UNDEPLOYED.equals(deploymentStatus)) {
log.info("Un-Deployment {} has finished successfully", paaSDeploymentId);
paaSDeploymentIdToAlienDeploymentIdMapping.remove(paaSDeploymentId);
alienDeploymentIdToPaaSDeploymentIdMapping.remove(event.getDeploymentId());
} else {
log.info("Deployment {} has finished with status {}", paaSDeploymentId,
((PaaSDeploymentStatusMonitorEvent) event).getDeploymentStatus());
}
}
}
}
@Override
public void onFailure(Throwable t) {
log.error("Error happened while trying to retrieve events", t);
}
});
return alienEventsFuture;
}
public synchronized void registerDeploymentEvent(String deploymentPaaSId, String deploymentId, DeploymentStatus deploymentStatus) {
statusService.registerDeploymentEvent(deploymentPaaSId, deploymentStatus);
paaSDeploymentIdToAlienDeploymentIdMapping.put(deploymentPaaSId, deploymentId);
alienDeploymentIdToPaaSDeploymentIdMapping.put(deploymentId, deploymentPaaSId);
PaaSDeploymentStatusMonitorEvent deploymentStatusMonitorEvent = new PaaSDeploymentStatusMonitorEvent();
deploymentStatusMonitorEvent.setDeploymentStatus(deploymentStatus);
deploymentStatusMonitorEvent.setDeploymentId(deploymentId);
internalProviderEventsQueue.add(deploymentStatusMonitorEvent);
}
/**
* Register an event to be added to the queue to dispatch it to Alien 4 Cloud.
*
* @param event The event to be dispatched.
*/
public synchronized void registerEvent(AbstractMonitorEvent event) {
internalProviderEventsQueue.add(event);
}
private ListenableFuture<AbstractMonitorEvent[]> processInternalQueue(int batchSize) {
if (internalProviderEventsQueue.isEmpty()) {
return null;
}
List<AbstractMonitorEvent> toBeReturned = internalProviderEventsQueue;
if (internalProviderEventsQueue.size() > batchSize) {
// There are more than the required batch
toBeReturned = internalProviderEventsQueue.subList(0, batchSize);
}
try {
if (log.isDebugEnabled()) {
for (AbstractMonitorEvent event : toBeReturned) {
log.debug("Send event {} to Alien", event);
}
}
return Futures.immediateFuture(toBeReturned.toArray(new AbstractMonitorEvent[toBeReturned.size()]));
} finally {
if (toBeReturned == internalProviderEventsQueue) {
// Less than required batch
internalProviderEventsQueue.clear();
} else {
// More than required batch
List<AbstractMonitorEvent> newQueue = Lists.newLinkedList();
for (int i = batchSize; i < internalProviderEventsQueue.size(); i++) {
newQueue.add(internalProviderEventsQueue.get(i));
}
internalProviderEventsQueue.clear();
internalProviderEventsQueue = newQueue;
}
}
}
private List<AbstractMonitorEvent> toAlienEvents(List<Event> cloudifyEvents) {
final List<AbstractMonitorEvent> alienEvents = Lists.newArrayList();
for (Event cloudifyEvent : cloudifyEvents) {
AbstractMonitorEvent alienEvent = toAlienEvent(cloudifyEvent);
if (alienEvent != null) {
if (log.isDebugEnabled()) {
log.debug("Received event {}", cloudifyEvent);
}
alienEvents.add(alienEvent);
// [[ Scaling issue workarround
scalableComputeReplacementService.processEventForSubstitutes(alienEvents, alienEvent, cloudifyEvent);
// Scaling issue workarround ]]
} else {
if (log.isDebugEnabled()) {
log.debug("Filtered event {}", cloudifyEvent);
}
}
}
return alienEvents;
}
private AbstractMonitorEvent toAlienEvent(Event cloudifyEvent) {
AbstractMonitorEvent alienEvent;
switch (cloudifyEvent.getEventType()) {
case EventType.WORKFLOW_SUCCEEDED:
PaaSDeploymentStatusMonitorEvent succeededStatusEvent = new PaaSDeploymentStatusMonitorEvent();
if (Workflow.INSTALL.equals(cloudifyEvent.getContext().getWorkflowId())) {
succeededStatusEvent.setDeploymentStatus(DeploymentStatus.DEPLOYED);
} else if (Workflow.DELETE_DEPLOYMENT_ENVIRONMENT.equals(cloudifyEvent.getContext().getWorkflowId())) {
succeededStatusEvent.setDeploymentStatus(DeploymentStatus.UNDEPLOYED);
} else {
return null;
}
alienEvent = succeededStatusEvent;
break;
case EventType.WORKFLOW_FAILED:
PaaSDeploymentStatusMonitorEvent failedStatusEvent = new PaaSDeploymentStatusMonitorEvent();
failedStatusEvent.setDeploymentStatus(DeploymentStatus.FAILURE);
alienEvent = failedStatusEvent;
break;
case EventType.TASK_SUCCEEDED:
if (Workflow.DELETE_DEPLOYMENT_ENVIRONMENT.equals(cloudifyEvent.getContext().getWorkflowId())
&& "riemann_controller.tasks.delete".equals(cloudifyEvent.getContext().getTaskName())) {
PaaSDeploymentStatusMonitorEvent undeployedEvent = new PaaSDeploymentStatusMonitorEvent();
undeployedEvent.setDeploymentStatus(DeploymentStatus.UNDEPLOYED);
alienEvent = undeployedEvent;
} else {
String newInstanceState = CloudifyLifeCycle.getSucceededInstanceState(cloudifyEvent.getContext().getOperation());
if (newInstanceState == null) {
return null;
}
PaaSInstanceStateMonitorEvent instanceTaskStartedEvent = new PaaSInstanceStateMonitorEvent();
instanceTaskStartedEvent.setInstanceId(cloudifyEvent.getContext().getNodeId());
instanceTaskStartedEvent.setNodeTemplateId(cloudifyEvent.getContext().getNodeName());
instanceTaskStartedEvent.setInstanceState(newInstanceState);
instanceTaskStartedEvent.setInstanceStatus(statusService.getInstanceStatusFromState(newInstanceState));
alienEvent = instanceTaskStartedEvent;
}
break;
case EventType.A4C_PERSISTENT_EVENT:
log.info("Received persistent event " + cloudifyEvent.getId());
String persistentCloudifyEvent = cloudifyEvent.getMessage().getText();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
try {
EventAlienPersistent eventAlienPersistent = objectMapper.readValue(persistentCloudifyEvent, EventAlienPersistent.class);
// query API
// TODO make that Async
NodeInstance instance = nodeInstanceClient.read(cloudifyEvent.getContext().getNodeId());
String attributeValue = (String) MapUtil.get(instance.getRuntimeProperties(), eventAlienPersistent.getPersistentResourceId());
alienEvent = new PaaSInstancePersistentResourceMonitorEvent(cloudifyEvent.getContext().getNodeName(), cloudifyEvent.getContext().getNodeId(),
eventAlienPersistent.getPersistentAlienAttribute(), attributeValue);
// [[ Scaling issue workarround
scalableComputeReplacementService.processPersistentResourceEvent(eventAlienPersistent, (PaaSInstancePersistentResourceMonitorEvent) alienEvent,
cloudifyEvent);
// Scaling issue workarround ]]
} catch (Exception e) {
return null;
}
break;
case EventType.A4C_WORKFLOW_STARTED:
String wfCloudifyEvent = cloudifyEvent.getMessage().getText();
objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
try {
EventAlienWorkflowStarted eventAlienWorkflowStarted = objectMapper.readValue(wfCloudifyEvent, EventAlienWorkflowStarted.class);
PaaSWorkflowMonitorEvent pwme = new PaaSWorkflowMonitorEvent();
pwme.setExecutionId(cloudifyEvent.getContext().getExecutionId());
pwme.setWorkflowId(eventAlienWorkflowStarted.getWorkflowName());
pwme.setSubworkflow(eventAlienWorkflowStarted.getSubworkflow());
alienEvent = pwme;
} catch (IOException e) {
return null;
}
break;
case EventType.A4C_WORKFLOW_EVENT:
wfCloudifyEvent = cloudifyEvent.getMessage().getText();
objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
try {
EventAlienWorkflow eventAlienPersistent = objectMapper.readValue(wfCloudifyEvent, EventAlienWorkflow.class);
PaaSWorkflowStepMonitorEvent e = new PaaSWorkflowStepMonitorEvent();
e.setNodeId(cloudifyEvent.getContext().getNodeName());
e.setInstanceId(cloudifyEvent.getContext().getNodeId());
e.setStepId(eventAlienPersistent.getStepId());
e.setStage(eventAlienPersistent.getStage());
String workflowId = cloudifyEvent.getContext().getWorkflowId();
e.setExecutionId(cloudifyEvent.getContext().getExecutionId());
if (workflowId.startsWith(Workflow.A4C_PREFIX)) {
workflowId = workflowId.substring(Workflow.A4C_PREFIX.length());
}
e.setWorkflowId(cloudifyEvent.getContext().getWorkflowId());
alienEvent = e;
} catch (IOException e) {
return null;
}
break;
default:
return null;
}
alienEvent.setDate(DatatypeConverter.parseDateTime(cloudifyEvent.getTimestamp()).getTimeInMillis());
String alienDeploymentId = paaSDeploymentIdToAlienDeploymentIdMapping.get(cloudifyEvent.getContext().getDeploymentId());
if (alienDeploymentId == null) {
if (log.isDebugEnabled()) {
log.debug("Alien deployment id is not found for paaS deployment {}, must ignore this event {}", cloudifyEvent.getContext().getDeploymentId(),
cloudifyEvent);
}
return null;
}
alienEvent.setDeploymentId(alienDeploymentId);
return alienEvent;
}
}
|
package edu.msu.nscl.olog.api;
import static edu.msu.nscl.olog.api.LogBuilder.log;
import static edu.msu.nscl.olog.api.PropertyBuilder.property;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.imageio.ImageIO;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriBuilder;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
import com.sun.jersey.client.urlconnection.HTTPSProperties;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import com.sun.jersey.client.apache.ApacheHttpClient;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.jackrabbit.webdav.DavConstants;
import org.apache.jackrabbit.webdav.DavException;
import org.apache.jackrabbit.webdav.MultiStatus;
import org.apache.jackrabbit.webdav.MultiStatusResponse;
import org.apache.jackrabbit.webdav.client.methods.DavMethod;
import org.apache.jackrabbit.webdav.client.methods.MkColMethod;
import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
import org.apache.jackrabbit.webdav.client.methods.PutMethod;
/**
*
* TODO: replace the usage of Xml* types with log,tag,logbooks
*
* @author Eric Berryman taken from shroffk
*
*/
public class OlogClientImpl implements OlogClient {
private final WebResource service;
private final HttpClient webdav;
private final ExecutorService executor;
private final URI ologJCRBaseURI;
/**
* Builder Class to help create a olog client.
*
* @author shroffk
*
*/
public static class OlogClientBuilder {
// required
private URI ologURI = null;
private URI ologJCRURI;
// optional
private boolean withHTTPAuthentication = false;
private ClientConfig clientConfig = null;
private TrustManager[] trustManager = new TrustManager[] { new DummyX509TrustManager() };;
@SuppressWarnings("unused")
private SSLContext sslContext = null;
private String protocol = null;
private String username = null;
private String password = null;
private ExecutorService executor = Executors.newSingleThreadExecutor();
private OlogProperties properties = new OlogProperties();
private static final String DEFAULT_OLOG_URL = "http://localhost:8080/Olog/resources"; //$NON-NLS-1$
private static final String DEFAULT_OLOG_JCR_URL = "http://localhost:8080/Olog/repository";
private OlogClientBuilder() {
this.ologURI = URI.create(this.properties.getPreferenceValue(
"olog_url", DEFAULT_OLOG_URL));
this.ologJCRURI = URI.create(this.properties.getPreferenceValue(
"olog_jcr_url", DEFAULT_OLOG_JCR_URL));
this.protocol = this.ologURI.getScheme();
}
private OlogClientBuilder(URI uri) {
this.ologURI = uri;
this.protocol = this.ologURI.getScheme();
}
/**
* Creates a {@link OlogClientBuilder} for a CF client to Default URL in
* the channelfinder.properties.
*
* @return
*/
public static OlogClientBuilder serviceURL() {
return new OlogClientBuilder();
}
/**
* Creates a {@link OlogClientBuilder} for a CF client to URI
* <tt>uri</tt>.
*
* @param uri
* @return {@link OlogClientBuilder}
*/
public static OlogClientBuilder serviceURL(String uri) {
return new OlogClientBuilder(URI.create(uri));
}
/**
* Creates a {@link OlogClientBuilder} for a CF client to {@link URI}
* <tt>uri</tt>.
*
* @param uri
* @return {@link OlogClientBuilder}
*/
public static OlogClientBuilder serviceURL(URI uri) {
return new OlogClientBuilder(uri);
}
/**
* Set the jcr url to be used for the attachment repository.
*
* @param username
* @return {@link OlogClientBuilder}
*/
public OlogClientBuilder jcrURI(URI jcrURI) {
this.ologJCRURI = jcrURI;
return this;
}
/**
* Set the jcr url to be used for the attachment repository.
*
* @param username
* @return {@link OlogClientBuilder}
*/
public OlogClientBuilder jcrURI(String jcrURI) {
this.ologJCRURI = UriBuilder.fromUri(jcrURI).build();
return this;
}
/**
* Enable of Disable the HTTP authentication on the client connection.
*
* @param withHTTPAuthentication
* @return {@link OlogClientBuilder}
*/
public OlogClientBuilder withHTTPAuthentication(
boolean withHTTPAuthentication) {
this.withHTTPAuthentication = withHTTPAuthentication;
return this;
}
/**
* Set the username to be used for HTTP Authentication.
*
* @param username
* @return {@link OlogClientBuilder}
*/
public OlogClientBuilder username(String username) {
this.username = username;
return this;
}
/**
* Set the password to be used for the HTTP Authentication.
*
* @param password
* @return {@link OlogClientBuilder}
*/
public OlogClientBuilder password(String password) {
this.password = password;
return this;
}
/**
* set the {@link ClientConfig} to be used while creating the
* channelfinder client connection.
*
* @param clientConfig
* @return {@link OlogClientBuilder}
*/
public OlogClientBuilder withClientConfig(ClientConfig clientConfig) {
this.clientConfig = clientConfig;
return this;
}
@SuppressWarnings("unused")
private OlogClientBuilder withSSLContext(SSLContext sslContext) {
this.sslContext = sslContext;
return this;
}
/**
* Set the trustManager that should be used for authentication.
*
* @param trustManager
* @return {@link OlogClientBuilder}
*/
public OlogClientBuilder withTrustManager(TrustManager[] trustManager) {
this.trustManager = trustManager;
return this;
}
/**
* Provide your own executor on which the queries are to be made. <br>
* By default a single threaded executor is used.
*
* @param executor
* @return {@link OlogClientBuilder}
*/
public OlogClientBuilder withExecutor(ExecutorService executor) {
this.executor = executor;
return this;
}
public OlogClientImpl create() {
if (this.protocol.equalsIgnoreCase("http")) { //$NON-NLS-1$
this.clientConfig = new DefaultClientConfig();
} else if (this.protocol.equalsIgnoreCase("https")) { //$NON-NLS-1$
if (this.clientConfig == null) {
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("SSL"); //$NON-NLS-1$
sslContext.init(null, this.trustManager, null);
} catch (NoSuchAlgorithmException e) {
throw new OlogException();
} catch (KeyManagementException e) {
throw new OlogException();
}
this.clientConfig = new DefaultClientConfig();
this.clientConfig.getProperties().put(
HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
new HTTPSProperties(new HostnameVerifier() {
@Override
public boolean verify(String hostname,
SSLSession session) {
return true;
}
}, sslContext));
}
this.username = ifNullReturnPreferenceValue(this.username,
"username", "username");
this.password = ifNullReturnPreferenceValue(this.password,
"password", "password");
}
return new OlogClientImpl(this.ologURI, this.ologJCRURI,
this.clientConfig, this.withHTTPAuthentication,
this.username, this.password, this.executor);
}
private String ifNullReturnPreferenceValue(String value, String key,
String Default) {
if (value == null) {
return this.properties.getPreferenceValue(key, Default);
} else {
return value;
}
}
}
private OlogClientImpl(URI ologURI, URI ologJCRURI, ClientConfig config,
boolean withHTTPBasicAuthFilter, String username, String password,
ExecutorService executor) {
this.ologJCRBaseURI = ologJCRURI;
this.executor = executor;
Client client = Client.create(config);
if (withHTTPBasicAuthFilter) {
client.addFilter(new HTTPBasicAuthFilter(username, password));
}
// client.addFilter(new
// RawLoggingFilter(Logger.getLogger(RawLoggingFilter.class.getName())));
service = client.resource(UriBuilder.fromUri(ologURI).build());
ApacheHttpClient client2Apache = ApacheHttpClient.create(config);
webdav = client2Apache.getClientHandler().getHttpClient();
webdav.getHostConfiguration().setHost(getJCRBaseURI().getHost(), 8181);
Credentials credentials = new UsernamePasswordCredentials(username,
password);
webdav.getState().setCredentials(AuthScope.ANY, credentials);
webdav.getParams().setAuthenticationPreemptive(true);
}
/**
* Get a list of all the logbooks currently existing
*
* @return string collection of logbooks
*/
public Collection<String> getAllLogbooks() {
return wrappedSubmit(new GetAllResrouce("logbooks"));
}
/**
* Get a list of all the tags currently existing
*
* @return string collection of tags
*/
public Collection<String> getAllTags() {
return wrappedSubmit(new GetAllResrouce("tags"));
}
/**
* Get a list of all the levels currently existing
*
* @return string collection of levels
*/
@SuppressWarnings("deprecation")
public Collection<String> getAllLevels() {
return wrappedSubmit(new GetAllResrouce("levels"));
}
private class GetAllResrouce implements Callable<Collection<String>> {
private final String path;
public GetAllResrouce(String path) {
this.path = path;
}
@Override
public Collection<String> call() throws UniformInterfaceException {
Collection<String> allResources = new HashSet<String>();
if (path.equalsIgnoreCase("logbooks")) {
XmlLogbooks allXmlLogbooks = service.path("logbooks")
.accept(MediaType.APPLICATION_XML)
.get(XmlLogbooks.class);
for (XmlLogbook xmlLogbook : allXmlLogbooks.getLogbooks()) {
allResources.add(xmlLogbook.getName());
}
} else if (path.equalsIgnoreCase("tags")) {
XmlTags allXmlTags = service.path("tags")
.accept(MediaType.APPLICATION_XML).get(XmlTags.class);
for (XmlTag xmlTag : allXmlTags.getTags()) {
allResources.add(xmlTag.getName());
}
} else if (path.equalsIgnoreCase("levels")) {
XmlLevels allXmlLevels = service.path("levels")
.accept(MediaType.APPLICATION_XML).get(XmlLevels.class);
for (XmlLevel xmlLevel : allXmlLevels.getLevels()) {
allResources.add(xmlLevel.getName());
}
}
return allResources;
}
}
private <T> T wrappedSubmit(Callable<T> callable) {
try {
return this.executor.submit(callable).get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
if (e.getCause() != null
&& e.getCause() instanceof UniformInterfaceException) {
throw new OlogException(
(UniformInterfaceException) e.getCause());
}
throw new RuntimeException(e);
}
}
private URI getJCRBaseURI() {
return this.ologJCRBaseURI;
}
/**
* Returns a collection of attachments that matches the logId <tt>logId</tt>
*
* @param logId
* log id
* @return attachments collection object
* @throws OlogException
*/
public Collection<String> getAttachments(Long logId) throws OlogException,
DavException {
Collection<String> allFiles = new HashSet<String>();
try {
URI remote = UriBuilder.fromUri(getJCRBaseURI()).path("{arg1}/")
.build(logId);
DavMethod pFind = new PropFindMethod(remote.toASCIIString(),
DavConstants.PROPFIND_ALL_PROP, DavConstants.DEPTH_1);
webdav.executeMethod(pFind);
MultiStatus multiStatus = pFind.getResponseBodyAsMultiStatus();
MultiStatusResponse[] responses = multiStatus.getResponses();
MultiStatusResponse currResponse;
for (int i = 0; i < responses.length; i++) {
currResponse = responses[i];
if (!currResponse.getHref().endsWith("/")) {
allFiles.add(currResponse.getHref());
}
}
pFind.releaseConnection();
return allFiles;
} catch (UniformInterfaceException e) {
throw new OlogException(e);
} catch (IOException e) {
throw new OlogException(e);
}
}
/**
* Returns a log that exactly matches the logId <tt>logId</tt>
*
* @param logId
* log id
* @return Log object
* @throws OlogException
*/
public Log getLog(Long logId) throws OlogException {
try {
return new Log(service.path("logs").path(logId.toString()).accept( //$NON-NLS-1$
MediaType.APPLICATION_XML).get(XmlLog.class));
} catch (UniformInterfaceException e) {
throw new OlogException(e);
}
}
/**
* Add a single log <tt>log</tt>
*
* @param log
* the log to be added
* @throws OlogException
*/
public Log add(LogBuilder log) throws OlogException {
try {
ClientResponse incResponse;
XmlLogs xmlLogs = new XmlLogs();
xmlLogs.addXmlLog(log.toXml());
if (log.toXml().getId() != null) {
// throw new OlogException();
// TODO: Fail? use UpdateLog instead?
// service logs/id does not reply with inserted Log
// this doesn't seem right to just return the object given
service.path("logs").path(log.toXml().getId().toString()).accept( //$NON-NLS-1$
MediaType.APPLICATION_XML).type( //$NON-NLS-1$
MediaType.APPLICATION_XML)
.put(ClientResponse.class, log.toXml());
return log.build();
} else {
incResponse = service.path("logs").accept( //$NON-NLS-1$
MediaType.APPLICATION_XML).type( //$NON-NLS-1$
MediaType.APPLICATION_XML)
.post(ClientResponse.class, xmlLogs);
}
XmlLogs response = incResponse.getEntity(XmlLogs.class);
return new Log(response.getLogs().iterator().next());
} catch (UniformInterfaceException e) {
throw new OlogException(e);
}
}
/**
* Add a set of logs
*
* @param logs
* set of logs to be added
* @throws OlogException
*/
public Collection<Log> add(Collection<LogBuilder> logs)
throws OlogException {
try {
XmlLogs xmlLogs = new XmlLogs();
Collection<Log> returnLogs = new HashSet<Log>();
for (LogBuilder log : logs) {
xmlLogs.addXmlLog(log.toXml());
}
ClientResponse incResponse = service.path("logs").accept( //$NON-NLS-1$
MediaType.APPLICATION_XML).type( //$NON-NLS-1$
MediaType.APPLICATION_XML)
.post(ClientResponse.class, xmlLogs);
XmlLogs response = incResponse.getEntity(XmlLogs.class);
for (XmlLog xmllog : response.getLogs()) {
returnLogs.add(new Log(xmllog));
}
return Collections.unmodifiableCollection(returnLogs);
} catch (UniformInterfaceException e) {
throw new OlogException(e);
}
}
/**
* Add a Tag <tt>tag</tt> with no associated logs to the database.
*
* @param tag
*/
public void add(TagBuilder tag) {
try {
XmlTag xmlTag = tag.toXml();
service.path("tags").path(xmlTag.getName())
.accept(MediaType.APPLICATION_XML)
.accept(MediaType.APPLICATION_JSON).put(xmlTag);
} catch (UniformInterfaceException e) {
throw new OlogException(e);
}
}
/**
* Add Tag <tt>tag </tt> to Log with name <tt>logName</tt>
*
* @param tag
* tag builder
* @param logId
* log id the tag to be added
*/
public void add(TagBuilder tag, Long logId) {
Log log = getLog(logId);
if (log != null) {
updateLog(log(log).with(tag));
}
}
/**
* Add the Tag <tt>tag</tt> to the set of the logs with ids <tt>logIds</tt>
*
* @param tag
* tag builder
* @param logIds
* collection of log ids
*/
public void add(TagBuilder tag, Collection<Long> logIds) {
for (Long logId : logIds) {
add(tag, logId);
}
}
/**
* Add a new logbook <tt>logbook</tt>
*
* @param logbookBuilder
*/
public void add(LogbookBuilder logbookBuilder) {
try {
XmlLogbook logbook = logbookBuilder.toXml();
service.path("logbooks").path(logbook.getName())
.accept(MediaType.APPLICATION_XML)
.accept(MediaType.APPLICATION_JSON).put(logbook);
} catch (UniformInterfaceException e) {
throw new OlogException(e);
}
}
/**
* Add Logbook <tt>logbook</tt> to the log <tt>logId</tt>
*
* @param logbook
* logbook builder
* @param logId
* log id
*/
public void add(LogbookBuilder logbook, Long logId) {
Log log = getLog(logId);
if (log != null) {
updateLog(log(log).in(logbook));
}
}
/**
* @param logIds
* @param logbook
*/
public void add(LogbookBuilder logbook, Collection<Long> logIds) {
for (Long logId : logIds) {
add(logbook, logId);
}
}
/**
* Add Property <tt>property</tt> to Log with id <tt>logId</tt>
*
* @param property
* property builder
* @param logId
* log id the property to be added
*/
public void add(PropertyBuilder property, Long logId) {
Log log = getLog(logId);
if (log != null) {
updateLog(log(log).property(property));
}
}
/**
* Add the Property <tt>property</tt> to the set of the logs with ids
* <tt>logIds</tt>
*
* @param property
* property builder
* @param logIds
* collection of log ids
*/
public void add(PropertyBuilder property, Collection<Long> logIds) {
for (Long logId : logIds) {
add(property, logId);
}
}
/**
* @param logId
* @param local
*/
public void add(File local, Long logId) {
URI remote = UriBuilder.fromUri(getJCRBaseURI()).path("{arg1}")
.path("{arg2}").build(logId, local.getName());
URI remoteThumb = UriBuilder.fromUri(getJCRBaseURI())
.path("thumbnails").path("{arg1}").path("{arg2}")
.build(logId, local.getName());
URI remoteDir = UriBuilder.fromUri(getJCRBaseURI()).path("{arg1}")
.build(logId);
URI remoteThumbDir = UriBuilder.fromUri(getJCRBaseURI())
.path("thumbnails").path("{arg1}").build(logId);
final int ndx = local.getName().lastIndexOf(".");
final String extension = local.getName().substring(ndx + 1);
DavMethod mkCol = new MkColMethod(remoteDir.toASCIIString());
DavMethod mkColThumb = new MkColMethod(remoteThumbDir.toASCIIString());
PutMethod putM = new PutMethod(remote.toASCIIString());
PutMethod putMThumb = new PutMethod(remoteThumb.toASCIIString());
try {
PropFindMethod propM = new PropFindMethod(remoteDir.toASCIIString());
webdav.executeMethod(propM);
if (!propM.succeeded())
webdav.executeMethod(mkCol);
propM.releaseConnection();
mkCol.releaseConnection();
} catch (IOException ex) {
throw new OlogException(ex);
}
try {
FileInputStream fis = new FileInputStream(local);
RequestEntity requestEntity = new InputStreamRequestEntity(fis);
putM.setRequestEntity(requestEntity);
webdav.executeMethod(putM);
putM.releaseConnection();
// If image add thumbnail
if ((extension.equals("jpeg") || extension.equals("jpg")
|| extension.equals("gif") || extension.equals("png"))) {
PropFindMethod propMThumb = new PropFindMethod(
remoteThumbDir.toASCIIString());
webdav.executeMethod(propMThumb);
if (!propMThumb.succeeded())
webdav.executeMethod(mkColThumb);
propMThumb.releaseConnection();
mkColThumb.releaseConnection();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Thumbnails.of(local).size(80, 80).outputFormat("jpg")
.toOutputStream(outputStream);
InputStream fis2 = new ByteArrayInputStream(
outputStream.toByteArray());
RequestEntity requestEntity2 = new InputStreamRequestEntity(
fis2);
putMThumb.setRequestEntity(requestEntity2);
webdav.executeMethod(putMThumb);
putMThumb.releaseConnection();
}
} catch (IOException e) {
throw new OlogException(e);
}
}
/**
*
* @param pattern
* @return collection of Log objects
*/
public Collection<Log> findLogsBySearch(String pattern)
throws OlogException {
return wrappedSubmit(new FindLogs("logs", pattern));
}
/**
*
* @param pattern
* @return collection of Log objects
*/
public Collection<Log> findLogsByTag(String pattern) throws OlogException {
return wrappedSubmit(new FindLogs("tag", pattern));
}
/**
* This function is a subset of queryLogs - should it be removed??
* <p>
* TODO: add the usage of patterns and implement on top of the general query
* using the map
*
* @param logbook
* logbook name
* @return collection of Log objects
* @throws OlogException
*/
public Collection<Log> findLogsByLogbook(String logbook)
throws OlogException {
return wrappedSubmit(new FindLogs("logbook", logbook));
}
/**
* Query for logs based on the criteria specified in the map
*
* @param map
* @return collection of Log objects
*/
public Collection<Log> findLogs(Map<String, String> map)
throws OlogException {
return wrappedSubmit(new FindLogs(map));
}
/**
* Multivalued map used to search for a key with multiple values. e.g.
* logbook a=1 or logbook a=2
*
* @param map
* Multivalue map for searching a key with multiple values
* @return collection of Log objects
*/
public Collection<Log> findLogs(MultivaluedMap<String, String> map)
throws OlogException {
return wrappedSubmit(new FindLogs(map));
}
private class FindLogs implements Callable<Collection<Log>> {
private final MultivaluedMap<String, String> map;
public FindLogs(String queryParameter, String pattern) {
MultivaluedMap<String, String> mMap = new MultivaluedMapImpl();
mMap.putSingle(queryParameter, pattern);
this.map = mMap;
}
public FindLogs(MultivaluedMap<String, String> map) {
this.map = map;
}
public FindLogs(Map<String, String> map) {
MultivaluedMap<String, String> mMap = new MultivaluedMapImpl();
Iterator<Map.Entry<String, String>> itr = map.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry<String, String> entry = itr.next();
mMap.put(entry.getKey(),
Arrays.asList(entry.getValue().split(",")));
}
this.map = mMap;
}
@Override
public Collection<Log> call() throws Exception {
Collection<Log> logs = new HashSet<Log>();
XmlLogs xmlLogs = service.path("logs").queryParams(map)
.accept(MediaType.APPLICATION_XML)
.accept(MediaType.APPLICATION_JSON).get(XmlLogs.class);
for (XmlLog xmllog : xmlLogs.getLogs()) {
logs.add(new Log(xmllog));
}
return Collections.unmodifiableCollection(logs);
}
}
/**
* Remove {tag} from all logs
*
* @param tag
*/
public void deleteTag(String tag) {
try {
service.path("tags").path(tag).accept(MediaType.APPLICATION_XML) //$NON-NLS-1$
.delete();
} catch (UniformInterfaceException e) {
throw new OlogException(e);
}
}
/**
*
* @param logbook
* @throws LogFinderException
*/
public void deleteLogbook(String logbook) throws OlogException {
try {
service.path("logbooks").path(logbook)
.accept(MediaType.APPLICATION_XML)
.accept(MediaType.APPLICATION_JSON).delete();
} catch (UniformInterfaceException e) {
throw new OlogException(e);
}
}
public Collection<Log> getAllLogs() {
try {
XmlLogs logs = service.path("logs").accept( //$NON-NLS-1$
MediaType.APPLICATION_XML).get(XmlLogs.class);
Collection<Log> set = new HashSet<Log>();
for (XmlLog log : logs.getLogs()) {
set.add(new Log(log));
}
return set;
} catch (UniformInterfaceException e) {
throw new OlogException(e);
}
}
/**
* Remove the log identified by <tt>log</tt>
*
* @param log
* log to be removed
* @throws OlogException
*/
public void remove(LogBuilder log) throws OlogException {
try {
service.path("logs").path(log.toXml().getId().toString()).delete(); //$NON-NLS-1$
} catch (UniformInterfaceException e) {
throw new OlogException(e);
}
}
/**
* Remove the log identified by <tt>log</tt>
*
* @param logId
* log id log id to be removed
* @throws OlogException
*/
public void remove(Long logId) throws OlogException {
try {
service.path("logs").path(logId.toString()).delete(); //$NON-NLS-1$
} catch (UniformInterfaceException e) {
throw new OlogException(e);
}
}
/**
* Remove the log collection identified by <tt>log</tt>
*
* @param logs
* logs to be removed
* @throws OlogException
*/
public void remove(Collection<Log> logs) throws OlogException {
try {
for (Log log : logs) {
service.path("logs").path(log.getId().toString()).delete(); //$NON-NLS-1$
}
} catch (UniformInterfaceException e) {
throw new OlogException(e);
}
}
/**
* Remove tag <tt>tag</tt> from the log with the id <tt>logId</tt>
*
* @param tag
* @param logId
*/
public void remove(TagBuilder tag, Long logId) throws OlogException {
wrappedSubmit(new RemoveResourcefromLog<TagBuilder>(tag, logId));
}
/**
* Remove the tag <tt>tag </tt> from all the logs <tt>logNames</tt>
*
* @param tag
* @param logIds
* @throws OlogException
*/
public void remove(TagBuilder tag, Collection<Long> logIds)
throws OlogException {
wrappedSubmit(new RemoveResourcefromLog<TagBuilder>(tag, logIds));
}
/**
* Remove logbook <tt>logbook</tt> from the log with name <tt>logName</tt>
*
* @param logbook
* logbook builder
* @param logId
* log id
* @throws OlogException
*/
public void remove(LogbookBuilder logbook, Long logId) throws OlogException {
wrappedSubmit(new RemoveResourcefromLog<LogbookBuilder>(logbook, logId));
}
/**
* Remove the logbook <tt>logbook</tt> from the set of logs <tt>logIds</tt>
*
* @param logbook
* @param logIds
* @throws OlogException
*/
public void remove(LogbookBuilder logbook, Collection<Long> logIds)
throws OlogException {
wrappedSubmit(new RemoveResourcefromLog<LogbookBuilder>(logbook, logIds));
}
/**
* Remove property <tt>property</tt> from the log with id <tt>logId</tt>
* TODO: Should this be it's own service?
*
* @param property
* property builder
* @param logId
* log id
* @throws OlogException
*/
public void remove(PropertyBuilder property, Long logId)
throws OlogException {
wrappedSubmit(new RemoveResourcefromLog<PropertyBuilder>(property,
logId));
}
/**
* Remove the property <tt>property</tt> from the set of logs
* <tt>logIds</tt>
*
* @param property
* @param logIds
* @throws OlogException
*/
public void remove(PropertyBuilder property, Collection<Long> logIds)
throws OlogException {
wrappedSubmit(new RemoveResourcefromLog<PropertyBuilder>(property,
logIds));
}
private class RemoveResourcefromLog<T> implements Callable<Void> {
private final Collection<Long> logIds;
private final T resource;
public RemoveResourcefromLog(T resource, Collection<Long> logIds) {
this.logIds = logIds;
this.resource = resource;
}
public RemoveResourcefromLog(T resource, Long logId) {
Collection<Long> ids = new ArrayList<Long>();
ids.add(logId);
this.logIds = ids;
this.resource = resource;
}
@Override
public Void call() throws OlogException {
if (resource instanceof TagBuilder) {
for (Long logId : logIds) {
try {
TagBuilder tag = (TagBuilder) resource;
service.path("tags").path(tag.toXml().getName()).path(logId.toString()).accept( //$NON-NLS-1$
MediaType.APPLICATION_XML).delete();
} catch (UniformInterfaceException e) {
throw new OlogException(e);
}
}
} else if (resource instanceof LogbookBuilder) {
for (Long logId : logIds) {
try {
LogbookBuilder logbook = (LogbookBuilder) resource;
service.path("logbooks")
.path(logbook.toXml().getName())
.path(logId.toString())
.accept(MediaType.APPLICATION_XML)
.accept(MediaType.APPLICATION_JSON).delete();
} catch (UniformInterfaceException e) {
throw new OlogException(e);
}
}
} else if (resource instanceof PropertyBuilder) {
for (Long logId : logIds) {
PropertyBuilder property = (PropertyBuilder) resource;
Log log = getLog(logId);
// TODO consider directly deleting the property.
XmlLog xmlLog = log(log).toXml();
XmlProperties props = new XmlProperties();
for (Property prop : log.getProperties()) {
if (!prop.getName().equals(property.toXml().getName())) {
props.addXmlProperty(property(prop).toXml());
}
}
xmlLog.setXmlProperties(props);
if (log != null) {
add(log(new Log(xmlLog)));
}
}
}
return null;
}
}
/**
* Remove file attachment from log <tt>logId<tt>
*
* TODO: sardine delete hangs up, using jersey for delete
*
* @param String
* fileName
* @param Long
* logId
* @throws OlogException
*/
public void remove(String fileName, Long logId) {
try {
URI remote = UriBuilder.fromUri(getJCRBaseURI()).path("{arg1}")
.path("{arg2}").build(logId, fileName);
service.uri(remote).accept(MediaType.APPLICATION_XML)
.accept(MediaType.APPLICATION_JSON).delete();
} catch (UniformInterfaceException e) {
throw new OlogException(e);
}
}
/**
* Update logbooks and tags of existing log <tt>log</tt>
*
* @param log
* @throws OlogException
*/
public void updateLog(LogBuilder log) throws OlogException {
try {
service.path("logs").path(log.toXml().getId().toString()).type( //$NON-NLS-1$
MediaType.APPLICATION_XML).post(log.toXml());
} catch (UniformInterfaceException e) {
throw new OlogException(e);
}
}
/**
* Add tag <tt>tag</tt> to log <tt>logId</tt> and remove the tag from all
* other logs
*
* @param tag
* @param logId
* @throws OlogException
*/
public void set(TagBuilder tag, Long logId) throws OlogException {
wrappedSubmit(new SetTag(tag, logId));
}
/**
* Set tag <tt>tag</tt> on the set of logs {logs} and remove it from all
* others
*
* @param tag
* tag builder
* @param logIds
* collection of log ids
*/
public void set(TagBuilder tag, Collection<Long> logIds) {
wrappedSubmit(new SetTag(tag, logIds));
}
private class SetTag implements Runnable {
private final TagBuilder tag;
private final Collection<Long> logIds;
public SetTag(TagBuilder tag, Long logId){
Collection<Long> logs = new ArrayList<Long>();
logs.add(logId);
this.tag = tag;
this.logIds = logs;
}
public SetTag(TagBuilder tag, Collection<Long> logIds) {
this.tag = tag;
this.logIds = logIds;
}
@Override
public void run() {
try {
XmlTag xmlTag = tag.toXml();
XmlLogs logs = new XmlLogs();
LogBuilder log = null;
for (Long logId : logIds) {
log = log(getLog(logId));
logs.addXmlLog(log.toXml());
}
xmlTag.setXmlLogs(logs);
service.path("tags").path(tag.toXml().getName())
.accept(MediaType.APPLICATION_XML).put(xmlTag);
} catch (UniformInterfaceException e) {
throw new OlogException(e);
}
}
}
private void wrappedSubmit(Runnable runnable) {
try {
this.executor.submit(runnable).get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
if (e.getCause() != null
&& e.getCause() instanceof UniformInterfaceException) {
throw new OlogException(
(UniformInterfaceException) e.getCause());
}
throw new RuntimeException(e);
}
}
}
|
package org.knopflerfish.framework;
import org.osgi.framework.InvalidSyntaxException;
import java.util.Dictionary;
import java.util.Vector;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Enumeration;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.math.BigInteger;
public class LDAPExpr {
public static final int AND = 0;
public static final int OR = 1;
public static final int NOT = 2;
public static final int EQ = 4;
public static final int LE = 8;
public static final int GE = 16;
public static final int APPROX = 32;
public static final int COMPLEX = AND | OR | NOT;
public static final int SIMPLE = EQ | LE | GE | APPROX;
private static final char WILDCARD = 65535;
private static final String WILDCARD_STRING =
new String(new char [] { WILDCARD });
private static final String NULL = "Null query";
private static final String GARBAGE = "Trailing garbage";
private static final String EOS = "Unexpected end of query";
private static final String MALFORMED = "Malformed query";
private static final String EMPTY = "Empty list";
private static final String SUBEXPR = "No subexpression";
private static final String OPERATOR = "Undefined operator";
private static Class classBigDecimal;
private static Constructor consBigDecimal;
private static Method compBigDecimal;
static {
try {
classBigDecimal = Class.forName("java.math.BigDecimal");
consBigDecimal = getConstructor(classBigDecimal);
compBigDecimal = classBigDecimal.getMethod("compareTo", new Class [] { classBigDecimal });
} catch (Exception ignore) {
classBigDecimal = null;
}
}
public int operator;
public LDAPExpr[] args;
public String attrName;
public String attrValue;
// If set to non-null, return this in toString() instead
// of correct, normalized form. Required to pass some
// incorrect R3 tests
String bug = null;
public LDAPExpr(String filter) throws InvalidSyntaxException {
if(Framework.R3_TESTCOMPLIANT) {
// Workaround for bug in R3 test suite which incorrectly thinks
// fix by saving the "incorrect but expected" filter string
// and return that in toString()
String zz = " \n(& ( \tn ame = TestService1 ) ( ma ne = ServiceTest1 ) ) \r ";
String zz2 = " \n(& ( \tname = TestService1 ) ( mane = ServiceTest1 ) ) \r ";
String zz3 = "(&(n ame= TestService1 )(ma ne= ServiceTest1 ))";
if(filter.equals(zz)) {
System.out.println("*** Gah! This string is incorrectly expected to parse by the R3 test case:\n" + zz);
filter = zz2;
bug = zz3;
}
// The UPnP reference implementation uses
// Filter.toString().indexOf("UPnP....")
// to look for properties. Since the filter is
// normalized to lower case, indexOf never matches
// and the UPnP event mechanism fails.
// Fix by saving the original filter string
// and return that in toString()
if(-1 != filter.indexOf("UPnP.device.") ||
-1 != filter.indexOf("UPnP.service.")) {
System.out.println("UPnP: saving original filter case: " + filter);
bug = filter;
}
}
ParseState ps = new ParseState(filter);
LDAPExpr expr = null;
try {
expr = parseExpr(ps);
} catch (StringIndexOutOfBoundsException e) {
ps.error(EOS);
}
if (ps.rest().trim().length() != 0)
ps.error(GARBAGE + " '" + ps.rest() + "'");
operator = expr.operator;
args = expr.args;
attrName = expr.attrName;
attrValue = expr.attrValue;
}
private LDAPExpr(int operator, LDAPExpr[] args) {
this.operator = operator;
this.args = args;
this.attrName = null;
this.attrValue = null;
}
private LDAPExpr(int operator, String attrName, String attrValue) {
this.operator = operator;
this.args = null;
this.attrName = attrName;
this.attrValue = attrValue;
}
/**
* Checks if this LDAP expression is "simple". The definition of
* a simple filter is:
* <ul>
* <li><code>(<it>name</it>=<it>value</it>)</code> is simple if
* <it>name</it> is a member of the provided <code>keywords</code>,
* and <it>value</it> does not contain a wildcard character;</li>
* <li><code>(| EXPR+ )</code> is simple if all <code>EXPR</code>
* expressions are simple;</li>
* <li>No other expressions are simple.</li>
* </ul>
* If the filter is found to be simple, the <code>cache</code> is
* filled with mappings from the provided keywords to lists
* of attribute values. The keyword-value-pairs are the ones that
* satisfy this expression, for the given keywords.
*
* @param keywords The keywords to look for.
* @param cache An array (indexed by the keyword indexes) of lists to
* fill in with values saturating this expression.
* @return <code>true</code> if this expression is simple,
* <code>false</code> otherwise.
*/
public boolean isSimple(List keywords, List[] cache) {
if (operator == EQ) {
int index;
if ((index = keywords.indexOf(attrName)) >= 0 &&
attrValue.indexOf(WILDCARD) < 0) {
if (cache[index] == null) {
cache[index] = new ArrayList();
}
cache[index].add(attrValue);
return true;
}
} else if (operator == OR) {
for (int i = 0; i < args.length; i++) {
if (!args[i].isSimple(keywords, cache))
return false;
}
return true;
}
return false;
}
public static boolean query(String filter, Dictionary pd)
throws InvalidSyntaxException {
return new LDAPExpr(filter).evaluate(pd);
}
/**
* Evaluate this LDAP filter.
*/
public boolean evaluate(Dictionary p) {
if ((operator & SIMPLE) != 0) {
return compare(p.get(attrName), operator, attrValue);
} else { // (operator & COMPLEX) != 0
switch (operator) {
case AND:
for (int i = 0; i < args.length; i++) {
if (!args[i].evaluate(p))
return false;
}
return true;
case OR:
for (int i = 0; i < args.length; i++) {
if (args[i].evaluate(p))
return true;
}
return false;
case NOT:
return !args[0].evaluate(p);
default:
return false; // Cannot happen
}
}
}
protected boolean compare(Object obj, int op, String s) {
if (obj == null)
return false;
if (op == EQ && s.equals(WILDCARD_STRING))
return true;
try {
if (obj instanceof String) {
return compareString((String)obj, op, s);
} else if (obj instanceof Character) {
return compareString(obj.toString(), op, s);
} else if (obj instanceof Boolean) {
if (op==LE || op==GE)
return false;
return ((Boolean)obj).equals(new Boolean(s));
} else if (obj instanceof Number) {
if (obj instanceof Byte) {
switch(op) {
case LE:
return ((Byte)obj).byteValue() <= Byte.parseByte(s);
case GE:
return ((Byte)obj).byteValue() >= Byte.parseByte(s);
default: /*APPROX and EQ*/
return (new Byte(s)).equals(obj);
}
} else if (obj instanceof Integer) {
switch(op) {
case LE:
return ((Integer)obj).intValue() <= Integer.parseInt(s);
case GE:
return ((Integer)obj).intValue() >= Integer.parseInt(s);
default: /*APPROX and EQ*/
return (new Integer(s)).equals(obj);
}
} else if (obj instanceof Short) {
switch(op) {
case LE:
return ((Short)obj).shortValue() <= Short.parseShort(s);
case GE:
return ((Short)obj).shortValue() >= Short.parseShort(s);
default: /*APPROX and EQ*/
return (new Short(s)).equals(obj);
}
} else if (obj instanceof Long) {
switch(op) {
case LE:
return ((Long)obj).longValue() <= Long.parseLong(s);
case GE:
return ((Long)obj).longValue() >= Long.parseLong(s);
default: /*APPROX and EQ*/
return (new Long(s)).equals(obj);
}
} else if (obj instanceof Float) {
switch(op) {
case LE:
return ((Float)obj).floatValue() <= (new Float(s)).floatValue();
case GE:
return ((Float)obj).floatValue() >= (new Float(s)).floatValue();
default: /*APPROX and EQ*/
return (new Float(s)).equals(obj);
}
} else if (obj instanceof Double) {
switch(op) {
case LE:
return ((Double)obj).doubleValue() <= (new Double(s)).doubleValue();
case GE:
return ((Double)obj).doubleValue() >= (new Double(s)).doubleValue();
default: /*APPROX and EQ*/
return (new Double(s)).equals(obj);
}
} else if (obj instanceof BigInteger) {
int c = ((BigInteger)obj).compareTo(new BigInteger(s));
switch(op) {
case LE:
return c <= 0;
case GE:
return c >= 0;
default: /*APPROX and EQ*/
return c == 0;
}
} else if (classBigDecimal != null && classBigDecimal.isInstance(obj)) {
Object n = consBigDecimal.newInstance(new Object [] { s });
int c = ((Integer)compBigDecimal.invoke(obj, new Object [] { n })).intValue();
switch(op) {
case LE:
return c <= 0;
case GE:
return c >= 0;
default: /*APPROX and EQ*/
return c == 0;
}
}
} else if (obj instanceof Vector) {
for (Enumeration e=((Vector)obj).elements(); e.hasMoreElements();)
if (compare(e.nextElement(), op, s))
return true;
} else if (obj.getClass().isArray()) {
int len = Array.getLength(obj);
for(int i=0; i<len; i++)
if (compare(Array.get(obj, i), op, s))
return true;
} else {
// Extended comparison
// Allow simple EQ comparison on all classes having
// a string constructor, and use compareTo if they
// implement Comparable
Class clazz = obj.getClass();
Constructor cons = getConstructor(clazz);
if(cons != null) {
Object other = cons.newInstance(new Object [] { s } );
if(obj instanceof Comparable) {
int c = ((Comparable)obj).compareTo(other);
switch(op) {
case LE:
return c <= 0;
case GE:
return c >= 0;
default: /*APPROX and EQ*/
return c == 0;
}
} else {
boolean b = op == EQ && (obj.equals(other));
return b;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
// Clazz -> Constructor(String)
private static HashMap constructorMap = new HashMap();
/**
* Get cached String constructor for a class
*/
private static Constructor getConstructor(Class clazz) {
synchronized(constructorMap) {
// This might be null
Constructor cons = (Constructor)constructorMap.get(clazz);
// ...check if we have tried before. A failed try
// is stored as null
if(!constructorMap.containsKey(clazz)) {
try {
cons = clazz.getConstructor(new Class [] { String.class });
} catch (Exception e) {
// remember by storing null in map
}
constructorMap.put(clazz, cons);
}
return cons;
}
}
private static boolean compareString(String s1, int op, String s2) {
switch(op) {
case LE:
return s1.compareTo(s2) <= 0;
case GE:
return s1.compareTo(s2) >= 0;
case EQ:
return patSubstr(s1,s2);
case APPROX:
return fixupString(s2).equals(fixupString(s1));
default:
return false;
}
}
private static String fixupString(String s) {
StringBuffer sb = new StringBuffer();
int len = s.length();
boolean isStart = true;
boolean isWhite = false;
for(int i=0; i<len; i++) {
char c = s.charAt(i);
if (Character.isWhitespace(c)) {
isWhite = true;
} else {
if (!isStart && isWhite)
sb.append(' ');
if (Character.isUpperCase(c))
c = Character.toLowerCase(c);
sb.append(c);
isStart = false;
isWhite = false;
}
}
return sb.toString();
}
private static boolean patSubstr(String s, String pat) {
return s==null ? false : patSubstr(s.toCharArray(),0,pat.toCharArray(),0);
}
private static boolean patSubstr(char[] s, int si, char[] pat, int pi) {
if (pat.length-pi == 0)
return s.length-si == 0;
if (pat[pi] == WILDCARD) {
pi++;
for (;;) {
if (patSubstr( s, si, pat, pi ))
return true;
if (s.length-si == 0)
return false;
si++;
}
} else {
if (s.length-si==0 || s[si]!=pat[pi])
return false;
return patSubstr( s, ++si, pat, ++pi );
}
}
private static LDAPExpr parseExpr(ParseState ps)
throws InvalidSyntaxException {
ps.skipWhite();
if (!ps.prefix("("))
ps.error(MALFORMED);
int operator;
ps.skipWhite();
switch(ps.peek()) {
case '&': operator = AND; break;
case '|': operator = OR; break;
case '!': operator = NOT; break;
default: return parseSimple(ps);
}
ps.skip(1); // Ignore the operator
List v = new ArrayList();
do {
v.add(parseExpr(ps));
ps.skipWhite();
} while (ps.peek() == '(');
int n = v.size();
if (!ps.prefix(")") || n == 0 || (operator == NOT && n > 1))
ps.error(MALFORMED);
LDAPExpr[] args = new LDAPExpr[n];
v.toArray(args);
return new LDAPExpr(operator, args);
}
private static LDAPExpr parseSimple(ParseState ps)
throws InvalidSyntaxException {
String attrName = ps.getAttributeName();
int operator = 0;
if (ps.prefix("="))
operator = EQ;
else if (ps.prefix("<="))
operator = LE;
else if(ps.prefix(">="))
operator = GE;
else if(ps.prefix("~="))
operator = APPROX;
else {
// System.out.println("undef op='" + ps.peek() + "'");
ps.error(OPERATOR); // Does not return
}
String attrValue = ps.getAttributeValue();
if (!ps.prefix(")"))
ps.error(MALFORMED);
return new LDAPExpr(operator, attrName, attrValue);
}
public String toString() {
if(Framework.R3_TESTCOMPLIANT) {
if(bug != null) {
return bug;
}
}
StringBuffer res = new StringBuffer();
res.append("(");
if ((operator & SIMPLE) != 0) {
res.append(attrName);
switch (operator) {
case EQ:
res.append("=");
break;
case LE:
res.append("<=");
break;
case GE:
res.append(">=");
break;
case APPROX:
res.append("~=");
break;
}
for (int i = 0; i < attrValue.length(); i++) {
char c = attrValue.charAt(i);
if (c == '(' || c == ')' || c == '*' || c == '\\') {
res.append('\\');
} else if (c == WILDCARD) {
c = '*';
}
res.append(c);
}
} else {
switch (operator) {
case AND:
res.append("&");
break;
case OR:
res.append("|");
break;
case NOT:
res.append("!");
break;
}
for (int i = 0; i < args.length; i++) {
res.append(args[i].toString());
}
}
res.append(")");
return res.toString();
}
/**
* Contains the current parser position and parsing utility methods.
*/
private static class ParseState {
int pos;
String str;
public ParseState(String str) throws InvalidSyntaxException {
this.str = str;
if (str == null || str.length() == 0)
error(NULL);
pos = 0;
}
public int getPos() {
return pos;
}
public boolean prefix(String pre) {
if (!str.startsWith(pre, pos))
return false;
pos += pre.length();
return true;
}
public char peek() {
return str.charAt(pos);
}
public void skip(int n) {
pos += n;
}
public String rest() {
return str.substring(pos);
}
public void skipWhite() {
while (Character.isWhitespace(str.charAt(pos))) {
pos++;
}
}
public String getAttributeName() {
int start = pos;
for(;; pos++) {
char c = str.charAt(pos);
if (Character.isWhitespace(c) ||
c == '(' || c == ')' ||
c == '<' || c == '>' ||
c == '=' || c == '~' ||
c == '*' || c == '\\') {
break;
}
}
String res = str.substring(start, pos).toLowerCase();
skipWhite();
return res;
}
public String getAttributeValue() {
StringBuffer sb = new StringBuffer();
label:
for(;; pos++) {
char c = str.charAt(pos);
switch(c) {
case '(':
case ')':
break label;
case '*':
sb.append(WILDCARD);
break;
case '\\':
sb.append(str.charAt(++pos));
break;
default:
sb.append(c);
break;
}
}
return sb.toString();
}
public void error(String m) throws InvalidSyntaxException {
throw new InvalidSyntaxException(m, (str == null) ? "" : str.substring(pos));
}
}
}
|
package edu.utah.sci.cyclist.core.util;
import java.util.ArrayList;
import java.util.List;
import edu.utah.sci.cyclist.core.model.Field;
import edu.utah.sci.cyclist.core.model.FieldProperties;
import edu.utah.sci.cyclist.core.model.Filter;
import edu.utah.sci.cyclist.core.model.Table;
public class QueryBuilder {
private Table _table;
private List<Field> _fields = new ArrayList<>();
private List<Filter> _filters = new ArrayList<>();
private List<Field> _aggregates = new ArrayList<>();
private List<Field> _grouping = new ArrayList<>();
private List<Filter> _having = new ArrayList<>();
private int _limit = -1;
public QueryBuilder(Table table) {
_table = table;
}
public QueryBuilder fields(List<Field> list) {
for (Field f : list)
field(f);
return this;
}
public QueryBuilder limit(int n) {
_limit = n;
return this;
}
public QueryBuilder field(Field field) {
if (_fields.contains(field)) {
return this;
}
_fields.add(field);
return this;
}
public QueryBuilder aggregates(List<Field> list) {
_aggregates = list;
return this;
}
public QueryBuilder grouping(List<Field> list) {
_grouping = list;
return this;
}
public QueryBuilder filters(List<Filter> list) {
//_filters.addAll(list);
for (Filter filter : list) {
// if (filter.getRole() == Role.DIMENSION || filter.getRole() == Role.INT_TIME)
// _filters.add(filter);
// else
// _having.add(filter);
_filters.add(filter);
}
return this;
}
private boolean append(StringBuilder builder, boolean first, List<Field> list) {
for (Field field : list) {
if (first) {
builder.append(" ");
first = false;
} else {
builder.append(", ");
}
builder.append(field.getName());
}
return first;
}
private boolean appendFilters(StringBuilder builder, boolean first, List<Filter> list) {
for (Filter filter : list) {
if (first) {
builder.append(" ");
first = false;
} else {
builder.append(" and ");
}
builder.append(filter.toString());
}
return first;
}
public List<Field> getOrder() {
List<Field> order = new ArrayList<>();
order.addAll(_fields);
order.addAll(_aggregates);
order.addAll(_grouping);
return order;
}
public String toString() {
boolean first = true;
StringBuilder builder = new StringBuilder("Select ");
// dims
if (!_fields.isEmpty()) {
first = append(builder, first, _fields);
}
// aggregates
for (Field field : _aggregates) {
if (first) {
builder.append(" ");
first = false;
} else {
builder.append(", ");
}
builder.append(SQL.getFunction(field.getString(FieldProperties.AGGREGATION_FUNC)).format(field.getName()));
}
first = append(builder, first, _grouping);
if (first) {
// no projection -> use '*'
builder.append("*");
}
// table
builder.append(" from ").append(_table.getName());
// where
first = true;
if (_filters.size() > 0) {
builder.append(" where ");
first = appendFilters(builder, first, _filters);
}
// group by
first = true;
if (_aggregates.size() > 0 && (_fields.size() > 0 || _grouping.size() > 0)) {
builder.append(" group by ");
first = append(builder, first, _fields);
append(builder, first, _grouping);
}
// filters
first = true;
if (_having.size() > 0) {
builder.append(" having ");
for (Filter filter : _having) {
if (first) {
builder.append(" ");
first = false;
} else {
builder.append(" AND ");
}
builder.append(filter.toString());
}
}
// order by
// TODO
// limit
if (_limit > 0) {
builder.append(" limit ").append(_limit);
}
builder.append(" COLLATE NOCASE");
String q = builder.toString();
if (_table.toString().equals("QuantityInventory")) {
q = q.replaceAll("(.*\\W)Quantity(\\W.*)", "$1inv\\.Quantity\\*c\\.MassFrac$2");
q = q.replaceAll("(.*\\W)Time(\\W.*)", "$1tl\\.Time$2");
q = q.replaceAll("(.*\\W)NucId(\\W.*)", "$1c\\.NucId$2");
q = q.replaceAll("(.*\\W)AgentId(\\W.*)", "$1ag\\.AgentId$2");
q = q.replaceAll("(.*\\W)Prototype(\\W.*)", "$1ag\\.Prototype$2");
q = q.replaceAll("(.*\\W)SimId(\\W.*)", "$1inv\\.SimId$2");
q = q.replaceAll("(.*\\W)QuantityInventory(\\W.*)", "$1Timelist AS tl JOIN Inventories AS inv ON inv.StartTime <= tl.Time AND inv.EndTime > tl.Time AND inv.SimId=tl.SimId JOIN Agents AS ag ON ag.AgentId = inv.AgentId AND ag.SimId=tl.SimId JOIN Compositions AS c ON c.QualId = inv.QualId AND c.SimId=tl.SimId$2");
q = q.replaceAll(" SimID ", "tl.SimID ");
}
return q;
}
}
|
package ch.fihlon.moodini.server;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import javax.json.Json;
import javax.json.JsonObject;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import java.util.ConcurrentModificationException;
import static javax.ws.rs.core.Response.Status.CONFLICT;
import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
import static javax.ws.rs.core.Response.Status.METHOD_NOT_ALLOWED;
import static javax.ws.rs.core.Response.Status.NOT_FOUND;
@Slf4j
@Provider
public class RuntimeExceptionMapper implements ExceptionMapper<RuntimeException> {
@Override
public Response toResponse(@NonNull final RuntimeException e) {
log.error(e.getMessage(), e);
return handleException(e);
}
private Response handleException(final Throwable e) {
if (e instanceof ConcurrentModificationException) {
return createResponse(CONFLICT, e.getMessage());
}
if (e instanceof NotFoundException) {
return createResponse(NOT_FOUND, e.getMessage());
}
if (e instanceof UnsupportedOperationException) {
return createResponse(METHOD_NOT_ALLOWED, e.getMessage());
}
if (e instanceof WebApplicationException) {
final WebApplicationException wae = (WebApplicationException) e;
return createResponse(Response.Status.fromStatusCode(wae.getResponse().getStatus()), wae.getMessage());
}
if (e.getCause() != null) {
return handleException(e.getCause());
}
return createResponse(INTERNAL_SERVER_ERROR, e.getMessage());
}
private Response createResponse(final Status status, final String message) {
final JsonObject entity = Json.createObjectBuilder()
.add("status", status.getStatusCode())
.add("message", message)
.build();
return Response.status(status)
.type(MediaType.APPLICATION_JSON)
.entity(entity).build();
}
}
|
package org.mini2Dx.tiled;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.mini2Dx.core.geom.Rectangle;
import org.mini2Dx.core.graphics.Graphics;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.g2d.SpriteCache;
import com.badlogic.gdx.math.MathUtils;
/**
* An implementation of a parsed map from Tiled
*
* @author Thomas Cashman
*/
public class TiledMap implements TiledParserListener {
private Orientation orientation;
private int width, height, tileWidth, tileHeight;
protected List<Tileset> tilesets;
protected List<TileLayer> tileLayers;
protected List<TiledObjectGroup> objectGroups;
private Map<String, String> properties;
private boolean loadTilesets = true;
private FileHandle fileHandle;
private SpriteCache layerCache;
private Map<TileLayer, Integer> layerCacheIds;
/**
* Constructs an empty map
*/
public TiledMap() {
tilesets = new ArrayList<Tileset>();
tileLayers = new ArrayList<TileLayer>();
objectGroups = new ArrayList<TiledObjectGroup>();
layerCacheIds = new HashMap<TileLayer, Integer>();
this.loadTilesets = false;
}
/**
* Constructs a map from a TMX file
*
* @param fileHandle
* A {@link FileHandle} to a .tmx file
* @throws IOException
* Thrown if the map file could not be parsed
*/
public TiledMap(FileHandle fileHandle) throws IOException {
this(fileHandle, true);
}
/**
* Constructs a map from a TMX file
*
* @param fileHandle
* A {@link FileHandle} to a .tmx file
* @param loadTilesets
* True if the tileset images should be loaded
* @throws IOException
* Thrown if the map file could not be parsed
*/
public TiledMap(FileHandle fileHandle, boolean loadTilesets) throws IOException {
this();
this.loadTilesets = loadTilesets;
this.fileHandle = fileHandle;
TiledParser parser = new TiledParser();
parser.addListener(this);
parser.parse(fileHandle);
if (loadTilesets) {
layerCache = new SpriteCache(getWidth() * getHeight() * tileLayers.size(), true);
for (int layer = 0; layer < tileLayers.size(); layer++) {
layerCache.beginCache();
for (int y = 0; y < getHeight(); y++) {
for (int x = 0; x < getWidth(); x++) {
int tileId = tileLayers.get(layer).getTileId(x, y);
if (tileId > 0) {
int tileRenderX = x * getTileWidth();
int tileRenderY = y * getTileHeight();
for (int i = 0; i < tilesets.size(); i++) {
Tileset tileset = tilesets.get(i);
if (tileset.contains(tileId)) {
layerCache.add(
tileset.getTileImage(tileId),
tileRenderX, tileRenderY);
break;
}
}
}
}
}
int layerCacheId = layerCache.endCache();
layerCacheIds.put(tileLayers.get(layer), layerCacheId);
}
}
}
/**
* Draws the entire map at the specified coordinates
*
* @param g
* The {@link Graphics} context available for rendering
* @param x
* The x coordinate to render at
* @param y
* The y coordinate to render at
*/
public void draw(Graphics g, int x, int y) {
draw(g, x, y, 0, 0, width, height);
}
/**
* Draws a layer of the map at the specified coordinates
*
* @param g
* The {@link Graphics} context available for rendering
* @param x
* The x coordinate to render at
* @param y
* The y coordinate to render at
* @param layer
* The layer index to render
*/
public void draw(Graphics g, int x, int y, int layer) {
draw(g, x, y, 0, 0, width, height, layer);
}
/**
* Draws a section of the map at the specified coordinates
*
* @param g
* The {@link Graphics} context available for rendering
* @param x
* The x coordinate to render at
* @param y
* The y coordinate to render at
* @param startTileX
* The x tile coordinate in the map to start from
* @param startTileY
* The y tile coordinate in the map to start from
* @param width
* The amount of tiles across the x axis to render
* @param height
* The amount of tiles across the y axis to render
*/
public void draw(Graphics g, int x, int y, int startTileX, int startTileY,
int width, int height) {
for (int i = 0; i < tileLayers.size(); i++) {
draw(g, x, y, startTileX, startTileY, width, height, i);
}
}
/**
* Draws a section of a specified layer of the map at the specified
* coordinates
*
* @param g
* The {@link Graphics} context available for rendering
* @param x
* The x coordinate to render at
* @param y
* The y coordinate to render at
* @param startTileX
* The x tile coordinate in the map to start from
* @param startTileY
* The y tile coordinate in the map to start from
* @param width
* The amount of tiles across the x axis to render
* @param height
* The amount of tiles across the y axis to render
* @param layer
* The layer index to render
*/
public void draw(Graphics g, int x, int y, int startTileX, int startTileY,
int width, int height, int layer) {
drawLayer(g, tileLayers.get(layer), x, y, startTileX, startTileY,
width, height);
}
/**
* Developers can override this method to implement sprite rendering
*
* @param g
* The {@link Graphics} context used for rendering
* @param layer
* The {@link TileLayer} which was just rendered
* @param startTileX
* The x coordinate in tiles where rendering started
* @param startTileY
* The y coordinate in tiles where rendering started
* @param width
* The amount of tiles that were rendered along the X axis
* @param height
* The amount of tiles that were rendered along the Y axis
*/
protected void onLayerRendered(Graphics g, TileLayer layer, int startTileX,
int startTileY, int width, int height) {
}
private void drawLayer(Graphics g, TileLayer layer, int renderX,
int renderY, int startTileX, int startTileY, int width, int height) {
int startTileRenderX = (startTileX * getTileWidth());
int startTileRenderY = (startTileY * getTileHeight());
int tileRenderX = MathUtils.round(renderX - startTileRenderX);
int tileRenderY = MathUtils.round(renderY - startTileRenderY);
Rectangle existingClip = g.removeClip();
Rectangle newClip = new Rectangle(startTileRenderX, startTileRenderY,
width * getTileWidth(), height * getTileHeight());
g.translate(-tileRenderX, -tileRenderY);
if (existingClip != null) {
if (existingClip.intersects(newClip)) {
g.setClip(existingClip.intersection(newClip));
} else {
g.setClip(existingClip);
}
} else {
g.setClip(newClip);
}
int layerCacheId = layerCacheIds.get(layer);
g.drawSpriteCache(layerCache, layerCacheId);
g.removeClip();
g.translate(tileRenderX, tileRenderY);
if (existingClip != null)
g.setClip(existingClip.getX(), existingClip.getY(),
existingClip.getWidth(), existingClip.getHeight());
onLayerRendered(g, layer, startTileX, startTileY, width, height);
}
/**
* Returns if the map contains the specified property
*
* @param propertyName
* The property name to search for
* @return True if the map contains the property
*/
public boolean containsProperty(String propertyName) {
if (properties == null)
return false;
return properties.containsKey(propertyName);
}
/**
* Returns the value of a specified property
*
* @param propertyName
* The property name to search for
* @return Null if there is no such property
*/
public String getProperty(String propertyName) {
if (properties == null)
return null;
return properties.get(propertyName);
}
/**
* Sets the value of a specified property
*
* @param propertyName
* The property name to set the value for
* @param value
* The value of the property to set
*/
public void setProperty(String propertyName, String value) {
if (properties == null)
properties = new HashMap<String, String>();
properties.put(propertyName, value);
}
@Override
public void onBeginParsing(String orientation, int width, int height,
int tileWidth, int tileHeight) {
try {
this.orientation = Orientation.valueOf(orientation.toUpperCase());
} catch (Exception e) {
this.orientation = Orientation.UNKNOWN;
}
this.width = width;
this.height = height;
this.tileWidth = tileWidth;
this.tileHeight = tileHeight;
}
@Override
public void onMapPropertyParsed(String propertyName, String value) {
setProperty(propertyName, value);
}
@Override
public void onTilePropertyParsed(int tileId, String propertyName,
String value) {
}
@Override
public void onTilesetParsed(Tileset parsedTileset) {
if (loadTilesets && !parsedTileset.isTextureLoaded()) {
parsedTileset.loadTexture(fileHandle.parent());
}
this.tilesets.add(parsedTileset);
}
@Override
public void onTileLayerParsed(TileLayer parsedLayer) {
this.tileLayers.add(parsedLayer);
}
@Override
public void onObjectGroupParsed(TiledObjectGroup parsedObjectGroup) {
this.objectGroups.add(parsedObjectGroup);
}
/**
* Returns the {@link TileLayer} with the given name
*
* @param name
* The name to search for
* @return Null if there is no such {@link TileLayer}
*/
public TileLayer getTileLayer(String name) {
for (TileLayer layer : tileLayers) {
if (layer.getName().compareTo(name) == 0) {
return layer;
}
}
return null;
}
/**
* Returns the {@link TiledObjectGroup} with the given name
*
* @param name
* The name to search for
* @return Null if there is no such {@link TiledObjectGroup}
*/
public TiledObjectGroup getObjectGroup(String name) {
for (TiledObjectGroup group : objectGroups) {
if (group.getName().compareTo(name) == 0) {
return group;
}
}
return null;
}
/**
* Returns the index of the {@link TileLayer} with the given name
*
* @param name
* The name to search for
* @return -1 if there is no such {@link TileLayer}
*/
public int getLayerIndex(String name) {
for (int i = 0; i < tileLayers.size(); i++) {
if (tileLayers.get(i).getName().compareTo(name) == 0) {
return i;
}
}
return -1;
}
/**
* Returns the {@link Orientation} of this map
*
* @return
*/
public Orientation getOrientation() {
return orientation;
}
/**
* Returns the width of the map in tiles
*
* @return
*/
public int getWidth() {
return width;
}
/**
* Returns the height of the map in tiles
*
* @return
*/
public int getHeight() {
return height;
}
/**
* Returns the width of tiles in pixels
*
* @return
*/
public int getTileWidth() {
return tileWidth;
}
/**
* Returns the height of tiles in pixels
*
* @return
*/
public int getTileHeight() {
return tileHeight;
}
/**
* Returns the {@link Tileset}s of this map
*
* @return An empty list if none have been loaded
*/
public List<Tileset> getTilesets() {
return tilesets;
}
/**
* Returns the {@link TileLayer}s of this map
*
* @return An empty list if none have been loaded
*/
public List<TileLayer> getTileLayers() {
return tileLayers;
}
/**
* Returns the {@link TiledObjectGroup}s of this map
*
* @return An empty list if none have been loaded
*/
public List<TiledObjectGroup> getObjectGroups() {
return objectGroups;
}
}
|
package ch.rasc.s4ws.echat;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class };
}
@Override
protected String[] getServletMappings() {
|
package bisq.network.p2p.network;
import bisq.network.p2p.NodeAddress;
import bisq.common.Timer;
import bisq.common.UserThread;
import bisq.common.proto.network.NetworkEnvelope;
import bisq.common.proto.network.NetworkProtoResolver;
import bisq.common.util.Utilities;
import com.runjva.sourceforge.jsocks.protocol.Socks5Proxy;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.SettableFuture;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
// Run in UserThread
public abstract class NetworkNode implements MessageListener {
private static final Logger log = LoggerFactory.getLogger(NetworkNode.class);
private static final int CREATE_SOCKET_TIMEOUT = (int) TimeUnit.SECONDS.toMillis(120);
final int servicePort;
private final NetworkProtoResolver networkProtoResolver;
private final CopyOnWriteArraySet<InboundConnection> inBoundConnections = new CopyOnWriteArraySet<>();
private final CopyOnWriteArraySet<MessageListener> messageListeners = new CopyOnWriteArraySet<>();
private final CopyOnWriteArraySet<ConnectionListener> connectionListeners = new CopyOnWriteArraySet<>();
final CopyOnWriteArraySet<SetupListener> setupListeners = new CopyOnWriteArraySet<>();
ListeningExecutorService executorService;
private Server server;
private volatile boolean shutDownInProgress;
// accessed from different threads
private final CopyOnWriteArraySet<OutboundConnection> outBoundConnections = new CopyOnWriteArraySet<>();
protected final ObjectProperty<NodeAddress> nodeAddressProperty = new SimpleObjectProperty<>();
// Constructor
NetworkNode(int servicePort, NetworkProtoResolver networkProtoResolver) {
this.servicePort = servicePort;
this.networkProtoResolver = networkProtoResolver;
}
// API
// Calls this (and other registered) setup listener's ``onTorNodeReady()`` and ``onHiddenServicePublished``
// when the events happen.
public abstract void start(@Nullable SetupListener setupListener);
public SettableFuture<Connection> sendMessage(@NotNull NodeAddress peersNodeAddress,
NetworkEnvelope networkEnvelope) {
if (log.isDebugEnabled()) {
log.debug("sendMessage: peersNodeAddress=" + peersNodeAddress + "\n\tmessage=" + Utilities.toTruncatedString(networkEnvelope));
}
checkNotNull(peersNodeAddress, "peerAddress must not be null");
Connection connection = getOutboundConnection(peersNodeAddress);
if (connection == null)
connection = getInboundConnection(peersNodeAddress);
if (connection != null) {
return sendMessage(connection, networkEnvelope);
} else {
log.debug("We have not found any connection for peerAddress {}.\n\t" +
"We will create a new outbound connection.", peersNodeAddress);
final SettableFuture<Connection> resultFuture = SettableFuture.create();
ListenableFuture<Connection> future = executorService.submit(() -> {
Thread.currentThread().setName("NetworkNode:SendMessage-to-" + peersNodeAddress.getFullAddress());
if (peersNodeAddress.equals(getNodeAddress())) {
throw new ConnectException("We do not send a message to ourselves");
}
OutboundConnection outboundConnection = null;
try {
// can take a while when using tor
long startTs = System.currentTimeMillis();
if (log.isDebugEnabled()) {
log.debug("Start create socket to peersNodeAddress {}", peersNodeAddress.getFullAddress());
}
Socket socket = createSocket(peersNodeAddress);
long duration = System.currentTimeMillis() - startTs;
log.info("Socket creation to peersNodeAddress {} took {} ms", peersNodeAddress.getFullAddress(),
duration);
if (duration > CREATE_SOCKET_TIMEOUT)
throw new TimeoutException("A timeout occurred when creating a socket.");
// Tor needs sometimes quite long to create a connection. To avoid that we get too many double
// sided connections we check again if we still don't have any connection for that node address.
Connection existingConnection = getInboundConnection(peersNodeAddress);
if (existingConnection == null)
existingConnection = getOutboundConnection(peersNodeAddress);
if (existingConnection != null) {
if (log.isDebugEnabled()) {
log.debug("We found in the meantime a connection for peersNodeAddress {}, " +
"so we use that for sending the message.\n" +
"That can happen if Tor needs long for creating a new outbound connection.\n" +
"We might have got a new inbound or outbound connection.",
peersNodeAddress.getFullAddress());
}
try {
socket.close();
} catch (Throwable throwable) {
log.error("Error at closing socket " + throwable);
}
existingConnection.sendMessage(networkEnvelope);
return existingConnection;
} else {
final ConnectionListener connectionListener = new ConnectionListener() {
@Override
public void onConnection(Connection connection) {
if (!connection.isStopped()) {
outBoundConnections.add((OutboundConnection) connection);
printOutBoundConnections();
connectionListeners.stream().forEach(e -> e.onConnection(connection));
}
}
@Override
public void onDisconnect(CloseConnectionReason closeConnectionReason,
Connection connection) {
log.trace("onDisconnect connectionListener\n\tconnection={}" + connection);
//noinspection SuspiciousMethodCalls
outBoundConnections.remove(connection);
printOutBoundConnections();
connectionListeners.stream().forEach(e -> e.onDisconnect(closeConnectionReason, connection));
}
@Override
public void onError(Throwable throwable) {
log.error("new OutboundConnection.ConnectionListener.onError " + throwable.getMessage());
connectionListeners.stream().forEach(e -> e.onError(throwable));
}
};
outboundConnection = new OutboundConnection(socket,
NetworkNode.this,
connectionListener,
peersNodeAddress,
networkProtoResolver);
if (log.isDebugEnabled()) {
log.debug("\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" +
"NetworkNode created new outbound connection:"
+ "\nmyNodeAddress=" + getNodeAddress()
+ "\npeersNodeAddress=" + peersNodeAddress
+ "\nuid=" + outboundConnection.getUid()
+ "\nmessage=" + networkEnvelope
+ "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n");
}
// can take a while when using tor
outboundConnection.sendMessage(networkEnvelope);
return outboundConnection;
}
} catch (Throwable throwable) {
if (!(throwable instanceof ConnectException ||
throwable instanceof IOException ||
throwable instanceof TimeoutException)) {
log.warn("Executing task failed. " + throwable.getMessage());
}
throw throwable;
}
});
Futures.addCallback(future, new FutureCallback<>() {
public void onSuccess(Connection connection) {
UserThread.execute(() -> resultFuture.set(connection));
}
public void onFailure(@NotNull Throwable throwable) {
log.debug("onFailure at sendMessage: peersNodeAddress={}\n\tmessage={}\n\tthrowable={}", peersNodeAddress, networkEnvelope.getClass().getSimpleName(), throwable.toString());
UserThread.execute(() -> resultFuture.setException(throwable));
}
});
return resultFuture;
}
}
@Nullable
private InboundConnection getInboundConnection(@NotNull NodeAddress peersNodeAddress) {
Optional<InboundConnection> inboundConnectionOptional = lookupInBoundConnection(peersNodeAddress);
if (inboundConnectionOptional.isPresent()) {
InboundConnection connection = inboundConnectionOptional.get();
log.trace("We have found a connection in inBoundConnections. Connection.uid={}", connection.getUid());
if (connection.isStopped()) {
log.warn("We have a connection which is already stopped in inBoundConnections. Connection.uid=" + connection.getUid());
inBoundConnections.remove(connection);
return null;
} else {
return connection;
}
} else {
return null;
}
}
@Nullable
private OutboundConnection getOutboundConnection(@NotNull NodeAddress peersNodeAddress) {
Optional<OutboundConnection> outboundConnectionOptional = lookupOutBoundConnection(peersNodeAddress);
if (outboundConnectionOptional.isPresent()) {
OutboundConnection connection = outboundConnectionOptional.get();
log.trace("We have found a connection in outBoundConnections. Connection.uid={}", connection.getUid());
if (connection.isStopped()) {
log.warn("We have a connection which is already stopped in outBoundConnections. Connection.uid=" + connection.getUid());
outBoundConnections.remove(connection);
return null;
} else {
return connection;
}
} else {
return null;
}
}
@Nullable
public Socks5Proxy getSocksProxy() {
return null;
}
public SettableFuture<Connection> sendMessage(Connection connection, NetworkEnvelope networkEnvelope) {
// connection.sendMessage might take a bit (compression, write to stream), so we use a thread to not block
ListenableFuture<Connection> future = executorService.submit(() -> {
String id = connection.getPeersNodeAddressOptional().isPresent() ? connection.getPeersNodeAddressOptional().get().getFullAddress() : connection.getUid();
Thread.currentThread().setName("NetworkNode:SendMessage-to-" + id);
connection.sendMessage(networkEnvelope);
return connection;
});
final SettableFuture<Connection> resultFuture = SettableFuture.create();
Futures.addCallback(future, new FutureCallback<Connection>() {
public void onSuccess(Connection connection) {
UserThread.execute(() -> resultFuture.set(connection));
}
public void onFailure(@NotNull Throwable throwable) {
UserThread.execute(() -> resultFuture.setException(throwable));
}
});
return resultFuture;
}
public ReadOnlyObjectProperty<NodeAddress> nodeAddressProperty() {
return nodeAddressProperty;
}
public Set<Connection> getAllConnections() {
// Can contain inbound and outbound connections with the same peer node address,
// as connection hashcode is using uid and port info
Set<Connection> set = new HashSet<>(inBoundConnections);
set.addAll(outBoundConnections);
return set;
}
public Set<Connection> getConfirmedConnections() {
// Can contain inbound and outbound connections with the same peer node address,
// as connection hashcode is using uid and port info
return getAllConnections().stream()
.filter(Connection::hasPeersNodeAddress)
.collect(Collectors.toSet());
}
public Set<NodeAddress> getNodeAddressesOfConfirmedConnections() {
// Does not contain inbound and outbound connection with the same peer node address
return getConfirmedConnections().stream()
.map(e -> e.getPeersNodeAddressOptional().get())
.collect(Collectors.toSet());
}
public void shutDown(Runnable shutDownCompleteHandler) {
if (!shutDownInProgress) {
shutDownInProgress = true;
if (server != null) {
server.shutDown();
server = null;
}
Set<Connection> allConnections = getAllConnections();
int numConnections = allConnections.size();
log.info("Shutdown {} connections", numConnections);
AtomicInteger shutdownCompleted = new AtomicInteger();
Timer timeoutHandler = UserThread.runAfter(() -> {
if (shutDownCompleteHandler != null) {
log.info("Shutdown completed due timeout");
shutDownCompleteHandler.run();
}
}, 3);
allConnections.forEach(c -> c.shutDown(CloseConnectionReason.APP_SHUT_DOWN,
() -> {
shutdownCompleted.getAndIncrement();
log.info("Shutdown of node {} completed", c.getPeersNodeAddressOptional());
if (shutdownCompleted.get() == numConnections) {
log.info("Shutdown completed with all connections closed");
timeoutHandler.stop();
if (shutDownCompleteHandler != null) {
shutDownCompleteHandler.run();
}
}
}));
}
}
// SetupListener
void addSetupListener(SetupListener setupListener) {
boolean isNewEntry = setupListeners.add(setupListener);
if (!isNewEntry)
log.warn("Try to add a setupListener which was already added.");
}
// MessageListener implementation
@Override
public void onMessage(NetworkEnvelope networkEnvelope, Connection connection) {
messageListeners.stream().forEach(e -> e.onMessage(networkEnvelope, connection));
}
// Listeners
public void addConnectionListener(ConnectionListener connectionListener) {
boolean isNewEntry = connectionListeners.add(connectionListener);
if (!isNewEntry)
log.warn("Try to add a connectionListener which was already added.\n\tconnectionListener={}\n\tconnectionListeners={}"
, connectionListener, connectionListeners);
}
public void removeConnectionListener(ConnectionListener connectionListener) {
boolean contained = connectionListeners.remove(connectionListener);
if (!contained)
log.debug("Try to remove a connectionListener which was never added.\n\t" +
"That might happen because of async behaviour of CopyOnWriteArraySet");
}
public void addMessageListener(MessageListener messageListener) {
boolean isNewEntry = messageListeners.add(messageListener);
if (!isNewEntry)
log.warn("Try to add a messageListener which was already added.");
}
public void removeMessageListener(MessageListener messageListener) {
boolean contained = messageListeners.remove(messageListener);
if (!contained)
log.debug("Try to remove a messageListener which was never added.\n\t" +
"That might happen because of async behaviour of CopyOnWriteArraySet");
}
// Protected
void createExecutorService() {
if (executorService == null)
executorService = Utilities.getListeningExecutorService("NetworkNode-" + servicePort, 15, 30, 60);
}
void startServer(ServerSocket serverSocket) {
final ConnectionListener connectionListener = new ConnectionListener() {
@Override
public void onConnection(Connection connection) {
if (!connection.isStopped()) {
inBoundConnections.add((InboundConnection) connection);
printInboundConnections();
connectionListeners.stream().forEach(e -> e.onConnection(connection));
}
}
@Override
public void onDisconnect(CloseConnectionReason closeConnectionReason, Connection connection) {
log.trace("onDisconnect at server socket connectionListener\n\tconnection={}", connection);
//noinspection SuspiciousMethodCalls
inBoundConnections.remove(connection);
printInboundConnections();
connectionListeners.stream().forEach(e -> e.onDisconnect(closeConnectionReason, connection));
}
@Override
public void onError(Throwable throwable) {
log.error("server.ConnectionListener.onError " + throwable.getMessage());
connectionListeners.stream().forEach(e -> e.onError(throwable));
}
};
server = new Server(serverSocket,
NetworkNode.this,
connectionListener,
networkProtoResolver);
executorService.submit(server);
}
private Optional<OutboundConnection> lookupOutBoundConnection(NodeAddress peersNodeAddress) {
log.trace("lookupOutboundConnection for peersNodeAddress={}", peersNodeAddress.getFullAddress());
printOutBoundConnections();
return outBoundConnections.stream()
.filter(connection -> connection.hasPeersNodeAddress() &&
peersNodeAddress.equals(connection.getPeersNodeAddressOptional().get())).findAny();
}
private void printOutBoundConnections() {
StringBuilder sb = new StringBuilder("outBoundConnections size()=")
.append(outBoundConnections.size()).append("\n\toutBoundConnections=");
outBoundConnections.stream().forEach(e -> sb.append(e).append("\n\t"));
log.debug(sb.toString());
}
private Optional<InboundConnection> lookupInBoundConnection(NodeAddress peersNodeAddress) {
log.trace("lookupInboundConnection for peersNodeAddress={}", peersNodeAddress.getFullAddress());
printInboundConnections();
return inBoundConnections.stream()
.filter(connection -> connection.hasPeersNodeAddress() &&
peersNodeAddress.equals(connection.getPeersNodeAddressOptional().get())).findAny();
}
private void printInboundConnections() {
StringBuilder sb = new StringBuilder("inBoundConnections size()=")
.append(inBoundConnections.size()).append("\n\tinBoundConnections=");
inBoundConnections.stream().forEach(e -> sb.append(e).append("\n\t"));
log.debug(sb.toString());
}
protected abstract Socket createSocket(NodeAddress peersNodeAddress) throws IOException;
@Nullable
public NodeAddress getNodeAddress() {
return nodeAddressProperty.get();
}
}
|
package com.psddev.dari.db;
import java.beans.BeanInfo;
import java.beans.PropertyDescriptor;
import java.beans.SimpleBeanInfo;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableList;
import com.psddev.dari.util.ClassFinder;
import com.psddev.dari.util.CodeUtils;
import com.psddev.dari.util.Lazy;
import com.psddev.dari.util.ObjectUtils;
import com.psddev.dari.util.Once;
import com.psddev.dari.util.PeriodicCache;
import com.psddev.dari.util.Task;
import com.psddev.dari.util.TypeDefinition;
public class DatabaseEnvironment implements ObjectStruct {
public static final String GLOBAL_FIELDS_FIELD = "globalFields";
public static final String GLOBAL_INDEXES_FIELD = "globalIndexes";
private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseEnvironment.class);
private final Database database;
private final boolean initializeClasses;
{
CodeUtils.addRedefineClassesListener(new CodeUtils.RedefineClassesListener() {
@Override
public void redefined(Set<Class<?>> classes) {
for (Class<?> c : classes) {
if (Recordable.class.isAssignableFrom(c)) {
TypeDefinition.Static.invalidateAll();
refreshTypes();
dynamicProperties.reset();
break;
}
}
}
});
}
/** Creates a new instance backed by the given {@code database}. */
public DatabaseEnvironment(Database database, boolean initializeClasses) {
this.database = database;
this.initializeClasses = initializeClasses;
}
/** Creates a new instance backed by the given {@code database}. */
public DatabaseEnvironment(Database database) {
this(database, true);
}
/** Returns the backing database. */
public Database getDatabase() {
return database;
}
/** Globals are stored at FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF. */
private static final UUID GLOBALS_ID = new UUID(-1L, -1L);
/** Field where the root type is stored within the globals. */
private static final String ROOT_TYPE_FIELD = "rootType";
private volatile State globals;
private volatile Date lastGlobalsUpdate;
private volatile Date lastTypesUpdate;
private volatile TypesCache permanentTypes = new TypesCache();
private final ThreadLocal<TypesCache> temporaryTypesLocal = new ThreadLocal<TypesCache>();
/** Aggregate of all maps used to cache type information. */
private static class TypesCache {
public final Map<String, ObjectType> byClassName = new HashMap<String, ObjectType>();
public final Map<UUID, ObjectType> byId = new HashMap<UUID, ObjectType>();
public final Map<String, ObjectType> byName = new HashMap<String, ObjectType>();
public final Map<String, Set<ObjectType>> byGroup = new HashMap<String, Set<ObjectType>>();
public final Set<UUID> changed = new HashSet<UUID>();
/** Adds the given {@code type} to all type cache maps. */
public void add(ObjectType type) {
String className = type.getObjectClassName();
if (!ObjectUtils.isBlank(className)) {
byClassName.put(className, type);
}
byId.put(type.getId(), type);
String internalName = type.getInternalName();
if (!ObjectUtils.isBlank(internalName)) {
byName.put(internalName, type);
}
for (String group : type.getGroups()) {
Set<ObjectType> groupTypes = byGroup.get(group);
if (groupTypes == null) {
groupTypes = new HashSet<ObjectType>();
byGroup.put(group, groupTypes);
}
groupTypes.remove(type);
groupTypes.add(type);
}
}
}
private final Once bootstrapOnce = new Once() {
@Override
protected void run() {
// Fetch the globals, which includes a reference to the root
// type. References to other objects can't be resolved,
// because the type definitions haven't been loaded yet.
refreshGlobals();
ObjectType rootType = getRootType();
if (rootType != null) {
// This isn't cleared later, because that's done within
// {@link refreshTypes} anyway.
TypesCache temporaryTypes = temporaryTypesLocal.get();
if (temporaryTypes == null) {
temporaryTypes = new TypesCache();
temporaryTypesLocal.set(temporaryTypes);
}
temporaryTypes.add(rootType);
LOGGER.info(
"Root type ID for [{}] is [{}]",
getDatabase().getName(),
rootType.getId());
}
// Load all other types based on the root type. Then globals
// again in case they reference other typed objects. Then
// types again using the information from the fully resolved
// globals.
refreshTypes();
refreshGlobals();
refreshTypes();
refresher.scheduleWithFixedDelay(5.0, 5.0);
}
};
/** Task for updating the globals and the types periodically. */
private final Task refresher = new Task(PeriodicCache.TASK_EXECUTOR_NAME, null) {
@Override
public void doTask() {
Database database = getDatabase();
Date newGlobalsUpdate = Query.
from(Object.class).
where("_id = ?", GLOBALS_ID).
using(database).
lastUpdate();
if (newGlobalsUpdate != null &&
(lastGlobalsUpdate == null ||
newGlobalsUpdate.after(lastGlobalsUpdate))) {
refreshGlobals();
}
Date newTypesUpdate = Query.
from(ObjectType.class).
using(database).
lastUpdate();
if (newTypesUpdate != null &&
(lastTypesUpdate == null ||
newTypesUpdate.after(lastTypesUpdate))) {
refreshTypes();
}
}
};
/** Immediately refreshes all globals using the backing database. */
public synchronized void refreshGlobals() {
bootstrapOnce.ensure();
Database database = getDatabase();
LOGGER.info("Loading globals from [{}]", database.getName());
State newGlobals = State.getInstance(Query.
from(Object.class).
where("_id = ?", GLOBALS_ID).
using(database).
first());
if (newGlobals == null) {
newGlobals = new State();
newGlobals.setDatabase(database);
newGlobals.setId(GLOBALS_ID);
newGlobals.save();
}
globals = newGlobals;
lastGlobalsUpdate = new Date();
fieldsCache.reset();
metricFieldsCache.reset();
indexesCache.reset();
}
/** Immediately refreshes all types using the backing database. */
public synchronized void refreshTypes() {
bootstrapOnce.ensure();
Database database = getDatabase();
try {
TypesCache temporaryTypes = temporaryTypesLocal.get();
if (temporaryTypes == null) {
temporaryTypes = new TypesCache();
temporaryTypesLocal.set(temporaryTypes);
}
List<ObjectType> types = Query.
from(ObjectType.class).
using(database).
selectAll();
int typesSize = types.size();
LOGGER.info("Loading [{}] types from [{}]", typesSize, database.getName());
// Load all types from the database first.
for (ObjectType type : types) {
type.getFields().size(); // Pre-fetch.
temporaryTypes.add(type);
}
if (initializeClasses) {
// Make sure that the root type exists.
ObjectType rootType = getRootType();
State rootTypeState;
if (rootType != null) {
rootTypeState = rootType.getState();
} else {
rootType = new ObjectType();
rootTypeState = rootType.getState();
rootTypeState.setDatabase(database);
}
Map<String, Object> rootTypeOriginals = rootTypeState.getSimpleValues();
UUID rootTypeId = rootTypeState.getId();
rootTypeState.setTypeId(rootTypeId);
rootTypeState.clear();
rootType.setObjectClassName(ObjectType.class.getName());
rootType.initialize();
temporaryTypes.add(rootType);
try {
database.beginWrites();
// Make the new root type available to other types.
temporaryTypes.add(rootType);
if (rootTypeState.isNew()) {
State globals = getGlobals();
globals.put(ROOT_TYPE_FIELD, rootType);
globals.save();
} else if (!rootTypeState.getSimpleValues().equals(rootTypeOriginals)) {
temporaryTypes.changed.add(rootTypeId);
}
Set<Class<? extends Recordable>> objectClasses = ClassFinder.Static.findClasses(Recordable.class);
for (Iterator<Class<? extends Recordable>> i = objectClasses.iterator(); i.hasNext(); ) {
Class<? extends Recordable> objectClass = i.next();
if (objectClass.isAnonymousClass()) {
i.remove();
}
}
Set<Class<?>> globalModifications = new HashSet<Class<?>>();
Map<ObjectType, List<Class<?>>> typeModifications = new HashMap<ObjectType, List<Class<?>>>();
// Make sure all types are accessible to the rest of the
// system as soon as possible, so that references can be
// resolved properly later.
for (Class<?> objectClass : objectClasses) {
ObjectType type = getTypeByClass(objectClass);
if (type == null) {
type = new ObjectType();
type.getState().setDatabase(database);
} else {
type.getState().clear();
}
type.setObjectClassName(objectClass.getName());
typeModifications.put(type, new ArrayList<Class<?>>());
temporaryTypes.add(type);
}
// Separate out all modifications from regular types.
for (Class<?> objectClass : objectClasses) {
if (!Modification.class.isAssignableFrom(objectClass)) {
continue;
}
@SuppressWarnings("unchecked")
Set<Class<?>> modifiedClasses = Modification.Static.getModifiedClasses((Class<? extends Modification<?>>) objectClass);
if (modifiedClasses.contains(Object.class)) {
globalModifications.add(objectClass);
continue;
}
for (Class<?> modifiedClass : modifiedClasses) {
List<Class<?>> assignableClasses = new ArrayList<Class<?>>();
for (Class<?> c : objectClasses) {
if (modifiedClass.isAssignableFrom(c)) {
assignableClasses.add(c);
}
}
for (Class<?> assignableClass : assignableClasses) {
ObjectType type = getTypeByClass(assignableClass);
if (type != null) {
List<Class<?>> modifications = typeModifications.get(type);
if (modifications == null) {
modifications = new ArrayList<Class<?>>();
typeModifications.put(type, modifications);
}
modifications.add(objectClass);
}
}
}
}
// Apply global modifications.
for (Class<?> modification : globalModifications) {
ObjectType.modifyAll(database, modification);
}
// Initialize all types.
List<Class<?>> rootTypeModifications = typeModifications.remove(rootType);
initializeAndModify(temporaryTypes, rootType, rootTypeModifications);
if (rootTypeModifications != null) {
for (Class<?> modification : rootTypeModifications) {
ObjectType t = getTypeByClass(modification);
initializeAndModify(temporaryTypes, t, typeModifications.remove(t));
}
}
ObjectType fieldType = getTypeByClass(ObjectField.class);
List<Class<?>> fieldModifications = typeModifications.remove(fieldType);
initializeAndModify(temporaryTypes, fieldType, fieldModifications);
if (fieldModifications != null) {
for (Class<?> modification : fieldModifications) {
ObjectType t = getTypeByClass(modification);
initializeAndModify(temporaryTypes, t, typeModifications.remove(t));
}
}
for (Map.Entry<ObjectType, List<Class<?>>> entry : typeModifications.entrySet()) {
initializeAndModify(temporaryTypes, entry.getKey(), entry.getValue());
}
database.commitWrites();
} finally {
database.endWrites();
}
}
// Merge temporary types into new permanent types.
TypesCache newPermanentTypes = new TypesCache();
for (ObjectType type : permanentTypes.byId.values()) {
newPermanentTypes.add(type);
}
for (ObjectType type : temporaryTypes.byId.values()) {
newPermanentTypes.add(type);
}
newPermanentTypes.changed.addAll(temporaryTypes.changed);
newPermanentTypes.changed.addAll(permanentTypes.changed);
permanentTypes = newPermanentTypes;
lastTypesUpdate = new Date();
} finally {
temporaryTypesLocal.remove();
}
ObjectType singletonType = getTypeByClass(Singleton.class);
if (singletonType != null) {
for (ObjectType type : singletonType.findConcreteTypes()) {
if (!Query.
fromType(type).
master().
noCache().
hasMoreThan(0)) {
try {
State.getInstance(type.createObject(null)).save();
} catch (Exception error) {
LOGGER.warn(String.format("Can't save [%s] singleton!", type.getLabel()), error);
}
}
}
}
}
private static void initializeAndModify(TypesCache temporaryTypes, ObjectType type, List<Class<?>> modifications) {
State typeState = type.getState();
Map<String, Object> typeOriginals = typeState.getSimpleValues();
try {
type.initialize();
temporaryTypes.add(type);
// Apply type-specific modifications.
if (modifications != null) {
for (Class<?> modification : modifications) {
type.modify(modification);
}
}
} catch (IncompatibleClassChangeError ex) {
LOGGER.info(
"Skipped initializing [{}] because its class is in an inconsistent state! ([{}])",
type.getInternalName(),
ex.getMessage());
}
if (typeState.isNew()) {
type.save();
} else if (!typeState.getSimpleValues().equals(typeOriginals)) {
temporaryTypes.changed.add(type.getId());
}
}
/**
* Returns all global values.
*
* @return May be {@code null}.
*/
public State getGlobals() {
bootstrapOnce.ensure();
return globals;
}
// Returns the root type from the globals.
private ObjectType getRootType() {
State globals = getGlobals();
if (globals != null) {
Object rootType = globals.get(ROOT_TYPE_FIELD);
if (rootType == null) {
rootType = globals.get("rootRecordType");
}
if (rootType instanceof ObjectType) {
return (ObjectType) rootType;
}
}
return null;
}
@Override
public DatabaseEnvironment getEnvironment() {
return this;
}
@Override
public List<ObjectField> getFields() {
return new ArrayList<ObjectField>(fieldsCache.get().values());
}
private final transient Lazy<Map<String, ObjectField>> fieldsCache = new Lazy<Map<String, ObjectField>>() {
@Override
@SuppressWarnings("unchecked")
protected Map<String, ObjectField> create() {
State globals = getGlobals();
Object definitions = globals != null ? globals.get(GLOBAL_FIELDS_FIELD) : null;
return ObjectField.Static.convertDefinitionsToInstances(
DatabaseEnvironment.this,
definitions instanceof List ?
(List<Map<String, Object>>) definitions :
null);
}
};
@Override
public ObjectField getField(String name) {
return fieldsCache.get().get(name);
}
@Override
public void setFields(List<ObjectField> fields) {
getGlobals().put(GLOBAL_FIELDS_FIELD, ObjectField.Static.convertInstancesToDefinitions(fields));
fieldsCache.reset();
metricFieldsCache.reset();
}
public List<ObjectField> getMetricFields() {
return metricFieldsCache.get();
}
private final transient Lazy<List<ObjectField>> metricFieldsCache = new Lazy<List<ObjectField>>() {
@Override
protected List<ObjectField> create() {
List<ObjectField> metricFields = new ArrayList<ObjectField>();
for (ObjectField field : getFields()) {
if (field.isMetric()) {
metricFields.add(field);
}
}
return metricFields;
}
};
@Override
public List<ObjectIndex> getIndexes() {
return new ArrayList<ObjectIndex>(indexesCache.get().values());
}
private final transient Lazy<Map<String, ObjectIndex>> indexesCache = new Lazy<Map<String, ObjectIndex>>() {
@Override
@SuppressWarnings("unchecked")
protected Map<String, ObjectIndex> create() {
State globals = getGlobals();
Object definitions = globals != null ? globals.get(GLOBAL_INDEXES_FIELD) : null;
return ObjectIndex.Static.convertDefinitionsToInstances(
DatabaseEnvironment.this,
definitions instanceof List ?
(List<Map<String, Object>>) definitions :
null);
}
};
@Override
public ObjectIndex getIndex(String name) {
return indexesCache.get().get(name);
}
@Override
public void setIndexes(List<ObjectIndex> indexes) {
getGlobals().put(GLOBAL_INDEXES_FIELD, ObjectIndex.Static.convertInstancesToDefinitions(indexes));
indexesCache.reset();
}
/**
* Initializes the given {@code objectClasses} so that they are
* usable as {@linkplain ObjectType types}.
*/
public void initializeTypes(Iterable<Class<?>> objectClasses) {
bootstrapOnce.ensure();
Set<String> classNames = new HashSet<String>();
for (Class<?> objectClass : objectClasses) {
classNames.add(objectClass.getName());
}
for (ObjectType type : getTypes()) {
UUID id = type.getId();
if (classNames.contains(type.getObjectClassName())) {
TypesCache temporaryTypes = temporaryTypesLocal.get();
if ((temporaryTypes != null &&
temporaryTypesLocal.get().changed.contains(id)) ||
permanentTypes.changed.contains(id)) {
type.save();
}
}
}
}
/**
* Returns all types.
* @return Never {@code null}. May be modified without any side effects.
*/
public Set<ObjectType> getTypes() {
bootstrapOnce.ensure();
Set<ObjectType> types = new HashSet<ObjectType>();
TypesCache temporaryTypes = temporaryTypesLocal.get();
if (temporaryTypes != null) {
types.addAll(temporaryTypes.byId.values());
}
types.addAll(permanentTypes.byId.values());
return types;
}
/**
* Returns the type associated with the given {@code id}.
* @return May be {@code null}.
*/
public ObjectType getTypeById(UUID id) {
bootstrapOnce.ensure();
TypesCache temporaryTypes = temporaryTypesLocal.get();
if (temporaryTypes != null) {
ObjectType type = temporaryTypes.byId.get(id);
if (type != null) {
return type;
}
}
return permanentTypes.byId.get(id);
}
/**
* Returns the type associated with the given {@code objectClass}.
* @return May be {@code null}.
*/
public ObjectType getTypeByName(String name) {
bootstrapOnce.ensure();
TypesCache temporaryTypes = temporaryTypesLocal.get();
if (temporaryTypes != null) {
ObjectType type = temporaryTypes.byName.get(name);
if (type != null) {
return type;
}
}
return permanentTypes.byName.get(name);
}
/**
* Returns a set of types associated with the given {@code group}.
* @return Never {@code null}. May be modified without any side effects.
*/
public Set<ObjectType> getTypesByGroup(String group) {
bootstrapOnce.ensure();
TypesCache temporaryTypes = temporaryTypesLocal.get();
Set<ObjectType> tTypes;
if (temporaryTypes != null) {
tTypes = temporaryTypes.byGroup.get(group);
} else {
tTypes = null;
}
Set<ObjectType> pTypes = permanentTypes.byGroup.get(group);
if (tTypes == null) {
return pTypes == null ?
new HashSet<ObjectType>() :
new HashSet<ObjectType>(pTypes);
} else {
tTypes = new HashSet<ObjectType>(tTypes);
if (pTypes != null) {
tTypes.addAll(pTypes);
}
return tTypes;
}
}
/**
* Returns the type associated with the given {@code objectClass}.
* @return May be {@code null}.
*/
public ObjectType getTypeByClass(Class<?> objectClass) {
bootstrapOnce.ensure();
String className = objectClass.getName();
TypesCache temporaryTypes = temporaryTypesLocal.get();
if (temporaryTypes != null) {
ObjectType type = temporaryTypes.byClassName.get(className);
if (type != null) {
return type;
}
}
return permanentTypes.byClassName.get(className);
}
/**
* Creates an object represented by the given {@code typeId} and
* {@code id}.
*/
public Object createObject(UUID typeId, UUID id) {
bootstrapOnce.ensure();
Class<?> objectClass = null;
ObjectType type = null;
if (typeId != null && !GLOBALS_ID.equals(id)) {
if (typeId.equals(id)) {
objectClass = ObjectType.class;
} else {
type = getTypeById(typeId);
if (type != null) {
objectClass = type.isAbstract() ?
Record.class :
type.getObjectClass();
}
}
}
boolean hasClass = true;
if (objectClass == null) {
objectClass = Record.class;
hasClass = false;
}
Object object = TypeDefinition.getInstance(objectClass).newInstance();
State state = State.getInstance(object);
state.setDatabase(getDatabase());
state.setId(id);
state.setTypeId(typeId);
if (type != null) {
if (!hasClass) {
for (ObjectField field : type.getFields()) {
Object defaultValue = field.getDefaultValue();
if (defaultValue != null) {
state.put(field.getInternalName(), defaultValue);
}
}
}
}
return object;
}
private final transient Lazy<List<DynamicProperty>> dynamicProperties = new Lazy<List<DynamicProperty>>() {
@Override
protected List<DynamicProperty> create() {
List<DynamicProperty> properties = new ArrayList<DynamicProperty>();
int index = 0;
for (ObjectType type : getTypes()) {
String beanProperty = type.getJavaBeanProperty();
if (ObjectUtils.isBlank(beanProperty)) {
continue;
} else if (index >= 29) {
throw new IllegalStateException("Can't create more than 30 dynamic properties!");
}
try {
properties.add(new DynamicProperty(type, beanProperty, index));
++ index;
} catch (Exception error) {
}
}
return ImmutableList.copyOf(properties);
}
};
private static class DynamicProperty extends SimpleBeanInfo {
public final ObjectType type;
public final int index;
private final PropertyDescriptor descriptor;
public DynamicProperty(ObjectType type, String name, int index) throws Exception {
Method readMethod = Record.class.getDeclaredMethod("getDynamicProperty" + index);
readMethod.setAccessible(true);
this.type = type;
this.index = index;
this.descriptor = new PropertyDescriptor(name, readMethod, null);
}
@Override
public PropertyDescriptor[] getPropertyDescriptors() {
return new PropertyDescriptor[] { descriptor };
}
}
/**
* Returns all additional {@link BeanInfo} instances appropriate for the
* class represented by the given {@code type}.
*
* @param type If {@code null}, returns global {@link BeanInfo} instances.
* @return May be {@code null}.
*/
@SuppressWarnings("unchecked")
public BeanInfo[] getAdditionalBeanInfoByType(ObjectType type) {
List<BeanInfo> beanInfos = null;
for (DynamicProperty property : dynamicProperties.get()) {
boolean add = false;
if (type != null &&
type.getModificationClassNames().contains(property.type.getObjectClassName())) {
add = true;
} else {
Class<?> modClass = property.type.getObjectClass();
if (modClass != null &&
Modification.class.isAssignableFrom(modClass) &&
Modification.Static.getModifiedClasses((Class<? extends Modification<?>>) modClass).contains(Object.class)) {
add = true;
}
}
if (add) {
if (beanInfos == null) {
beanInfos = new ArrayList<BeanInfo>();
}
beanInfos.add(property);
}
}
return beanInfos != null ?
beanInfos.toArray(new BeanInfo[beanInfos.size()]) :
null;
}
/**
* Returns the type that's bound to the given dynamic property
* {@code index}.
*
* @return May be {@code null}.
*/
public ObjectType getTypeByDynamicPropertyIndex(int index) {
for (DynamicProperty property : dynamicProperties.get()) {
if (property.index == index) {
return property.type;
}
}
return null;
}
/** @deprecated Use {@link #getGlobals} instead. */
@Deprecated
public Object getGlobal(String key) {
State globals = getGlobals();
return globals != null ? globals.getValue(key) : null;
}
/** @deprecated Use {@link #getGlobals} instead. */
@Deprecated
public void putGlobal(String key, Object value) {
State globals = getGlobals();
globals.putValue(key, value);
globals.save();
}
}
|
package bisq.network.p2p.network;
import bisq.network.p2p.NodeAddress;
import bisq.common.UserThread;
import bisq.common.app.Log;
import bisq.common.proto.network.NetworkEnvelope;
import bisq.common.proto.network.NetworkProtoResolver;
import bisq.common.util.Utilities;
import com.runjva.sourceforge.jsocks.protocol.Socks5Proxy;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.SettableFuture;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
// Run in UserThread
public abstract class NetworkNode implements MessageListener {
private static final Logger log = LoggerFactory.getLogger(NetworkNode.class);
private static final int CREATE_SOCKET_TIMEOUT = (int) TimeUnit.SECONDS.toMillis(120);
final int servicePort;
private final NetworkProtoResolver networkProtoResolver;
private final CopyOnWriteArraySet<InboundConnection> inBoundConnections = new CopyOnWriteArraySet<>();
private final CopyOnWriteArraySet<MessageListener> messageListeners = new CopyOnWriteArraySet<>();
private final CopyOnWriteArraySet<ConnectionListener> connectionListeners = new CopyOnWriteArraySet<>();
final CopyOnWriteArraySet<SetupListener> setupListeners = new CopyOnWriteArraySet<>();
ListeningExecutorService executorService;
private Server server;
private volatile boolean shutDownInProgress;
// accessed from different threads
private final CopyOnWriteArraySet<OutboundConnection> outBoundConnections = new CopyOnWriteArraySet<>();
protected final ObjectProperty<NodeAddress> nodeAddressProperty = new SimpleObjectProperty<>();
// Constructor
NetworkNode(int servicePort, NetworkProtoResolver networkProtoResolver) {
this.servicePort = servicePort;
this.networkProtoResolver = networkProtoResolver;
}
// API
// Calls this (and other registered) setup listener's ``onTorNodeReady()`` and ``onHiddenServicePublished``
// when the events happen.
abstract public void start(@Nullable SetupListener setupListener);
public SettableFuture<Connection> sendMessage(@NotNull NodeAddress peersNodeAddress, NetworkEnvelope networkEnvelope) {
log.debug("sendMessage: peersNodeAddress=" + peersNodeAddress + "\n\tmessage=" + Utilities.toTruncatedString(networkEnvelope));
checkNotNull(peersNodeAddress, "peerAddress must not be null");
Connection connection = getOutboundConnection(peersNodeAddress);
if (connection == null)
connection = getInboundConnection(peersNodeAddress);
if (connection != null) {
return sendMessage(connection, networkEnvelope);
} else {
log.debug("We have not found any connection for peerAddress {}.\n\t" +
"We will create a new outbound connection.", peersNodeAddress);
final SettableFuture<Connection> resultFuture = SettableFuture.create();
ListenableFuture<Connection> future = executorService.submit(() -> {
Thread.currentThread().setName("NetworkNode:SendMessage-to-" + peersNodeAddress);
OutboundConnection outboundConnection = null;
try {
// can take a while when using tor
long startTs = System.currentTimeMillis();
log.debug("Start create socket to peersNodeAddress {}", peersNodeAddress.getFullAddress());
Socket socket = createSocket(peersNodeAddress);
long duration = System.currentTimeMillis() - startTs;
log.debug("Socket creation to peersNodeAddress {} took {} ms", peersNodeAddress.getFullAddress(),
duration);
if (duration > CREATE_SOCKET_TIMEOUT)
throw new TimeoutException("A timeout occurred when creating a socket.");
// Tor needs sometimes quite long to create a connection. To avoid that we get too many double
// sided connections we check again if we still don't have any connection for that node address.
Connection existingConnection = getInboundConnection(peersNodeAddress);
if (existingConnection == null)
existingConnection = getOutboundConnection(peersNodeAddress);
if (existingConnection != null) {
log.debug("We found in the meantime a connection for peersNodeAddress {}, " +
"so we use that for sending the message.\n" +
"That can happen if Tor needs long for creating a new outbound connection.\n" +
"We might have got a new inbound or outbound connection.",
peersNodeAddress.getFullAddress());
try {
socket.close();
} catch (Throwable throwable) {
log.error("Error at closing socket " + throwable);
}
existingConnection.sendMessage(networkEnvelope);
return existingConnection;
} else {
final ConnectionListener connectionListener = new ConnectionListener() {
@Override
public void onConnection(Connection connection) {
if (!connection.isStopped()) {
outBoundConnections.add((OutboundConnection) connection);
printOutBoundConnections();
connectionListeners.stream().forEach(e -> e.onConnection(connection));
}
}
@Override
public void onDisconnect(CloseConnectionReason closeConnectionReason, Connection connection) {
log.trace("onDisconnect connectionListener\n\tconnection={}" + connection);
//noinspection SuspiciousMethodCalls
outBoundConnections.remove(connection);
printOutBoundConnections();
connectionListeners.stream().forEach(e -> e.onDisconnect(closeConnectionReason, connection));
}
@Override
public void onError(Throwable throwable) {
log.error("new OutboundConnection.ConnectionListener.onError " + throwable.getMessage());
connectionListeners.stream().forEach(e -> e.onError(throwable));
}
};
outboundConnection = new OutboundConnection(socket,
NetworkNode.this,
connectionListener,
peersNodeAddress,
networkProtoResolver);
log.debug("\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" +
"NetworkNode created new outbound connection:"
+ "\nmyNodeAddress=" + getNodeAddress()
+ "\npeersNodeAddress=" + peersNodeAddress
+ "\nuid=" + outboundConnection.getUid()
+ "\nmessage=" + networkEnvelope
+ "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n");
// can take a while when using tor
outboundConnection.sendMessage(networkEnvelope);
return outboundConnection;
}
} catch (Throwable throwable) {
if (!(throwable instanceof ConnectException ||
throwable instanceof IOException ||
throwable instanceof TimeoutException)) {
log.warn("Executing task failed. " + throwable.getMessage());
}
throw throwable;
}
});
Futures.addCallback(future, new FutureCallback<>() {
public void onSuccess(Connection connection) {
UserThread.execute(() -> resultFuture.set(connection));
}
public void onFailure(@NotNull Throwable throwable) {
log.info("onFailure at sendMessage: peersNodeAddress={}\n\tmessage={}\n\tthrowable={}", peersNodeAddress, networkEnvelope.getClass().getSimpleName(), throwable.toString());
UserThread.execute(() -> resultFuture.setException(throwable));
}
});
return resultFuture;
}
}
@Nullable
private InboundConnection getInboundConnection(@NotNull NodeAddress peersNodeAddress) {
Optional<InboundConnection> inboundConnectionOptional = lookupInBoundConnection(peersNodeAddress);
if (inboundConnectionOptional.isPresent()) {
InboundConnection connection = inboundConnectionOptional.get();
log.trace("We have found a connection in inBoundConnections. Connection.uid=" + connection.getUid());
if (connection.isStopped()) {
log.warn("We have a connection which is already stopped in inBoundConnections. Connection.uid=" + connection.getUid());
inBoundConnections.remove(connection);
return null;
} else {
return connection;
}
} else {
return null;
}
}
@Nullable
private OutboundConnection getOutboundConnection(@NotNull NodeAddress peersNodeAddress) {
Optional<OutboundConnection> outboundConnectionOptional = lookupOutBoundConnection(peersNodeAddress);
if (outboundConnectionOptional.isPresent()) {
OutboundConnection connection = outboundConnectionOptional.get();
log.trace("We have found a connection in outBoundConnections. Connection.uid=" + connection.getUid());
if (connection.isStopped()) {
log.warn("We have a connection which is already stopped in outBoundConnections. Connection.uid=" + connection.getUid());
outBoundConnections.remove(connection);
return null;
} else {
return connection;
}
} else {
return null;
}
}
@Nullable
public Socks5Proxy getSocksProxy() {
return null;
}
public SettableFuture<Connection> sendMessage(Connection connection, NetworkEnvelope networkEnvelope) {
Log.traceCall("\n\tmessage=" + Utilities.toTruncatedString(networkEnvelope) + "\n\tconnection=" + connection);
// connection.sendMessage might take a bit (compression, write to stream), so we use a thread to not block
ListenableFuture<Connection> future = executorService.submit(() -> {
Thread.currentThread().setName("NetworkNode:SendMessage-to-" + connection.getUid());
connection.sendMessage(networkEnvelope);
return connection;
});
final SettableFuture<Connection> resultFuture = SettableFuture.create();
Futures.addCallback(future, new FutureCallback<Connection>() {
public void onSuccess(Connection connection) {
UserThread.execute(() -> resultFuture.set(connection));
}
public void onFailure(@NotNull Throwable throwable) {
UserThread.execute(() -> resultFuture.setException(throwable));
}
});
return resultFuture;
}
public ReadOnlyObjectProperty<NodeAddress> nodeAddressProperty() {
return nodeAddressProperty;
}
public Set<Connection> getAllConnections() {
// Can contain inbound and outbound connections with the same peer node address,
// as connection hashcode is using uid and port info
Set<Connection> set = new HashSet<>(inBoundConnections);
set.addAll(outBoundConnections);
return set;
}
public Set<Connection> getConfirmedConnections() {
// Can contain inbound and outbound connections with the same peer node address,
// as connection hashcode is using uid and port info
return getAllConnections().stream()
.filter(Connection::hasPeersNodeAddress)
.collect(Collectors.toSet());
}
public Set<NodeAddress> getNodeAddressesOfConfirmedConnections() {
// Does not contain inbound and outbound connection with the same peer node address
return getConfirmedConnections().stream()
.map(e -> e.getPeersNodeAddressOptional().get())
.collect(Collectors.toSet());
}
public void shutDown(Runnable shutDownCompleteHandler) {
Log.traceCall();
if (!shutDownInProgress) {
shutDownInProgress = true;
if (server != null) {
server.shutDown();
server = null;
}
getAllConnections().stream().forEach(c -> c.shutDown(CloseConnectionReason.APP_SHUT_DOWN));
log.debug("NetworkNode shutdown complete");
}
if (shutDownCompleteHandler != null) shutDownCompleteHandler.run();
}
// SetupListener
void addSetupListener(SetupListener setupListener) {
boolean isNewEntry = setupListeners.add(setupListener);
if (!isNewEntry)
log.warn("Try to add a setupListener which was already added.");
}
// MessageListener implementation
@Override
public void onMessage(NetworkEnvelope networkEnvelope, Connection connection) {
messageListeners.stream().forEach(e -> e.onMessage(networkEnvelope, connection));
}
// Listeners
public void addConnectionListener(ConnectionListener connectionListener) {
boolean isNewEntry = connectionListeners.add(connectionListener);
if (!isNewEntry)
log.warn("Try to add a connectionListener which was already added.\n\tconnectionListener={}\n\tconnectionListeners={}"
, connectionListener, connectionListeners);
}
public void removeConnectionListener(ConnectionListener connectionListener) {
boolean contained = connectionListeners.remove(connectionListener);
if (!contained)
log.debug("Try to remove a connectionListener which was never added.\n\t" +
"That might happen because of async behaviour of CopyOnWriteArraySet");
}
public void addMessageListener(MessageListener messageListener) {
boolean isNewEntry = messageListeners.add(messageListener);
if (!isNewEntry)
log.warn("Try to add a messageListener which was already added.");
}
public void removeMessageListener(MessageListener messageListener) {
boolean contained = messageListeners.remove(messageListener);
if (!contained)
log.debug("Try to remove a messageListener which was never added.\n\t" +
"That might happen because of async behaviour of CopyOnWriteArraySet");
}
// Protected
void createExecutorService() {
if (executorService == null)
executorService = Utilities.getListeningExecutorService("NetworkNode-" + servicePort, 15, 30, 60);
}
void startServer(ServerSocket serverSocket) {
final ConnectionListener connectionListener = new ConnectionListener() {
@Override
public void onConnection(Connection connection) {
if (!connection.isStopped()) {
inBoundConnections.add((InboundConnection) connection);
printInboundConnections();
connectionListeners.stream().forEach(e -> e.onConnection(connection));
}
}
@Override
public void onDisconnect(CloseConnectionReason closeConnectionReason, Connection connection) {
log.trace("onDisconnect at server socket connectionListener\n\tconnection={}" + connection);
//noinspection SuspiciousMethodCalls
inBoundConnections.remove(connection);
printInboundConnections();
connectionListeners.stream().forEach(e -> e.onDisconnect(closeConnectionReason, connection));
}
@Override
public void onError(Throwable throwable) {
log.error("server.ConnectionListener.onError " + throwable.getMessage());
connectionListeners.stream().forEach(e -> e.onError(throwable));
}
};
server = new Server(serverSocket,
NetworkNode.this,
connectionListener,
networkProtoResolver);
executorService.submit(server);
}
private Optional<OutboundConnection> lookupOutBoundConnection(NodeAddress peersNodeAddress) {
log.trace("lookupOutboundConnection for peersNodeAddress={}", peersNodeAddress.getFullAddress());
printOutBoundConnections();
return outBoundConnections.stream()
.filter(connection -> connection.hasPeersNodeAddress() &&
peersNodeAddress.equals(connection.getPeersNodeAddressOptional().get())).findAny();
}
private void printOutBoundConnections() {
StringBuilder sb = new StringBuilder("outBoundConnections size()=")
.append(outBoundConnections.size()).append("\n\toutBoundConnections=");
outBoundConnections.stream().forEach(e -> sb.append(e).append("\n\t"));
log.debug(sb.toString());
}
private Optional<InboundConnection> lookupInBoundConnection(NodeAddress peersNodeAddress) {
log.trace("lookupInboundConnection for peersNodeAddress={}", peersNodeAddress.getFullAddress());
printInboundConnections();
return inBoundConnections.stream()
.filter(connection -> connection.hasPeersNodeAddress() &&
peersNodeAddress.equals(connection.getPeersNodeAddressOptional().get())).findAny();
}
private void printInboundConnections() {
StringBuilder sb = new StringBuilder("inBoundConnections size()=")
.append(inBoundConnections.size()).append("\n\tinBoundConnections=");
inBoundConnections.stream().forEach(e -> sb.append(e).append("\n\t"));
log.debug(sb.toString());
}
abstract protected Socket createSocket(NodeAddress peersNodeAddress) throws IOException;
@Nullable
public NodeAddress getNodeAddress() {
return nodeAddressProperty.get();
}
}
|
import org.junit.jupiter.api.Test;
import org.xwiki.user.GuestUserReference;
import org.xwiki.user.UserReference;
import com.xpn.xwiki.doc.XWikiDocument;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link DefaultDocumentAuthors}.
*
* @version $Id$
* @since 14.0RC1
*/
class DefaultDocumentAuthorsTest
{
@Test
void copyAuthors()
{
XWikiDocument xWikiDocument = mock(XWikiDocument.class);
UserReference contentAuthorRef = mock(UserReference.class);
UserReference creatorRef = mock(UserReference.class);
UserReference metadataAuthorRef = mock(UserReference.class);
UserReference displayedAuthorRef = mock(UserReference.class);
DefaultDocumentAuthors documentAuthors = new DefaultDocumentAuthors(xWikiDocument);
documentAuthors.setCreator(creatorRef);
documentAuthors.setContentAuthor(contentAuthorRef);
documentAuthors.setEffectiveMetadataAuthor(metadataAuthorRef);
documentAuthors.setOriginalMetadataAuthor(displayedAuthorRef);
DefaultDocumentAuthors otherDocumentAuthors = new DefaultDocumentAuthors(xWikiDocument);
assertNotEquals(documentAuthors, otherDocumentAuthors);
otherDocumentAuthors.copyAuthors(documentAuthors);
assertEquals(otherDocumentAuthors, documentAuthors);
}
@Test
void getOriginalMetadataAuthor()
{
XWikiDocument xWikiDocument = mock(XWikiDocument.class);
UserReference contentAuthorRef = mock(UserReference.class);
UserReference creatorRef = mock(UserReference.class);
UserReference metadataAuthorRef = mock(UserReference.class);
UserReference displayedAuthorRef = mock(UserReference.class);
DefaultDocumentAuthors documentAuthors = new DefaultDocumentAuthors(xWikiDocument);
documentAuthors.setCreator(creatorRef);
documentAuthors.setContentAuthor(contentAuthorRef);
documentAuthors.setEffectiveMetadataAuthor(metadataAuthorRef);
documentAuthors.setOriginalMetadataAuthor(displayedAuthorRef);
assertSame(displayedAuthorRef, documentAuthors.getOriginalMetadataAuthor());
documentAuthors = new DefaultDocumentAuthors(xWikiDocument);
documentAuthors.setCreator(creatorRef);
documentAuthors.setContentAuthor(contentAuthorRef);
documentAuthors.setEffectiveMetadataAuthor(metadataAuthorRef);
assertSame(GuestUserReference.INSTANCE, documentAuthors.getOriginalMetadataAuthor());
}
@Test
void setEffectiveMetadataAuthor()
{
XWikiDocument xWikiDocument = mock(XWikiDocument.class);
UserReference effectiveMetadataAuthor = mock(UserReference.class);
DefaultDocumentAuthors documentAuthors = new DefaultDocumentAuthors(xWikiDocument);
documentAuthors.setEffectiveMetadataAuthor(effectiveMetadataAuthor);
verify(xWikiDocument).setMetaDataDirty(true);
documentAuthors.setEffectiveMetadataAuthor(effectiveMetadataAuthor);
// should have been triggered only once since it's not modified again
verify(xWikiDocument).setMetaDataDirty(true);
documentAuthors.setEffectiveMetadataAuthor(mock(UserReference.class));
// not the same author, so should be triggered once more
verify(xWikiDocument, times(2)).setMetaDataDirty(true);
}
}
|
package com.aotal.frisket.service;
import org.apache.tika.Tika;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.sleuth.Span;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Service
public class ConversionServiceImpl implements ConversionService {
private static Logger logger = LoggerFactory.getLogger(ConversionServiceImpl.class);
private final Tika tika;
private final Tracer tracer;
@Inject
public ConversionServiceImpl(Tika tika, Tracer tracer) {
this.tika = tika;
this.tracer = tracer;
}
@Override
public void convert(Span span, Path from, Path to, String filename) throws IOException {
List<String> files = new ArrayList<>();
Files.list(from).forEach(path -> {
try {
// Not guaranteed to work
final String mime = tika.detect(path.toFile());
switch (mime) {
case "application/pdf":
Files.createSymbolicLink(to.resolve(path.getFileName()), path);
break;
case "text/html":
case "text/htm":
ProcessBuilder pb = new ProcessBuilder("wkhtmltopdf", "--quiet", path.toString(), to.resolve(path.getFileName()).toString());
try {
pb.start().waitFor();
} catch (InterruptedException e) {
// Deliberaterly left blank
}
break;
default:
files.add(path.toString());
}
} catch (IOException e) {
logger.debug("Conversion exception", e);
}
});
ProcessBuilder dos2unix = new ProcessBuilder(Stream.concat(Stream.of("dos2unix", "--quiet"), files.stream()).collect(Collectors.toList()));
Span dos2unixSp = tracer.createSpan("Dos2Unix converting", span);
try {
dos2unix.start().waitFor();
} catch (InterruptedException e) {
// Deliberaterly left blank
} finally {
tracer.close(dos2unixSp);
}
ProcessBuilder libre = new ProcessBuilder(Stream.concat(Stream.of("lowriter", "--invisible", "--convert-to", "pdf:writer_pdf_Export:UTF8", "--outdir", to.toString()), files.stream()).collect(Collectors.toList()));
Span libreSp = tracer.createSpan("Libreoffice Converting", span);
try {
libre.start().waitFor();
} catch (InterruptedException e) {
// Deliberaterly left blank
} finally {
tracer.close(libreSp);
}
ProcessBuilder gs = new ProcessBuilder(Stream.concat(Stream.of("gs", "-dBATCH", "-dNOPAUSE", "-dPDFFitPage", "-q", "-sOwnerPassword=reallylongandsecurepassword", "-sDEVICE=pdfwrite", "-sOutputFile=" + to.resolve(filename).toString() + ".pdf"), Files.list(to).map(Path::toString)).collect(Collectors.toList()));
Span gsSp = tracer.createSpan("Stitching", span);
try {
gs.start().waitFor();
} catch (InterruptedException e) {
// Deliberaterly left blank
} finally {
tracer.close(gsSp);
}
}
}
|
package org.broadleafcommerce.admin.catalog.service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.broadleafcommerce.catalog.domain.Category;
import org.broadleafcommerce.catalog.domain.CategoryImpl;
import org.broadleafcommerce.catalog.domain.CrossSaleProductImpl;
import org.broadleafcommerce.catalog.domain.Product;
import org.broadleafcommerce.catalog.domain.RelatedProduct;
import org.broadleafcommerce.catalog.domain.Sku;
import org.broadleafcommerce.catalog.service.CatalogService;
import org.broadleafcommerce.media.domain.Media;
import org.broadleafcommerce.media.domain.MediaImpl;
import org.springframework.stereotype.Service;
import flex.messaging.io.amf.ASObject;
@Service("blAdminCatalogService")
public class AdminCatalogService {
@Resource(name = "blCatalogService")
CatalogService catalogService;
public Product findProductById(Long productId) {
return catalogService.findProductById(productId);
}
public List<Product> findProductsByName(String searchName) {
return catalogService.findProductsByName(searchName);
}
public List<Product> findProductsByCategory(Category category) {
List<Product> p = catalogService.findProductsForCategory(category);
return p;
}
public Product saveProduct(Product product) {
// Map<String, String> images = product.getProductImages();
// Map<String, Media> media = product.getProductMedia();
Product newProduct = catalogService.findProductById(product.getId());
// List<Product> c2 = catalogService.findActiveProductsByCategory(newProduct.getDefaultCategory());
// List<Category> c = newProduct.getAllParentCategories();
// List<RelatedProduct> x = newProduct.getCrossSaleProducts();
// int y = x.size();
// Category cat = c.get(0);
// newProduct.getAllParentCategories().clear();
// newProduct.getAllParentCategories().add(newProduct.getDefaultCategory());
List<Sku> skus = new ArrayList<Sku>(product.getAllSkus().size());
skus.addAll(product.getAllSkus());
product.getAllSkus().clear();
for (int i=0; i< skus.size(); i++){
product.getAllSkus().add(catalogService.saveSku(skus.get(i)));
}
return catalogService.saveProduct(product);
}
public Category findCategoryById(Long categoryId) {
return catalogService.findCategoryById(categoryId);
}
public Category findCategoryByName(String categoryName) {
return catalogService.findCategoryByName(categoryName);
}
public Category saveCategory(Category category) {
if(category.getCategoryImages() != null && category.getCategoryImages() instanceof ASObject) {
category.setCategoryImages(getImagesMapFromAsObject((ASObject)category.getCategoryImages()));
}
if(category.getCategoryMedia() != null && category.getCategoryMedia() instanceof ASObject) {
category.setCategoryMedia(getMediaMapFromAsObject((ASObject)category.getCategoryMedia()));
}
return catalogService.saveCategory(category);
}
public List<Category> findAllCategories() {
List<Category> c = catalogService.findAllCategories();
return c;
}
public List<Product> findAllProducts() {
return catalogService.findAllProducts();
}
public List<Sku> findAllSkus() {
return catalogService.findAllSkus();
}
public Sku findSkuById(Long skuId) {
return catalogService.findSkuById(skuId);
}
public Sku saveSku(Sku sku) {
if(sku.getSkuImages() != null && sku.getSkuImages() instanceof ASObject){
sku.setSkuImages(getImagesMapFromAsObject((ASObject)sku.getSkuImages()));
}
if(sku.getSkuMedia() != null && sku.getSkuMedia() instanceof ASObject){
sku.setSkuMedia(getMediaMapFromAsObject((ASObject)sku.getSkuMedia()));
}
return catalogService.saveSku(sku);
}
public List<Sku> findSkusByIds(List<Long> ids) {
return catalogService.findSkusByIds(ids);
}
private Map<String, String> getImagesMapFromAsObject(ASObject oldImages){
Map<String, String> newImages = new HashMap<String, String>();
for(Object key : oldImages.keySet()) {
if(String.class.equals(key.getClass())) {
Object test = oldImages.get(key);
if(String.class.equals(test.getClass())) {
newImages.put((String)key, (String)oldImages.get(key));
}
}
}
return newImages;
}
private Map<String,Media> getMediaMapFromAsObject(ASObject oldMedia){
Map<String, Media> newMedia = new HashMap<String, Media>();
for(Object key:oldMedia.keySet()) {
if(String.class.equals(key.getClass())) {
Object test = oldMedia.get(key);
if(test instanceof MediaImpl) {
String keyString = (String)key;
newMedia.put(keyString, (MediaImpl)oldMedia.get(key));
}
}
}
return newMedia;
}
private List<Category> normalizeCategories(List<Category> asObjectCategories){
List<Category> normalizedCategories = new ArrayList<Category>();
for (Category category : asObjectCategories){
category.setCategoryImages(getImagesMapFromAsObject((ASObject)category.getCategoryImages()));
category.setCategoryMedia(getMediaMapFromAsObject((ASObject)category.getCategoryMedia()));
normalizedCategories.add(category);
}
return normalizedCategories;
}
}
|
package com.appdynamics.monitors.nginx;
import java.io.IOException;
public class TestNGinXMonitor {
// @Test
public void parseResultsSuccessfully() throws IOException {
String response = "Active connections: 37 \n" +
"server accepts handled requests \n" +
"10574 10574 10649 \n" +
"Reading: 0 Writing: 1 Waiting: 36";
NGinXMonitor nGinXMonitor = new NGinXMonitor();
nGinXMonitor.parseResults(response);
}
}
|
package org.pac4j.core.client;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.exception.TechnicalException;
import org.pac4j.core.util.CommonHelper;
import org.pac4j.core.util.InitializableObject;
/**
* <p>This class is made to group multiple clients using a specific parameter to distinguish them, generally on one
* callback url.</p>
* <p>The {@link #init()} method is used to initialize the callback urls of the clients from the callback url of the
* clients group if empty and a specific parameter added to define the client targeted. It is implicitly called by the
* "finders" methods and doesn't need to be called explicitly.</p>
* <p>The {@link #findClient(WebContext)}, {@link #findClient(String)} or {@link #findClient(Class)} methods must be called
* to find the right client according to the input context or type. The {@link #findAllClients()} method returns all the
* clients.</p>
*
* @author Jerome Leleu
* @since 1.3.0
*/
@SuppressWarnings("rawtypes")
public class Clients extends InitializableObject {
public final static String DEFAULT_CLIENT_NAME_PARAMETER = "client_name";
private String clientNameParameter = DEFAULT_CLIENT_NAME_PARAMETER;
private List<Client> clients;
private String callbackUrl = null;
private Client defaultClient;
public Clients() {
}
public Clients(final String callbackUrl, final List<Client> clients) {
setCallbackUrl(callbackUrl);
setClients(clients);
}
public Clients(final String callbackUrl, final Client... clients) {
setCallbackUrl(callbackUrl);
setClients(clients);
}
public Clients(final String callbackUrl, final Client client) {
setCallbackUrl(callbackUrl);
setClients(Arrays.asList(client));
}
public Clients(final List<Client> clients) {
setClients(clients);
}
public Clients(final Client... clients) {
setClients(clients);
}
public Clients(final Client client) {
setClients(Arrays.asList(client));
}
/**
* Initialize all clients by computing callback urls if necessary.
*/
@Override
protected void internalInit() {
CommonHelper.assertNotNull("clients", getClients());
final HashSet<String> names = new HashSet<>();
for (final Client client : getClients()) {
final String name = client.getName();
final String lowerName = name.toLowerCase();
if (names.contains(lowerName)) {
throw new TechnicalException("Duplicate name in clients: " + name);
}
names.add(lowerName);
if (CommonHelper.isNotBlank(this.callbackUrl) && client instanceof IndirectClient) {
final IndirectClient indirectClient = (IndirectClient) client;
String indirectClientCallbackUrl = indirectClient.getCallbackUrl();
// no callback url defined for the client -> set it with the group callback url
if (indirectClientCallbackUrl == null) {
indirectClient.setCallbackUrl(this.callbackUrl);
indirectClientCallbackUrl = this.callbackUrl;
}
// if the "client_name" parameter is not already part of the callback url, add it unless the client
// has indicated to not include it.
if (indirectClient.isIncludeClientNameInCallbackUrl() &&
indirectClientCallbackUrl.indexOf(this.clientNameParameter + "=") < 0) {
indirectClient.setCallbackUrl(CommonHelper.addParameter(indirectClientCallbackUrl, this.clientNameParameter,
name));
}
}
}
}
/**
* Return the right client according to the web context.
*
* @param context web context
* @return the right client
*/
public Client findClient(final WebContext context) {
final String name = context.getRequestParameter(this.clientNameParameter);
if (name == null && defaultClient != null) {
return defaultClient;
}
CommonHelper.assertNotBlank("name", name);
return findClient(name);
}
/**
* Return the right client according to the specific name.
*
* @param name name of the client
* @return the right client
*/
public Client findClient(final String name) {
init();
for (final Client client : getClients()) {
if (CommonHelper.areEqualsIgnoreCaseAndTrim(name, client.getName())) {
return client;
}
}
final String message = "No client found for name: " + name;
throw new TechnicalException(message);
}
/**
* Return the right client according to the specific class.
*
* @param clazz class of the client
* @param <C> the kind of client
* @return the right client
*/
@SuppressWarnings("unchecked")
public <C extends Client> C findClient(final Class<C> clazz) {
init();
if (clazz != null) {
for (final Client client : getClients()) {
if (clazz.isAssignableFrom(client.getClass())) {
return (C) client;
}
}
}
final String message = "No client found for class: " + clazz;
throw new TechnicalException(message);
}
/**
* Find all the clients.
*
* @return all the clients
*/
public List<Client> findAllClients() {
init();
return getClients();
}
public String getClientNameParameter() {
return this.clientNameParameter;
}
public void setClientNameParameter(final String clientNameParameter) {
this.clientNameParameter = clientNameParameter;
}
public String getCallbackUrl() {
return this.callbackUrl;
}
public void setCallbackUrl(final String callbackUrl) {
this.callbackUrl = callbackUrl;
}
public void setClients(final List<Client> clients) {
this.clients = clients;
}
public void setClients(final Client... clients) {
this.clients = Arrays.asList(clients);
}
public List<Client> getClients() {
return this.clients;
}
@Override
public String toString() {
return CommonHelper.toString(this.getClass(), "callbackUrl", this.callbackUrl, "clientNameParameter",
this.clientNameParameter, "clients", getClients());
}
public void setDefaultClient(Client defaultClient) {
this.defaultClient = defaultClient;
}
public Client getDefaultClient() {
return defaultClient;
}
}
|
package com.buuz135.industrial.gui.conveyor;
import com.buuz135.industrial.api.conveyor.ConveyorUpgrade;
import com.buuz135.industrial.api.conveyor.gui.IGuiComponent;
import com.buuz135.industrial.gui.component.FilterGuiComponent;
import com.buuz135.industrial.proxy.block.filter.IFilter;
import com.buuz135.industrial.proxy.network.ConveyorButtonInteractMessage;
import com.buuz135.industrial.utils.Reference;
import com.hrznstudio.titanium.network.NetworkHandler;
import com.mojang.blaze3d.platform.GlStateManager;
import net.minecraft.client.gui.screen.inventory.ContainerScreen;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GuiConveyor extends ContainerScreen<ContainerConveyor> {
public static final ResourceLocation BG_TEXTURE = new ResourceLocation(Reference.MOD_ID, "textures/gui/conveyor.png");
private ConveyorUpgrade upgrade;
private List<IGuiComponent> componentList;
private int x;
private int y;
private List<IFilter.GhostSlot> ghostSlots;
public GuiConveyor(ContainerConveyor inventorySlotsIn, PlayerInventory inventory, ITextComponent component) {
super(inventorySlotsIn, inventory, component);
this.upgrade = getContainer().getConveyor().getUpgradeMap().get(getContainer().getFacing());
this.componentList = new ArrayList<>();
this.ghostSlots = new ArrayList<>();
}
@Override
protected void init() {
super.init();
componentList.clear();
upgrade.addComponentsToGui(componentList);
for (IGuiComponent iGuiComponent : componentList) {
if (iGuiComponent instanceof FilterGuiComponent) {
ghostSlots.addAll(Arrays.asList(((FilterGuiComponent) iGuiComponent).getFilter().getFilter()));
}
}
}
@Override
protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
this.renderBackground();
GlStateManager.color4f(1, 1, 1, 1);
minecraft.getTextureManager().bindTexture(BG_TEXTURE);
x = (width - xSize) / 2;
y = (height - ySize) / 2;
blit(x, y, 0, 0, xSize, ySize);
if (upgrade != null) {
String localized = new TranslationTextComponent(String.format("conveyor.upgrade.%s.%s", upgrade.getFactory().getRegistryName().getNamespace(), upgrade.getFactory().getRegistryName().getPath())).getFormattedText();
minecraft.fontRenderer.drawString(localized, x + xSize / 2 - minecraft.fontRenderer.getStringWidth(localized) / 2, y + 6, 0x404040);
}
for (IGuiComponent iGuiComponent : componentList) {
iGuiComponent.drawGuiBackgroundLayer(x, y, mouseX, mouseY);
}
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
super.drawGuiContainerForegroundLayer(mouseX, mouseY);
x = (width - xSize) / 2;
y = (height - ySize) / 2;
for (IGuiComponent iGuiComponent : componentList) {
iGuiComponent.drawGuiForegroundLayer(x, y, mouseX, mouseY);
}
renderHoveredToolTip(mouseX - x, mouseY - y);
for (IGuiComponent iGuiComponent : componentList) {
if (iGuiComponent.isInside(mouseX - x, mouseY - y)) {
List<String> tooltips = iGuiComponent.getTooltip(x, y, mouseX, mouseY);
if (tooltips != null) renderTooltip(tooltips, mouseX - x, mouseY - y);
}
}
}
public ContainerConveyor getContainer() {
return (ContainerConveyor) super.getContainer();
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) {
boolean click = super.mouseClicked(mouseX, mouseY, mouseButton);
for (IGuiComponent iGuiComponent : componentList) {
if (iGuiComponent.isInside(mouseX - x, mouseY - y)) {
if(iGuiComponent.handleClick(this, x, y, mouseX, mouseY))
return true;
}
}
return click;
}
public void sendMessage(int id, CompoundNBT compound) {
NetworkHandler.NETWORK.sendToServer(new ConveyorButtonInteractMessage(upgrade.getPos(), id, upgrade.getSide(), compound));
}
public List<IFilter.GhostSlot> getGhostSlots() {
return ghostSlots;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
|
package org.openhab.binding.freeswitch.internal;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.openhab.binding.freeswitch.internal.FreeswitchMessageHeader.*;
import org.openhab.binding.freeswitch.FreeswitchBindingProvider;
import org.apache.commons.lang.StringUtils;
import org.freeswitch.esl.client.IEslEventListener;
import org.freeswitch.esl.client.inbound.Client;
import org.freeswitch.esl.client.inbound.InboundConnectionFailure;
import org.freeswitch.esl.client.transport.event.EslEvent;
import org.freeswitch.esl.client.transport.message.EslMessage;
import org.openhab.core.binding.AbstractBinding;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.StringItem;
import org.openhab.core.library.items.SwitchItem;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.StringType;
import org.openhab.core.types.Command;
import org.openhab.library.tel.items.CallItem;
import org.openhab.library.tel.types.CallType;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* FreeswitchBinding connects to a Freeswitch instance using a ESL Client
* connection. From this connection we listen for call life cycle events, message
* waiting (MWI) events as well as send generic API commands.
* @author Dan Cunningham
* @since 1.4.0
*/
public class FreeswitchBinding extends AbstractBinding<FreeswitchBindingProvider> implements ManagedService, IEslEventListener {
private static final Logger logger =
LoggerFactory.getLogger(FreeswitchBinding.class);
private static int DEFAULT_PORT = 8021;
/*
* How long we check to reconnect
*/
private long WATCHDOG_INTERVAL = 30000;
//all calls are cached, we can lookup channles by thier UUID
protected Map<String, Channel> eventCache;
//map channels by UUID to one or more binding configs
protected Map<String, LinkedList<FreeswitchBindingConfig>> itemMap;
//Maps freeswitch accounts (vmail boxes) to MessageWaiting objects
protected Map<String,MWIModel> mwiCache;
private Client inboudClient;
private String host;
private String password;
private int port;
private WatchDog watchDog;
public FreeswitchBinding() {
}
@Override
public void activate() {
logger.trace("activate() is called!");
}
@Override
public void deactivate() {
logger.trace("deactivate() is called!");
stopWatchdog();
disconnect();
}
/**
* @{inheritDoc}
*/
@Override
protected void internalReceiveCommand(String itemName, Command command) {
logger.trace("Received command for item '{}' with command '{}'",itemName, command);
for (FreeswitchBindingProvider provider : providers) {
FreeswitchBindingConfig config = provider.getFreeswitchBindingConfig(itemName);
switch(config.getType()){
case CMD_API:{
if (!(command instanceof StringType)){
logger.warn("could not process command '{}' for item '{}': command is not a StringType", command, itemName);
return;
}
String str = ((StringType) command).toString().toLowerCase();
String response = executeApiCommand(str);
eventPublisher.postUpdate(itemName, new StringType(response));
}
break;
default:
break;
}
}
}
/**
* @{inheritDoc}
*/
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
logger.trace("updated() is called!");
if (config != null) {
startWatchdog();
port = DEFAULT_PORT;
host = (String) config.get("host");
password = (String) config.get("password");
String portString = (String) config.get("port");
if(StringUtils.isNotBlank(portString))
port = Integer.parseInt(portString);
eventCache = new LinkedHashMap<String, Channel>();
mwiCache = new HashMap<String, FreeswitchBinding.MWIModel>();
itemMap = new LinkedHashMap<String, LinkedList<FreeswitchBindingConfig>>();
try {
connect();
} catch (InboundConnectionFailure e) {
logger.error("Could not connect to freeswitch server",e);
//clean up
disconnect();
}
} else {
//if we no longer have a config, make sure we are not connected and
//that our watchdog thread is not running.
stopWatchdog();
disconnect();
}
}
@Override
public void eventReceived( EslEvent event) {
logger.debug("Recieved ESLEvent {}", event.getEventName());
logger.trace(printEvent(event));
if(CHANNEl_CREATE.matches(event.getEventName())){
handleNewCallEvent(event);
}
else if(CHANNEL_DESTROY.matches(event.getEventName())){
handleHangupCallEvent(event);
}
else if(MESSAGE_WAITING.matches(event.getEventName())){
handleMessageWaiting(event);
}
}
@Override
public void backgroundJobResultReceived(EslEvent arg0) {
}
/**
* Starts our watchdog thread to reconnect
*/
private void startWatchdog(){
//start our watch dog if we have been configued at least
//once, we will stop when the binding is unloaded
if(watchDog == null || !watchDog.isRunning()){
watchDog = new WatchDog();
watchDog.start();
}
}
/**
* stops our watchdog thread;
*/
private void stopWatchdog(){
if(watchDog != null)
watchDog.stopRunning();
}
/**
* Connect inbound client to freeswitch
* @throws InboundConnectionFailure
*/
private void connect() throws InboundConnectionFailure {
disconnect();
logger.debug("Connecting to {} on port {} with pass {}",
host, port, password);
inboudClient = new Client();
inboudClient.connect(host, port,password, 10);
inboudClient.addEventListener(this);
inboudClient.setEventSubscriptions("plain",String.format("%s %s %s",
CHANNEl_CREATE,
CHANNEL_DESTROY,
MESSAGE_WAITING));
logger.debug(String.format("Connected"));
initMessageItems();
}
/**
* disconnect inbound client from freeswitch
*/
private void disconnect() {
if(inboudClient != null){
try {
inboudClient.close();
} catch (Exception ignored) {
} finally{
inboudClient = null;
}
}
}
/**
* Handle Answer or Media (ringing) events and add an entry to our cache
* @param event
*/
private void handleNewCallEvent(EslEvent event) {
String uuid = getHeader(event, UUID);
logger.debug("Adding Call with uuid " + uuid);
Channel channel = new Channel(event);
//we should not get duplicate events, but lets be safe
if(eventCache.containsKey(uuid))
return;
eventCache.put(uuid, channel);
itemMap.put(uuid, new LinkedList<FreeswitchBindingConfig>());
CallType call = channel.getCall();
logger.debug("new call to : {} from : {}",
call.getDestNum(), call.getOrigNum());
for (FreeswitchBindingProvider provider : providers) {
for (String itemName : provider.getItemNames()) {
FreeswitchBindingConfig config = provider
.getFreeswitchBindingConfig(itemName);
if (config.getType() == FreeswitchBindingType.ACTIVE) {
/*
* Add the item if it is filtered and matches or if it is
* un-filtered and inbound
*/
if ((config.filtered() && matchCall(channel,config.getArgument()))
|| (!config.filtered() && isInboundCall(channel))) {
itemMap.get(uuid).add(config);
newCallItemUpdate(config, channel);
}
}
}
}
}
/**
* MatchCall will attempt to match all the filters in a given filterString
* against the headers in a Channel. If all filters are satisfied
* (matched) then we return true, if any filter fails we will stop
* processing and return false.
* @param channel
* @param filterString
* @return true if all filters match, false if any one does not.
*/
private boolean matchCall(Channel channel, String filterString){
logger.debug("Trying to match filter string {}", filterString);
//split our filter string rule pairs
String[] filters = filterString.split(",");
//out return value
boolean matched = true;
//for each filter try and match any channel headers
for(String filter : filters){
//break filter into header key and value
String [] args = filter.split(":");
//check that we have a key and value, and that neither is blank/null
if(args.length == 2 && StringUtils.isNotBlank(args[0]) && StringUtils.isNotBlank(args[1])){
String eventHeader = channel.getEventHeader(args[0]);
try {
//is the header blank/null or does the filter value not match the header value
if(StringUtils.isBlank(eventHeader) || !args[1].equals(URLDecoder.decode(eventHeader, "UTF-8"))){
//this item is filtered, but this call does not match
matched = false;
}
} catch (UnsupportedEncodingException e) {
logger.warn("Could not decode event header {}", eventHeader );
matched = false;
}
} else {
logger.warn("The filter string {} does not look valid, not updating item", filter);
matched = false;
}
/*
* we have failed one of the filters, stop processing
*/
if(!matched)
break;
}
return matched;
}
/**
* Check if this channel is an inbound call
* @param channel
* @return true if the channel is inbound
*/
private boolean isInboundCall(Channel channel){
String direction = channel.getEventHeader(CALL_DIRECTION);
return StringUtils.isNotBlank(direction) && "inbound".equals(direction);
}
/**
* Handle channel destroy events and remove entries from our cache
* @param event
*/
private void handleHangupCallEvent(EslEvent event) {
String uuid = getHeader(event, UUID);
logger.debug("Removing Call with uuid " + uuid);
eventCache.remove(uuid);
LinkedList<FreeswitchBindingConfig> configs =
itemMap.remove(getHeader(event, UUID));
if( configs != null ){
for(FreeswitchBindingConfig config : configs){
endCallItemUpdate(config);
}
}
}
/**
* Update items for new calls
* @param config
* @param channel
*/
private void newCallItemUpdate(FreeswitchBindingConfig config, Channel channel){
if (config.getItemType().isAssignableFrom(SwitchItem.class)) {
eventPublisher.postUpdate(config.getItemName(), OnOffType.ON);
}
else if (config.getItemType().isAssignableFrom(CallItem.class)) {
eventPublisher.postUpdate(config.getItemName(), channel.getCall());
}
else if (config.getItemType().isAssignableFrom(StringItem.class)) {
eventPublisher.postUpdate(config.getItemName(),
new StringType(String.format("%s : %s",
channel.getEventHeader(CID_NAME),
channel.getEventHeader(CID_NUMBER))));
}
else {
logger.warn("handleHangupCall - postUpdate for itemType '{}' is undefined", config.getItemName());
}
}
/**
* update items on call end
* @param config
*/
private void endCallItemUpdate(FreeswitchBindingConfig config){
OnOffType activeState = OnOffType.OFF;;
CallType callType = (CallType)CallType.EMPTY;
StringType callerId = StringType.EMPTY;
/*
* A channel has ended that has this item associated with it
* We still need to check if this item is associated with other
* channels.
* We are going to iterate backwards to get the last added channel;
*/
ListIterator<String> it =
new ArrayList<String>(itemMap.keySet()).listIterator(itemMap.size());
//if we get a match we will stop processing
boolean match = false;
while (it.hasPrevious()) {
String uuid = it.previous();
for(FreeswitchBindingConfig c : itemMap.get(uuid)){
if(c.getItemName().equals(config.getItemName())){
Channel channel = eventCache.get(uuid);
activeState = OnOffType.ON;
callType = channel.getCall();
callerId = new StringType(String.format("%s : %s",
channel.getEventHeader(CID_NAME),
channel.getEventHeader(CID_NUMBER)));
match = true;
break;
}
}
if(match)
break;
}
if (config.getItemType().isAssignableFrom(SwitchItem.class)) {
eventPublisher.postUpdate(config.getItemName(), activeState);
}
else if (config.getItemType().isAssignableFrom(CallItem.class)) {
eventPublisher.postUpdate(config.getItemName(), callType);
}
else if (config.getItemType().isAssignableFrom(StringItem.class)) {
eventPublisher.postUpdate(config.getItemName(), callerId);
}
else {
logger.warn("handleHangupCall - postUpdate for itemType '{}' is undefined", config.getItemName());
}
}
/**
* Handle message waiting indicator events (MWI)
*
* A MWI looks has the following format
*
* MWI-Messages-Waiting: yes
* MWI-Message-Account: jonas@gauffin.com
* MWI-Voice-Message: 2/1 (1/1)
*
* The voice message line format translates to:
* total_new_messages / total_saved_messages (total_new_urgent_messages / total_saved_urgent_messages)
*
* @param event to parse
*/
private void handleMessageWaiting(EslEvent event) {
logger.debug("MWI event\\n {}", event.toString());
for(String key : event.getEventHeaders().keySet()){
logger.debug("MWI Message header {} : {}",
key,event.getEventHeaders().get(key));
}
String account = null;
try {
account = URLDecoder.decode(getHeader(event, MWI_ACCOUNT), "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.error("Could not decode account for event {} : {}", event, e);
return;
}
boolean waiting = "yes".equalsIgnoreCase(getHeader(event, MWI_WAITING));
String messagesString = getHeader(event, MWI_MESSAGE);
logger.debug("Message header: {}", messagesString);
if(StringUtils.isBlank(messagesString)){
logger.debug("message is not for us.");
return;
}
Pattern pattern = Pattern.compile("([0-9]+)/([0-9]+).*");
Matcher matcher = pattern.matcher(messagesString);
int messages = 0;
if(matcher.matches()){
logger.debug("trying to parse message number {} ", matcher.group(1));
try {
messages = Integer.parseInt(matcher.group(1));
} catch (Exception e) {
logger.warn("Could not parse message number from message {} : {}", messagesString, e);
}
}
logger.debug("Updating MWI to {} VMs", messages);
mwiCache.put(account, new MWIModel(waiting, messages));
updateMessageWaitingItems();
}
/**
* update items for message waiting types for all providers
*/
private void updateMessageWaitingItems(){
for (FreeswitchBindingProvider provider : providers) {
for (String itemName : provider.getItemNames()) {
FreeswitchBindingConfig config = provider.getFreeswitchBindingConfig(itemName);
if(config.getType() == FreeswitchBindingType.MESSAGE_WAITING){
updateMessageWaitingItem(config);
}
}
}
}
/**
* update items for message waiting types
* @param itemName
* @param config
*/
private void updateMessageWaitingItem(FreeswitchBindingConfig config) {
MWIModel model = mwiCache.get(config.getArgument());
/*
* see if this is for us
*/
if(model == null)
return;
if (config.getItemType().isAssignableFrom(SwitchItem.class)) {
eventPublisher.postUpdate(config.getItemName(), model.mwi ? OnOffType.ON : OnOffType.OFF);
}
else if (config.getItemType().isAssignableFrom(NumberItem.class)) {
eventPublisher.postUpdate(config.getItemName(), new DecimalType(model.messages));
}
else {
logger.warn("handle call for item type '{}' is undefined", config.getItemName());
}
}
/**
* query freeswitch for the message count for VM accounts. This should
* be done every time we connect to the system.
*/
private void initMessageItems(){
mwiCache.clear();
for (FreeswitchBindingProvider provider : providers) {
for (String itemName : provider.getItemNames()) {
FreeswitchBindingConfig config = provider.getFreeswitchBindingConfig(itemName);
if(config.getType() == FreeswitchBindingType.MESSAGE_WAITING){
String account = config.getArgument();
if(!mwiCache.containsKey(account) && clientValid()){
EslMessage msg = inboudClient.sendSyncApiCommand("vm_boxcount", account);
if(msg.getBodyLines().size() == 1){
try {
int messages = Integer.parseInt(msg.getBodyLines().get(0));
mwiCache.put(account, new MWIModel(messages > 0, messages));
updateMessageWaitingItem(config);
} catch (Exception e) {
logger.error("Could not parse messages", e);
}
}
}
}
}
}
}
/**
* Execute a api command and return the body as a
* single comma delimited String
* @param command
* @return Each line of the response will be appended to the string,
* delimited by a comma
*/
public String executeApiCommand(String command){
logger.debug("Trying to execute API command {}", command);
if(!clientValid() && StringUtils.isBlank(command)){
logger.error("Bad command {}", command);
return null;
}
String [] args = command.split(" ", 1);
/*
* if we do not have 2 args then this is not valid
*/
if(args.length == 0){
logger.error("Command did not contain a valid command string {}");
return null;
}
EslMessage msg = inboudClient.sendSyncApiCommand(args[0],
args.length > 1 ? args[1] : "");
List<String> bodyLines = msg.getBodyLines();
StringBuilder builder = new StringBuilder();
for(String line : bodyLines){
if(builder.length() > 0)
builder.append(",");
builder.append(line);
}
return builder.toString();
}
/**
* Get a header from a esl event object
* @param event
* @param name
* @return
*/
private static String getHeader(EslEvent event, FreeswitchMessageHeader name){
return getHeader(event, name.toString());
}
private static String getHeader(EslEvent event, String name){
return event.getEventHeaders().get(name);
}
private boolean clientValid(){
return inboudClient != null && inboudClient.canSend();
}
private String printEvent(EslEvent event){
Map<String, String> headers = event.getEventHeaders();
StringBuilder sb = new StringBuilder();
for(String key : headers.keySet()){
sb.append('\t').append(key).append(" = ").append(headers.get(key)).append('\n');
}
return sb.toString();
}
private class MWIModel {
protected boolean mwi = false;
protected int messages = 0;
public MWIModel(boolean mwi, int messages) {
super();
this.mwi = mwi;
this.messages = messages;
}
}
private class Channel {
protected EslEvent event;
public Channel(EslEvent newChannelEvent) {
super();
this.event = newChannelEvent;
}
public CallType getCall(){
String dest = getEventHeader(DEST_NUMBER);
String orig = getEventHeader(ORIG_NUMBER);
if(StringUtils.isBlank(dest))
dest = "unknown";
if(StringUtils.isBlank(orig))
orig = "unknown";
return new CallType(orig,dest);
}
public String getEventHeader(FreeswitchMessageHeader header){
return getEventHeader(header.toString());
}
public String getEventHeader(String header){
return getHeader(event, header);
}
}
/**
* The Freeswitch ESL library we are using does not tell us when
* a connection dies, we need to poll and reconnect, which is what the
* WatchDog class does.
* @author daniel
*
*/
private class WatchDog extends Thread{
private boolean running;
private Object lock = new Object();
public WatchDog(){
super("Freeswitch WatchDog");
running = true;
}
@Override
public void run(){
/*
* Check that our client is connected, try reconnecting if not
*/
while(running){
if(!clientValid()){
try {
logger.warn("Client is not connected, reconnecting");
connect();
} catch (InboundConnectionFailure e) {
logger.error("Could not connect to freeswitch server",e);
}
}
synchronized (lock) {
try {
lock.wait(WATCHDOG_INTERVAL);
} catch (InterruptedException ignored) {
}
}
}
}
/**
* Stops the watchdog from running
*/
public void stopRunning(){
this.running = false;
lock.notifyAll();
}
public boolean isRunning(){
return running;
}
}
}
|
package com.cazsius.solcarrot.client.gui;
import com.cazsius.solcarrot.SOLCarrot;
import com.cazsius.solcarrot.SOLCarrotConfig;
import com.cazsius.solcarrot.client.gui.elements.*;
import com.cazsius.solcarrot.tracking.FoodList;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.StringTextComponent;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import static com.cazsius.solcarrot.lib.Localization.localized;
@OnlyIn(Dist.CLIENT)
public final class FoodBookScreen extends Screen implements PageFlipButton.Pageable {
private static final ResourceLocation texture = SOLCarrot.resourceLocation("textures/gui/food_book.png");
private static final UIImage.Image bookImage = new UIImage.Image(texture, new Rectangle(0, 0, 186, 192));
static final UIImage.Image carrotImage = new UIImage.Image(texture, new Rectangle(0, 240, 16, 16));
static final UIImage.Image spiderEyeImage = new UIImage.Image(texture, new Rectangle(16, 240, 16, 16));
static final UIImage.Image heartImage = new UIImage.Image(texture, new Rectangle(0, 224, 15, 15));
static final UIImage.Image drumstickImage = new UIImage.Image(texture, new Rectangle(16, 224, 15, 15));
static final UIImage.Image blacklistImage = new UIImage.Image(texture, new Rectangle(32, 224, 15, 15));
static final UIImage.Image whitelistImage = new UIImage.Image(texture, new Rectangle(48, 224, 15, 15));
static final Color fullBlack = Color.BLACK;
static final Color lessBlack = new Color(0, 0, 0, 128);
static final Color leastBlack = new Color(0, 0, 0, 64);
private final List<UIElement> elements = new ArrayList<>();
private UIImage background;
private UILabel pageNumberLabel;
private PageFlipButton nextPageButton;
private PageFlipButton prevPageButton;
private PlayerEntity player;
private FoodData foodData;
private final List<Page> pages = new ArrayList<>();
private int currentPageNumber = 0;
public static void open(PlayerEntity player) {
Minecraft.getInstance().displayGuiScreen(new FoodBookScreen(player));
}
public FoodBookScreen(PlayerEntity player) {
super(new StringTextComponent(""));
this.player = player;
}
@Override
public void init() {
super.init();
foodData = new FoodData(FoodList.get(player));
background = new UIImage(bookImage);
background.setCenterX(width / 2);
background.setCenterY(height / 2);
elements.clear();
// page number
pageNumberLabel = new UILabel("1");
pageNumberLabel.setCenterX(background.getCenterX());
pageNumberLabel.setMinY(background.getMinY() + 156);
elements.add(pageNumberLabel);
initPages();
int pageFlipButtonSpacing = 50;
prevPageButton = addButton(new PageFlipButton(
background.getCenterX() - pageFlipButtonSpacing / 2 - PageFlipButton.width,
background.getMinY() + 152,
PageFlipButton.Direction.BACKWARD,
this
));
nextPageButton = addButton(new PageFlipButton(
background.getCenterX() + pageFlipButtonSpacing / 2,
background.getMinY() + 152,
PageFlipButton.Direction.FORWARD,
this
));
updateButtonVisibility();
}
private void initPages() {
pages.clear();
pages.add(new StatListPage(foodData, background.frame));
pages.add(new ConfigInfoPage(foodData, background.frame));
addPages("eaten_foods", foodData.eatenFoods);
if (SOLCarrotConfig.shouldShowUneatenFoods()) {
addPages("uneaten_foods", foodData.uneatenFoods);
}
}
private void addPages(String headerLocalizationPath, List<Item> items) {
String header = localized("gui", "food_book." + headerLocalizationPath, items.size());
List<ItemStack> stacks = items.stream().map(ItemStack::new).collect(Collectors.toList());
pages.addAll(ItemListPage.pages(background.frame, header, stacks));
}
@Override
public void render(int mouseX, int mouseY, float partialTicks) {
renderBackground();
UIElement.render(background, mouseX, mouseY);
super.render(mouseX, mouseY, partialTicks);
// current page
UIElement.render(elements, mouseX, mouseY);
UIElement.render(pages.get(currentPageNumber), mouseX, mouseY);
}
@Override
public void switchToPage(int pageNumber) {
if (!isWithinRange(pageNumber)) return;
currentPageNumber = pageNumber;
updateButtonVisibility();
pageNumberLabel.text = "" + (currentPageNumber + 1);
}
@Override
public int getCurrentPageNumber() {
return currentPageNumber;
}
@Override
public boolean isWithinRange(int pageNumber) {
return pageNumber >= 0 && pageNumber < pages.size();
}
private void updateButtonVisibility() {
prevPageButton.updateState();
nextPageButton.updateState();
}
}
|
package org.openhab.binding.insteonhub.internal;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.lang.StringUtils;
import org.openhab.binding.insteonhub.InsteonHubBindingProvider;
import org.openhab.binding.insteonhub.internal.InsteonHubBindingConfig.BindingType;
import org.openhab.binding.insteonhub.internal.hardware.InsteonHubAdjustmentType;
import org.openhab.binding.insteonhub.internal.hardware.InsteonHubLevelUpdateType;
import org.openhab.binding.insteonhub.internal.hardware.InsteonHubProxy;
import org.openhab.binding.insteonhub.internal.hardware.InsteonHubProxyListener;
import org.openhab.binding.insteonhub.internal.util.InsteonHubBindingConfigUtil;
import org.openhab.core.binding.AbstractActiveBinding;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.IncreaseDecreaseType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.OpenClosedType;
import org.openhab.core.library.types.PercentType;
import org.openhab.core.library.types.StopMoveType;
import org.openhab.core.library.types.UpDownType;
import org.openhab.core.types.Command;
import org.openhab.core.types.State;
import org.openhab.core.types.UnDefType;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Insteon Hub binding. Handles all commands and polls configured devices to
* process updates.
*
* @author Eric Thill
* @since 1.4.0
*/
public class InsteonHubBinding extends AbstractActiveBinding<InsteonHubBindingProvider>implements ManagedService {
private static final Logger logger = LoggerFactory.getLogger(InsteonHubBinding.class);
public static final String DEFAULT_HUB_ID = "_default";
private static final long DEFAULT_REFRESH_INTERVAL = 60000;
private static final String BINDING_NAME = "InsteonHubBinding";
private final Map<String, AtomicLong> itemDimTimeouts = Collections
.synchronizedMap(new HashMap<String, AtomicLong>());
private long refreshInterval = DEFAULT_REFRESH_INTERVAL;
private volatile boolean activated;
// Map of proxies. key=hubId, value=proxy
// Used to keep track of proxies
private final Map<String, InsteonHubProxy> proxies = new HashMap<String, InsteonHubProxy>();
@Override
protected long getRefreshInterval() {
return refreshInterval;
}
@Override
protected String getName() {
return "InsteonHub Refresh Service";
}
@Override
protected void execute() {
logger.debug(BINDING_NAME + " execute");
Set<InsteonHubBindingDeviceInfo> deviceInfos = InsteonHubBindingConfigUtil.getConfiguredDevices(providers);
// loop through all configured devices
for (InsteonHubBindingDeviceInfo deviceInfo : deviceInfos) {
// lookup proxy for device
InsteonHubProxy proxy = proxies.get(deviceInfo.getHubId());
if (proxy != null) {
// request device level from proxy
// this will callback in AsyncEventPublisher if device exists
proxy.requestDeviceLevel(deviceInfo.getDeviceId());
}
}
logger.debug(BINDING_NAME + " execute complete");
}
private static int levelToPercent(int level) {
return (int) (100 * level / 255.0);
}
@Override
protected void internalReceiveCommand(String itemName, Command command) {
// get configuration for this item
InsteonHubBindingConfig config = InsteonHubBindingConfigUtil.getConfigForItem(providers, itemName);
if (config == null) {
logger.error(BINDING_NAME + " received command for unknown item '" + itemName + "'");
return;
}
// parse info from config
BindingType type = config.getBindingType();
String hubId = config.getDeviceInfo().getHubId();
String deviceId = config.getDeviceInfo().getDeviceId();
// lookup proxy from this configuration
InsteonHubProxy proxy = proxies.get(hubId);
if (proxy == null) {
logger.error(BINDING_NAME + " received command for unknown hub id '" + hubId + "'");
return;
}
if (logger.isDebugEnabled()) {
logger.debug(BINDING_NAME + " processing command '" + command + "' of type '"
+ command.getClass().getSimpleName() + "' for item '" + itemName + "'");
}
try {
// process according to type
if (type == BindingType.SWITCH) {
// set value on or off
if (command instanceof OnOffType) {
proxy.setDevicePower(deviceId, command == OnOffType.ON);
}
} else if (type == BindingType.DIMMER) {
// INSTEON Dimmer supports Dimmer and RollerShutter types
if (command instanceof OnOffType) {
// ON or OFF => Set level to 255 or 0
int level = command == OnOffType.ON ? 255 : 0;
proxy.setDeviceLevel(deviceId, level);
} else if (command instanceof IncreaseDecreaseType) {
// Increase/Decrease => Incremental Brighten/Dim
InsteonHubAdjustmentType adjustmentType;
if (command == IncreaseDecreaseType.INCREASE) {
adjustmentType = InsteonHubAdjustmentType.BRIGHTEN;
} else {
adjustmentType = InsteonHubAdjustmentType.DIM;
}
if (setDimTimeout(itemName)) {
proxy.startDeviceAdjustment(deviceId, adjustmentType);
}
} else if (command instanceof UpDownType) {
// Up/Down => Start Brighten/Dim
InsteonHubAdjustmentType adjustmentType;
if (command == UpDownType.UP) {
adjustmentType = InsteonHubAdjustmentType.BRIGHTEN;
} else {
adjustmentType = InsteonHubAdjustmentType.DIM;
}
proxy.startDeviceAdjustment(deviceId, adjustmentType);
} else if (command instanceof StopMoveType) {
// Stop => Stop Brighten/Dim
if (command == StopMoveType.STOP) {
proxy.stopDeviceAdjustment(deviceId);
}
} else {
// set level from 0 to 100 percent value
byte percentByte = Byte.parseByte(command.toString());
float percent = percentByte * .01f;
int level = (int) (255 * percent);
proxy.setDeviceLevel(deviceId, level);
}
}
} catch (Throwable t) {
logger.error("Error processing command '" + command + "' for item '" + itemName + "'", t);
}
}
// returns true if the timeout was not already set
private boolean setDimTimeout(String itemName) {
AtomicLong timeout = itemDimTimeouts.get(itemName);
if (timeout == null) {
timeout = new AtomicLong(System.currentTimeMillis() + 400);
itemDimTimeouts.put(itemName, timeout);
return true;
} else {
long existing = timeout.getAndSet(System.currentTimeMillis() + 400);
return existing == 0;
}
}
protected void addBindingProvider(InsteonHubBindingProvider bindingProvider) {
super.addBindingProvider(bindingProvider);
}
protected void removeBindingProvider(InsteonHubBindingProvider bindingProvider) {
super.removeBindingProvider(bindingProvider);
}
@Override
public synchronized void updated(Dictionary<String, ?> config) throws ConfigurationException {
logger.debug(BINDING_NAME + " updated");
try {
// Process device configuration
if (config != null) {
String refreshIntervalString = (String) config.get("refresh");
if (StringUtils.isNotBlank(refreshIntervalString)) {
refreshInterval = Long.parseLong(refreshIntervalString);
}
// Stop all existing proxy async threads
for (InsteonHubProxy proxy : proxies.values()) {
proxy.stop();
}
// Clear proxy map. It will be rebuilt.
proxies.clear();
// Load new proxies
Map<String, InsteonHubProxy> newProxies = InsteonHubProxyFactory.createInstances(config);
proxies.putAll(newProxies);
for (Map.Entry<String, InsteonHubProxy> entry : proxies.entrySet()) {
String hubId = entry.getKey();
InsteonHubProxy proxy = entry.getValue();
proxy.addListener(new AsyncEventPublisher(hubId));
// If activated, start proxy now
if (activated) {
proxy.start();
}
}
// Set properly configured
setProperlyConfigured(true);
}
} catch (Throwable t) {
logger.error("Error configuring " + getName(), t);
setProperlyConfigured(false);
}
}
@Override
public synchronized void activate() {
logger.debug(BINDING_NAME + " activated");
activated = true;
dimStopThread.start();
// start all proxy async threads
for (InsteonHubProxy proxy : proxies.values()) {
proxy.start();
}
}
@Override
public synchronized void deactivate() {
logger.debug(BINDING_NAME + " deactivated");
activated = false;
// stop all proxy async threads
for (InsteonHubProxy proxy : proxies.values()) {
proxy.stop();
}
}
@Override
protected void internalReceiveUpdate(String itemName, State newState) {
if (logger.isTraceEnabled()) {
logger.trace(BINDING_NAME + " received update for '" + itemName + "' of type '"
+ newState.getClass().getSimpleName() + "' with value '" + newState + "'");
}
// ignore
}
/**
* This class listens for updates from the InsteonHubProxy.
*/
private class AsyncEventPublisher implements InsteonHubProxyListener {
private final String hubId;
public AsyncEventPublisher(String hubId) {
this.hubId = hubId;
}
@Override
public void onLevelUpdate(String device, int level, InsteonHubLevelUpdateType updateType) {
Collection<InsteonHubBindingConfig> configs = InsteonHubBindingConfigUtil.getConfigsForDevice(providers,
hubId, device);
for (InsteonHubBindingConfig config : configs) {
BindingType type = config.getBindingType();
// FIXME Currently filtering STATUS_CHANGE out for non-dimmer types b/c it's not working properly. Need
// to learn more.
if (type == BindingType.SWITCH && updateType == InsteonHubLevelUpdateType.STATUS_CHANGE) {
// switch => 0=OFF, else=ON
State update = level == 0 ? OnOffType.OFF : OnOffType.ON;
sendUpdate(config, update);
} else if (type == BindingType.DIMMER && updateType == InsteonHubLevelUpdateType.STATUS_CHANGE) {
// dimmer => 0-255 to percent
State update = new PercentType(levelToPercent(level));
sendUpdate(config, update);
} else if (type == BindingType.INPUT_ON_OFF && updateType == InsteonHubLevelUpdateType.STATUS_CHANGE) {
// on/off input => translate
Integer onValue = config.getOnValue();
Integer offValue = config.getOffValue();
State update = parseDigitalUpdate(level, onValue, offValue, OnOffType.ON, OnOffType.OFF);
sendUpdate(config, update);
} else if (type == BindingType.INPUT_OPEN_CLOSED
&& updateType == InsteonHubLevelUpdateType.STATUS_CHANGE) {
// open/closed input => translate
Integer openValue = config.getOpenValue();
Integer closedValue = config.getClosedValue();
State update = parseDigitalUpdate(level, openValue, closedValue, OpenClosedType.OPEN,
OpenClosedType.CLOSED);
sendUpdate(config, update);
} else if (type == BindingType.INPUT_UBYTE) {
// analog byte value => 0-255
sendUpdate(config, new DecimalType(level));
} else if (type == BindingType.INPUT_PERCENT) {
// analog percentage => 0-255 to percent
sendUpdate(config, new PercentType(levelToPercent(level)));
}
}
}
// Get the corresponding on/off value depending on the configured values
private State parseDigitalUpdate(int value, Integer onValue, Integer offValue, State onState, State offState) {
if (onValue != null && offValue != null) {
// if on and off configured,
// if either match => use state
// otherwise => UNDEF
if (value == onValue) {
return onState;
} else if (value == offValue) {
return offState;
} else {
return UnDefType.UNDEF;
}
} else if (onValue != null) {
// if only on configured,
// if on matches => ON
// otherwise => OFF
if (value == onValue) {
return onState;
} else {
return offState;
}
} else if (offValue != null) {
// if only off configured,
// if off matches => OFF
// otherwise => ON
if (value == offValue) {
return offState;
} else {
return onState;
}
} else {
// if neither configured,
// if 0 => OFF
// otherwise => ON
if (value == 0) {
return offState;
} else {
return onState;
}
}
}
private void sendUpdate(InsteonHubBindingConfig config, State update) {
eventPublisher.postUpdate(config.getItemName(), update);
}
}
private final Thread dimStopThread = new Thread() {
@Override
public void run() {
while (activated) {
long curTime = System.currentTimeMillis();
synchronized (itemDimTimeouts) {
// check all timeouts
for (Map.Entry<String, AtomicLong> entry : itemDimTimeouts.entrySet()) {
// parse from entry
String itemName = entry.getKey();
AtomicLong timeout = entry.getValue();
// check if timeout is set and has elapsed
if (timeout.get() > 0 && curTime > timeout.get()) {
// timeout elapsed => reset timeout and stop dim/brt
timeout.set(0);
InsteonHubBindingConfig config = InsteonHubBindingConfigUtil.getConfigForItem(providers,
itemName);
InsteonHubProxy proxy = proxies.get(config.getDeviceInfo().getHubId());
proxy.stopDeviceAdjustment(config.getDeviceInfo().getDeviceId());
}
}
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// ignore
}
}
}
};
}
|
package com.cflint.plugins.core;
import net.htmlparser.jericho.Element;
import cfml.parsing.cfscript.script.CFCompDeclStatement;
import cfml.parsing.cfscript.script.CFFuncDeclStatement;
import cfml.parsing.cfscript.script.CFFunctionParameter;
import cfml.parsing.cfscript.script.CFScriptStatement;
import com.cflint.BugInfo;
import com.cflint.BugList;
import com.cflint.plugins.CFLintScannerAdapter;
import com.cflint.plugins.Context;
import com.cflint.tools.CFTool;
public class TooManyFunctionsChecker extends CFLintScannerAdapter {
final String severity = "WARNING";
final int FUNCTION_THRESHOLD = 10;
protected int functionCount = 0;
protected boolean alreadyTooMany = false;
@Override
public void expression(final CFScriptStatement expression, final Context context, final BugList bugs) {
if (expression instanceof CFCompDeclStatement) {
functionCount = 0;
alreadyTooMany = false;
}
else if (expression instanceof CFFuncDeclStatement) {
final CFFuncDeclStatement function = (CFFuncDeclStatement) expression;
if (!trivalFunction(context.getFunctionName())) {
functionCount++;
if (!alreadyTooMany) {
checkNumberFunctions(functionCount, 1, context, bugs);
}
}
}
}
@Override
public void element(final Element element, final Context context, final BugList bugs) {
if (element.getName().equals("cfcomponent")) {
functionCount = 0;
alreadyTooMany = false;
}
else if (element.getName().equals("cffunction")) {
if (!trivalFunction(context.getFunctionName())) {
functionCount++;
if (!alreadyTooMany) {
checkNumberFunctions(functionCount, 1, context, bugs);
}
}
}
}
protected boolean trivalFunction(String name) {
final int length = name.length();
return length >= 3 && name.substring(1,3) == "get"
|| length >= 3 && name.substring(1,3) == "set"
|| length >= 2 && name.substring(1,2) == "is";
}
protected void checkNumberFunctions(int functionCount, int atLine, Context context, BugList bugs) {
String functionThreshold = getParameter("maximum");
int threshold = FUNCTION_THRESHOLD;
if (functionThreshold != null) {
threshold = Integer.parseInt(functionThreshold);
}
if (functionCount > threshold) {
alreadyTooMany = true;
bugs.add(new BugInfo.BugInfoBuilder().setLine(atLine).setMessageCode("EXCESSIVE_FUNCTIONS")
.setSeverity(severity).setFilename(context.getFilename())
.setMessage("Function " + context.getFunctionName() + " has too many functions. Should be less than " + Integer.toString(threshold) + ".")
.build());
}
}
}
|
package org.eclipse.smarthome.core.scheduler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.eclipse.smarthome.core.common.ThreadPoolManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This is an extended version of {@link ThreadPoolManager}, which can also handle expressions for scheduling tasks.
*
* @author Karel Goderis - Initial contribution
*
*/
public class ExpressionThreadPoolManager extends ThreadPoolManager {
/**
* Returns an instance of an expression-driven scheduled thread pool service. If it is the first request for the
* given pool name, the instance is newly created.
*
* @param poolName a short name used to identify the pool, e.g. "discovery"
* @return an instance to use
*/
public static ExpressionThreadPoolExecutor getExpressionScheduledPool(String poolName) {
ExecutorService pool = pools.get(poolName);
if (pool == null) {
synchronized (pools) {
// do a double check if it is still null or if another thread might have created it meanwhile
pool = pools.get(poolName);
if (pool == null) {
Integer cfg = getConfig(poolName);
pool = new ExpressionThreadPoolExecutor(poolName, cfg);
((ThreadPoolExecutor) pool).setKeepAliveTime(THREAD_TIMEOUT, TimeUnit.SECONDS);
((ThreadPoolExecutor) pool).allowCoreThreadTimeOut(true);
pools.put(poolName, pool);
LoggerFactory.getLogger(ExpressionThreadPoolManager.class)
.debug("Created an expression-drive scheduled thread pool '{}' of size {}", poolName, cfg);
}
}
}
if (pool instanceof ExpressionThreadPoolExecutor) {
return (ExpressionThreadPoolExecutor) pool;
} else {
throw new IllegalArgumentException("Pool " + poolName + " is not an expression-driven scheduled pool!");
}
}
public static class ExpressionThreadPoolExecutor extends ScheduledThreadPoolExecutor {
private final Logger logger = LoggerFactory.getLogger(ExpressionThreadPoolExecutor.class);
private Map<Expression, Runnable> scheduled = new ConcurrentHashMap<>();
private Map<Runnable, ArrayList<Future<?>>> futures = Collections
.synchronizedMap(new HashMap<Runnable, ArrayList<Future<?>>>());
private Map<Future<?>, Date> timestamps = Collections.synchronizedMap(new HashMap<Future<?>, Date>());
private Thread monitor;
private NamedThreadFactory monitorThreadFactory;
public ExpressionThreadPoolExecutor(final String poolName, int corePoolSize) {
this(poolName, corePoolSize, new NamedThreadFactory(poolName), new ThreadPoolExecutor.DiscardPolicy() {
private final Logger logger = LoggerFactory.getLogger(ThreadPoolExecutor.DiscardPolicy.class);
// The pool is bounded and rejections will happen during shutdown
@Override
public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) {
// Log and discard
logger.debug("Thread pool '{}' rejected execution of {}", poolName, runnable.getClass());
super.rejectedExecution(runnable, threadPoolExecutor);
}
});
}
public ExpressionThreadPoolExecutor(String threadPool, int corePoolSize, NamedThreadFactory threadFactory,
RejectedExecutionHandler rejectedHandler) {
super(corePoolSize, threadFactory, rejectedHandler);
this.monitorThreadFactory = new NamedThreadFactory(threadFactory.getName() + "-" + "Monitor");
}
@Override
protected void afterExecute(Runnable runnable, Throwable throwable) {
logger.trace("Cleaning up after the execution of '{}'", runnable);
super.afterExecute(runnable, throwable);
if (runnable instanceof Future) {
synchronized (futures) {
for (Runnable aRunnable : futures.keySet()) {
futures.get(aRunnable).removeIf(future -> future == runnable);
}
}
timestamps.remove(runnable);
} else {
ArrayList<Future<?>> obsoleteFutures = new ArrayList<Future<?>>();
synchronized (futures) {
ArrayList<Future<?>> taskFutures = futures.get(runnable);
if (taskFutures != null) {
logger.trace("Runnable '{}' has {} Futures scheduled", runnable, taskFutures.size());
for (Future<?> future : taskFutures) {
if (future.isDone()) {
obsoleteFutures.add(future);
}
}
logger.trace("Runnable '{}' has {} Futures that will be removed", runnable,
obsoleteFutures.size());
for (Future<?> future : obsoleteFutures) {
taskFutures.remove(future);
timestamps.remove(future);
}
} else {
logger.trace("Runnable '{}' has no Futures scheduled", runnable);
}
}
}
if (throwable != null) {
Throwable cause = throwable.getCause();
if (cause instanceof InterruptedException) {
// Ignore this, might happen when we shutdownNow() the executor. We can't
// log at this point as the logging system might be stopped already.
return;
}
}
}
Runnable monitorTask = new Runnable() {
@Override
public void run() {
logger.trace("Starting the monitor thread '{}'", Thread.currentThread().getName());
while (true) {
try {
Date firstExecution = null;
Date now = new Date();
List<Expression> finishedExpressions = new ArrayList<Expression>();
logger.trace("There are {} scheduled expressions", scheduled.keySet().size());
for (Expression e : scheduled.keySet()) {
Date time = e.getTimeAfter(now);
if (time != null) {
logger.trace("Expression's '{}' next execution time is {}", e, time);
Runnable task = scheduled.get(e);
if (task != null) {
synchronized (futures) {
ArrayList<Future<?>> taskFutures = futures.get(task);
if (taskFutures == null) {
taskFutures = new ArrayList<Future<?>>();
futures.put(task, taskFutures);
}
boolean schedule = false;
if (taskFutures.size() == 0) {
// if no futures are currently scheduled, we definitely have to schedule the
// task
schedule = true;
} else {
// check the time stamp of the last scheduled task if an additional task
// needs
// to be scheduled
Date timestamp = timestamps.get(taskFutures.get(taskFutures.size() - 1));
if (time.after(timestamp)) {
schedule = true;
} else {
logger.trace("The task '{}' is already scheduled to execute in {} ms",
task, time.getTime() - now.getTime());
}
}
if (schedule) {
logger.trace("Scheduling the task '{}' to execute in {} ms", task,
time.getTime() - now.getTime());
Future<?> newFuture = ExpressionThreadPoolExecutor.this.schedule(task,
time.getTime() - now.getTime(), TimeUnit.MILLISECONDS);
taskFutures.add(newFuture);
logger.trace("Task '{}' has now {} Futures", task, taskFutures.size());
timestamps.put(newFuture, time);
}
}
} else {
logger.trace("Expressions without tasks are not valid");
}
if (firstExecution == null) {
firstExecution = time;
} else {
if (time.before(firstExecution)) {
firstExecution = time;
}
}
} else {
logger.info("Expression '{}' has no future executions anymore", e);
finishedExpressions.add(e);
}
}
for (Expression e : finishedExpressions) {
scheduled.remove(e);
}
if (firstExecution != null) {
while (now.before(firstExecution)) {
logger.trace("Putting the monitor thread '{}' to sleep for {} ms",
Thread.currentThread().getName(), firstExecution.getTime() - now.getTime());
Thread.sleep(firstExecution.getTime() - now.getTime());
now = new Date();
}
} else {
logger.trace("Putting the monitor thread '{}' to sleep for {} ms",
Thread.currentThread().getName(), THREAD_MONITOR_SLEEP);
Thread.sleep(THREAD_MONITOR_SLEEP);
}
} catch (RejectedExecutionException ex) {
logger.error("The executor has already shutdown : '{}'", ex.getMessage());
} catch (CancellationException ex) {
logger.error("Non executed tasks are cancelled : '{}'", ex.getMessage());
} catch (InterruptedException ex) {
logger.trace("The monitor thread as interrupted : '{}'", ex.getMessage());
}
}
}
};
public void schedule(final Runnable task, final Expression expression) {
if (task == null || expression == null) {
throw new IllegalArgumentException("Task can not be scheduled as task or expression is null.");
}
if (monitor == null) {
monitor = monitorThreadFactory.newThread(monitorTask);
monitor.start();
}
scheduled.put(expression, task);
logger.trace("Scheduled task '{}' using expression '{}'", task, expression);
monitor.interrupt();
}
public boolean remove(Expression expression) {
logger.trace("Removing the expression '{}' from the scheduler", expression);
Runnable task = scheduled.remove(expression);
if (task != null) {
return removeFutures(task);
} else {
return false;
}
}
@Override
public boolean remove(Runnable task) {
Expression theExpression = null;
for (Expression anExpression : scheduled.keySet()) {
if (task.equals(scheduled.get(anExpression))) {
theExpression = anExpression;
break;
}
}
if (theExpression != null) {
return remove(theExpression);
} else {
return super.remove(task);
}
}
public boolean removeFutures(Runnable task) {
logger.trace("Removing Runnable '{}' from the scheduler", task);
ArrayList<Future<?>> obsoleteFutures = new ArrayList<Future<?>>();
synchronized (futures) {
ArrayList<Future<?>> taskFutures = futures.get(task);
if (taskFutures != null) {
if (taskFutures.size() != 0) {
logger.trace("Runnable '{}' has {} Futures to be removed", task, taskFutures.size());
for (Future<?> future : taskFutures) {
future.cancel(false);
timestamps.remove(future);
obsoleteFutures.add(future);
}
}
for (Future<?> future : obsoleteFutures) {
taskFutures.remove(future);
}
super.purge();
if (taskFutures.size() == 0) {
futures.remove(task);
return true;
}
}
return false;
}
}
}
}
|
package com.easternedgerobotics.rov.video;
/**
* The {@code PicameraVideo} class represents a external video process that transmits its video to a known recipient.
*/
public final class PicameraVideo {
/**
* The address of the video player.
*/
private final String host;
/**
* The port on the destination for the video player.
*/
private final int port;
/**
* The external video process.
*/
private UnixProcess process;
/**
* Constructs a new {@code PicameraVideo} instance.
* @param host the address of the host of the video player
* @param port the port on the host of the video player
*/
public PicameraVideo(final String host, final int port) {
this.host = host;
this.port = port;
}
/**
* Start transmitting the video feed.
*/
public final void start() {
process = UnixProcess.start("eer-camera", host, String.valueOf(port));
}
/**
* Flip the video feed.
*/
public final void flip() {
if (process == null) {
throw new IllegalStateException("The process must be started before its video can be flipped.");
}
process.sigusr1();
}
/**
* Stop the video feed.
*/
public final void stop() {
if (process == null) {
throw new IllegalStateException("The process must be started before it can be killed.");
}
process.kill();
process = null;
}
}
|
package com.fluffypeople.managesieve;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Holds deatils about the a servers capabilities.
* @author "Osric Wilkinson" <osric@fluffypeople.com>
*/
public class ServerCapabilities {
private String implementationName = null;
private final Set<String> SASLMethods;
private final Set<String> sieveExtensions;
private boolean tls = false;
private int maxRedirects = 0;
private final Set<String> notify;
private String language = null;
private String owner = null;
private String version = null;
public ServerCapabilities() {
SASLMethods = new LinkedHashSet<String>();
sieveExtensions = new HashSet<String>();
notify = new HashSet<String>();
}
public void setImplementationName(final String name) {
this.implementationName = name;
}
public String getImplementationName() {
return implementationName;
}
public void setSASLMethods(final String raw) {
SASLMethods.clear();
parseString(SASLMethods, raw);
}
public boolean hasSASLMethod(final String method) {
return SASLMethods.contains(method);
}
public String[] getSASLMethods() {
String[] result = new String[SASLMethods.size()];
return SASLMethods.toArray(result);
}
public void setSieveExtensions(final String raw) {
sieveExtensions.clear();
parseString(sieveExtensions, raw);
}
public boolean hasSieveExtension(final String extension) {
return sieveExtensions.contains(extension);
}
public void setHasTLS(final boolean tls) {
this.tls = tls;
}
public boolean hasTLS() {
return tls;
}
public void setNotify(final String raw) {
notify.clear();
parseString(notify, raw);
}
public void setMaxRedirects(final int maxRedirects) {
this.maxRedirects = maxRedirects;
}
public int getMaxRedirects() {
return maxRedirects;
}
public void setLanguage(final String language) {
this.language = language;
}
public String getLanguage() {
return language;
}
public void setOwner(final String owner) {
this.owner = owner;
}
public String getOwner() {
return owner;
}
public void setVersion(final String version) {
this.version = version;
}
public String getVersion() {
return version;
}
public boolean hasNoitfy(final String method) {
return notify.contains(method.toLowerCase());
}
/**
* Checks to see if the server is valid.
* @return boolean true if the version is 1.0, and sieve extensions and implementation
* have been set, false otherwise
*/
public boolean isValid() {
if (version == null || !version.equals("1.0")) {
return false;
}
if (implementationName == null || implementationName.isEmpty()) {
return false;
}
if (sieveExtensions.isEmpty()) {
return false;
}
return true;
}
private static void parseString(final Set<String> target, final String raw) {
String[] parts = raw.split("\\s+");
target.addAll(Arrays.asList(parts));
}
}
|
package edu.kit.iti.formal.pse.worthwhile.interpreter;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import org.eclipse.emf.common.util.EList;
import edu.kit.iti.formal.pse.worthwhile.model.BooleanValue;
import edu.kit.iti.formal.pse.worthwhile.model.CompositeValue;
import edu.kit.iti.formal.pse.worthwhile.model.IntegerValue;
import edu.kit.iti.formal.pse.worthwhile.model.Value;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Addition;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Annotation;
import edu.kit.iti.formal.pse.worthwhile.model.ast.ArrayLiteral;
import edu.kit.iti.formal.pse.worthwhile.model.ast.ArrayType;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Assertion;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Assignment;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Assumption;
import edu.kit.iti.formal.pse.worthwhile.model.ast.AstFactory;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Axiom;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Block;
import edu.kit.iti.formal.pse.worthwhile.model.ast.BooleanLiteral;
import edu.kit.iti.formal.pse.worthwhile.model.ast.BooleanType;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Conditional;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Conjunction;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Disjunction;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Division;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Equal;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Equivalence;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Expression;
import edu.kit.iti.formal.pse.worthwhile.model.ast.FunctionCall;
import edu.kit.iti.formal.pse.worthwhile.model.ast.FunctionDeclaration;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Greater;
import edu.kit.iti.formal.pse.worthwhile.model.ast.GreaterOrEqual;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Implication;
import edu.kit.iti.formal.pse.worthwhile.model.ast.IntegerLiteral;
import edu.kit.iti.formal.pse.worthwhile.model.ast.IntegerType;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Invariant;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Less;
import edu.kit.iti.formal.pse.worthwhile.model.ast.LessOrEqual;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Loop;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Minus;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Modulus;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Multiplication;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Negation;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Plus;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Postcondition;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Precondition;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Program;
import edu.kit.iti.formal.pse.worthwhile.model.ast.QuantifiedExpression;
import edu.kit.iti.formal.pse.worthwhile.model.ast.ReturnStatement;
import edu.kit.iti.formal.pse.worthwhile.model.ast.ReturnValueReference;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Statement;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Subtraction;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Type;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Unequal;
import edu.kit.iti.formal.pse.worthwhile.model.ast.VariableDeclaration;
import edu.kit.iti.formal.pse.worthwhile.model.ast.VariableReference;
import edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.ASTNodeBottomUpVisitor;
import edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.ASTNodeReturnVisitor;
import edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor;
import edu.kit.iti.formal.pse.worthwhile.prover.SpecificationChecker;
import edu.kit.iti.formal.pse.worthwhile.prover.Validity;
import edu.kit.iti.formal.pse.worthwhile.typesystem.WorthwhileTypesystem;
/**
* The AST-visitor implementing the functionality of the interpreter module.
*
* @author Chris
*
*/
class InterpreterASTNodeVisitor extends HierarchialASTNodeVisitor {
/**
* The specification checker.
*/
private SpecificationChecker specificationChecker;
/**
* The execution event handlers.
*/
private Set<AbstractExecutionEventListener> executionEventHandlers = new HashSet<AbstractExecutionEventListener>();
/**
* Gets the execution event handlers.
*
* @return the executionEventHandlers
*/
public Set<AbstractExecutionEventListener> getExecutionEventHandlers() {
return this.executionEventHandlers;
}
/**
* Sets the execution event handlers.
*
* @param executionEventHandlers
* the executionEventHandlers to set
*/
public void setExecutionEventHandlers(final Set<AbstractExecutionEventListener> executionEventHandlers) {
this.executionEventHandlers = executionEventHandlers;
}
/**
* The {@link InterpreterASTNodeVisitor} that was created to execute a function.
*
* <code>executingVisitor</code> is not <code>null</code> if and only if this
* <code>InterpreterASTNodeVisitor</code> has instantiated another <code>InterpreterASTNodeVisitor</code> and
* waits for that to finish the execution of a {@link FunctionDeclaration}.
*/
private InterpreterASTNodeVisitor executingVisitor = null;
/**
* Determine the currently executing {@link InterpreterASTNodeVisitor}.
*
* @return the currently executing <code>InterpreterASTNodeVisitor</code>
*/
InterpreterASTNodeVisitor getExecutingVisitor() {
if (this.executingVisitor != null) {
return this.executingVisitor.getExecutingVisitor();
} else {
return this;
}
}
/**
* The result stack.
*/
private Stack<Value> resultStack = new Stack<Value>();
/**
* Indicates whether the function handled by this visitor has returned.
*/
private boolean functionReturned = false;
/**
* A stack of symbol maps.
*/
private Stack<Map<VariableDeclaration, Value>> symbolStack = new Stack<Map<VariableDeclaration, Value>>();
/**
* Gets the symbol.
*
* @param key
* the key
* @return the symbol
*/
protected Value getSymbol(final VariableDeclaration key) {
for (int i = this.symbolStack.size() - 1; i >= 0; i
// I won't take the 'nice' variant here because I want to start at the top of the stack
Value temp = this.symbolStack.get(i).get(key);
if (temp != null) {
return temp;
}
}
return null;
}
/**
* Get the value of a symbol by its name.
*
* @param key
* the name of the Symbol to look up the value for
* @return the current value of the Symbol or null if no such symbol exists
*/
protected Value getSymbol(final String key) {
for (VariableDeclaration declaration : this.getAllSymbols().keySet()) {
if (declaration.getName().equals(key)) {
return this.getSymbol(declaration);
}
}
// no such symbol
return null;
}
/**
* Sets the symbol.
*
* @param key
* the key
* @param value
* the value
*/
protected void setSymbol(final VariableDeclaration key, final Value value) {
for (int i = this.symbolStack.size() - 1; i >= 0; i
// I won't take the 'nice' variant here because I want to start at the top of the stack
Map<VariableDeclaration, Value> temp = this.symbolStack.get(i);
if (temp.get(key) != null) {
temp.put(key, value);
return;
}
}
this.symbolStack.peek().put(key, value);
}
/**
* Gets all symbols.
*
* @return all symbols
*/
protected Map<VariableDeclaration, Value> getAllSymbols() {
Map<VariableDeclaration, Value> result = new LinkedHashMap<VariableDeclaration, Value>();
ListIterator<Map<VariableDeclaration, Value>> i = this.symbolStack
.listIterator(this.symbolStack.size());
while (i.hasPrevious()) {
result.putAll(i.previous());
}
return result;
}
/**
* Constructs a new {@link InterpreterASTNodeVisitor} with the given {@link SpecificationChecker}.
*
* @param specificationChecker
* the prover used to check formulas
*/
protected InterpreterASTNodeVisitor(final SpecificationChecker specificationChecker) {
this.specificationChecker = specificationChecker;
}
/**
* Signals that a {@link Statement} has been executed by the {@link Interpreter}.
*
* @param statement
* the <code>Statement</code> that was executed
*/
private void statementExecuted(final Statement statement) {
for (AbstractExecutionEventListener listener : this.executionEventHandlers) {
listener.statementExecuted(statement);
}
}
/**
* the statement which is currently executed.
*/
private Statement currentStatement;
/**
* the statement which is currently executed.
*/
private Annotation currentAnnotation;
/**
* Signals that a {@link Statement} will be executed.
*
* @param statement
* the <code>Statement</code> that will be executed
*/
private void statementWillExecute(final Statement statement) {
this.currentStatement = statement;
for (AbstractExecutionEventListener listener : this.executionEventHandlers) {
listener.statementWillExecute(statement);
}
}
/**
* Signals that the execution of a {@link Statement} failed.
*
* @param statement
* the <code>Statement</code> that failed to execute
* @param error
* an {@link InterpreterError} object that describes the error
*/
private void executionFailed(final Statement statement, final InterpreterError error) {
for (AbstractExecutionEventListener listener : this.executionEventHandlers) {
listener.executionFailed(statement, error);
}
}
/**
* Signals the start of the execution of a {@link edu.kit.iti.formal.pse.worthwhile.model.ast.Program}.
*/
private void executionStarted() {
for (AbstractExecutionEventListener listener : this.executionEventHandlers) {
listener.executionStarted();
}
}
/**
* Signals the successful completion of execution of a
* {@link edu.kit.iti.formal.pse.worthwhile.model.ast.Program}.
*/
private void executionCompleted() {
for (AbstractExecutionEventListener listener : this.executionEventHandlers) {
listener.executionCompleted();
}
}
/**
* Signals the execution of an {@link Annotation} that was not valid.
*
* @param annotation
* the invalid <code>Annotation</code>
*/
private void annotationFailed(final Annotation annotation) {
for (AbstractExecutionEventListener listener : this.executionEventHandlers) {
listener.annotationFailed(annotation);
}
}
/**
* Signals the execution of an {@link Annotation} that was valid.
*
* @param annotation
* the valid <code>Annotation</code>
*/
private void annotationSucceeded(final Annotation annotation) {
for (AbstractExecutionEventListener listener : this.executionEventHandlers) {
listener.annotationSucceeded(annotation);
}
}
/**
* Signals the evaluation of a {@link Expression}.
*
* @param expression
* the <code>Expression</code> that was evaluated
*/
private void expressionEvaluated(final Expression expression) {
for (AbstractExecutionEventListener listener : this.executionEventHandlers) {
listener.expressionEvaluated(expression);
}
}
/**
* Signals the failure of a {@link Expression}.
*
* @param expression
* the <code>Expression</code> that failed
* @param error
* the error that was caused
*/
private void expressionFailed(final Expression expression, final InterpreterError error) {
for (AbstractExecutionEventListener listener : this.executionEventHandlers) {
listener.expressionFailed(expression, error);
}
}
/**
* Returns the value generated by the last return statement ran in this context.
*
* @return the return value or null if none is available
*/
protected Value getReturnValue() {
return this.resultStack.peek();
}
/**
* Adds a debug event handler to this context.
*
* @param handler
* the handler
*/
protected void addExecutionEventHandler(final AbstractExecutionEventListener handler) {
this.executionEventHandlers.add(handler);
}
/**
* Removes a debug event handler from this context.
*
* @param handler
* the handler
*/
protected void removeExecutionEventHandler(final AbstractExecutionEventListener handler) {
this.executionEventHandlers.remove(handler);
}
/**
* Clones this visitor.
*
* @return a new {@link InterpreterASTNodeVisitor} that contains an equal {@link symbolStack}
*/
@Override
protected InterpreterASTNodeVisitor clone() {
final InterpreterASTNodeVisitor clone = new InterpreterASTNodeVisitor(this.specificationChecker);
// Values are immutable so that it is efficient to clone the array and
// not the elements
for (final Map<VariableDeclaration, Value> m : this.symbolStack) {
clone.symbolStack.push(new HashMap<VariableDeclaration, Value>(m));
}
return clone;
}
/**
* Pops a boolean value from the result stack. Fails the execution if there is no boolean value on the stack.
*
* @return the {@link BooleanValue} that is on top of the stack.
*/
private BooleanValue popBooleanValue() {
synchronized (this.resultStack) {
if (this.resultStack.peek() instanceof BooleanValue) {
return (BooleanValue) this.resultStack.pop();
} else {
throw new RuntimeException("result type error on resultStack: boolean expected");
}
}
}
/**
* Pops an integer value from the result stack. Fails the execution if there is no integer value on the stack.
*
* @return the {@link IntegerValue} that is on top of the stack.
*/
private IntegerValue popIntegerValue() {
synchronized (this.resultStack) {
if (this.resultStack.peek() instanceof IntegerValue) {
return (IntegerValue) this.resultStack.pop();
} else {
throw new RuntimeException("result type error on resultStack: integer expected");
}
}
}
/**
* Pops a composite value from the result stack. Fails the execution if there is no composite value on the
* stack.
*
* @return the {@link CompositeValue} that is on top of the stack.
*/
private CompositeValue<?> popCompositeValue() {
synchronized (this.resultStack) {
if (this.resultStack.peek() instanceof IntegerValue) {
return (CompositeValue<?>) this.resultStack.pop();
} else {
throw new RuntimeException("result type error on resultStack: composite expected");
}
}
}
/**
* Evaluates an annotation.
*
* @param annotation
* the Annotation to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Annotation)
*/
private void visitAnnotation(final Annotation annotation) {
this.statementWillExecute(annotation);
this.currentAnnotation = annotation;
try {
annotation.getExpression().accept(this);
if (this.popBooleanValue().getValue()) {
annotationSucceeded(annotation);
} else {
annotationFailed(annotation);
}
} catch (StatementException e) {
this.executionFailed(annotation, e.getError());
return;
}
this.currentAnnotation = null;
this.statementExecuted(annotation);
}
/**
* adds the {@link IntegerValue}s of the {@link expression}s addition.left and addition.right and pushes the
* result on the resultStack.
*
* @param addition
* the Addition to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Addition)
*/
public void visit(final Addition addition) {
addition.getLeft().accept(this);
IntegerValue left = this.popIntegerValue();
addition.getRight().accept(this);
IntegerValue right = this.popIntegerValue();
this.resultStack.push(new IntegerValue(left.getValue().add(right.getValue())));
this.expressionEvaluated(addition);
}
/**
* Pushes an array-literal onto the resultStack.
*
* @param arrayLiteral
* the ArrayLiteral to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.ArrayLiteral)
*/
@Override
public void visit(final ArrayLiteral arrayLiteral) {
final List<Expression> values = arrayLiteral.getValues();
final Value[] subValues = new Value[values.size()];
int i = 0;
for (Expression e : values) {
e.accept(this);
subValues[i++] = this.resultStack.pop();
}
this.resultStack.push(new CompositeValue<Value>(subValues));
this.expressionEvaluated(arrayLiteral);
}
/**
* Evaluates an assertion.
*
* @param assertion
* the Assertion to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Assertion)
*/
public void visit(final Assertion assertion) {
this.visitAnnotation(assertion);
}
/**
* @param assumption
* the Assumption to visit
*/
public void visit(final Assumption assumption) {
this.statementWillExecute(assumption);
// TODO do this
this.statementExecuted(assumption);
}
/**
* assigns a new {@link Value} to a variable in the current symbol map.
*
* @param assignment
* the Assignment to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Assignment)
*/
public void visit(final Assignment assignment) {
this.statementWillExecute(assignment);
try {
assignment.getValue().accept(this);
VariableReference reference = assignment.getVariable();
// Decide if we have to handle arrays
if (reference.getIndex() == null) {
this.setSymbol(reference.getVariable(), this.resultStack.pop());
} else {
// create a new array with the new value and replace the old one
reference.getIndex().accept(this);
IntegerValue index = this.popIntegerValue();
CompositeValue<? extends Value> oldValue = (CompositeValue<?>) this.getSymbol(reference
.getVariable());
CompositeValue<? extends Value> newValue = oldValue.replaceUntypedValue(
index.getValue(), this.resultStack.pop());
this.setSymbol(reference.getVariable(), newValue);
}
} catch (StatementException e) {
this.executionFailed(assignment, e.getError());
return;
}
this.statementExecuted(assignment);
}
/**
* @param axiom
* the Axiom to visit
*/
public void visit(final Axiom axiom) {
this.statementWillExecute(axiom);
// TODO do this
this.statementExecuted(axiom);
}
/**
* executes the statements of the block.
*
* @param block
* the Block to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Block)
*/
public void visit(final Block block) {
Map<VariableDeclaration, Value> symbolMap = new HashMap<VariableDeclaration, Value>();
this.symbolStack.push(symbolMap);
this.statementWillExecute(block);
EList<Statement> statements = block.getStatements();
for (Statement statement : statements) {
statement.accept(this);
if (this.functionReturned) {
this.statementExecuted(block);
return;
}
}
this.statementExecuted(block);
this.symbolStack.pop();
}
/**
* Pushes the {@link BooleanValue} of the booleanLiteral onto the resultStack.
*
* @param booleanLiteral
* the BooleanLiteral to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.BooleanLiteral)
*/
public void visit(final BooleanLiteral booleanLiteral) {
this.resultStack.push(new BooleanValue(booleanLiteral.getValue()));
this.expressionEvaluated(booleanLiteral);
}
/**
* Visits one of two {@link Block}s depending on a condition.
*
* @param conditional
* the Conditional to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Conditional)
*/
public void visit(final Conditional conditional) {
this.statementWillExecute(conditional);
try {
conditional.getCondition().accept(this);
if (this.popBooleanValue().getValue()) {
conditional.getTrueBlock().accept(this);
} else {
if (conditional.getFalseBlock() != null) {
conditional.getFalseBlock().accept(this);
}
}
} catch (StatementException e) {
this.executionFailed(conditional, e.getError());
return;
}
this.statementExecuted(conditional);
}
/**
* checks if the {@link Value}s of the {@link expression}s conjunction.left and conjunction.right are both true
* and pushes the result on the resultStack.
*
* @param conjunction
* the Conjunction to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Conjunction)
*/
public void visit(final Conjunction conjunction) {
conjunction.getLeft().accept(this);
BooleanValue left = this.popBooleanValue();
conjunction.getRight().accept(this);
BooleanValue right = this.popBooleanValue();
this.resultStack.push(new BooleanValue(left.getValue() && right.getValue()));
this.expressionEvaluated(conjunction);
}
/**
* checks if at least one the {@link Value}s of the {@link expression}s disjunction.left and disjunction.right
* are both true and pushes the result on the resultStack.
*
* @param disjunction
* the Disjunction to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Disjunction)
*/
public void visit(final Disjunction disjunction) {
disjunction.getLeft().accept(this);
BooleanValue left = this.popBooleanValue();
disjunction.getRight().accept(this);
BooleanValue right = this.popBooleanValue();
this.resultStack.push(new BooleanValue(left.getValue() || right.getValue()));
this.expressionEvaluated(disjunction);
}
/**
* divides the {@link IntegerValue} of the {@link expression} division.left by the {@link IntegerValue} of the
* {@link expression} division.right and pushes the result on the resultStack.
*
* @param division
* the Division to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Division)
*/
public void visit(final Division division) {
division.getLeft().accept(this);
IntegerValue left = this.popIntegerValue();
division.getRight().accept(this);
IntegerValue right = this.popIntegerValue();
if (right.getValue().equals(BigInteger.ZERO)) {
expressionFailed(division, new DivisionByZeroInterpreterError(currentStatement));
return;
} else {
this.resultStack.push(new IntegerValue(left.getValue().divide(right.getValue())));
this.expressionEvaluated(division);
}
}
/**
* checks if the {@link Value}s of the {@link expression}s equal.left and equal.right are equal and pushes the
* result on the resultStack.
*
* @param equal
* the Equal to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Equal)
*/
public void visit(final Equal equal) {
equal.getLeft().accept(this);
Value left = this.resultStack.pop();
equal.getRight().accept(this);
Value right = this.resultStack.pop();
this.resultStack.push(new BooleanValue(left.equals(right)));
this.expressionEvaluated(equal);
}
/**
* compares the {@link BooleanValue}s of the {@link expression}s equivalence.left and equivalence.right and
* pushes the result on the resultStack.
*
* @param equivalence
* the Equivalence to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Equivalence)
*/
public void visit(final Equivalence equivalence) {
equivalence.getLeft().accept(this);
BooleanValue left = this.popBooleanValue();
equivalence.getRight().accept(this);
BooleanValue right = this.popBooleanValue();
this.resultStack.push(new BooleanValue(left.getValue() == right.getValue()));
this.expressionEvaluated(equivalence);
}
/**
* executes a function with a new InterpreterASTNodeVisitor.
*
* @param functionCall
* the called function
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.FunctionCall)
*/
public void visit(final FunctionCall functionCall) {
this.executingVisitor = new InterpreterASTNodeVisitor(this.specificationChecker);
this.executingVisitor.setExecutionEventHandlers(this.executionEventHandlers);
EList<Expression> actuals = functionCall.getActuals();
this.executingVisitor.symbolStack.push(new HashMap<VariableDeclaration, Value>());
// calculate the actual parameters
for (int i = 0; i < actuals.size(); i++) {
actuals.get(i).accept(this);
this.executingVisitor.setSymbol(functionCall.getFunction().getParameters().get(i),
this.resultStack.pop());
}
functionCall.getFunction().accept(this);
Value returnValue = this.executingVisitor.getReturnValue();
this.executingVisitor.resultStack.push(returnValue);
this.resultStack.push(returnValue);
// get execution control back from the function visitor that just
// returned
this.executingVisitor = null;
this.expressionEvaluated(functionCall);
}
/**
* handles preconditions, body and postconditions of a function.
*
* @param functionDeclaration
* the FunctionDeclaration to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.FunctionDeclaration)
*/
public void visit(final FunctionDeclaration functionDeclaration) {
for (Precondition precondition : functionDeclaration.getPreconditions()) {
precondition.accept(this.executingVisitor);
}
functionDeclaration.getBody().accept(this.executingVisitor);
for (Postcondition postcondition : functionDeclaration.getPostconditions()) {
postcondition.accept(this.executingVisitor);
}
}
/**
* checks if the {@link IntegerValue} of the {@link expression} greater.left is greater as the
* {@link IntegerValue} of the {@link expression} greater.right and pushes the result on the resultStack.
*
* @param greater
* the Greater to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Greater)
*/
public void visit(final Greater greater) {
greater.getLeft().accept(this);
IntegerValue left = this.popIntegerValue();
greater.getRight().accept(this);
IntegerValue right = this.popIntegerValue();
this.resultStack.push(new BooleanValue((left.getValue().compareTo(right.getValue()) == 1)));
this.expressionEvaluated(greater);
}
/**
* checks if the {@link IntegerValue} of the {@link expression} greaterOrEqual.left is greater or equal as the
* {@link IntegerValue} of the {@link expression} greaterOrEqual.right and pushes the result on the resultStack.
*
* @param greaterOrEqual
* the GreaterOrEqual to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.GreaterOrEqual)
*/
public void visit(final GreaterOrEqual greaterOrEqual) {
greaterOrEqual.getLeft().accept(this);
IntegerValue left = this.popIntegerValue();
greaterOrEqual.getRight().accept(this);
IntegerValue right = this.popIntegerValue();
this.resultStack.push(new BooleanValue((left.getValue().compareTo(right.getValue()) != -1)));
this.expressionEvaluated(greaterOrEqual);
}
/**
* checks if the {@link BooleanValue} of the {@link expression} implication.left implies the
* {@link IntegerValue} of the {@link expression} implication.right and pushes the result on the resultStack.
*
* @param implication
* the Implication to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Implication)
*/
public void visit(final Implication implication) {
implication.getLeft().accept(this);
BooleanValue left = this.popBooleanValue();
implication.getRight().accept(this);
BooleanValue right = this.popBooleanValue();
this.resultStack.push(new BooleanValue(!(left.getValue() && !right.getValue())));
this.expressionEvaluated(implication);
}
/**
* Pushes the {@link IntegerValue} of the integerLiteral onto the resultStack.
*
* @param integerLiteral
* the IntegerLiteral to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.IntegerLiteral)
*/
public void visit(final IntegerLiteral integerLiteral) {
this.resultStack.push(new IntegerValue(integerLiteral.getValue()));
this.expressionEvaluated(integerLiteral);
}
/**
* Evaluates an invariant.
*
* @param invariant
* the Invariant to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Invariant)
*/
public void visit(final Invariant invariant) {
this.visitAnnotation(invariant);
}
/**
* checks if the {@link IntegerValue} of the {@link expression} less.left is less than the {@link IntegerValue}
* of the {@link expression} less.right and pushes the result on the resultStack.
*
* @param less
* the Less to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Less)
*/
public void visit(final Less less) {
less.getLeft().accept(this);
IntegerValue left = this.popIntegerValue();
less.getRight().accept(this);
IntegerValue right = this.popIntegerValue();
this.resultStack.push(new BooleanValue((left.getValue().compareTo(right.getValue()) == -1)));
this.expressionEvaluated(less);
}
/**
* checks if the {@link IntegerValue} of the {@link expression} lessOrEqual.left is less or equal than the
* {@link IntegerValue} of the {@link expression} lessOrEqual.right and pushes the result on the resultStack.
*
* @param lessOrEqual
* the LessOrEqual to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.LessOrEqual)
*/
public void visit(final LessOrEqual lessOrEqual) {
lessOrEqual.getLeft().accept(this);
IntegerValue left = this.popIntegerValue();
lessOrEqual.getRight().accept(this);
IntegerValue right = this.popIntegerValue();
this.resultStack.push(new BooleanValue((left.getValue().compareTo(right.getValue()) != 1)));
this.expressionEvaluated(lessOrEqual);
}
/**
* Visit a {@link Block} as long as a condition is true.
*
* @param loop
* the Loop to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Loop)
*/
public void visit(final Loop loop) {
this.statementWillExecute(loop);
try {
for (Invariant invariant : loop.getInvariants()) {
invariant.accept(this);
}
loop.getCondition().accept(this);
while (this.popBooleanValue().getValue()) {
loop.getBody().accept(this);
for (Invariant invariant : loop.getInvariants()) {
invariant.accept(this);
}
loop.getCondition().accept(this);
}
} catch (StatementException e) {
this.executionFailed(loop, e.getError());
return;
}
this.statementExecuted(loop);
}
/**
* negates the {@link IntegerValue} of the {@link expression} minus.operand and pushes the result on the
* resultStack.
*
* @param minus
* the Minus to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Minus)
*/
public void visit(final Minus minus) {
minus.getOperand().accept(this);
this.resultStack.push(new IntegerValue(this.popIntegerValue().getValue().negate()));
this.expressionEvaluated(minus);
}
/**
* calculates the modulus of the {@link IntegerValue}s of the {@link expression}s modulus.left and modulus.right
* and pushes the result on the resultStack.
*
* @param modulus
* the Modulus to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Modulus)
*/
public void visit(final Modulus modulus) {
modulus.getLeft().accept(this);
IntegerValue left = this.popIntegerValue();
modulus.getRight().accept(this);
IntegerValue right = this.popIntegerValue();
if (right.getValue().equals(BigInteger.ZERO)) {
expressionFailed(modulus, new DivisionByZeroInterpreterError(currentStatement));
return;
} else {
this.resultStack.push(new IntegerValue(left.getValue().mod(right.getValue())));
this.expressionEvaluated(modulus);
}
}
/**
* multiplies the {@link IntegerValue}s of the {@link expression}s multiplication.left and multiplication.right
* and pushes the result on the resultStack.
*
* @param multiplication
* the Multiplication to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Multiplication)
*/
public void visit(final Multiplication multiplication) {
multiplication.getLeft().accept(this);
IntegerValue left = this.popIntegerValue();
multiplication.getRight().accept(this);
IntegerValue right = this.popIntegerValue();
this.resultStack.push(new IntegerValue(left.getValue().multiply(right.getValue())));
this.expressionEvaluated(multiplication);
}
/**
* negates the {@link BooleanValue} of the {@link expression} negation.oparand and pushes the result on the
* resultStack.
*
* @param negation
* the Negation to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Negation)
*/
public void visit(final Negation negation) {
negation.getOperand().accept(this);
this.resultStack.push(new BooleanValue(!(this.popBooleanValue().getValue())));
this.expressionEvaluated(negation);
}
/**
* does nothing with the {@link IntegerValue} of the {@link expression} plus.operand and pushes the result on
* the resultStack.
*
* @param plus
* the Plus to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Plus)
*/
public void visit(final Plus plus) {
plus.getOperand().accept(this);
this.expressionEvaluated(plus);
}
/**
* Evaluates an postcondition.
*
* @param postcondition
* the Postcondition to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Postcondition)
*/
public void visit(final Postcondition postcondition) {
this.visitAnnotation(postcondition);
}
/**
* Evaluates an precondition.
*
* @param precondition
* the Precondition to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Precondition)
*/
public void visit(final Precondition precondition) {
this.visitAnnotation(precondition);
}
/**
* Executes a program.
*
* @param program
* the Program to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Program)
*/
public void visit(final Program program) {
this.executionStarted();
for (Axiom axiom : program.getAxioms()) {
axiom.accept(this);
}
program.getMainBlock().accept(this);
this.executionCompleted();
}
/**
* Evaluates a quantified expression and pushes the result onto the resultStack.
*
* @param quantifiedExpression
* the QuantifiedExpression to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.QuantifiedExpression)
*/
public void visit(final QuantifiedExpression quantifiedExpression) {
if (this.specificationChecker == null) {
throw new IllegalArgumentException("No SpecificationChecker supplied");
}
Validity validity = this.specificationChecker.checkFormula(quantifiedExpression, this.getAllSymbols());
if (validity.equals(Validity.UNKNOWN)) {
annotationFailed(this.currentAnnotation);
this.resultStack.push(new BooleanValue(false));
return;
} else {
this.resultStack.push(new BooleanValue(validity.equals(Validity.VALID)));
this.expressionEvaluated(quantifiedExpression);
}
}
/**
* Pushes the return-value onto the resultStack and terminate the execution of this function.
*
* @param returnStatement
* the ReturnStatement to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.ReturnStatement)
*/
public void visit(final ReturnStatement returnStatement) {
this.statementWillExecute(returnStatement);
try {
returnStatement.getReturnValue().accept(this);
// Put a new symbol named "_return" on the symbol stack to be used by the prover.
VariableDeclaration variableDeclaration = AstFactory.eINSTANCE.createVariableDeclaration();
variableDeclaration.setName("_return");
variableDeclaration.setType(new ASTNodeBottomUpVisitor<Type>() {
@Override
public final void visit(final FunctionDeclaration node) {
this.setReturnValue(node.getReturnType());
}
}.apply(returnStatement));
Value returnValue = this.resultStack.peek();
this.setSymbol(variableDeclaration, returnValue);
this.functionReturned = true;
} catch (StatementException e) {
this.executionFailed(returnStatement, e.getError());
return;
}
this.statementExecuted(returnStatement);
}
/**
* subtracts the {@link IntegerValue} of the {@link expression} subtraction.right from the {@link IntegerValue}
* of the {@link expression} subtraction.left and pushes the result on the resultStack.
*
* @param subtraction
* the subtraction to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Subtraction)
*/
public void visit(final Subtraction subtraction) {
subtraction.getLeft().accept(this);
IntegerValue left = this.popIntegerValue();
subtraction.getRight().accept(this);
IntegerValue right = this.popIntegerValue();
this.resultStack.push(new IntegerValue(left.getValue().subtract(right.getValue())));
this.expressionEvaluated(subtraction);
}
/**
* checks if the {@link Value}s of the {@link expression}s unequal.left and unequal.right are unequal and pushes
* the result on the resultStack.
*
* @param unequal
* the Unequal to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.Unequal)
*/
public void visit(final Unequal unequal) {
unequal.getLeft().accept(this);
Value left = this.resultStack.pop();
unequal.getRight().accept(this);
Value right = this.resultStack.pop();
this.resultStack.push(new BooleanValue(!(left.equals(right))));
this.expressionEvaluated(unequal);
}
/**
* Adds a variable to the actual symbol map.
*
* @param variableDeclaration
* the variableDeclaration to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.VariableDeclaration)
*/
public void visit(final VariableDeclaration variableDeclaration) {
this.statementWillExecute(variableDeclaration);
try {
// just set the variable if the declaration includes a definition...
if (variableDeclaration.getInitialValue() != null) {
variableDeclaration.getInitialValue().accept(this);
this.setSymbol(variableDeclaration, this.resultStack.pop());
} else {
this.setSymbol(variableDeclaration,
this.getDefaultValueForType(variableDeclaration.getType()));
}
} catch (StatementException e) {
this.executionFailed(variableDeclaration, e.getError());
return;
}
this.statementExecuted(variableDeclaration);
}
/**
* Gets the default value for the given type.
*
* @param type
* The type to get the default value for.
* @return The default value for the given type.
*/
private Value getDefaultValueForType(final Type type) {
return (new ASTNodeReturnVisitor<Value>() {
@Override
public void visit(final ArrayType node) {
if (node.getBaseType() instanceof BooleanType) {
this.setReturnValue(new CompositeValue<BooleanValue>(new BooleanValue[0]));
} else if (node.getBaseType() instanceof IntegerType) {
this.setReturnValue(new CompositeValue<IntegerValue>(new IntegerValue[0]));
}
}
@Override
public void visit(final BooleanType node) {
this.setReturnValue(new BooleanValue(Boolean.FALSE));
}
@Override
public void visit(final IntegerType node) {
this.setReturnValue(new IntegerValue(BigInteger.ZERO));
}
}).apply(type);
}
/**
* Pushes the {@link Value} of the referenced variable or return {@link Value} of a function onto the
* resultStack.
*
* @param variableReference
* the VariableReference to visit
*
* @see edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor#visit(edu.kit.iti.formal.pse
* .worthwhile.model.ast.VariableReference)
*/
public void visit(final VariableReference variableReference) {
Value variableValue;
if (variableReference instanceof ReturnValueReference) {
variableValue = this.getReturnValue();
} else {
variableValue = this.getSymbol(variableReference.getVariable());
}
if (variableReference.getIndex() == null) {
this.resultStack.push(variableValue);
} else {
// Evaluate the index expression
variableReference.getIndex().accept(this);
BigInteger index = this.popIntegerValue().getValue();
// Get the appropriate value from the array, or get the default value
CompositeValue<?> completeArray = (CompositeValue<?>) variableValue;
Map<BigInteger, ?> arrayValues = completeArray.getSubValues();
if (arrayValues.containsKey(index)) {
this.resultStack.push((Value) arrayValues.get(index));
} else {
// FIXME
WorthwhileTypesystem ts = new WorthwhileTypesystem();
// push the default value onto the result stack
this.resultStack.push(this.getDefaultValueForType((Type) ts.typeof(variableReference)));
}
}
this.expressionEvaluated(variableReference);
}
}
|
package org.cagrid.tests.data.styles.cacore42.steps;
import gov.nih.nci.cagrid.testing.system.deployment.SecureContainer;
import java.io.File;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.globus.gsi.GlobusCredential;
public class ChangeCsmUserInDatabaseStep extends AbstractDatabaseStep {
private static Log LOG = LogFactory.getLog(ChangeCsmUserInDatabaseStep.class);
public static final String USER_PROXY_FILE = "user.proxy";
public static final String SDK_USER_ID = "/O=caBIG/OU=caGrid/OU=Training/OU=Dorian/CN=SDKUser1";
private SecureContainer serviceContainer = null;
public ChangeCsmUserInDatabaseStep(SecureContainer container) {
super();
this.serviceContainer = container;
}
public void runStep() throws Throwable {
String userId = getTestUserId();
StringBuffer update = new StringBuffer();
update.append("Update CSM_USER set LOGIN_NAME = '");
update.append(userId).append("' ");
update.append("where LOGIN_NAME = '");
update.append(SDK_USER_ID).append("';");
LOG.debug("Executing SQL: " + update.toString());
getDatabase().update(update.toString());
}
private String getTestUserId() {
String id = null;
try {
File proxyFile = new File(serviceContainer.getCertificatesDirectory(), USER_PROXY_FILE);
GlobusCredential cred = new GlobusCredential(proxyFile.getAbsolutePath());
id = cred.getIdentity();
LOG.debug("Test user identity determined to be " + id);
} catch (Exception ex) {
ex.printStackTrace();
fail("Error obtaining test user proxy: " + ex.getMessage());
}
return id;
}
}
|
package de.factoryfx.javafx.editor.attribute.visualisation;
import de.factoryfx.data.Data;
import de.factoryfx.javafx.editor.attribute.ListAttributeEditorVisualisation;
import de.factoryfx.javafx.editor.data.DataEditor;
import de.factoryfx.javafx.util.UniformDesign;
import de.factoryfx.javafx.widget.datalistedit.ReferenceListAttributeEditWidget;
import de.factoryfx.javafx.widget.table.TableControlWidget;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import java.util.List;
import java.util.function.Consumer;
public class ReferenceListAttributeVisualisation extends ListAttributeEditorVisualisation<Data> {
private final UniformDesign uniformDesign;
private final Consumer<Data> navigateToData;
private final ReferenceListAttributeEditWidget<Data> dataListEditWidget;
private final TableView<Data> tableView;
private DoubleBinding heightBinding;
public ReferenceListAttributeVisualisation(UniformDesign uniformDesign, Consumer<Data> navigateToData, TableView<Data> tableView, ReferenceListAttributeEditWidget<Data> dataListEditWidget) {
this.uniformDesign = uniformDesign;
this.navigateToData = navigateToData;
this.dataListEditWidget = dataListEditWidget;
this.tableView = tableView;
}
@Override
public Node createContent(ObservableList<Data> readOnlyList, Consumer<Consumer<List<Data>>> listModifyingAction, boolean readonly) {
tableView.setItems(readOnlyList);
tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
TableColumn<Data, String> test = new TableColumn<>("Data");
test.setCellValueFactory(param -> new SimpleStringProperty(param.getValue().internal().getDisplayText()));
tableView.getColumns().add(test);
tableView.getStyleClass().add("hidden-tableview-headers");
heightBinding = Bindings.createDoubleBinding(() ->
readOnlyList.size() < 4 ? 74d : 243d, readOnlyList);
tableView.prefHeightProperty().bind(heightBinding);
tableView.setOnMouseClicked(mouseEvent -> {
if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) {
if (mouseEvent.getClickCount() == 2 && tableView.getSelectionModel().getSelectedItem()!=null) {
navigateToData.accept(tableView.getSelectionModel().getSelectedItem());
}
}
});
TableControlWidget<Data> tableControlWidget = new TableControlWidget<>(tableView,uniformDesign);
Node tableControlWidgetContent = tableControlWidget.createContent();
HBox.setHgrow(tableControlWidgetContent, Priority.ALWAYS);
HBox.setMargin(tableControlWidgetContent, new Insets(0,1,0,0));
HBox buttons = (HBox)dataListEditWidget.createContent();
buttons.getChildren().add(tableControlWidgetContent);
VBox vbox = new VBox();
VBox.setVgrow(tableView,Priority.ALWAYS);
vbox.getChildren().add(tableView);
vbox.getChildren().add(buttons);
buttons.setDisable(readonly);
return vbox;
}
}
|
package alfredo.geom;
import alfredo.Rand;
/**
*
* @author TheMonsterOfTheDeep
*/
public class Vector {
public float x;
public float y;
private boolean cached = false;
private float magnitude;
private float direction;
public static Vector random(float sx, float sy, float ex, float ey) {
return new Vector(Rand.f(sx, ex), Rand.f(sy, ey));
}
public static Vector random(Vector start, Vector end) {
return random(start.x, start.y, end.x, end.y);
}
public static Vector fromDirection(float length, float direction) {
return new Vector(length * (float)Math.cos(Math.toRadians(direction)), length * (float)Math.sin(Math.toRadians(direction)));
}
private void checkCache() {
if(!cached) {
magnitude = (float)Math.sqrt(x * x + y * y);
direction = (float)Math.toDegrees(Math.atan2(y, x));
cached = true;
}
}
public Vector() {
x = y = 0;
}
public Vector(float dupli) {
x = y = dupli;
}
public Vector(float x, float y) {
this.x = x;
this.y = y;
}
public Vector(Vector orig) {
this.x = orig.x;
this.y = orig.y;
}
public Vector copy() {
return new Vector(this);
}
public void set(float x, float y) {
this.x = x;
this.y = y;
cached = false;
}
public void set(Vector dupli) {
x = dupli.x;
y = dupli.y;
cached = false;
}
public void zero() {
set(0, 0);
}
public void setX(float x) { this.x = x; cached = false; }
public void setY(float y) { this.y = y; cached = false; }
public void setX(Vector dupli) { this.x = dupli.x; cached = false; }
public void setY(Vector dupli) { this.y = dupli.y; cached = false; }
public void add(float x, float y) {
this.x += x;
this.y += y;
cached = false;
}
public void add(Vector dupli) {
this.x += dupli.x;
this.y += dupli.y;
cached = false;
}
public void addX(float x) { this.x += x; cached = false; }
public void addY(float y) { this.y += y; cached = false; }
public void addX(Vector dupli) { this.x += dupli.x; cached = false; }
public void addY(Vector dupli) { this.y += dupli.y; cached = false; }
public void subtract(float x, float y) {
this.x -= x;
this.y -= y;
cached = false;
}
public void subtract(Vector dupli) {
this.x -= dupli.x;
this.y -= dupli.y;
cached = false;
}
public void subtractX(float x) { this.x -= x; cached = false; }
public void subtractY(float y) { this.y -= y; cached = false; }
public void subtractX(Vector dupli) { this.x -= dupli.x; cached = false; }
public void subtractY(Vector dupli) { this.y -= dupli.y; cached = false; }
public Vector plus(Vector v) {
return new Vector(this.x + v.x, this.y + v.y);
}
public Vector minus(Vector v) {
return new Vector(this.x - v.x, this.y - v.y);
}
public Vector times(float scalar) {
return new Vector(this.x * scalar, this.y * scalar);
}
public void scale(float scalar) {
this.x *= scalar;
this.y *= scalar;
cached = false;
}
public void rotate(float px, float py, double theta) {
float dx = x - px;
float dy = y - py;
theta = Math.toRadians(theta);
double cos = Math.cos(theta);
double sin = Math.sin(theta);
x = (float)(px + (dx * cos) + (dy * sin));
y = (float)(py - (dx * sin) + (dy * cos));
cached = false;
}
public void move(float distance, double direction) {
x += distance * Math.cos(Math.toRadians(direction));
y += distance * Math.sin(Math.toRadians(direction));
}
public float getMagnitude() {
checkCache();
return magnitude;
}
public float getDirection() {
checkCache();
return direction;
}
public float distance(Vector other) {
return (float) Math.sqrt( (other.x - x) * (other.x - x) + (other.y - y) * (other.y - y) );
}
@Override
public String toString() {
//Only show two decimals worth of precision - I feel like this will be more useful for debugging
float xd = Math.abs(x);
float yd = Math.abs(y);
int xi = (int)Math.floor(xd);
int xf = Math.round(xd * 100) - 100 * xi;
int yi = (int)Math.floor(yd);
int yf = Math.round(yd * 100) - 100 * yi;
if(x < 0) { xi = -xi; }
if(y < 0) { yi = -yi; }
return "Vector(" + xi + "." + xf + ", " + yi + "." + yf + ")";
}
}
|
package com.github.davidcarboni.restolino;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import org.apache.commons.lang3.StringUtils;
/**
* Determines the correct configuration, based on environment variables, system
* properties and checking the classloader hierarchy for a classes URL.
*
* @author david
*
*/
public class Configuration {
public static final String PORT = "PORT";
public static final String CLASSES = "restolino.classes";
public static final String FILES = "restolino.files";
public static final String FILES_RESOURCE = "files";
/** The Jetty server port. */
public int port = 8080;
/** If files will be dynamically reloaded, true. */
public boolean filesReloadable;
/**
* If files will be dynamically reloaded, the URL from which they will be
* loaded. If not reloading, this will typically be URL that points to a
* <code>files/...</code> resource directory in your JAR.
*/
public URL filesUrl;
/** If classes will be dynamically reloaded, true. */
public boolean classesReloadable;
/**
* If a <code>.../classes</code> entry is present on the classpath, that URL
* from the classloader hierarchy. This is designed to prevent uncertainty
* and frustration if you have correctly configured class reloading, but
* have also accidentally includedd your classes on the classpath. This
* would leand to code not being reloaded and possibly even confusing error
* messages because the classes on the classpath will take precedence
* (because class loaders delegate upwards).
*/
public URL classesInClasspath;
/**
* If classes will be dynamically reloaded, a file URL for the path which
* will be monitored for changes in order to trigger reloading.
*/
public URL classesUrl;
public Configuration() {
// The server port:
String port = getValue("PORT");
// The reloadable parameters:
String files = getValue(FILES);
String classes = getValue(CLASSES);
// Set up the configuration:
configurePort(port);
configureFiles(files);
configureClasses(classes);
}
/**
* Configures the server port by attempting to parse the given parameter,
* but failing gracefully if that doesn't work out.
*
* @param port
* The value of the {@value Port} parameter.
*/
void configurePort(String port) {
if (StringUtils.isNotBlank(port)) {
try {
this.port = Integer.parseInt(port);
} catch (NumberFormatException e) {
System.out.println("Unable to parse server PORT variable ("
+ port + ") using port " + port);
}
}
}
/**
* Sets up configuration for serving static files (if any).
*
* @param path
* The directory that contains static files.
*/
void configureFiles(String path) {
// If the property is set, reload from a local directory:
if (StringUtils.isNotBlank(path)) {
configureFilesReloadable(path);
} else {
configureFilesResource();
}
filesReloadable = filesUrl != null;
// Communicate:
showFilesConfiguration();
}
/**
* Sets up configuration for reloading classes.
*
* @param path
* The directory that contains compiled classes. This will be
* monitored for changes.
*/
void configureClasses(String path) {
findClassesInClasspath();
if (StringUtils.isNotBlank(path)) {
// If the path is set, set up class reloading:
configureClassesReloadable(path);
}
classesReloadable = classesUrl != null && classesInClasspath == null;
// Communicate:
showClassesConfiguration();
}
/**
* Configures static file serving from a directory. This will be reloadable,
* so is most useful for development (rather than deployment). This
* typically serves files from the <code>src/main/resources/files/...</code>
* directory of your development project.
* <p>
* NB This provides an efficient development workflow, allowing you to see
* static file changes without having to rebuild.
*/
void configureFilesReloadable(String path) {
try {
// Running with reloading:
Path filesPath = FileSystems.getDefault().getPath(path);
filesUrl = filesPath.toUri().toURL();
} catch (IOException e) {
throw new RuntimeException("Error determining files path/url for: "
+ path, e);
}
}
/**
* Configures static file serving from the classpath. This will not be
* reloadable, so is most useful for deployment (rather than development).
* This typically serves files from the <code>files/...</code> directory at
* the root of a <code>*-jar-with-dependencies.jar</code> artifact.
* <p>
* NB Part of the intent here is to support a compact and simple deployment
* model (single JAR) that discourages changes in the target environment
* (because the JAR is not unpacked) and favours automated deployment of a
* new version (or rollback to a previous version) as the way to make
* changes.
*/
void configureFilesResource() {
// Check for a resource on the classpath (production):
ClassLoader classLoader = Configuration.class.getClassLoader();
filesUrl = classLoader.getResource(FILES_RESOURCE);
}
/**
* Scans the {@link ClassLoader} hierarchy to check if there is a
* <code>.../classes</code> entry present. This is designed to prevent
* uncertainty and frustration if you have correctly configured class
* reloading, but have also accidentally included your classes on the
* classpath. This would lead to code not being reloaded and possibly even
* confusing error messages because the classes on the classpath will take
* precedence over reloaded classes (because class loaders normally delegate
* upwards).
*/
void findClassesInClasspath() {
ClassLoader classLoader = Configuration.class.getClassLoader();
do {
if (URLClassLoader.class.isAssignableFrom(classLoader.getClass())) {
URLClassLoader urlClassLoader = (URLClassLoader) classLoader;
findClassesInClassloader(urlClassLoader);
if (classesInClasspath != null)
break;
}
// Check the parent:
classLoader = classLoader.getParent();
} while (classLoader != null);
}
/**
* Scans the {@link ClassLoader} hierarchy to check if there is a
* <code>.../classes</code> entry present. This is designed to prevent
* uncertainty and frustration if you have correctly configured class
* reloading, but have also accidentally included your classes on the
* classpath. This would lead to code not being reloaded and possibly even
* confusing error messages because the classes on the classpath will take
* precedence over reloaded classes (because class loaders normally delegate
* upwards).
*/
void findClassesInClassloader(URLClassLoader urlClassLoader) {
// Check for a "classes" URL:
for (URL url : urlClassLoader.getURLs()) {
String urlPath = StringUtils.lowerCase(url.getPath());
if (StringUtils.endsWithAny(urlPath, "/classes", "/classes/"))
classesInClasspath = url;
}
}
/**
* Configures dynamic class reloading. This is most useful for development
* (rather than deployment). This typically reloads classes from the
* <code>target/classes/...</code> directory of your development project.
* <p>
* NB This provides an efficient development workflow, allowing you to see
* code changes without having to redeploy. It also supports stateless
* webapp design because the entire classes classloader is replaced every
* time there is a change (so you'll lose stuff like static variable
* values).
*/
void configureClassesReloadable(String path) {
try {
// Set up reloading:
Path classesPath = FileSystems.getDefault().getPath(path);
classesUrl = classesPath.toUri().toURL();
} catch (IOException e) {
throw new RuntimeException("Error starting class reloader", e);
}
}
/**
* Prints out a message confirming the static file serving configuration.
*/
void showFilesConfiguration() {
// Message to communicate the resolved configuration:
String message;
if (filesUrl != null) {
String reload = filesReloadable ? "reloadable" : "non-reloadable";
message = "Files will be served from: " + filesUrl + " (" + reload
+ ")";
} else {
message = "No static files will be served.";
}
System.out.println("Files reloading: " + message);
}
/**
* Prints out a message confirming the class reloading configuration.
*/
void showClassesConfiguration() {
// Warning about a classes folder present in the classpath:
if (classesInClasspath != null) {
System.out
.println("WARNING: Dynamic class reloading is disabled because a classes URL is present in the classpath. P"
+ "lease launch without including your classes directory: "
+ classesInClasspath);
}
// Message to communicate the resolved configuration:
String message;
if (classesReloadable) {
message = "Classes will be reloaded from: " + classesUrl;
} else {
message = "Classes will not be dynamically reloaded.";
}
System.out.println("Files reloading: " + message);
}
/**
* Gets a configured value for the given key from either the system
* properties or an environment variable.
*
* @param key
* The name of the configuration value.
* @return The system property corresponding to the given key (e.g.
* -Dkey=value). If that is blank, the environment variable
* corresponding to the given key (e.g. EXPORT key=value). If that
* is blank, {@link StringUtils#EMPTY}.
*/
static String getValue(String key) {
String result = StringUtils.defaultIfBlank(System.getProperty(key),
StringUtils.EMPTY);
result = StringUtils.defaultIfBlank(result, System.getenv(key));
return result;
}
}
|
package org.lttng.scope.lttng.kernel.core.analysis.os.statesystem;
import ca.polymtl.dorsal.libdelorean.statevalue.ITmfStateValue;
import ca.polymtl.dorsal.libdelorean.statevalue.TmfStateValue;
/**
* Expected return values of querying test trace #1's state system at time
* "18670067372290L + 1331649577946812237L".
*
* This file is can be generated using the {@link GenerateTestValues} script.
*
* @author Alexandre Montplaisir
*/
interface TestValues {
int size = 922;
long[] startTimes = {
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247399757985L,
1331668247316334243L,
1331668247399757985L,
1331668247316320929L,
1331668247316334243L,
1331668247314046266L,
1331668247314046266L,
1331668247399148733L,
1331668247316120937L,
1331668248014183954L,
1331668248014145796L,
1331668247314851888L,
1331668247327098502L,
1331668247327098502L,
1331668247327098502L,
1331668247314851888L,
1331668247327098502L,
1331668247399704235L,
1331668247415001807L,
1331668247399704235L,
1331668247415001807L,
1331668247415001807L,
1331668248014145796L,
1331668247314038062L,
1331668247314601653L,
1331668247314601653L,
1331668247314601653L,
1331668248013353414L,
1331668247314607227L,
1331668247314607227L,
1331668247314607227L,
1331668248014130616L,
1331668248014184526L,
1331668247314038062L,
1331668248011090056L,
1331668247931793142L,
1331668247931793142L,
1331668247930941981L,
1331668247314038062L,
1331668247314038062L,
1331668248011125682L,
1331668247959024716L,
1331668248011129576L,
1331668247314038062L,
1331668247315471788L,
1331668247335106720L,
1331668247335106720L,
1331668247335106720L,
1331668247315471788L,
1331668247335106720L,
1331668247931782426L,
1331668247315274351L,
1331668247316120937L,
1331668247335112802L,
1331668247335112802L,
1331668247335112802L,
1331668247316120937L,
1331668247335112802L,
1331668248004705322L,
1331668248004935409L,
1331668248004935409L,
1331668248004770916L,
1331668248004925240L,
1331668247316553071L,
1331668247399743968L,
1331668247314038062L,
1331668247999256178L,
1331668247999256178L,
1331668247999239403L,
1331668247999250697L,
1331668247318567561L,
1331668247999336085L,
1331668247999336085L,
1331668247999131058L,
1331668247999327778L,
1331668247318631139L,
1331668247959041965L,
1331668247960265258L,
1331668247903884233L,
1331668247903884233L,
1331668247902254797L,
1331668247903869067L,
1331668247328403934L,
1331668247908495390L,
1331668247908495390L,
1331668247908391792L,
1331668247908464125L,
1331668247328921944L,
1331668247903840082L,
1331668247903840082L,
1331668247902986051L,
1331668247903831313L,
1331668247329404733L,
1331668247960291263L,
1331668247960291263L,
1331668247960272741L,
1331668247314038062L,
1331668247330548245L,
1331668247919182446L,
1331668247340039213L,
1331668247340083580L,
1331668247966976915L,
1331668248004729173L,
1331668248004729173L,
1331668248004720009L,
1331668247314038062L,
1331668247371137735L,
1331668247387196023L,
1331668247387196023L,
1331668247387154824L,
1331668247387191465L,
1331668247376420842L,
1331668247400231496L,
1331668247400231496L,
1331668247400130260L,
1331668247400218303L,
1331668247378430187L,
1331668247751186217L,
1331668247751186217L,
1331668247751173305L,
1331668247314038062L,
1331668247387136191L,
1331668247400779449L,
1331668247400779449L,
1331668247415047817L,
1331668247415047817L,
1331668247415047817L,
1331668247400095883L,
1331668247400095883L,
1331668247399991225L,
1331668247400085049L,
1331668247399991225L,
1331668247401441000L,
1331668247401441000L,
1331668247401341331L,
1331668247401428073L,
1331668247400779449L,
1331668247410754305L,
1331668247410754305L,
1331668247410594291L,
1331668247519727372L,
1331668247519727372L,
1331668247519619353L,
1331668247412887695L,
1331668247412887695L,
1331668247412803787L,
1331668247413704524L,
1331668247413704524L,
1331668247413576917L,
1331668247412877246L,
1331668247410583861L,
1331668247410735104L,
1331668247410594291L,
1331668247413682702L,
1331668247410844189L,
1331668247519712481L,
1331668247411099759L,
1331668247924029486L,
1331668247924029486L,
1331668247923412966L,
1331668247924012402L,
1331668247412302666L,
1331668247924105876L,
1331668247924105876L,
1331668247924010016L,
1331668247924098044L,
1331668247417574343L,
1331668248014184526L,
1331668248014184526L,
1331668248013799545L,
1331668248014130616L,
1331668247417635948L,
1331668247928627023L,
1331668247928627023L,
1331668247928556625L,
1331668247928621067L,
1331668247417978805L,
1331668247928556625L,
1331668247928556625L,
1331668247927469138L,
1331668247928529840L,
1331668247418470511L,
1331668247930341625L,
1331668247930341625L,
1331668247928614605L,
1331668248014184526L,
1331668248014089924L,
1331668248014184526L,
1331668248013793850L,
1331668247419578477L,
1331668247930328175L,
1331668247419655652L,
1331668248013753736L,
1331668248013331679L,
1331668248013353414L,
1331668248013749389L,
1331668247420382626L,
1331668247930579872L,
1331668247930579872L,
1331668247930316322L,
1331668247930574368L,
1331668247420451876L,
1331668247926378321L,
1331668247926378321L,
1331668247925622863L,
1331668247926367737L,
1331668247423543945L,
1331668247619316825L,
1331668247619491008L,
1331668247619505885L,
1331668247619505885L,
1331668247619392829L,
1331668247619495072L,
1331668247434248026L,
1331668247434551326L,
1331668247434551326L,
1331668247434365352L,
1331668247434546203L,
1331668247434365352L,
1331668247908325947L,
1331668247908325947L,
1331668247908264450L,
1331668247908319810L,
1331668247467380509L,
1331668247908677700L,
1331668247908677700L,
1331668247908325947L,
1331668247908640244L,
1331668247467447781L,
1331668247869556425L,
1331668247869556425L,
1331668247869483379L,
1331668247869544380L,
1331668247503177108L,
1331668247504321893L,
1331668247504321893L,
1331668247504294050L,
1331668247504319470L,
1331668247503423094L,
1331668248014183954L,
1331668248014135819L,
1331668248014145796L,
1331668248014183954L,
1331668247512172527L,
1331668247539381562L,
1331668247539381562L,
1331668247539325848L,
1331668247539369787L,
1331668247539325848L,
1331668247735177820L,
1331668247735177820L,
1331668247735128110L,
1331668247735170303L,
1331668247735128110L,
1331668247735168206L,
1331668247735168206L,
1331668247735152717L,
1331668247735161964L,
1331668247735152717L,
1331668247775218227L,
1331668247775218227L,
1331668247775191569L,
1331668247775231079L,
1331668247775231079L,
1331668247775218227L,
1331668247775205377L,
1331668247775191569L,
1331668247775223776L,
1331668247775218227L,
1331668247869483379L,
1331668247869483379L,
1331668247869457807L,
1331668247869477795L,
1331668247869457807L,
1331668247941667986L,
1331668247941667986L,
1331668247941620894L,
1331668247941650415L,
1331668247941620894L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247966976915L,
1331668247340039213L,
1331668247960265258L,
1331668247619316825L,
1331668247314038062L,
1331668248004705322L,
1331668248011125682L,
1331668247619491008L,
1331668247340083580L,
1331668248011129576L,
1331668247959041965L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
1331668247314038062L,
};
long[] endTimes = {
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054130388L,
1331668259054285979L,
1331668259054130388L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054130388L,
1331668259054285979L,
1331668248014185078L,
1331668248014620024L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668248014620024L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668248015333196L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668248014188534L,
1331668248014548923L,
1331668259054285979L,
1331668248015040151L,
1331668248482978166L,
1331668248482978166L,
1331668248482983146L,
1331668259054285979L,
1331668259054285979L,
1331668248015170799L,
1331668248015172434L,
1331668248015176320L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668248483009726L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668248015959980L,
1331668248016172023L,
1331668248016172023L,
1331668248016172023L,
1331668248016194935L,
1331668259054285979L,
1331668259054136697L,
1331668259054285979L,
1331668248016556933L,
1331668248016556933L,
1331668248016556933L,
1331668248016592456L,
1331668252511012367L,
1331668248016623209L,
1331668248016623209L,
1331668248016623209L,
1331668248016645047L,
1331668252843104826L,
1331668248015041609L,
1331668248486545657L,
1331668248502954816L,
1331668248502954816L,
1331668248502954816L,
1331668248503000162L,
1331668259054285979L,
1331668248020359475L,
1331668248020359475L,
1331668248020364249L,
1331668248020419523L,
1331668259054285979L,
1331668248020866943L,
1331668248020866943L,
1331668248020866943L,
1331668248020888352L,
1331668259054285979L,
1331668248531200073L,
1331668248531200073L,
1331668248531200073L,
1331668259054285979L,
1331668259054285979L,
1331668248019005964L,
1331668257323835062L,
1331668257323879563L,
1331668248021867385L,
1331668248175307354L,
1331668248175307354L,
1331668248175307354L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259051873438L,
1331668259051873438L,
1331668259051873438L,
1331668259051879701L,
1331668259054285979L,
1331668248751061201L,
1331668248751061201L,
1331668248751061201L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259054285979L,
1331668259051834588L,
1331668259051834588L,
1331668259051838247L,
1331668259051846351L,
1331668259054285979L,
1331668257325265220L,
1331668257325265220L,
1331668257325265220L,
1331668257325277639L,
1331668259054285979L,
1331668250005939534L,
1331668250005939534L,
1331668250005943125L,
1331668248014565260L,
1331668248014565260L,
1331668248014565260L,
1331668250006219013L,
1331668250006219013L,
1331668250006219013L,
1331668250004649129L,
1331668250004649129L,
1331668250004649129L,
1331668250006228246L,
1331668259054285979L,
1331668250005962644L,
1331668259054285979L,
1331668250004668081L,
1331668259054285979L,
1331668248014624125L,
1331668259054285979L,
1331668248414826115L,
1331668248414826115L,
1331668248414826115L,
1331668248414875444L,
1331668259054285979L,
1331668248420327828L,
1331668248420327828L,
1331668248420327828L,
1331668248420342919L,
1331668259054285979L,
1331668248015347726L,
1331668248015347726L,
1331668248015353903L,
1331668248015428919L,
1331668259054285979L,
1331668248420613401L,
1331668248420613401L,
1331668248420617453L,
1331668248420709272L,
1331668259054285979L,
1331668248421112139L,
1331668248421112139L,
1331668248421112139L,
1331668248421137268L,
1331668259054285979L,
1331668248421291701L,
1331668248421291701L,
1331668248421291701L,
1331668248014188534L,
1331668248014548923L,
1331668248015518081L,
1331668248014188534L,
1331668259054285979L,
1331668248421940554L,
1331668259054285979L,
1331668248014548923L,
1331668248014614755L,
1331668248016397030L,
1331668248014550770L,
1331668259054285979L,
1331668248422509298L,
1331668248422509298L,
1331668248422509298L,
1331668248422523601L,
1331668259054285979L,
1331668248424325503L,
1331668248424325503L,
1331668248424325503L,
1331668248424394073L,
1331668259054285979L,
1331668248140683324L,
1331668248140686546L,
1331668248140727269L,
1331668248140727269L,
1331668248140727269L,
1331668248140780012L,
1331668259054285979L,
1331668251031789570L,
1331668251031789570L,
1331668251031789570L,
1331668251031812282L,
1331668252047037657L,
1331668248269586770L,
1331668248269586770L,
1331668248269586770L,
1331668248269613258L,
1331668259054285979L,
1331668248141167328L,
1331668248141167328L,
1331668248141167328L,
1331668248141400164L,
1331668259054285979L,
1331668248141004006L,
1331668248141004006L,
1331668248141004006L,
1331668248141028631L,
1331668259054285979L,
1331668248141324868L,
1331668248141324868L,
1331668248141324868L,
1331668248141345677L,
1331668259054285979L,
1331668248014185078L,
1331668248014620024L,
1331668248015165243L,
1331668248014185078L,
1331668259054285979L,
1331668248539549580L,
1331668248539549580L,
1331668248539549580L,
1331668248539579511L,
1331668259054285979L,
1331668255234884605L,
1331668255234884605L,
1331668255234884605L,
1331668255234905622L,
1331668259054285979L,
1331668255234936617L,
1331668255234936617L,
1331668255234936617L,
1331668255234941684L,
1331668259054285979L,
1331668252778982101L,
1331668252778982101L,
1331668252778982101L,
1331668252779007563L,
1331668252779007563L,
1331668252779007563L,
1331668252781320133L,
1331668259054285979L,
1331668252781341690L,
1331668259054285979L,
1331668248869653287L,
1331668248869653287L,
1331668248869653287L,
1331668248869679933L,
1331668259054285979L,
1331668248941858743L,
1331668248941858743L,
1331668248941858743L,
1331668248941885421L,
1331668252782929207L,
1331668248207116451L,
1331668248207116451L,
1331668248207116451L,
1331668248207177650L,
1331668248207163589L,
1331668248207165629L,
1331668248207165629L,
1331668248207165629L,
1331668248207212201L,
1331668248207197204L,
1331668248763171129L,
1331668248763171129L,
1331668248763171129L,
1331668259054285979L,
1331668248763179780L,
1331668248895005379L,
1331668248895005379L,
1331668248895005379L,
1331668248895062414L,
1331668248895035146L,
1331668249000328909L,
1331668249000328909L,
1331668249000328909L,
1331668249000373092L,
1331668249000350716L,
1331668249548101920L,
1331668249947171998L,
1331668249947171998L,
1331668249947171998L,
1331668249947269897L,
1331668249947249018L,
1331668249951033184L,
1331668249951033184L,
1331668249951033184L,
1331668249951077605L,
1331668249951058138L,
1331668249959079406L,
1331668249959079406L,
1331668249959079406L,
1331668259054285979L,
1331668249959100633L,
1331668249970937981L,
1331668249970937981L,
1331668249970937981L,
1331668259054285979L,
1331668249970963407L,
1331668250007423753L,
1331668250007423753L,
1331668250007423753L,
1331668250007449251L,
1331668250007428034L,
1331668250231124169L,
1331668250231124169L,
1331668250231124169L,
1331668250231169946L,
1331668250231148973L,
1331668250326525622L,
1331668250326525622L,
1331668250326525622L,
1331668250329519305L,
1331668250329507458L,
1331668251063191270L,
1331668251063191270L,
1331668251063191270L,
1331668251063256143L,
1331668251063222335L,
1331668251065026369L,
1331668251065026369L,
1331668251065026369L,
1331668251065048462L,
1331668251065030498L,
1331668251065058051L,
1331668251065058051L,
1331668251065058051L,
1331668251065091761L,
1331668251065069765L,
1331668251065364590L,
1331668251065364590L,
1331668251065364590L,
1331668251065412381L,
1331668251065407607L,
1331668251065462500L,
1331668251065462500L,
1331668251065462500L,
1331668251065477027L,
1331668251065465604L,
1331668251065780572L,
1331668251065780572L,
1331668251065780572L,
1331668251065836719L,
1331668251065829440L,
1331668251065899750L,
1331668251065899750L,
1331668251065899750L,
1331668251065913891L,
1331668251065902892L,
1331668251066057402L,
1331668251066057402L,
1331668251066057402L,
1331668251066070617L,
1331668251066060363L,
1331668251066495616L,
1331668251066495616L,
1331668251066495616L,
1331668251066520321L,
1331668251066506338L,
1331668251066532840L,
1331668251066532840L,
1331668251066532840L,
1331668251066546436L,
1331668251066535866L,
1331668251066658006L,
1331668251066658006L,
1331668251066658006L,
1331668251066671812L,
1331668251066660635L,
1331668251066883302L,
1331668251066883302L,
1331668251066883302L,
1331668251066906446L,
1331668251066887423L,
1331668251067153808L,
1331668251067153808L,
1331668251067153808L,
1331668251067176405L,
1331668251067157534L,
1331668251067407214L,
1331668251067407214L,
1331668251067407214L,
1331668251067420770L,
1331668251067410220L,
1331668251067763731L,
1331668251067763731L,
1331668251067763731L,
1331668251067818612L,
1331668251067811009L,
1331668251067884367L,
1331668251067884367L,
1331668251067884367L,
1331668251067897382L,
1331668251067887136L,
1331668251068275691L,
1331668251068275691L,
1331668251068275691L,
1331668251068288692L,
1331668251068278423L,
1331668251068706355L,
1331668251068706355L,
1331668251068706355L,
1331668251068719015L,
1331668251068709290L,
1331668251069067645L,
1331668251069067645L,
1331668251069067645L,
1331668251069122518L,
1331668251069116275L,
1331668251069178617L,
1331668251069178617L,
1331668251069178617L,
1331668251069191305L,
1331668251069181300L,
1331668251069664884L,
1331668251069664884L,
1331668251069664884L,
1331668251069684555L,
1331668251069668097L,
1331668251069682852L,
1331668251069682852L,
1331668251069682852L,
1331668251069708201L,
1331668251069690226L,
1331668251715054925L,
1331668251715054925L,
1331668251715054925L,
1331668259054285979L,
1331668251715066022L,
1331668251803784493L,
1331668251803784493L,
1331668251803784493L,
1331668251803827591L,
1331668251803808547L,
1331668251983438636L,
1331668251983438636L,
1331668251983438636L,
1331668251983448709L,
1331668251983441583L,
1331668251992993580L,
1331668251992993580L,
1331668251992993580L,
1331668251993008591L,
1331668251992998928L,
1331668252022091542L,
1331668252022091542L,
1331668252022091542L,
1331668252022091542L,
1331668252022093473L,
1331668252022095079L,
1331668252031771660L,
1331668252031771660L,
1331668252031771660L,
1331668252031777595L,
1331668252031773847L,
1331668252032463013L,
1331668252032463013L,
1331668252032463013L,
1331668252032502964L,
1331668252032497700L,
1331668252032506884L,
1331668252032506884L,
1331668252032506884L,
1331668252032559227L,
1331668252032539402L,
1331668252039535067L,
1331668252039535067L,
1331668252039535067L,
1331668259054285979L,
1331668252039537404L,
1331668252044008981L,
1331668252044008981L,
1331668252044008981L,
1331668252044014257L,
1331668252044010861L,
1331668252044059151L,
1331668252044059151L,
1331668252044059151L,
1331668252044064004L,
1331668252044060420L,
1331668252179391423L,
1331668252179391423L,
1331668252179391423L,
1331668252184781913L,
1331668252184772369L,
1331668252193422093L,
1331668252193422093L,
1331668252193425490L,
1331668252193432385L,
1331668252193427706L,
1331668252253575716L,
1331668252253575716L,
1331668252253575716L,
1331668252253592491L,
1331668252253581852L,
1331668252472449352L,
1331668252472449352L,
1331668252472449352L,
1331668252472474547L,
1331668252472458163L,
1331668252487295286L,
1331668252487295286L,
1331668252487295286L,
1331668252487300925L,
1331668252487297683L,
1331668252495759849L,
1331668252495759849L,
1331668252495759849L,
1331668252495766026L,
1331668252495762178L,
1331668252496219924L,
1331668252496219924L,
1331668252496219924L,
1331668252496245837L,
1331668252496228816L,
1331668252523291829L,
1331668252523291829L,
1331668252523291829L,
1331668252523482082L,
1331668252523469395L,
1331668252764810964L,
1331668252764810964L,
1331668252764810964L,
1331668252764829827L,
1331668252764814570L,
1331668252765021775L,
1331668252765021775L,
1331668252765021775L,
1331668252765026623L,
1331668252765023841L,
1331668252769399706L,
1331668252769399706L,
1331668252769399706L,
1331668252769401404L,
1331668252769401404L,
1331668252769401404L,
1331668259054285979L,
1331668252769446847L,
1331668259054285979L,
1331668252769456141L,
1331668252784988923L,
1331668252784988923L,
1331668252784988923L,
1331668259054285979L,
1331668252785262589L,
1331668252795062126L,
1331668252795062126L,
1331668252795062126L,
1331668259054285979L,
1331668252795122600L,
1331668252828832090L,
1331668252828832090L,
1331668252828832090L,
1331668252828859292L,
1331668252828859292L,
1331668252828859292L,
1331668252828904216L,
1331668252828866041L,
1331668252829060434L,
1331668252828992804L,
1331668252829505108L,
1331668252829505108L,
1331668252829505108L,
1331668252829527974L,
1331668252829527974L,
1331668252829527974L,
1331668252829719292L,
1331668252829638887L,
1331668252829643060L,
1331668252829643060L,
1331668252829643060L,
1331668252829660274L,
1331668252829660274L,
1331668252829660274L,
1331668252829679280L,
1331668252829679280L,
1331668252829683896L,
1331668252829799248L,
1331668252829799248L,
1331668252829799248L,
1331668252829802278L,
1331668252829802278L,
1331668252829802278L,
1331668252829821642L,
1331668252829821642L,
1331668252829821642L,
1331668252829837120L,
1331668252829837120L,
1331668252829840961L,
1331668252829859256L,
1331668252829859256L,
1331668252829859256L,
1331668252829976501L,
1331668252829976501L,
1331668252829976501L,
1331668252830107659L,
1331668252830085595L,
1331668252830154848L,
1331668252830139534L,
1331668252830212497L,
1331668252830194969L,
1331668252830382459L,
1331668252830368625L,
1331668252830526491L,
1331668252830499169L,
1331668252830576634L,
1331668252830564658L,
1331668252831112505L,
1331668252831083126L,
1331668252831228714L,
1331668252831228714L,
1331668252831228714L,
1331668252831318123L,
1331668252831301843L,
1331668252831543926L,
1331668252831527998L,
1331668252831834393L,
1331668252831817197L,
1331668252832056760L,
1331668252832046333L,
1331668252883172744L,
1331668252883172744L,
1331668252883172744L,
1331668252883172744L,
1331668252883175483L,
1331668252883178472L,
1331668252885827603L,
1331668252885827603L,
1331668252885827603L,
1331668252885827603L,
1331668252885830887L,
1331668252885834716L,
1331668252889337098L,
1331668252889337098L,
1331668252889337098L,
1331668252889396688L,
1331668252889396688L,
1331668252889396688L,
1331668252889396688L,
1331668252889398308L,
1331668252889399649L,
1331668252901232798L,
1331668252901118256L,
1331668252901540914L,
1331668252901540914L,
1331668252901540914L,
1331668252901540914L,
1331668252901543057L,
1331668252901545242L,
1331668252901570182L,
1331668252901570182L,
1331668252901573889L,
1331668252901586635L,
1331668252901577276L,
1331668252906764880L,
1331668252906764880L,
1331668252906764880L,
1331668252906764880L,
1331668252906767341L,
1331668252906769816L,
1331668252912042743L,
1331668252912042743L,
1331668252912042743L,
1331668259054285979L,
1331668252912048618L,
1331668252927449371L,
1331668252927449371L,
1331668252927449371L,
1331668252927449371L,
1331668252927451828L,
1331668252927454567L,
1331668252947156908L,
1331668252947156908L,
1331668252947156908L,
1331668252947156908L,
1331668252947159721L,
1331668252947162086L,
1331668252947197386L,
1331668252947197386L,
1331668252947197386L,
1331668252947197386L,
1331668252947198431L,
1331668252947200470L,
1331668253035499713L,
1331668253035499713L,
1331668253035499713L,
1331668253035499713L,
1331668253035502156L,
1331668253035505047L,
1331668253036766769L,
1331668253036766769L,
1331668253036766769L,
1331668253036766769L,
1331668253036768579L,
1331668253036770602L,
1331668253037890651L,
1331668253037890651L,
1331668253037890651L,
1331668253037890651L,
1331668253037892239L,
1331668253037894147L,
1331668253051945128L,
1331668253051945128L,
1331668253051945128L,
1331668253051945128L,
1331668253051946758L,
1331668253051948233L,
1331668253054627961L,
1331668253054627961L,
1331668253054627961L,
1331668253054627961L,
1331668253054629309L,
1331668253054630786L,
1331668253057609433L,
1331668253057609433L,
1331668253057609433L,
1331668253057609433L,
1331668253057610859L,
1331668253057612341L,
1331668253062222314L,
1331668253062222314L,
1331668253062222314L,
1331668253062222314L,
1331668253062224822L,
1331668253062227485L,
1331668253097239708L,
1331668253097239708L,
1331668253097239708L,
1331668253097239708L,
1331668253097243218L,
1331668253097246792L,
1331668253097518746L,
1331668253097518746L,
1331668253097518746L,
1331668253097518746L,
1331668253097520381L,
1331668253097521994L,
1331668253267104284L,
1331668253267104284L,
1331668253267104284L,
1331668253267117055L,
1331668253267107624L,
1331668253267342015L,
1331668253267342015L,
1331668253267342015L,
1331668253267378405L,
1331668253267367303L,
1331668253278218713L,
1331668253278218713L,
1331668253278218713L,
1331668253278218713L,
1331668253278220690L,
1331668253278223105L,
1331668253324119756L,
1331668253324119756L,
1331668253324119756L,
1331668253324119756L,
1331668253324121432L,
1331668253324123194L,
1331668253614347227L,
1331668253614347227L,
1331668253614347227L,
1331668253614347227L,
1331668253614349655L,
1331668253614351910L,
1331668253619459320L,
1331668253619459320L,
1331668253619459320L,
1331668253619459320L,
1331668253619461110L,
1331668253619462745L,
1331668253619867625L,
1331668253619867625L,
1331668253619867625L,
1331668253619867625L,
1331668253619868862L,
1331668253619870183L,
1331668253621486721L,
1331668253621486721L,
1331668253621486721L,
1331668253621508851L,
1331668253621491536L,
1331668253622429608L,
1331668253622429608L,
1331668253622429608L,
1331668253622429608L,
1331668253622431253L,
1331668253622432889L,
1331668253857465365L,
1331668253857465365L,
1331668253857465365L,
1331668253857465365L,
1331668253857467365L,
1331668253857469629L,
1331668253858125091L,
1331668253858125091L,
1331668253858125091L,
1331668253858125091L,
1331668253858126443L,
1331668253858128274L,
1331668253910194540L,
1331668253910194540L,
1331668253910194540L,
1331668253910194540L,
1331668253910196637L,
1331668253910198633L,
1331668253910329721L,
1331668253910329721L,
1331668253910329721L,
1331668253910329721L,
1331668253910331219L,
1331668253910333029L,
1331668253984922308L,
1331668253984922308L,
1331668253984922308L,
1331668253984922308L,
1331668253984924387L,
1331668253984926366L,
1331668254004098152L,
1331668254004098152L,
1331668254004098152L,
1331668254004098152L,
1331668254004100182L,
1331668254004102129L,
1331668254047839900L,
1331668254047839900L,
1331668254047839900L,
1331668254047839900L,
1331668254047841816L,
1331668254047843621L,
1331668254093066195L,
1331668254093066195L,
1331668254093066195L,
1331668254093066195L,
1331668254093068895L,
1331668254093071603L,
1331668254106326339L,
1331668254106326339L,
1331668254106326339L,
1331668254106326339L,
1331668254106328356L,
1331668254106330527L,
1331668255052411647L,
1331668255052411647L,
1331668255052411647L,
1331668255052411647L,
1331668255052414949L,
1331668255052417904L,
1331668255157088064L,
1331668255157088064L,
1331668255157088064L,
1331668255157101973L,
1331668255157091812L,
1331668256244508635L,
1331668256244508635L,
1331668256244508635L,
1331668256244508635L,
1331668256244510940L,
1331668256244513337L,
1331668257246987050L,
1331668257246987050L,
1331668257246987050L,
1331668257247036372L,
1331668257247027684L,
1331668248021867385L,
1331668257323835062L,
1331668248486545657L,
1331668248140683324L,
1331668249548101920L,
1331668248015959980L,
1331668248015040151L,
1331668248140686546L,
1331668257323879563L,
1331668248015176320L,
1331668248015041609L,
1331668259045096840L,
1331668259045096840L,
1331668259045096840L,
1331668259045096840L,
1331668259045100234L,
1331668259045103189L,
1331668259052126585L,
1331668259052126585L,
1331668259052126585L,
1331668259052126585L,
1331668259052128494L,
1331668259052129986L,
1331668259053345550L,
1331668259053345550L,
1331668259053345550L,
1331668259054285979L,
1331668259053349544L,
};
ITmfStateValue[] values = {
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(1),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.nullValue(),
TmfStateValue.newValueString("lttng-sessiond"),
TmfStateValue.newValueString("lttng-consumerd"),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueInt(2),
TmfStateValue.newValueInt(1397),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(5),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(0),
TmfStateValue.newValueString("swapper/0"),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueInt(5),
TmfStateValue.newValueInt(1),
TmfStateValue.newValueString("swapper/1"),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueInt(4),
TmfStateValue.newValueInt(1432),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("lttng-consumerd"),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(-6),
TmfStateValue.newValueString("sys_ppoll"),
TmfStateValue.newValueString("alsa-sink"),
TmfStateValue.newValueString("sys_epoll_wait"),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_futex"),
TmfStateValue.newValueString("firefox"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("firefox"),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("gnome-terminal"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_select"),
TmfStateValue.newValueString("Xorg"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("metacity"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.nullValue(),
TmfStateValue.newValueString("kworker/0:1"),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.nullValue(),
TmfStateValue.newValueString("ksoftirqd/0"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_read"),
TmfStateValue.newValueString("rsyslogd"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_futex"),
TmfStateValue.newValueString("rs:main Q:Reg"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.nullValue(),
TmfStateValue.newValueString("kworker/1:1"),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_select"),
TmfStateValue.newValueString("rsyslogd"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_read"),
TmfStateValue.newValueString("bash"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("bamfdaemon"),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("gnome-settings-"),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("unity-2d-shell"),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("unity-2d-panel"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("indicator-multi"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("gdbus"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("dbus-daemon"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("gdbus"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("indicator-appli"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueInt(3),
TmfStateValue.newValueInt(1),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("gdbus"),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("gdbus"),
TmfStateValue.newValueInt(5),
TmfStateValue.newValueInt(1),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_futex"),
TmfStateValue.newValueString("unity-panel-ser"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("hud-service"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("gdbus"),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("openvpn"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("firefox"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_futex"),
TmfStateValue.newValueString("thunderbird-bin"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("thunderbird-bin"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("thunderbird-bin"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_futex"),
TmfStateValue.newValueString("thunderbird-bin"),
TmfStateValue.newValueInt(2),
TmfStateValue.newValueInt(0),
TmfStateValue.newValueInt(20),
TmfStateValue.nullValue(),
TmfStateValue.newValueString("gdbus"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_nanosleep"),
TmfStateValue.newValueString("gvfs-afc-volume"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("rtkit-daemon"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(-100),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("rtkit-daemon"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("thunderbird-bin"),
TmfStateValue.newValueString("sys_poll"),
TmfStateValue.newValueString("thunderbird-bin"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_futex"),
TmfStateValue.newValueString("thunderbird-bin"),
TmfStateValue.newValueInt(1),
TmfStateValue.nullValue(),
TmfStateValue.newValueInt(20),
TmfStateValue.newValueString("sys_futex"),
TmfStateValue.newValueString("firefox"),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
TmfStateValue.nullValue(),
};
}
|
package org.phenotips.matchingnotification.internal;
import org.phenotips.data.Patient;
import org.phenotips.data.PatientRepository;
import org.phenotips.data.permissions.PermissionsManager;
import org.phenotips.data.permissions.Visibility;
import org.phenotips.data.similarity.PatientSimilarityView;
import org.phenotips.matchingnotification.MatchingNotificationManager;
import org.phenotips.matchingnotification.finder.MatchFinderManager;
import org.phenotips.matchingnotification.match.PatientMatch;
import org.phenotips.matchingnotification.match.internal.DefaultPatientMatch;
import org.phenotips.matchingnotification.notification.PatientMatchEmail;
import org.phenotips.matchingnotification.notification.PatientMatchNotificationResponse;
import org.phenotips.matchingnotification.notification.PatientMatchNotifier;
import org.phenotips.matchingnotification.storage.MatchStorageManager;
import org.xwiki.component.annotation.Component;
import org.xwiki.query.Query;
import org.xwiki.query.QueryException;
import org.xwiki.query.QueryManager;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Joiner;
/**
* @version $Id$
*/
@Component
@Singleton
public class DefaultMatchingNotificationManager implements MatchingNotificationManager
{
private Logger logger = LoggerFactory.getLogger(DefaultMatchingNotificationManager.class);
@Inject
private QueryManager qm;
@Inject
private PatientRepository patientRepository;
@Inject
private PermissionsManager permissionsManager;
@Inject
@Named("matchable")
private Visibility matchableVisibility;
@Inject
private PatientMatchNotifier notifier;
@Inject
private MatchFinderManager matchFinderManager;
@Inject
private MatchStorageManager matchStorageManager;
@Override
public List<PatientMatch> findAndSaveMatches(double score)
{
List<PatientMatch> addedMatches = new LinkedList<>();
List<Patient> patients = this.getPatientsList();
for (Patient patient : patients) {
this.logger.debug("Finding matches for patient {}.", patient.getId());
List<PatientMatch> matchesForPatient = this.matchFinderManager.findMatches(patient);
this.filterMatchesByScore(matchesForPatient, score);
this.filterExistingMatches(matchesForPatient);
this.matchStorageManager.saveMatches(matchesForPatient);
addedMatches.addAll(matchesForPatient);
}
return addedMatches;
}
/*
* Returns a list of patients with visibility>=matchable
*/
private List<Patient> getPatientsList()
{
List<String> potentialPatientIds = null;
List<Patient> patients = new LinkedList<>();
try {
Query q = this.qm.createQuery(
"select doc.name "
+ "from Document doc, "
+ "doc.object(PhenoTips.PatientClass) as patient "
+ "where patient.identifier is not null order by patient.identifier desc", Query.XWQL);
potentialPatientIds = q.execute();
} catch (QueryException e) {
this.logger.error("Error retrieving a list of patients for matching: {}", e);
return null;
}
for (String patientId : potentialPatientIds) {
Patient patient = this.patientRepository.getPatientById(patientId);
if (patient == null) {
continue;
}
Visibility patientVisibility = this.permissionsManager.getPatientAccess(patient).getVisibility();
if (patientVisibility.compareTo(matchableVisibility) >= 0) {
patients.add(patient);
}
}
return patients;
}
@Override
public List<PatientMatchNotificationResponse> sendNotifications(List<Long> matchesIds)
{
if (matchesIds == null || matchesIds.size() == 0) {
return Collections.emptyList();
}
List<PatientMatch> matches = matchStorageManager.loadMatchesByIds(matchesIds);
List<PatientMatchEmail> emails = notifier.createEmails(matches);
List<PatientMatchNotificationResponse> responses = new LinkedList<>();
for (PatientMatchEmail email : emails) {
Session session = this.matchStorageManager.beginNotificationMarkingTransaction();
List<PatientMatchNotificationResponse> notificationResults = notifier.notify(email);
this.markSuccessfulNotification(session, notificationResults);
boolean successful = this.matchStorageManager.endNotificationMarkingTransaction(session);
if (!successful) {
this.logger.error("Error on committing transaction for matching notification for patient {}.",
email.getSubjectPatientId());
}
responses.addAll(notificationResults);
}
return responses;
}
private void markSuccessfulNotification(Session session, List<PatientMatchNotificationResponse> notificationResults)
{
List<PatientMatch> successfulMatches = new LinkedList<>();
for (PatientMatchNotificationResponse response : notificationResults) {
PatientMatch match = response.getPatientMatch();
if (response.isSuccessul()) {
successfulMatches.add(match);
} else {
this.logger.error("Error on sending email for match {}: {}.", match, response.getErrorMessage());
}
}
this.matchStorageManager.markNotified(session, successfulMatches);
}
/*
* Removes all matches from list with score lower than score.
*/
private void filterMatchesByScore(List<PatientMatch> matches, double score)
{
List<PatientMatch> toRemove = new LinkedList<PatientMatch>();
for (PatientMatch match : matches) {
if (match.getScore() < score) {
toRemove.add(match);
}
}
matches.removeAll(toRemove);
}
/*
* Gets a list of matches and removes matches that already exist in the database. When this is more mature, it might
* belong in a separate component.
*/
private void filterExistingMatches(List<PatientMatch> matches)
{
Map<String, List<PatientMatch>> matchesByPatientId = new HashMap<>();
List<PatientMatch> toRemove = new LinkedList<>();
for (PatientMatch match : matches) {
// Read existing matches for same patient id, from db or cache
String patientId = match.getReferencePatientId();
List<PatientMatch> matchesForPatient = matchesByPatientId.get(patientId);
if (matchesForPatient == null) {
// TODO use loadMatchesByIds instead.
matchesForPatient = this.matchStorageManager.loadMatchesByReferencePatientId(patientId);
matchesByPatientId.put(patientId, matchesForPatient);
}
// Filter out existing matches from list parameter
if (matchesForPatient.contains(match)) {
toRemove.add(match);
}
}
matches.removeAll(toRemove);
}
@Override
public boolean saveIncomingMatches(List<PatientSimilarityView> similarityViews, String remoteId)
{
List<PatientMatch> matches = new LinkedList<>();
for (PatientSimilarityView view : similarityViews) {
PatientMatch match = new DefaultPatientMatch(view, remoteId, null);
matches.add(match);
}
this.filterExistingMatches(matches);
this.matchStorageManager.saveMatches(matches);
return true;
}
@Override
public boolean markRejected(List<Long> matchesIds, boolean rejected)
{
boolean successful = false;
try {
List<PatientMatch> matches = matchStorageManager.loadMatchesByIds(matchesIds);
Session session = this.matchStorageManager.beginNotificationMarkingTransaction();
this.matchStorageManager.markRejected(session, matches, rejected);
successful = this.matchStorageManager.endNotificationMarkingTransaction(session);
} catch (HibernateException e) {
this.logger.error("Error while marking matches {} as rejected.", Joiner.on(",").join(matchesIds), e);
}
return successful;
}
}
|
package es.uah.aut.srg.micobs.mclev.library.mclevlibrary.presentation;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.emf.common.command.BasicCommandStack;
import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.common.command.CommandStack;
import org.eclipse.emf.common.command.CommandStackListener;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.impl.AdapterImpl;
import org.eclipse.emf.common.ui.MarkerHelper;
import org.eclipse.emf.common.ui.editor.ProblemEditorPart;
import org.eclipse.emf.common.ui.viewer.IViewerProvider;
import org.eclipse.emf.common.util.BasicDiagnostic;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EValidator;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.util.EContentAdapter;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.domain.IEditingDomainProvider;
import org.eclipse.emf.edit.provider.AdapterFactoryItemDelegator;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.ReflectiveItemProviderAdapterFactory;
import org.eclipse.emf.edit.provider.resource.ResourceItemProviderAdapterFactory;
import org.eclipse.emf.edit.ui.celleditor.AdapterFactoryTreeEditor;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
import org.eclipse.emf.edit.ui.provider.UnwrappingSelectionProvider;
import org.eclipse.emf.edit.ui.util.EditUIMarkerHelper;
import org.eclipse.emf.edit.ui.util.EditUIUtil;
import org.eclipse.emf.edit.ui.view.ExtendedPropertySheetPage;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.dialogs.SaveAsDialog;
import org.eclipse.ui.ide.IGotoMarker;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.part.MultiPageEditorPart;
import org.eclipse.ui.views.contentoutline.ContentOutline;
import org.eclipse.ui.views.contentoutline.ContentOutlinePage;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.ui.views.properties.IPropertySheetPage;
import org.eclipse.ui.views.properties.PropertySheet;
import org.eclipse.ui.views.properties.PropertySheetPage;
import es.uah.aut.srg.micobs.common.provider.commonItemProviderAdapterFactory;
import es.uah.aut.srg.micobs.library.LibraryManagerException;
import es.uah.aut.srg.micobs.library.ui.MICOBSLibraryEditorActionBarContributor;
import es.uah.aut.srg.micobs.mclev.library.mclevlibrary.manager.MCLEVLibraryManager;
import es.uah.aut.srg.micobs.mclev.library.mclevlibrary.provider.mclevlibraryItemProviderAdapterFactory;
import es.uah.aut.srg.micobs.mclev.plugin.MCLEVPlugin;
import es.uah.aut.srg.micobs.util.impl.MICOBSAdapterFactoryLabelProvider;
/**
* MCLEV Library editor.
* @generated NOT
*/
public class mclevlibraryEditor
extends MultiPageEditorPart
implements IEditingDomainProvider, ISelectionProvider, IMenuListener, IViewerProvider, IGotoMarker {
/**
* This keeps track of the editing domain that is used to track all changes to the model.
* @generated
*/
protected AdapterFactoryEditingDomain editingDomain;
/**
* This is the one adapter factory used for providing views of the model.
* @generated
*/
protected ComposedAdapterFactory adapterFactory;
/**
* This is the content outline page.
* @generated
*/
protected IContentOutlinePage contentOutlinePage;
/**
* This is a kludge...
* @generated
*/
protected IStatusLineManager contentOutlineStatusLineManager;
/**
* This is the content outline page's viewer.
* @generated
*/
protected TreeViewer contentOutlineViewer;
/**
* This is the property sheet page.
* @generated
*/
protected PropertySheetPage propertySheetPage;
/**
* This is the viewer that shadows the selection in the content outline.
* The parent relation must be correctly defined for this to work.
* @generated
*/
protected TreeViewer selectionViewer;
/**
* This keeps track of the active content viewer, which may be either one of the viewers in the pages or the content outline viewer.
* @generated
*/
protected Viewer currentViewer;
/**
* This listens to which ever viewer is active.
* @generated
*/
protected ISelectionChangedListener selectionChangedListener;
/**
* This keeps track of all the {@link org.eclipse.jface.viewers.ISelectionChangedListener}s that are listening to this editor.
* @generated
*/
protected Collection<ISelectionChangedListener> selectionChangedListeners = new ArrayList<ISelectionChangedListener>();
/**
* This keeps track of the selection of the editor as a whole.
* @generated
*/
protected ISelection editorSelection = StructuredSelection.EMPTY;
/**
* The MarkerHelper is responsible for creating workspace resource markers presented
* in Eclipse's Problems View.
* @generated
*/
protected MarkerHelper markerHelper = new EditUIMarkerHelper();
/**
* This listens for when the outline becomes active
* @generated
*/
protected IPartListener partListener =
new IPartListener() {
public void partActivated(IWorkbenchPart p) {
if (p instanceof ContentOutline) {
if (((ContentOutline)p).getCurrentPage() == contentOutlinePage) {
getActionBarContributor().setActiveEditor(mclevlibraryEditor.this);
setCurrentViewer(contentOutlineViewer);
}
}
else if (p instanceof PropertySheet) {
if (((PropertySheet)p).getCurrentPage() == propertySheetPage) {
getActionBarContributor().setActiveEditor(mclevlibraryEditor.this);
handleActivate();
}
}
else if (p == mclevlibraryEditor.this) {
handleActivate();
}
}
public void partBroughtToTop(IWorkbenchPart p) {
// Ignore.
}
public void partClosed(IWorkbenchPart p) {
// Ignore.
}
public void partDeactivated(IWorkbenchPart p) {
// Ignore.
}
public void partOpened(IWorkbenchPart p) {
// Ignore.
}
};
/**
* Resources that have been removed since last activation.
* @generated
*/
protected Collection<Resource> removedResources = new ArrayList<Resource>();
/**
* Resources that have been changed since last activation.
* @generated
*/
protected Collection<Resource> changedResources = new ArrayList<Resource>();
/**
* Resources that have been saved.
* @generated
*/
protected Collection<Resource> savedResources = new ArrayList<Resource>();
/**
* Map to store the diagnostic associated with a resource.
* @generated
*/
protected Map<Resource, Diagnostic> resourceToDiagnosticMap = new LinkedHashMap<Resource, Diagnostic>();
/**
* Controls whether the problem indication should be updated.
* @generated
*/
protected boolean updateProblemIndication = true;
/**
* Adapter used to update the problem indication when resources are demanded loaded.
* @generated
*/
protected EContentAdapter problemIndicationAdapter =
new EContentAdapter() {
@Override
public void notifyChanged(Notification notification) {
if (notification.getNotifier() instanceof Resource) {
switch (notification.getFeatureID(Resource.class)) {
case Resource.RESOURCE__IS_LOADED:
case Resource.RESOURCE__ERRORS:
case Resource.RESOURCE__WARNINGS: {
Resource resource = (Resource)notification.getNotifier();
Diagnostic diagnostic = analyzeResourceProblems(resource, null);
if (diagnostic.getSeverity() != Diagnostic.OK) {
resourceToDiagnosticMap.put(resource, diagnostic);
}
else {
resourceToDiagnosticMap.remove(resource);
}
if (updateProblemIndication) {
getSite().getShell().getDisplay().asyncExec
(new Runnable() {
public void run() {
updateProblemIndication();
}
});
}
break;
}
}
}
else {
super.notifyChanged(notification);
}
}
@Override
protected void setTarget(Resource target) {
basicSetTarget(target);
}
@Override
protected void unsetTarget(Resource target) {
basicUnsetTarget(target);
}
};
/**
* This listens for workspace changes.
* @generated
*/
protected IResourceChangeListener resourceChangeListener =
new IResourceChangeListener() {
public void resourceChanged(IResourceChangeEvent event) {
IResourceDelta delta = event.getDelta();
try {
class ResourceDeltaVisitor implements IResourceDeltaVisitor {
protected ResourceSet resourceSet = editingDomain.getResourceSet();
protected Collection<Resource> changedResources = new ArrayList<Resource>();
protected Collection<Resource> removedResources = new ArrayList<Resource>();
public boolean visit(IResourceDelta delta) {
if (delta.getResource().getType() == IResource.FILE) {
if (delta.getKind() == IResourceDelta.REMOVED ||
delta.getKind() == IResourceDelta.CHANGED && delta.getFlags() != IResourceDelta.MARKERS) {
Resource resource = resourceSet.getResource(URI.createPlatformResourceURI(delta.getFullPath().toString(), true), false);
if (resource != null) {
if (delta.getKind() == IResourceDelta.REMOVED) {
removedResources.add(resource);
}
else if (!savedResources.remove(resource)) {
changedResources.add(resource);
}
}
}
}
return true;
}
public Collection<Resource> getChangedResources() {
return changedResources;
}
public Collection<Resource> getRemovedResources() {
return removedResources;
}
}
final ResourceDeltaVisitor visitor = new ResourceDeltaVisitor();
delta.accept(visitor);
if (!visitor.getRemovedResources().isEmpty()) {
getSite().getShell().getDisplay().asyncExec
(new Runnable() {
public void run() {
removedResources.addAll(visitor.getRemovedResources());
if (!isDirty()) {
getSite().getPage().closeEditor(mclevlibraryEditor.this, false);
}
}
});
}
if (!visitor.getChangedResources().isEmpty()) {
getSite().getShell().getDisplay().asyncExec
(new Runnable() {
public void run() {
changedResources.addAll(visitor.getChangedResources());
if (getSite().getPage().getActiveEditor() == mclevlibraryEditor.this) {
handleActivate();
}
}
});
}
}
catch (CoreException exception) {
MCLEVPlugin.INSTANCE.log(exception);
}
}
};
protected Adapter resourceListener = new AdapterImpl() {
@Override
public boolean isAdapterForType(Object type) {
return type == Resource.class;
}
};
protected class EditingDomainProviderAdapter extends AdapterImpl
implements IEditingDomainProvider
{
@Override
public boolean isAdapterForType(Object type) {
return type == IEditingDomainProvider.class;
}
@Override
public EditingDomain getEditingDomain() {
return mclevlibraryEditor.this.getEditingDomain();
}
}
protected EditingDomainProviderAdapter editingDomainProviderAdapter = new EditingDomainProviderAdapter();
/**
* Handles activation of the editor or it's associated views.
* @generated
*/
protected void handleActivate() {
// Recompute the read only state.
if (editingDomain.getResourceToReadOnlyMap() != null) {
editingDomain.getResourceToReadOnlyMap().clear();
// Refresh any actions that may become enabled or disabled.
setSelection(getSelection());
}
if (!removedResources.isEmpty()) {
if (handleDirtyConflict()) {
getSite().getPage().closeEditor(mclevlibraryEditor.this, false);
}
else {
removedResources.clear();
changedResources.clear();
savedResources.clear();
}
}
else if (!changedResources.isEmpty()) {
changedResources.removeAll(savedResources);
handleChangedResources();
changedResources.clear();
savedResources.clear();
}
}
/**
* Handles what to do with changed resources on activation.
* @generated
*/
protected void handleChangedResources() {
if (!changedResources.isEmpty() && (!isDirty() || handleDirtyConflict())) {
if (isDirty()) {
changedResources.addAll(editingDomain.getResourceSet().getResources());
}
editingDomain.getCommandStack().flush();
updateProblemIndication = false;
for (Resource resource : changedResources) {
if (resource.isLoaded()) {
resource.unload();
try {
resource.load(Collections.EMPTY_MAP);
}
catch (IOException exception) {
if (!resourceToDiagnosticMap.containsKey(resource)) {
resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
}
}
}
if (AdapterFactoryEditingDomain.isStale(editorSelection)) {
setSelection(StructuredSelection.EMPTY);
}
updateProblemIndication = true;
updateProblemIndication();
}
}
/**
* Updates the problems indication with the information described in the specified diagnostic.
* @generated
*/
protected void updateProblemIndication() {
if (updateProblemIndication) {
BasicDiagnostic diagnostic =
new BasicDiagnostic
(Diagnostic.OK,
"es.uah.aut.srg.micobs.mclev",
0,
null,
new Object [] { editingDomain.getResourceSet() });
for (Diagnostic childDiagnostic : resourceToDiagnosticMap.values()) {
if (childDiagnostic.getSeverity() != Diagnostic.OK) {
diagnostic.add(childDiagnostic);
}
}
int lastEditorPage = getPageCount() - 1;
if (lastEditorPage >= 0 && getEditor(lastEditorPage) instanceof ProblemEditorPart) {
((ProblemEditorPart)getEditor(lastEditorPage)).setDiagnostic(diagnostic);
if (diagnostic.getSeverity() != Diagnostic.OK) {
setActivePage(lastEditorPage);
}
}
else if (diagnostic.getSeverity() != Diagnostic.OK) {
ProblemEditorPart problemEditorPart = new ProblemEditorPart();
problemEditorPart.setDiagnostic(diagnostic);
problemEditorPart.setMarkerHelper(markerHelper);
try {
addPage(++lastEditorPage, problemEditorPart, getEditorInput());
setPageText(lastEditorPage, problemEditorPart.getPartName());
setActivePage(lastEditorPage);
showTabs();
}
catch (PartInitException exception) {
MCLEVPlugin.INSTANCE.log(exception);
}
}
if (markerHelper.hasMarkers(editingDomain.getResourceSet())) {
markerHelper.deleteMarkers(editingDomain.getResourceSet());
if (diagnostic.getSeverity() != Diagnostic.OK) {
try {
markerHelper.createMarkers(diagnostic);
}
catch (CoreException exception) {
MCLEVPlugin.INSTANCE.log(exception);
}
}
}
}
}
/**
* Shows a dialog that asks if conflicting changes should be discarded.
* @generated
*/
protected boolean handleDirtyConflict() {
return
MessageDialog.openQuestion
(getSite().getShell(),
getString("_UI_FileConflict_label"),
getString("_WARN_FileConflict"));
}
/**
* This creates a model editor.
* @generated
*/
public mclevlibraryEditor() {
super();
initializeEditingDomain();
}
/**
* This sets up the editing domain for the model editor.
* @generated NOT
*/
protected void initializeEditingDomain() {
// Create an adapter factory that yields item providers.
adapterFactory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
adapterFactory.addAdapterFactory(new ResourceItemProviderAdapterFactory());
adapterFactory.addAdapterFactory(new mclevlibraryItemProviderAdapterFactory());
adapterFactory.addAdapterFactory(new commonItemProviderAdapterFactory());
adapterFactory.addAdapterFactory(new ReflectiveItemProviderAdapterFactory());
// Create the command stack that will notify this editor as commands are executed.
BasicCommandStack commandStack = new BasicCommandStack();
// Add a listener to set the most recent command's affected objects to be the selection of the viewer with focus.
commandStack.addCommandStackListener
(new CommandStackListener() {
public void commandStackChanged(final EventObject event) {
getContainer().getDisplay().asyncExec
(new Runnable() {
public void run() {
firePropertyChange(IEditorPart.PROP_DIRTY);
final Map<Object, Object> saveOptions = new HashMap<Object, Object>();
saveOptions.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED, Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER);
// We have to save the resource in any case on
// every modification
try {
resource.save(saveOptions);
} catch (IOException e) {
MCLEVPlugin.INSTANCE.log(e);
}
// Try to select the affected objects.
Command mostRecentCommand = ((CommandStack)event.getSource()).getMostRecentCommand();
if (mostRecentCommand != null) {
setSelectionToViewer(mostRecentCommand.getAffectedObjects());
}
if (propertySheetPage != null && !propertySheetPage.getControl().isDisposed()) {
propertySheetPage.refresh();
}
}
});
}
});
// Create the editing domain with a special command stack.
try {
editingDomain = new AdapterFactoryEditingDomain(adapterFactory, commandStack, MCLEVLibraryManager.getLibraryManager().getLibraryResourceSet());
} catch (LibraryManagerException e) {
MCLEVPlugin.INSTANCE.log(e);
editingDomain = new AdapterFactoryEditingDomain(adapterFactory, commandStack);
}
}
/**
* This is here for the listener to be able to call it.
* @generated
*/
@Override
protected void firePropertyChange(int action) {
super.firePropertyChange(action);
}
/**
* This sets the selection into whichever viewer is active.
* @generated
*/
public void setSelectionToViewer(Collection<?> collection) {
final Collection<?> theSelection = collection;
// Make sure it's okay.
if (theSelection != null && !theSelection.isEmpty()) {
Runnable runnable =
new Runnable() {
public void run() {
// Try to select the items in the current content viewer of the editor.
if (currentViewer != null) {
currentViewer.setSelection(new StructuredSelection(theSelection.toArray()), true);
}
}
};
getSite().getShell().getDisplay().asyncExec(runnable);
}
}
/**
* This returns the editing domain as required by the {@link IEditingDomainProvider} interface.
* This is important for implementing the static methods of {@link AdapterFactoryEditingDomain}
* and for supporting {@link org.eclipse.emf.edit.ui.action.CommandAction}.
* @generated
*/
public EditingDomain getEditingDomain() {
return editingDomain;
}
/**
* @generated
*/
public class ReverseAdapterFactoryContentProvider extends AdapterFactoryContentProvider {
/**
* @generated
*/
public ReverseAdapterFactoryContentProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* @generated
*/
@Override
public Object [] getElements(Object object) {
Object parent = super.getParent(object);
return (parent == null ? Collections.EMPTY_SET : Collections.singleton(parent)).toArray();
}
/**
* @generated
*/
@Override
public Object [] getChildren(Object object) {
Object parent = super.getParent(object);
return (parent == null ? Collections.EMPTY_SET : Collections.singleton(parent)).toArray();
}
/**
* @generated
*/
@Override
public boolean hasChildren(Object object) {
Object parent = super.getParent(object);
return parent != null;
}
/**
* @generated
*/
@Override
public Object getParent(Object object) {
return null;
}
}
/**
* This makes sure that one content viewer, either for the current page or the outline view, if it has focus,
* is the current one.
* @generated
*/
public void setCurrentViewer(Viewer viewer) {
// If it is changing...
if (currentViewer != viewer) {
if (selectionChangedListener == null) {
// Create the listener on demand.
selectionChangedListener =
new ISelectionChangedListener() {
// This just notifies those things that are affected by the section.
public void selectionChanged(SelectionChangedEvent selectionChangedEvent) {
setSelection(selectionChangedEvent.getSelection());
}
};
}
// Stop listening to the old one.
if (currentViewer != null) {
currentViewer.removeSelectionChangedListener(selectionChangedListener);
}
// Start listening to the new one.
if (viewer != null) {
viewer.addSelectionChangedListener(selectionChangedListener);
}
// Remember it.
currentViewer = viewer;
// Set the editors selection based on the current viewer's selection.
setSelection(currentViewer == null ? StructuredSelection.EMPTY : currentViewer.getSelection());
}
}
/**
* This returns the viewer as required by the {@link IViewerProvider} interface.
* @generated
*/
public Viewer getViewer() {
return currentViewer;
}
/**
* This creates a context menu for the viewer and adds a listener as well registering the menu for extension.
* @generated
*/
protected void createContextMenuFor(StructuredViewer viewer) {
MenuManager contextMenu = new MenuManager("#PopUp");
contextMenu.add(new Separator("additions"));
contextMenu.setRemoveAllWhenShown(true);
contextMenu.addMenuListener(this);
Menu menu= contextMenu.createContextMenu(viewer.getControl());
viewer.getControl().setMenu(menu);
getSite().registerContextMenu(contextMenu, new UnwrappingSelectionProvider(viewer));
}
Resource resource = null;
/**
* This is the method called to load a resource into the editing domain's resource set based on the editor's input.
* @generated NOT
*/
public void createModel() {
URI resourceURI = EditUIUtil.getURI(getEditorInput());
Exception exception = null;
try {
// Load the resource through the editing domain.
resource = editingDomain.getResourceSet().getResource(resourceURI, true);
}
catch (Exception e) {
exception = e;
resource = editingDomain.getResourceSet().getResource(resourceURI, false);
}
Diagnostic diagnostic = analyzeResourceProblems(resource, exception);
if (diagnostic.getSeverity() != Diagnostic.OK) {
resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
editingDomain.getResourceSet().eAdapters().add(problemIndicationAdapter);
if (resource != null)
{
resource.eAdapters().add(resourceListener);
resource.eAdapters().add(editingDomainProviderAdapter);
}
}
/**
* Returns a diagnostic describing the errors and warnings listed in the resource
* and the specified exception (if any).
* @generated
*/
public Diagnostic analyzeResourceProblems(Resource resource, Exception exception) {
if (!resource.getErrors().isEmpty() || !resource.getWarnings().isEmpty()) {
BasicDiagnostic basicDiagnostic =
new BasicDiagnostic
(Diagnostic.ERROR,
"es.uah.aut.srg.micobs.mclev",
0,
getString("_UI_CreateModelError_message", resource.getURI()),
new Object [] { exception == null ? (Object)resource : exception });
basicDiagnostic.merge(EcoreUtil.computeDiagnostic(resource, true));
return basicDiagnostic;
}
else if (exception != null) {
return
new BasicDiagnostic
(Diagnostic.ERROR,
"es.uah.aut.srg.micobs.mclev",
0,
getString("_UI_CreateModelError_message", resource.getURI()),
new Object[] { exception });
}
else {
return Diagnostic.OK_INSTANCE;
}
}
protected URI editorInputResourceURI;
protected URI getEditorInputResourceURI() {
if (editorInputResourceURI == null)
{
editorInputResourceURI = EditUIUtil.getURI(getEditorInput());
}
return editorInputResourceURI;
}
/**
* This is the method used by the framework to install your own controls.
* @generated NOT
*/
@Override
public void createPages() {
// Creates the model from the editor input
createModel();
// Only creates the other pages if there is something that can be edited
if (!getEditingDomain().getResourceSet().getResources().isEmpty()) {
// Create a page for the selection tree view.
Tree tree = new Tree(getContainer(), SWT.MULTI);
selectionViewer = new TreeViewer(tree);
setCurrentViewer(selectionViewer);
selectionViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
selectionViewer.setLabelProvider(new MICOBSAdapterFactoryLabelProvider(adapterFactory));
selectionViewer.setInput(editingDomain.getResourceSet().getResource(getEditorInputResourceURI(), false));
selectionViewer.setSelection(new StructuredSelection(editingDomain.getResourceSet().getResources().get(0)), true);
new AdapterFactoryTreeEditor(selectionViewer.getTree(), adapterFactory);
createContextMenuFor(selectionViewer);
int pageIndex = addPage(tree);
setPageText(pageIndex, getString("_UI_SelectionPage_label"));
getSite().getShell().getDisplay().asyncExec
(new Runnable() {
public void run() {
setActivePage(0);
}
});
}
// Ensures that this editor will only display the page's tab
// area if there are more than one page
getContainer().addControlListener
(new ControlAdapter() {
boolean guard = false;
@Override
public void controlResized(ControlEvent event) {
if (!guard) {
guard = true;
hideTabs();
guard = false;
}
}
});
getSite().getShell().getDisplay().asyncExec
(new Runnable() {
public void run() {
updateProblemIndication();
}
});
}
/**
* If there is just one page in the multi-page editor part,
* this hides the single tab at the bottom.
* @generated
*/
protected void hideTabs() {
if (getPageCount() <= 1) {
setPageText(0, "");
if (getContainer() instanceof CTabFolder) {
((CTabFolder)getContainer()).setTabHeight(1);
Point point = getContainer().getSize();
getContainer().setSize(point.x, point.y + 6);
}
}
}
/**
* If there is more than one page in the multi-page editor part,
* this shows the tabs at the bottom.
* @generated
*/
protected void showTabs() {
if (getPageCount() > 1) {
setPageText(0, getString("_UI_SelectionPage_label"));
if (getContainer() instanceof CTabFolder) {
((CTabFolder)getContainer()).setTabHeight(SWT.DEFAULT);
Point point = getContainer().getSize();
getContainer().setSize(point.x, point.y - 6);
}
}
}
/**
* This is used to track the active viewer.
* @generated
*/
@Override
protected void pageChange(int pageIndex) {
super.pageChange(pageIndex);
if (contentOutlinePage != null) {
handleContentOutlineSelection(contentOutlinePage.getSelection());
}
}
/**
* This is how the framework determines which interfaces we implement.
* @generated
*/
@SuppressWarnings("rawtypes")
@Override
public Object getAdapter(Class key) {
if (key.equals(IContentOutlinePage.class)) {
return showOutlineView() ? getContentOutlinePage() : null;
}
else if (key.equals(IPropertySheetPage.class)) {
return getPropertySheetPage();
}
else if (key.equals(IGotoMarker.class)) {
return this;
}
else {
return super.getAdapter(key);
}
}
/**
* This accesses a cached version of the content outliner.
* @generated
*/
public IContentOutlinePage getContentOutlinePage() {
if (contentOutlinePage == null) {
// The content outline is just a tree.
class MyContentOutlinePage extends ContentOutlinePage {
@Override
public void createControl(Composite parent) {
super.createControl(parent);
contentOutlineViewer = getTreeViewer();
contentOutlineViewer.addSelectionChangedListener(this);
// Set up the tree viewer.
contentOutlineViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
contentOutlineViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
contentOutlineViewer.setInput(editingDomain.getResourceSet());
// Make sure our popups work.
createContextMenuFor(contentOutlineViewer);
if (!editingDomain.getResourceSet().getResources().isEmpty()) {
// Select the root object in the view.
contentOutlineViewer.setSelection(new StructuredSelection(editingDomain.getResourceSet().getResources().get(0)), true);
}
}
@Override
public void makeContributions(IMenuManager menuManager, IToolBarManager toolBarManager, IStatusLineManager statusLineManager) {
super.makeContributions(menuManager, toolBarManager, statusLineManager);
contentOutlineStatusLineManager = statusLineManager;
}
@Override
public void setActionBars(IActionBars actionBars) {
super.setActionBars(actionBars);
getActionBarContributor().shareGlobalActions(this, actionBars);
}
}
contentOutlinePage = new MyContentOutlinePage();
// Listen to selection so that we can handle it is a special way.
contentOutlinePage.addSelectionChangedListener
(new ISelectionChangedListener() {
// This ensures that we handle selections correctly.
public void selectionChanged(SelectionChangedEvent event) {
handleContentOutlineSelection(event.getSelection());
}
});
}
return contentOutlinePage;
}
/**
* This accesses a cached version of the property sheet.
* @generated
*/
public IPropertySheetPage getPropertySheetPage() {
if (propertySheetPage == null) {
propertySheetPage =
new ExtendedPropertySheetPage(editingDomain) {
@Override
public void setSelectionToViewer(List<?> selection) {
mclevlibraryEditor.this.setSelectionToViewer(selection);
mclevlibraryEditor.this.setFocus();
}
@Override
public void setActionBars(IActionBars actionBars) {
super.setActionBars(actionBars);
getActionBarContributor().shareGlobalActions(this, actionBars);
}
};
propertySheetPage.setPropertySourceProvider(new AdapterFactoryContentProvider(adapterFactory));
}
return propertySheetPage;
}
/**
* This deals with how we want selection in the outliner to affect the other views.
* @generated
*/
public void handleContentOutlineSelection(ISelection selection) {
if (selectionViewer != null && !selection.isEmpty() && selection instanceof IStructuredSelection) {
Iterator<?> selectedElements = ((IStructuredSelection)selection).iterator();
if (selectedElements.hasNext()) {
// Get the first selected element.
Object selectedElement = selectedElements.next();
ArrayList<Object> selectionList = new ArrayList<Object>();
selectionList.add(selectedElement);
while (selectedElements.hasNext()) {
selectionList.add(selectedElements.next());
}
// Set the selection to the widget.
selectionViewer.setSelection(new StructuredSelection(selectionList));
}
}
}
/**
* This is for implementing {@link IEditorPart} and simply tests the command stack.
* @generated NOT
*/
@Override
public boolean isDirty() {
return false;
}
/**
* This is for implementing {@link IEditorPart} and simply saves the model file.
* @generated
*/
@Override
public void doSave(IProgressMonitor progressMonitor) {
// Save only resources that have actually changed.
final Map<Object, Object> saveOptions = new HashMap<Object, Object>();
saveOptions.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED, Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER);
// Do the work within an operation because this is a long running activity that modifies the workbench.
WorkspaceModifyOperation operation =
new WorkspaceModifyOperation() {
// This is the method that gets invoked when the operation runs.
@Override
public void execute(IProgressMonitor monitor) {
// Save the resources to the file system.
boolean first = true;
for (Resource resource : editingDomain.getResourceSet().getResources()) {
if ((first || !resource.getContents().isEmpty() || isPersisted(resource)) && !editingDomain.isReadOnly(resource)) {
try {
long timeStamp = resource.getTimeStamp();
resource.save(saveOptions);
if (resource.getTimeStamp() != timeStamp) {
savedResources.add(resource);
}
}
catch (Exception exception) {
resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
first = false;
}
}
}
};
updateProblemIndication = false;
try {
// This runs the options, and shows progress.
new ProgressMonitorDialog(getSite().getShell()).run(true, false, operation);
// Refresh the necessary state.
((BasicCommandStack)editingDomain.getCommandStack()).saveIsDone();
firePropertyChange(IEditorPart.PROP_DIRTY);
}
catch (Exception exception) {
// Something went wrong that shouldn't.
MCLEVPlugin.INSTANCE.log(exception);
}
updateProblemIndication = true;
updateProblemIndication();
}
/**
* This returns whether something has been persisted to the URI of the specified resource.
* The implementation uses the URI converter from the editor's resource set to try to open an input stream.
* @generated
*/
protected boolean isPersisted(Resource resource) {
boolean result = false;
try {
InputStream stream = editingDomain.getResourceSet().getURIConverter().createInputStream(resource.getURI());
if (stream != null) {
result = true;
stream.close();
}
}
catch (IOException e) {
// Ignore
}
return result;
}
/**
* This always returns true because it is not currently supported.
* @generated
*/
@Override
public boolean isSaveAsAllowed() {
return true;
}
/**
* This also changes the editor's input.
* @generated
*/
@Override
public void doSaveAs() {
SaveAsDialog saveAsDialog = new SaveAsDialog(getSite().getShell());
saveAsDialog.open();
IPath path = saveAsDialog.getResult();
if (path != null) {
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
if (file != null) {
doSaveAs(URI.createPlatformResourceURI(file.getFullPath().toString(), true), new FileEditorInput(file));
}
}
}
/**
* @generated
*/
protected void doSaveAs(URI uri, IEditorInput editorInput) {
(editingDomain.getResourceSet().getResources().get(0)).setURI(uri);
setInputWithNotify(editorInput);
setPartName(editorInput.getName());
IProgressMonitor progressMonitor =
getActionBars().getStatusLineManager() != null ?
getActionBars().getStatusLineManager().getProgressMonitor() :
new NullProgressMonitor();
doSave(progressMonitor);
}
/**
* @generated
*/
public void gotoMarker(IMarker marker) {
try {
if (marker.getType().equals(EValidator.MARKER)) {
String uriAttribute = marker.getAttribute(EValidator.URI_ATTRIBUTE, null);
if (uriAttribute != null) {
URI uri = URI.createURI(uriAttribute);
EObject eObject = editingDomain.getResourceSet().getEObject(uri, true);
if (eObject != null) {
setSelectionToViewer(Collections.singleton(editingDomain.getWrapper(eObject)));
}
}
}
}
catch (CoreException exception) {
MCLEVPlugin.INSTANCE.log(exception);
}
}
/**
* This is called during startup.
* @generated NOT
*/
@Override
public void init(IEditorSite site, IEditorInput editorInput) {
setSite(site);
setInputWithNotify(editorInput);
setPartName(MCLEVPlugin.INSTANCE.getString("_UI_MMCLEVLibrary_partName"));
site.setSelectionProvider(this);
site.getPage().addPartListener(partListener);
ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceChangeListener, IResourceChangeEvent.POST_CHANGE);
}
/**
* @generated
*/
@Override
public void setFocus() {
getControl(getActivePage()).setFocus();
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider}.
* @generated
*/
public void addSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.add(listener);
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider}.
* @generated
*/
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.remove(listener);
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider} to return this editor's overall selection.
* @generated
*/
public ISelection getSelection() {
return editorSelection;
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider} to set this editor's overall selection.
* Calling this result will notify the listeners.
* @generated
*/
public void setSelection(ISelection selection) {
editorSelection = selection;
for (ISelectionChangedListener listener : selectionChangedListeners) {
listener.selectionChanged(new SelectionChangedEvent(this, selection));
}
setStatusLineManager(selection);
}
/**
* @generated
*/
public void setStatusLineManager(ISelection selection) {
IStatusLineManager statusLineManager = currentViewer != null && currentViewer == contentOutlineViewer ?
contentOutlineStatusLineManager : getActionBars().getStatusLineManager();
if (statusLineManager != null) {
if (selection instanceof IStructuredSelection) {
Collection<?> collection = ((IStructuredSelection)selection).toList();
switch (collection.size()) {
case 0: {
statusLineManager.setMessage(getString("_UI_NoObjectSelected"));
break;
}
case 1: {
String text = new AdapterFactoryItemDelegator(adapterFactory).getText(collection.iterator().next());
statusLineManager.setMessage(getString("_UI_SingleObjectSelected", text));
break;
}
default: {
statusLineManager.setMessage(getString("_UI_MultiObjectSelected", Integer.toString(collection.size())));
break;
}
}
}
else {
statusLineManager.setMessage("");
}
}
}
/**
* This looks up a string in the plugin's plugin.properties file.
* @generated
*/
private static String getString(String key) {
return MCLEVPlugin.INSTANCE.getString(key);
}
/**
* This looks up a string in plugin.properties, making a substitution.
* @generated
*/
private static String getString(String key, Object s1) {
return MCLEVPlugin.INSTANCE.getString(key, new Object [] { s1 });
}
/**
* This implements {@link org.eclipse.jface.action.IMenuListener} to help fill the context menus with contributions from the Edit menu.
* @generated
*/
public void menuAboutToShow(IMenuManager menuManager) {
((IMenuListener)getEditorSite().getActionBarContributor()).menuAboutToShow(menuManager);
}
/**
* @generated NOT
*/
public MICOBSLibraryEditorActionBarContributor getActionBarContributor() {
return (MICOBSLibraryEditorActionBarContributor)getEditorSite().getActionBarContributor();
}
/**
* @generated
*/
public IActionBars getActionBars() {
return getActionBarContributor().getActionBars();
}
/**
* @generated
*/
public AdapterFactory getAdapterFactory() {
return adapterFactory;
}
/**
* @generated
*/
@Override
public void dispose() {
updateProblemIndication = false;
ResourcesPlugin.getWorkspace().removeResourceChangeListener(resourceChangeListener);
getSite().getPage().removePartListener(partListener);
adapterFactory.dispose();
if (getActionBarContributor().getActiveEditor() == this) {
getActionBarContributor().setActiveEditor(null);
}
if (propertySheetPage != null) {
propertySheetPage.dispose();
}
if (contentOutlinePage != null) {
contentOutlinePage.dispose();
}
if (resource != null)
{
resource.eAdapters().remove(resourceListener);
resource.eAdapters().remove(editingDomainProviderAdapter);
}
super.dispose();
}
/**
* Returns whether the outline view should be presented to the user.
* @generated
*/
protected boolean showOutlineView() {
return false;
}
}
|
package com.imcode.imcms.imagearchive.entity;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "categories")
@NamedQuery(name = "availableImageCategoriesAdmin",
query = "SELECT c.id AS id, c.name AS name " +
"FROM Categories c " +
"WHERE c.type.name = 'Images' AND NOT EXISTS " +
"(FROM ImageCategories ic WHERE ic.imageId = :imageId AND ic.categoryId = c.id)")
public class Categories implements Serializable {
private static final long serialVersionUID = 7533187253952781894L;
@Id
@Column(name = "category_id", nullable = false)
@GeneratedValue
private int id;
@Column(name = "category_type_id", nullable = false)
private int typeId;
@ManyToOne
@JoinColumn(name = "category_type_id", referencedColumnName = "category_type_id", insertable = false, updatable = false)
private CategoryTypes type;
@Column(name = "name", length = 128, nullable = false)
private String name;
@Column(name = "description", length = 500)
private String description;
@Column(name = "image", length = 255, nullable = false)
private String image;
public Categories() {
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public CategoryTypes getType() {
return type;
}
public void setType(CategoryTypes type) {
this.type = type;
}
public int getTypeId() {
return typeId;
}
public void setTypeId(int typeId) {
this.typeId = typeId;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Categories other = (Categories) obj;
if (this.id != other.id) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 97 * hash + this.id;
return hash;
}
@Override
public String toString() {
return String.format("Categories[id: %d, typeId: %d, name: %s]",
id, typeId, name);
}
}
|
package com.mpalourdio.html5.config;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.PathResourceResolver;
import org.springframework.web.servlet.resource.TransformedResource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@Configuration
public class SinglePageAppConfig implements WebMvcConfigurer {
private static final String API_PATH = "/api";
|
package com.pesegato.MonkeySheet.batch;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.control.AbstractControl;
public abstract class BGeometryControl extends AbstractControl {
protected BGeometry bgeo;
boolean mustInit = true;
protected BGeometryControl(BGeometry bgeo) {
this.bgeo = bgeo;
}
abstract protected void binit();
abstract protected void bupdate(float tpf);
@Override
protected void controlUpdate(float tpf) {
if (mustInit) {
binit();
mustInit = false;
}
bupdate(tpf);
bgeo.applyTransform();
//duration -= tpf;
//if (duration < 0) {
//setEnabled(false);
}
@Override
public void setEnabled(boolean enabled) {
this.enabled = enabled;
if (!enabled) {
bgeo.removeFromParent();
spatial.removeControl(this);
}
}
@Override
protected void controlRender(RenderManager rm, ViewPort vp) {
}
}
|
package com.opengamma.financial.analytics.parameters;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeSet;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSortedSet;
import com.opengamma.util.test.TestGroup;
import com.opengamma.util.time.Tenor;
/**
* Check that the table of entries is correctly validated.
*/
@Test(groups = TestGroup.UNIT)
public class HullWhiteOneFactorVolatilityTableTest {
@Test(expectedExceptions = IllegalArgumentException.class)
public void tableWithNoEntriesIsNotValid() {
HullWhiteOneFactorVolatilityTable.builder()
.entries(ImmutableSortedSet.<HullWhiteOneFactorVolatilityEntry>of())
.build();
}
// NPE is expected in this case as it is the Guava immutable
// collections throwing within the Joda-beans convert
@Test(expectedExceptions = NullPointerException.class)
public void nullEntryIsNotValid() {
// We have to override the comparator as the one defined for
// HullWhiteOneFactorVolatilityEntry doesn't support nulls
SortedSet<HullWhiteOneFactorVolatilityEntry> entries = new TreeSet<>(
new Comparator<HullWhiteOneFactorVolatilityEntry>() {
@Override
public int compare(HullWhiteOneFactorVolatilityEntry o1, HullWhiteOneFactorVolatilityEntry o2) {
return 0;
}
});
entries.add(null);
HullWhiteOneFactorVolatilityTable.builder()
.entries(entries)
.build();
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void singleEntryWithEndIsNotValid() {
SortedSet<HullWhiteOneFactorVolatilityEntry> entries = ImmutableSortedSet.of(
HullWhiteOneFactorVolatilityEntry.builder()
.startTenor(Tenor.ofDays(0))
.endTenor(Tenor.ofDays(10))
.volatility(1.0)
.build());
HullWhiteOneFactorVolatilityTable.builder()
.entries(entries)
.build();
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void tableWithOverlappingEntriesIsNotValid() {
SortedSet<HullWhiteOneFactorVolatilityEntry> entries = ImmutableSortedSet.of(
HullWhiteOneFactorVolatilityEntry.builder()
.startTenor(Tenor.ofDays(0))
.endTenor(Tenor.ofDays(5))
.volatility(1.0)
.build(),
HullWhiteOneFactorVolatilityEntry.builder()
.startTenor(Tenor.ofDays(3))
.endTenor(Tenor.ofDays(10))
.volatility(2.0)
.build());
HullWhiteOneFactorVolatilityTable.builder()
.entries(entries)
.build();
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void tableWithDisjointEntriesIsNotValid() {
SortedSet<HullWhiteOneFactorVolatilityEntry> entries = ImmutableSortedSet.of(
HullWhiteOneFactorVolatilityEntry.builder()
.startTenor(Tenor.ofDays(0))
.endTenor(Tenor.ofDays(5))
.volatility(1.0)
.build(),
HullWhiteOneFactorVolatilityEntry.builder()
.startTenor(Tenor.ofDays(7))
.endTenor(Tenor.ofDays(10))
.volatility(2.0)
.build());
HullWhiteOneFactorVolatilityTable.builder()
.entries(entries)
.build();
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void tableWithNonZeroStartIsNotValid() {
SortedSet<HullWhiteOneFactorVolatilityEntry> entries = ImmutableSortedSet.of(
HullWhiteOneFactorVolatilityEntry.builder()
.startTenor(Tenor.ofDays(1))
.endTenor(Tenor.ofDays(5))
.volatility(1.0)
.build(),
HullWhiteOneFactorVolatilityEntry.builder()
.startTenor(Tenor.ofDays(5))
.volatility(2.0)
.build());
HullWhiteOneFactorVolatilityTable.builder()
.entries(entries)
.build();
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void tableWithFixedEndIsNotValid() {
SortedSet<HullWhiteOneFactorVolatilityEntry> entries = ImmutableSortedSet.of(
HullWhiteOneFactorVolatilityEntry.builder()
.startTenor(Tenor.ofDays(0))
.endTenor(Tenor.ofDays(5))
.volatility(1.0)
.build(),
HullWhiteOneFactorVolatilityEntry.builder()
.startTenor(Tenor.ofDays(5))
.endTenor(Tenor.ofDays(10))
.volatility(2.0)
.build());
HullWhiteOneFactorVolatilityTable.builder()
.entries(entries)
.build();
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void tableWithEmptyEndTenorInMiddleIsNotValid() {
SortedSet<HullWhiteOneFactorVolatilityEntry> entries = ImmutableSortedSet.of(
HullWhiteOneFactorVolatilityEntry.builder()
.startTenor(Tenor.ofDays(0))
.volatility(1.0)
.build(),
HullWhiteOneFactorVolatilityEntry.builder()
.startTenor(Tenor.ofDays(5))
.endTenor(Tenor.ofDays(10))
.volatility(2.0)
.build());
HullWhiteOneFactorVolatilityTable.builder()
.entries(entries)
.build();
}
@Test
public void singleEntryIsValid() {
SortedSet<HullWhiteOneFactorVolatilityEntry> entries = ImmutableSortedSet.of(
HullWhiteOneFactorVolatilityEntry.builder()
.startTenor(Tenor.ofDays(0))
.volatility(1.0)
.build());
HullWhiteOneFactorVolatilityTable table = HullWhiteOneFactorVolatilityTable.builder()
.entries(entries)
.build();
assertThat(table.getEntries().size(), is(1));
}
@Test
public void initialStartTenorCanUseAnyUnits() {
SortedSet<HullWhiteOneFactorVolatilityEntry> entries = ImmutableSortedSet.of(
HullWhiteOneFactorVolatilityEntry.builder()
.startTenor(Tenor.ofYears(0))
.volatility(1.0)
.build());
HullWhiteOneFactorVolatilityTable table = HullWhiteOneFactorVolatilityTable.builder()
.entries(entries)
.build();
assertThat(table.getEntries().size(), is(1));
}
@Test
public void multipleEntriesAreValid() {
SortedSet<HullWhiteOneFactorVolatilityEntry> entries = ImmutableSortedSet.of(
HullWhiteOneFactorVolatilityEntry.builder()
.startTenor(Tenor.ofDays(0))
.endTenor(Tenor.SIX_MONTHS)
.volatility(1.0)
.build(),
HullWhiteOneFactorVolatilityEntry.builder()
.startTenor(Tenor.SIX_MONTHS)
.endTenor(Tenor.ONE_YEAR)
.volatility(2.0)
.build(),
HullWhiteOneFactorVolatilityEntry.builder()
.startTenor(Tenor.ONE_YEAR)
.endTenor(Tenor.THREE_YEARS)
.volatility(1.0)
.build(),
HullWhiteOneFactorVolatilityEntry.builder()
.startTenor(Tenor.THREE_YEARS)
.endTenor(Tenor.TEN_YEARS)
.volatility(2.0)
.build(),
HullWhiteOneFactorVolatilityEntry.builder()
.startTenor(Tenor.TEN_YEARS)
.volatility(1.0)
.build());
HullWhiteOneFactorVolatilityTable table = HullWhiteOneFactorVolatilityTable.builder()
.entries(entries)
.build();
assertThat(table.getEntries().size(), is(5));
}
}
|
package com.qpark.maven.plugin.flowmapper;
import javax.xml.namespace.QName;
import com.qpark.maven.xmlbeans.ComplexType;
class ComplexContent {
ComplexType ct;
String interfaceClassName = "";
boolean isComplex;
boolean isComplexUUID;
boolean isDefault;
boolean isDirect;
boolean isInterfaceType;
boolean isTabular;
String interfacePackageName;
QName qName;
ComplexContent(final ComplexType ct) {
this.ct = ct;
this.qName = ct.getType().getName();
}
public String getFQInterfaceName() {
return String.format("%s.%s", this.ct.getPackageName(),
this.interfaceClassName).toString();
}
public String getInterfaceName() {
return this.interfaceClassName;
}
ComplexContent setComplex() {
this.isComplex = true;
return this;
}
ComplexContent setComplexUUID() {
this.isComplexUUID = true;
return this;
}
ComplexContent setDefault() {
this.isDefault = true;
return this;
}
ComplexContent setDirect() {
this.isDirect = true;
return this;
}
ComplexContent setInterface() {
this.isInterfaceType = true;
return this;
}
ComplexContent setTabular() {
this.isTabular = true;
return this;
}
}
|
package com.sunny.grokkingalgorithms.gfg.amz;
import com.sunny.grokkingalgorithms.gfg.amz.util.AlgoUtil;
import com.sunny.grokkingalgorithms.gfg.amz.util.BinaryNode;
import java.util.Scanner;
class Node {
int data;
Node left;
Node right;
}
public class BSTChecker {
/**
*
* @param root
* @return
*/
public static boolean checkBST(Node root){
boolean isBST = false;
if(root == null){
isBST = true;
}
else{
int maxLeft = findMaximum(root.left, Integer.MIN_VALUE);
int minRight = findMinimum(root.right, Integer.MAX_VALUE);
if(root.data > maxLeft && root.data < minRight){
isBST = true;
}
else{
isBST = false;
}
isBST = isBST && checkBST(root.left) && checkBST(root.right);
}
return isBST;
}
public static boolean checkBSTOptimized(Node root){
return isBST(root,Integer.MIN_VALUE,Integer.MAX_VALUE);
}
public static boolean isBST(Node root,int min,int max){
if(root == null){
return true;
}
if(root.data <= min || root.data >= max){
return false;
}
return isBST(root.left,min,root.data) && isBST(root.right,root.data,max);
}
/**
*
* @param root
* @return
*/
public static int findMaximum(Node root,int max){
if(root != null){
if(root.data > max){
max = root.data;
}
int left = findMaximum(root.left, max);
max = Math.max(max,left);
int right = findMaximum(root.right, max);
max = Math.max(max,right);
}
return max;
}
/**
*
* @param root
* @return
*/
public static int findMinimum(Node root, int min){
if(root != null){
if(root.data < min){
min = root.data;
}
int left = findMinimum(root.left, min);
min = Math.min(min,left);
int right = findMinimum(root.right, min);
min = Math.min(min, right);
}
return min;
}
}
|
package com.weis.darklaf.components.alignment;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
import java.util.function.BiFunction;
import static com.weis.darklaf.components.alignment.AlignmentHelper.*;
/**
* Alignment for GUI elements.
*
* @author Jannis Weis
* @since 2018
*/
public enum Alignment {
NORTH(AlignmentHelper.align(HOR_CENTER_INSIDE, VERT_TOP_INSIDE),
AlignmentHelper.align(HOR_CENTER_OUTSIDE, VERT_TOP_OUTSIDE), 0
),
SOUTH(AlignmentHelper.align(HOR_CENTER_INSIDE, VERT_BOTTOM_INSIDE),
AlignmentHelper.align(HOR_CENTER_OUTSIDE, VERT_BOTTOM_OUTSIDE), 1
),
EAST(AlignmentHelper.align(HOR_RIGHT_INSIDE, VERT_CENTER_INSIDE),
AlignmentHelper.align(HOR_RIGHT_OUTSIDE, VERT_CENTER_OUTSIDE), 2
),
WEST(AlignmentHelper.align(HOR_LEFT_INSIDE, VERT_CENTER_INSIDE),
AlignmentHelper.align(HOR_LEFT_OUTSIDE, VERT_CENTER_OUTSIDE), 3
),
NORTH_EAST(AlignmentHelper.align(HOR_RIGHT_INSIDE, VERT_TOP_INSIDE),
AlignmentHelper.align(HOR_RIGHT_OUTSIDE, VERT_TOP_OUTSIDE), 4
),
NORTH_WEST(AlignmentHelper.align(HOR_LEFT_INSIDE, VERT_TOP_INSIDE),
AlignmentHelper.align(HOR_LEFT_OUTSIDE, VERT_TOP_OUTSIDE), 5
),
SOUTH_EAST(AlignmentHelper.align(HOR_RIGHT_INSIDE, VERT_BOTTOM_INSIDE),
AlignmentHelper.align(HOR_RIGHT_OUTSIDE, VERT_BOTTOM_OUTSIDE), 6
),
SOUTH_WEST(AlignmentHelper.align(HOR_LEFT_INSIDE, VERT_BOTTOM_INSIDE),
AlignmentHelper.align(HOR_LEFT_OUTSIDE, VERT_BOTTOM_OUTSIDE), 7
),
CENTER(AlignmentHelper.align(HOR_CENTER_INSIDE, VERT_CENTER_INSIDE),
AlignmentHelper.align(HOR_CENTER_OUTSIDE, VERT_CENTER_OUTSIDE), 8
);
private final BiFunction<Dimension, Rectangle, Point> alignInside;
private final BiFunction<Dimension, Rectangle, Point> alignOutside;
private final int index;
@Contract(pure = true)
Alignment(final BiFunction<Dimension, Rectangle, Point> alignInside,
final BiFunction<Dimension, Rectangle, Point> alignOutside,
final int index) {
this.index = index;
this.alignInside = alignInside;
this.alignOutside = alignOutside;
}
/**
* Get fitting alignment.
*
* @param point point to align at.
* @param size Size of rectangle to align.
* @param outerBounds outer boundaries to align in.
* @param hint preferred alignment.
* @return fitting alignment. If none is found wit is defaulted to {@link Alignment#CENTER}.
*/
@NotNull
public static Alignment getAlignment(@NotNull final Point point,
@NotNull final Dimension size,
@NotNull final Rectangle outerBounds,
@NotNull final Alignment hint) {
if (hint.canBeAligned(point, size, outerBounds)) {
return hint;
}
for (var alignment : Alignment.values()) {
if (alignment != CENTER && alignment != hint
&& alignment.canBeAligned(point, size, outerBounds)) {
return alignment;
}
}
return CENTER;
}
/**
* Get the index of the alignment. This function is for utility purposes where one might save
* settings based on alignment in an array.
*
* @return the index.
*/
@Contract(pure = true)
public int getIndex() {
return index;
}
/**
* Get the opposite alignment.
*
* @return Alignment opposite on the compass.
*/
@Contract(pure = true)
@NotNull
@SuppressWarnings("Duplicates")
public Alignment opposite() {
switch (this) {
case NORTH:
return SOUTH;
case NORTH_EAST:
return SOUTH_WEST;
case EAST:
return WEST;
case SOUTH_EAST:
return NORTH_WEST;
case SOUTH:
return NORTH;
case SOUTH_WEST:
return NORTH_EAST;
case WEST:
return EAST;
case NORTH_WEST:
return SOUTH_EAST;
case CENTER:
return CENTER;
default:
throw new IllegalArgumentException();
}
}
@NotNull
@Contract(pure = true)
@SuppressWarnings("Duplicates")
public Alignment anticlockwise() {
switch (this) {
case NORTH:
return NORTH_WEST;
case NORTH_EAST:
return NORTH;
case EAST:
return NORTH_EAST;
case SOUTH_EAST:
return EAST;
case SOUTH:
return SOUTH_EAST;
case SOUTH_WEST:
return SOUTH;
case WEST:
return SOUTH_WEST;
case NORTH_WEST:
return WEST;
case CENTER:
return CENTER;
default:
throw new IllegalArgumentException();
}
}
@NotNull
@Contract(pure = true)
@SuppressWarnings("Duplicates")
public Alignment clockwise() {
switch (this) {
case NORTH:
return NORTH_EAST;
case NORTH_EAST:
return EAST;
case EAST:
return SOUTH_EAST;
case SOUTH_EAST:
return SOUTH;
case SOUTH:
return SOUTH_WEST;
case SOUTH_WEST:
return WEST;
case WEST:
return NORTH_WEST;
case NORTH_WEST:
return NORTH;
case CENTER:
return CENTER;
default:
throw new IllegalArgumentException();
}
}
@NotNull
@Contract(pure = true)
public Insets maskInsets(@NotNull final Insets insets) {
switch (this) {
case NORTH:
return new Insets(insets.top, 0, 0, 0);
case NORTH_EAST:
return new Insets(insets.top, 0, 0, insets.right);
case EAST:
return new Insets(0, 0, 0, insets.right);
case SOUTH_EAST:
return new Insets(0, 0, insets.bottom, insets.right);
case SOUTH:
return new Insets(0, 0, insets.bottom, 0);
case SOUTH_WEST:
return new Insets(0, insets.left, insets.bottom, 0);
case WEST:
return new Insets(0, insets.left, 0, 0);
case NORTH_WEST:
return new Insets(insets.top, insets.left, 0, 0);
case CENTER:
return new Insets(0, 0, 0, 0);
default:
throw new IllegalArgumentException();
}
}
/**
* Get the relative Position of Rectangle to Point with respect to the alignment.
*
* @param toAlign size of Rectangle to align.
* @param alignAt point to align at.
* @return top/left position of aligned rectangle
*/
public Point relativePos(@NotNull final Dimension toAlign, @NotNull final Point alignAt) {
return alignOutside(toAlign, new Rectangle(alignAt.x, alignAt.y, 0, 0));
}
/**
* Check whether the given Rectangle can be aligned at point inside boundaries.
*
* @param point point to align at.
* @param size size of rectangle to align.
* @param outerBounds boundaries.
* @return true if can be aligned.
*/
public boolean canBeAligned(@NotNull final Point point,
@NotNull final Dimension size,
@NotNull final Rectangle outerBounds) {
var p = relativePos(size, point);
return p.x >= outerBounds.x && p.y >= outerBounds.y
&& p.x + size.width < outerBounds.x + outerBounds.width
&& p.y + size.height < outerBounds.x + outerBounds.height;
}
/**
* Align Rectangle inside other rectangle with respect to the alignment.
*
* @param toAlign size of rectangle to align
* @param outerBounds bounds of outer rectangle
* @return top/left point of aligned rectangle
*/
public Point alignInside(@NotNull final Dimension toAlign,
@NotNull final Rectangle outerBounds) {
return this.alignInside.apply(toAlign, outerBounds);
}
/**
* Align Rectangle outside other rectangle with respect to the alignment.
*
* @param toAlign size of rectangle to align
* @param innerBounds bounds of inside rectangle
* @return top/left point of aligned rectangle
*/
public Point alignOutside(@NotNull final Dimension toAlign,
@NotNull final Rectangle innerBounds) {
return this.alignOutside.apply(toAlign, innerBounds);
}
}
|
package daxum.temporalconvergence.tileentity;
import java.util.ArrayList;
import java.util.List;
import daxum.temporalconvergence.recipes.DimGenRecipes;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.ItemStackHandler;
public class TileDimGen extends TileEntity implements ITickable {
protected ItemStackHandler inventory = new SingleInventory(this);
protected BlockPos[] pedLocs = new BlockPos[12];
protected BlockPos prevPos = BlockPos.ORIGIN;
protected AxisAlignedBB fullClock;
protected AxisAlignedBB smallClock;
protected boolean crafting = false;
protected boolean done = false;
protected boolean successful = false;
protected boolean isLinkRecipe = false;
protected int craftTicks = 0;
protected List<ItemStack> currentRecipe = new ArrayList<>();
public float scale = 1.0f;
public float prevScale = 1.0f;
public float[] rotations = {0.0f, 0.0f, 0.0f, 0.0f}; //Face, hour, minute, second
public float[] prevRotations = {0.0f, 0.0f, 0.0f, 0.0f};
@Override
public void update() {
if (!prevPos.equals(pos))
onLoad(); //Just in case
prevScale = scale;
for (int i = 0; i < rotations.length; i++) {
prevRotations[i] = rotations[i];
}
if (crafting) {
if (scale < 15.0f && !done) {
if (!world.isRemote) {
List<ItemStack> stacks = getInputs();
if (!shouldCraft(stacks, false)) {
done = true;
sendBlockUpdate();
}
}
scale += 0.2f;
if (scale > 15.0f) {
scale = 15.0f;
craftTicks = 400;
clearPedestals();
}
setTime(1);
}
else if (scale >= 15.0f && !done) {
if (!world.isRemote && !ItemStack.areItemStacksEqual(inventory.getStackInSlot(0), currentRecipe.get(0))) {
done = true;
sendBlockUpdate();
}
else {
setTime(2);
craftTicks
if (craftTicks <= 0) {
done = true;
successful = true;
if (!world.isRemote)
sendBlockUpdate();
}
}
}
else if (done) {
scale -= 0.2f;
if (scale < 1.0f)
scale = 1.0f;
setTime(3);
if (scale == 1.0f) {
crafting = false;
done = false;
if (currentRecipe.size() > 1 && successful && !world.isRemote) {
if (isLinkRecipe) {
inventory.setStackInSlot(0, DimGenRecipes.getNewDimLink(world, currentRecipe));
isLinkRecipe = false;
}
else
inventory.setStackInSlot(0, DimGenRecipes.getOutput(currentRecipe.get(0), currentRecipe.subList(1, currentRecipe.size())));
successful = false;
}
currentRecipe.clear();
}
}
}
else {
setTime(0);
}
}
//0-not crafting, 1-spinup, 2-crafting, 3-spindown. Only executed on client.
protected void setTime(int stage) {
if (world.isRemote) {
if (stage == 0) {
rotations[0] = 0.0f; //Not sure why this sometimes isn't set right
rotations[1] = (world.getWorldTime() + 6000) % 12000 / 12000.0f * 360.0f;
rotations[2] = rotations[1] % 30.0f / 30.0f * 360.0f;
rotations[3] = rotations[2] % 30.0f / 30.0f * 360.0f;
for (int i = 1; i < rotations.length; i++) {
if (rotations[i] < prevRotations[i])
prevRotations[i] -= 360.0;
}
}
else if (stage == 1) {
rotations[0] = 720.0f * ((scale - 1) / 14.0f);
if (rotations[0] >= 720.0f)
rotations[0] = 720.0f;
for (int i = 1; i < rotations.length; i++)
rotations[i] = 360.0f * (i + 3) * (rotations[0] / 720.0f);
}
else if (stage == 2) {
rotations[0] = 720.0f;
rotations[1] = (400.0f - craftTicks) / 400.0f * 360.0f + 1440;
rotations[2] = 1800.0f + (400.0f - craftTicks) / 400.0f * 5040.0f;
rotations[3] = 7200.0f - (400.0f - craftTicks) / 400.0f * 5040.0f;
if (rotations[3] == 7200.0f)
prevRotations[3] += 5040.0f;
if (rotations[1] >= 1800.0f) {
rotations[1] = 1440.0f;
rotations[2] = 1800.0f;
rotations[3] = 2160.0f;
prevRotations[1] -= 360.0f;
prevRotations[3] -= 5040.0f;
}
}
else if (stage == 3) {
rotations[0] = 720.0f * ((scale - 1) / 14.0f);
if (rotations[0] <= 0.0f)
rotations[0] = 0.0f;
for (int i = 1; i < rotations.length; i++)
rotations[i] = 360.0f * (i + 3) * (rotations[0] / 720.0f);
}
}
}
public void setCrafting() {
if (!world.isRemote && !crafting) {
List<ItemStack> stacks = getInputs();
if (shouldCraft(stacks, true)) {
crafting = true;
currentRecipe = stacks;
sendBlockUpdate();
}
}
}
protected boolean shouldCraft(List<ItemStack> stacks, boolean setLinkRecipe) {
if (validatePedestals()) {
if (!isLinkRecipe && stacks.size() >= 2 && DimGenRecipes.isValid(stacks.get(0), stacks.subList(1, stacks.size())) && checkAmount(stacks.size() - 1)) {
return true;
}
else if (stacks.size() > 1 && DimGenRecipes.isValidDimLink(stacks)) {
if (setLinkRecipe) //I know what you want to do here. Don't do it. Move along.
isLinkRecipe = true;
return true;
}
}
return false;
}
public boolean validatePedestals() {
for (int i = 0; i < pedLocs.length; i++)
if (!(world.getTileEntity(pedLocs[i]) instanceof TilePedestal)) //Should I check if the chunk is loaded?
return false;
return true;
}
public List<ItemStack> getInputs() {
List<ItemStack> inputs = new ArrayList<>();
inputs.add(inventory.getStackInSlot(0));
for (int i = 0; i < pedLocs.length; i++) {
ItemStack stack = getSpot(pedLocs[i]);
if (!stack.isEmpty())
inputs.add(stack);
}
return inputs;
}
public boolean checkAmount(int amount) {
switch (amount) {
case 2: if (getSpot(pedLocs[1]) != ItemStack.EMPTY && getSpot(pedLocs[3]) != ItemStack.EMPTY //East and west
|| getSpot(pedLocs[0]) != ItemStack.EMPTY && getSpot(pedLocs[2]) != ItemStack.EMPTY) return true; else break; //North and south
case 4: if (getSpot(pedLocs[0]) != ItemStack.EMPTY && getSpot(pedLocs[1]) != ItemStack.EMPTY
&& getSpot(pedLocs[2]) != ItemStack.EMPTY && getSpot(pedLocs[3]) != ItemStack.EMPTY) return true; else break; //North, south, east, and west
case 8: if (getSpot(pedLocs[0]).isEmpty() && getSpot(pedLocs[1]).isEmpty()
&& getSpot(pedLocs[2]).isEmpty() && getSpot(pedLocs[3]).isEmpty()) return true; else break; //Not four
case 12: return true;
}
return false;
}
protected ItemStack getSpot(BlockPos position) {
if (world.getTileEntity(position) instanceof TilePedestal)
return ((TilePedestal)world.getTileEntity(position)).getInventory().getStackInSlot(0).copy();
return ItemStack.EMPTY;
}
protected void clearPedestals() {
if (world.isRemote) return;
for (int i = 0; i < pedLocs.length; i++)
clearPedestal(pedLocs[i]);
}
protected void clearPedestal(BlockPos position) {
if (world.getTileEntity(position) instanceof TilePedestal)
((TilePedestal)world.getTileEntity(position)).getInventory().setStackInSlot(0, ItemStack.EMPTY);
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound comp) {
comp.setTag("inv", inventory.serializeNBT());
comp.setBoolean("craft", crafting);
comp.setBoolean("done", done);
comp.setBoolean("success", successful);
comp.setBoolean("linkrecipe", isLinkRecipe);
comp.setFloat("scale", scale);
comp.setInteger("ctick", craftTicks);
if (crafting)
for (int i = 0; i < currentRecipe.size(); i++)
comp.setTag("cur" + i, currentRecipe.get(i).serializeNBT());
return super.writeToNBT(comp);
}
@Override
public void readFromNBT(NBTTagCompound comp) {
if (comp.hasKey("inv"))
inventory.deserializeNBT(comp.getCompoundTag("inv"));
if (comp.hasKey("craft"))
crafting = comp.getBoolean("craft");
if (comp.hasKey("done"))
done = comp.getBoolean("done");
if (comp.hasKey("scale"))
scale = comp.getFloat("scale");
if (comp.hasKey("success"))
successful = comp.getBoolean("success");
if (comp.hasKey("linkrecipe"))
isLinkRecipe = comp.getBoolean("linkrecipe");
if (comp.hasKey("ctick"))
craftTicks = comp.getInteger("ctick");
currentRecipe.clear();
for (int i = 0; i < 13; i++) {
if (!comp.hasKey("cur" + i))
break;
currentRecipe.add(new ItemStack((NBTTagCompound) comp.getTag("cur" + i)));
}
super.readFromNBT(comp);
}
@Override
public SPacketUpdateTileEntity getUpdatePacket() {
NBTTagCompound comp = new NBTTagCompound();
comp = writeToNBT(comp);
return new SPacketUpdateTileEntity(pos, -42, comp);
}
@Override
public NBTTagCompound getUpdateTag() {
return writeToNBT(new NBTTagCompound());
}
@Override
public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) {
readFromNBT(pkt.getNbtCompound());
}
@Override
public boolean hasCapability(Capability<?> cap, EnumFacing face) {
return cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY || super.hasCapability(cap, face);
}
@Override
public <T> T getCapability (Capability<T> cap, EnumFacing face) {
return cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY ? (T)inventory : super.getCapability(cap, face);
}
public ItemStackHandler getInventory() {
return inventory;
}
@Override
public AxisAlignedBB getRenderBoundingBox() {
if (scale > 1.0f)
return fullClock;
return smallClock;
}
@Override
public void onLoad() {
//Why didn't this work before, and why did it randomly start working?
fullClock = new AxisAlignedBB(pos.add(-6, 0, -6), pos.add(6, 1, 6));
smallClock = new AxisAlignedBB(pos, pos.add(1, 1, 1));
//Cache pedestal locations
pedLocs[0] = pos.north(6);
pedLocs[1] = pos.east(6);
pedLocs[2] = pos.south(6);
pedLocs[3] = pos.west(6);
pedLocs[4] = pos.add(5, 0, 3);
pedLocs[5] = pos.add(5, 0, -3);
pedLocs[6] = pos.add(-5, 0, 3);
pedLocs[7] = pos.add(-5, 0, -3);
pedLocs[8] = pos.add(3, 0, 5);
pedLocs[9] = pos.add(3, 0, -5);
pedLocs[10] = pos.add(-3, 0, 5);
pedLocs[11] = pos.add(-3, 0, -5);
prevPos = pos;
}
public static class SingleInventory extends ItemStackHandler {
private final TileDimGen parent;
public SingleInventory(TileDimGen tp) {
super();
parent = tp;
}
@Override
public int getSlotLimit(int slot) {
return 1;
}
@Override
protected void onContentsChanged(int slot) {
parent.sendBlockUpdate();
}
}
public void sendBlockUpdate() {
if (!world.isRemote) {
world.notifyBlockUpdate(pos, world.getBlockState(pos), world.getBlockState(pos), 8);
markDirty();
}
}
}
|
package test;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;
import static play.test.Helpers.fakeApplication;
import static play.test.Helpers.inMemoryDatabase;
import org.junit.After;
import org.junit.Before;
import org.mockito.Mockito;
import play.test.FakeApplication;
import play.test.Helpers;
import plugins.GuicePlugin;
import plugins.S3Plugin;
import com.amazonaws.services.s3.AmazonS3Client;
public class BaseTest {
protected FakeApplication app;
protected <T> T mock(Class<T> type) {
T m = Mockito.mock(type);
return m;
}
protected <T> T getInstance(Class<T> type) {
GuicePlugin guice = GuicePlugin.getInstance();
T t = guice.getInstance(type);
return t;
}
@Before
public void startApp() {
S3Plugin.amazonS3 = Mockito.mock(AmazonS3Client.class);
when(S3Plugin.amazonS3.doesBucketExist(anyString())).thenReturn(true);
if (app == null)
app = fakeApplication(inMemoryDatabase());
Helpers.start(app);
}
@After
public void stopApp() {
Helpers.stop(app);
app = null;
}
}
|
package eg;
import java.util.Locale;
import java.awt.EventQueue;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
//--Eadgyth--/
import eg.ui.MainWin;
import eg.ui.ViewSettingWin;
import eg.utils.FileUtils;
/**
* Contains the main method
* <p>
* @version 1.0 beta
* @author Malte Bussiek, m.bussiek@web.de
*/
public class Eadgyth {
public static void main(String[] arg) {
Locale.setDefault(Locale.US);
uiManagerSettings();
setLaf();
MainWin mw = new MainWin();
ViewSettingWin viewSetWin = new ViewSettingWin();
ViewSetter viewSet = new ViewSetter(viewSetWin, mw);
EditAreaFormat format = new EditAreaFormat(viewSetWin);
TabbedFiles tabFiles = new TabbedFiles(format, mw);
mw.setFileActions(tabFiles);
mw.setViewSettingWinAction(viewSetWin);
mw.setFormatActions(format);
viewSetWin.setOkAct(e -> {
viewSet.applySetWinOk();
format.applySetWinOk();
viewSetWin.makeVisible(false);
});
EventQueue.invokeLater(() -> {
mw.makeVisible();
tabFiles.openEmptyTab();
});
}
private static void uiManagerSettings() {
UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE);
UIManager.put("Menu.font", Constants.SANSSERIF_PLAIN_9);
UIManager.put("MenuItem.font", Constants.SANSSERIF_PLAIN_9);
UIManager.put("CheckBoxMenuItem.font", Constants.SANSSERIF_PLAIN_9);
UIManager.put("SplitPaneDivider.border", new EmptyBorder(0, 0, 0, 0));
UIManager.put("Tree.rowHeight", eg.utils.ScreenParams.scaledSize(14));
}
private static void setLaf() {
Preferences prefs = new Preferences();
prefs.readPrefs();
if ("System".equals(prefs.getProperty("LaF"))) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (ClassNotFoundException
| IllegalAccessException
| InstantiationException
| UnsupportedLookAndFeelException e) {
FileUtils.logStack(e);
}
}
}
}
|
package de.learnlib.weblearner.rest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Proxy class needed to workaround some 'iframe' restrictions when working with multiple domains.
* @exclude
* @resourcePath Proxy for IFrame
*/
@Path("proxy")
public class IFrameProxyResource {
/** Use the logger for the server part. */
private static final Logger LOGGER = LogManager.getLogger("server");
/** Get the UriInfo from the Context. */
@Context
private UriInfo uriInfo;
/**
* Method used to pretend the requested site has our domain.
*
* @param url
* The URL of the requested page.
* @return The requested page, modified to fit our needs.
*/
@GET
@Produces(MediaType.TEXT_HTML)
public Response doGetProxy(@QueryParam("url") String url, @HeaderParam("Cookie") String cookies) {
try {
Connection connection = Jsoup.connect(url);
connection = parseAndProcessCookies(connection, cookies);
connection = connection.method(Connection.Method.GET);
return createResponse(connection);
} catch (IllegalArgumentException e) { // Java 1.6 has no multi catch
LOGGER.info("Bad URL: {}", url);
LOGGER.info(e);
return Response.status(Status.BAD_REQUEST).entity("400 - Bad Request: Unknown URL").build();
} catch (IOException e) {
LOGGER.info("Bad request type: {}", url);
LOGGER.info(e);
return Response.status(Status.BAD_REQUEST).entity("400 - Bad Request: Unknown request type").build();
}
}
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
public Response doPostProxy(@QueryParam("url") String url, @HeaderParam("Cookie") String cookies, MultivaluedMap<String, String> body) {
try {
Connection connection = Jsoup.connect(url);
connection = parseAndProcessCookies(connection, cookies);
connection = parseAndProcessFormData(connection, body);
connection = connection.method(Connection.Method.POST);
return createResponse(connection);
} catch (IllegalArgumentException e) {
LOGGER.info("Bad URL: {}", url);
LOGGER.info(e);
return Response.status(Status.BAD_REQUEST).entity("400 - Bad Request: Unknown URL").build();
} catch (IOException e) {
LOGGER.info("Bad request type: {}", url);
LOGGER.info(e);
return Response.status(Status.BAD_REQUEST).entity("400 - Bad Request: Unknown request type").build();
}
}
private Connection parseAndProcessCookies(Connection connection, String cookies) {
if (cookies == null) {
return connection;
}
for (String cookie : cookies.split(";")) {
String[] keyValuePair = cookie.split("=");
String key = keyValuePair[0].trim();
String value = keyValuePair[1].trim();
connection = connection.cookie(key, value);
}
return connection;
}
private Connection parseAndProcessFormData(Connection connection, MultivaluedMap<String, String> body) {
for (String key : body.keySet()) {
List<String> values = body.get(key);
for (String value : values) {
connection = connection.data(key, value);
}
}
return connection;
}
private Response createResponse(Connection connection) throws IOException {
Connection.Response response = connection.execute();
Document doc = response.parse();
proxiefy(doc);
List<NewCookie> cookieList = new LinkedList<>();
response.cookies().forEach((key, value) -> cookieList.add(new NewCookie(key, value)));
NewCookie[] cookiesAsArray = cookieList.toArray(new NewCookie[cookieList.size()]);
return Response.status(response.statusCode()).cookie(cookiesAsArray).entity(doc.html()).build();
}
/**
* Changes all references to other sites, images, ... in one Document to an absolute path or to a path using this
* proxy.
*
* @param doc
* The Document to change.
*/
private void proxiefy(Document doc) {
// make references from elements with a 'src' attribute absolute
for (Element style : doc.select("img, script")) {
absolutifyURL(style, "src");
}
// make references from elements with a 'href' attribute absolute
for (Element link : doc.select("link")) {
absolutifyURL(link, "href");
}
// links should use this proxy
for (Element link : doc.getElementsByTag("a")) {
proxiefy(link, "href");
}
// forms
for (Element form : doc.getElementsByTag("form")) {
proxiefy(form, "action");
}
}
/**
* Changes an URL in one attribute of an element to an absolute path. Is 'absolutify a real word?
*
* @param elem
* The Element having the relative attribute.
* @param attribute
* The Attribute to change.
*/
private void absolutifyURL(Element elem, String attribute) {
String url = elem.attr(attribute);
if (!url.isEmpty()) {
elem.attr(attribute, elem.absUrl(attribute));
}
}
/**
* Changes the 'href' attribute of a link to a version which uses this proxy. Is 'proxiefy' a real word?
*
* @param elem
* The Link-Element to proxiefy.
* @param attribute
* The Attribute to change.
*/
private void proxiefy(Element elem, String attribute) {
try {
String originalReference = elem.attr(attribute);
if (!originalReference.startsWith("
absolutifyURL(elem, attribute);
elem.attr(attribute, uriInfo.getAbsolutePath() + "?url=" + URLEncoder.encode(elem.attr(attribute), "UTF-8"));
}
} catch (UnsupportedEncodingException e) {
// should never happen
LOGGER.error("Could not encode the URL because of an unsupported encoding", e);
}
}
}
|
package de.retest.recheck.review.ignore;
import static java.lang.Float.parseFloat;
import static java.lang.Math.abs;
import static java.lang.Math.min;
import static java.lang.Math.round;
import java.awt.Color;
import java.io.Serializable;
import java.util.Optional;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import de.retest.recheck.ignore.Filter;
import de.retest.recheck.review.ignore.io.RegexLoader;
import de.retest.recheck.ui.descriptors.Element;
import de.retest.recheck.ui.diff.AttributeDifference;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
@Getter
@Slf4j
public class ColorDiffFilter implements Filter {
private static final Pattern RGB = Pattern.compile( "rgb\\((\\d+),\\s?(\\d+),\\s?(\\d+)(,\\s?(\\d+))?\\)" );
private static final double MAX_DISTANCE = 255.0;
private final String givenInput;
private final double colorDiff;
public ColorDiffFilter( final String givenInput, final double colorDiff ) {
this.givenInput = givenInput;
this.colorDiff = colorDiff;
}
@Override
public boolean matches( final Element element ) {
return false;
}
@Override
public boolean matches( final Element element, final AttributeDifference attributeDifference ) {
final Color expected = parse( attributeDifference.getExpected() );
final Color actual = parse( attributeDifference.getActual() );
if ( expected == null || actual == null ) {
return false;
}
final double distance = calculateColorDistance( expected, actual ) * 100;
return distance < colorDiff;
}
/**
* Return the color distance as a value in the range of [0.0, 1.0]. Note this is about perception: any one of the
* rgba values is reviewed in isolation, as a change from e.g. white to red or green to yellow already constitutes a
* 100% change in the perceived color.
*/
static double calculateColorDistance( final Color expected, final Color actual ) {
final double redDiff = abs( expected.getRed() - actual.getRed() );
final double greenDiff = abs( expected.getGreen() - actual.getGreen() );
final double blueDiff = abs( expected.getBlue() - actual.getBlue() );
final double alphaDiff = abs( expected.getAlpha() - actual.getAlpha() );
// min so we don't exceed max_distance
final double distance = min( redDiff + greenDiff + blueDiff + alphaDiff, 255 );
return distance / MAX_DISTANCE;
}
static Color parse( final Serializable input ) {
if ( input == null || !(input instanceof String) ) {
return null;
}
final String color = (String) input;
if ( color.startsWith( "
return Color.decode( color );
}
final Matcher matcher = RGB.matcher( color );
if ( !matcher.find() ) {
return null;
}
try {
final String red = matcher.group( 1 );
final String green = matcher.group( 2 );
final String blue = matcher.group( 3 );
final String alpha = matcher.group( 5 );
if ( alpha != null ) {
return new Color( round( parseFloat( red ) ), round( parseFloat( green ) ), round( parseFloat( blue ) ),
round( parseFloat( alpha ) ) );
}
return new Color( round( parseFloat( red ) ), round( parseFloat( green ) ), round( parseFloat( blue ) ) );
} catch ( final Exception e ) {
log.debug( "Error parsing input {} to color: ", input, e );
return null;
}
}
@Override
public String toString() {
return String.format( ColorDiffFilterLoader.FORMAT, givenInput );
}
public static class ColorDiffFilterLoader extends RegexLoader<ColorDiffFilter> {
private static final String KEY = "color-diff=";
private static final String FORMAT = KEY + "%s";
private static final Pattern REGEX = Pattern.compile( KEY + "(\\d+(\\.\\d+)?)(\\%)?" );
public ColorDiffFilterLoader() {
super( REGEX );
}
@Override
protected Optional<ColorDiffFilter> load( final MatchResult regex ) {
final String value = regex.group( 1 );
final double colorDiff = Double.parseDouble( value );
return Optional.of( new ColorDiffFilter( value, colorDiff ) );
}
}
}
|
package de.tum.in.www1.exerciseapp.domain;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;
/**
* A LtiOutcomeUrl.
*/
@Entity
@Table(name = "lti_outcome_url")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class LtiOutcomeUrl implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "url")
private String url;
@Column(name = "sourced_id")
private String sourcedId;
@ManyToOne
private User user;
@ManyToOne
private Exercise exercise;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getSourcedId() {
return sourcedId;
}
public void setSourcedId(String sourcedId) {
this.sourcedId = sourcedId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Exercise getExercise() {
return exercise;
}
public void setExercise(Exercise exercise) {
this.exercise = exercise;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LtiOutcomeUrl ltiOutcomeUrl = (LtiOutcomeUrl) o;
if(ltiOutcomeUrl.id == null || id == null) {
return false;
}
return Objects.equals(id, ltiOutcomeUrl.id);
}
@Override
public int hashCode() {
return Objects.hashCode(id);
}
@Override
public String toString() {
return "LtiOutcomeUrl{" +
"id=" + id +
", url='" + url + "'" +
", sourcedId='" + sourcedId + "'" +
'}';
}
}
|
package eu.h2020.symbiote.security.services;
import eu.h2020.symbiote.security.commons.Certificate;
import eu.h2020.symbiote.security.commons.SecurityConstants;
import eu.h2020.symbiote.security.commons.enums.IssuingAuthorityType;
import eu.h2020.symbiote.security.commons.exceptions.custom.AAMException;
import eu.h2020.symbiote.security.commons.exceptions.custom.InvalidArgumentsException;
import eu.h2020.symbiote.security.communication.AAMClient;
import eu.h2020.symbiote.security.communication.IAAMClient;
import eu.h2020.symbiote.security.communication.payloads.AAM;
import eu.h2020.symbiote.security.repositories.ComponentCertificatesRepository;
import eu.h2020.symbiote.security.repositories.PlatformRepository;
import eu.h2020.symbiote.security.repositories.entities.ComponentCertificate;
import eu.h2020.symbiote.security.repositories.entities.Platform;
import eu.h2020.symbiote.security.services.helpers.CertificationAuthorityHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
@Service
public class AAMServices {
private final CertificationAuthorityHelper certificationAuthorityHelper;
private final PlatformRepository platformRepository;
private final ComponentCertificatesRepository componentCertificatesRepository;
private final String coreInterfaceAddress;
private final String platformAAMSuffixAtInterWorkingInterface;
@Autowired
public AAMServices(CertificationAuthorityHelper certificationAuthorityHelper,
PlatformRepository platformRepository,
ComponentCertificatesRepository componentCertificatesRepository,
@Value("${symbIoTe.core.interface.url}") String coreInterfaceAddress,
@Value("${aam.environment.platformAAMSuffixAtInterWorkingInterface:/paam}") String platformAAMSuffixAtInterWorkingInterface) {
this.certificationAuthorityHelper = certificationAuthorityHelper;
this.platformRepository = platformRepository;
this.componentCertificatesRepository = componentCertificatesRepository;
this.coreInterfaceAddress = coreInterfaceAddress;
this.platformAAMSuffixAtInterWorkingInterface = platformAAMSuffixAtInterWorkingInterface;
}
public Map<String, AAM> getAvailableAAMs() throws
NoSuchProviderException,
KeyStoreException,
IOException,
CertificateException,
NoSuchAlgorithmException {
Map<String, AAM> availableAAMs = new TreeMap<>();
if (certificationAuthorityHelper.getDeploymentType() == IssuingAuthorityType.CORE) {
// if Core AAM then we know the available AAMs
Certificate coreCertificate = new Certificate(certificationAuthorityHelper.getAAMCert());
// adding core aam info to the response
availableAAMs.put(SecurityConstants.CORE_AAM_INSTANCE_ID, new AAM(coreInterfaceAddress,
SecurityConstants.CORE_AAM_FRIENDLY_NAME,
SecurityConstants.CORE_AAM_INSTANCE_ID,
coreCertificate, fillComponentCertificatesMap()));
// registered platforms' AAMs
for (Platform platform : platformRepository.findAll()) {
AAM platformAAM = new AAM(platform.getPlatformInterworkingInterfaceAddress() + platformAAMSuffixAtInterWorkingInterface, platform.getPlatformInstanceFriendlyName(), platform
.getPlatformInstanceId(), platform.getPlatformAAMCertificate(), platform.getComponentCertificates());
// add the platform AAM entry point to the results
availableAAMs.put(platformAAM.getAamInstanceId(), platformAAM);
}
} else {
// a PAAM needs to fetch them from core
IAAMClient aamClient = new AAMClient(coreInterfaceAddress);
availableAAMs = aamClient.getAvailableAAMs().getAvailableAAMs();
String deploymentId = certificationAuthorityHelper.getAAMInstanceIdentifier();
AAM aam = availableAAMs.get(deploymentId);
aam.setComponentCertificates(fillComponentCertificatesMap());
}
return availableAAMs;
}
private Map<String, Certificate> fillComponentCertificatesMap() {
Map<String, Certificate> componentsCertificatesMap = new HashMap<>();
List<ComponentCertificate> componentCertificatesFromRepository = componentCertificatesRepository.findAll();
for (ComponentCertificate certificate : componentCertificatesFromRepository) {
componentsCertificatesMap.put(certificate.getName(), certificate.getCertificate());
}
return componentsCertificatesMap;
}
public String getComponentCertificate(String componentIdentifier, String platformIdentifier) throws
NoSuchAlgorithmException,
CertificateException,
NoSuchProviderException,
KeyStoreException,
IOException,
AAMException,
InvalidArgumentsException {
String deploymentId = certificationAuthorityHelper.getAAMInstanceIdentifier();
// our platform case
if (platformIdentifier.equals(deploymentId)) {
if (componentIdentifier.equals(SecurityConstants.AAM_COMPONENT_NAME))
return certificationAuthorityHelper.getAAMCert();
if (!componentCertificatesRepository.exists(componentIdentifier))
throw new InvalidArgumentsException("Component doesn't exist in this platform");
return componentCertificatesRepository.findOne(componentIdentifier).getCertificate().getCertificateString();
}
// not our platform
Map<String, AAM> availableAAMs = getAvailableAAMs();
if (availableAAMs.containsKey(platformIdentifier)) {
AAM aam = availableAAMs.get(platformIdentifier);
if (componentIdentifier.equals(SecurityConstants.AAM_COMPONENT_NAME)) {
// AAM cert can be fetched without contacting the platform AAM itself
return aam.getAamCACertificate().getCertificateString();
} else {
IAAMClient aamClient = new AAMClient(aam.getAamAddress());
return aamClient.getComponentCertificate(componentIdentifier, platformIdentifier);
}
}
throw new AAMException("Selected certificate could not be found/retrieved");
}
}
|
package eu.scape_project.pt.executors;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.Text;
import eu.scape_project.pt.fs.util.Filer;
import eu.scape_project.pt.proc.FileProcessor;
/**
* Executes a Taverna workflow using the Taverna shell script from the installation.
*
* @author Martin Schenck [schenck]
*
*/
public class TavernaCLExecutor implements Executor {
private static Log LOG = LogFactory.getLog(TavernaCLExecutor.class);
// Locations of the Taverna installation and the workflow
private String tavernaHome;
private String workflowLocation;
private String resultOutDir;
// File processor to get temporary input files
FileProcessor fileProcessor;
// Taverna output directory
private String tavernaOutput;
public TavernaCLExecutor(String tavernaHome, String workflowLocation, String resultOutDir) {
this.tavernaHome = tavernaHome;
this.workflowLocation = workflowLocation;
this.resultOutDir = resultOutDir;
}
@Override
public void setup() {
// Add trailing slash if missing to given directories
if(tavernaHome != null && !tavernaHome.endsWith(File.separator))
tavernaHome += File.separator;
if(!resultOutDir.endsWith(File.separator))
resultOutDir += File.separator;
}
@Override
public void map(Object key, Text value) throws IOException {
// Also get a local copy of the workflow
StringBuilder stringBuilder = new StringBuilder(value.toString());
stringBuilder.append(" ");
stringBuilder.append(workflowLocation);
// Split input to find file handles with the file processor
String[] values = stringBuilder.toString().split(" ");
// Create a file processor and assign the hdfs
FileSystem hdfs = FileSystem.get(new Configuration());
FileProcessor fileProcessor = new FileProcessor(values);
fileProcessor.setHadoopFS(hdfs);
// Retrieve all files
try {
fileProcessor.resolvePrecondition();
} catch(Exception e) {
LOG.error("Exception in preprocessing phase: " + e.getMessage(), e);
e.printStackTrace();
}
// Replace all file handles with the temporary local ones
Map<String, String> retrievedFiles = fileProcessor.getRetrievedFiles();
String workflowInput = value.toString();
for(String retrievedFile : retrievedFiles.keySet()) {
workflowInput = workflowInput.replaceAll(retrievedFile,
retrievedFiles.get(retrievedFile));
}
// Workflow
try {
LOG.info("Starting workflow with input: " + workflowInput);
// The list of command and arguments for the process builder
List<String> command = new ArrayList<String>();
// Taverna from path or given directory?
if(tavernaHome == null) {
command.add("executeworkflow.sh");
} else {
command.add("sh");
command.add(tavernaHome + "executeworkflow.sh");
}
List<String> inputList = new ArrayList<String>();
for(String input : workflowInput.split(" ")) {
inputList.add(input);
}
command.addAll(inputList);
command.add(retrievedFiles.get(workflowLocation));
ProcessBuilder processBuilder = new ProcessBuilder(command);
Process process = processBuilder.start();
// Read the Streams
InputStream errorStream = process.getErrorStream();
InputStream outStream = process.getInputStream();
// FIXME needs time out, but uncertain how long a workflow can run. Hours?!
process.waitFor();
// Output the streams
outputStream(errorStream);
outputStream(outStream);
} catch (Exception e) {
LOG.error("Could not run workflow: " + e.getMessage(), e);
e.printStackTrace();
}
// Write the results to the corresponding directory
try {
Filer filer = fileProcessor.getFiler(resultOutDir);
filer.depositDirectoryOrFile(tavernaOutput, resultOutDir + UUID.randomUUID() + File.separator);
} catch (URISyntaxException e) {
LOG.error("Could not create filer for URI syntax: " + resultOutDir);
e.printStackTrace();
}
}
private void outputStream(InputStream stream) {
BufferedReader bufferedStream = null;
try {
bufferedStream = new BufferedReader(new InputStreamReader(stream));
String line;
while((line = bufferedStream.readLine()) != null) {
LOG.info("Taverna: " + line);
// Get Taverna output directory
if(line.startsWith("Outputs will be saved to the directory:"))
tavernaOutput = line.substring(40);
}
} catch (IOException e) {
LOG.error("Error while outputting stream from Taverna process.");
e.printStackTrace();
} finally {
try { bufferedStream.close(); } catch (Exception e) { /* ignore */ }
}
}
}
|
package falgout.jrepl.command.execute;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ExpressionStatement;
import org.eclipse.jdt.core.dom.Statement;
import org.eclipse.jdt.core.dom.VariableDeclarationStatement;
import com.google.inject.Inject;
import falgout.jrepl.Environment;
import falgout.jrepl.LocalVariable;
import falgout.jrepl.command.execute.codegen.CodeExecutor;
import falgout.jrepl.command.execute.codegen.GeneratedMethod;
import falgout.jrepl.command.execute.codegen.SourceCode;
import falgout.jrepl.guice.MethodExecutorFactory;
import falgout.util.Optionals;
public class StatementExecutor extends AbstractExecutor<Block, List<? extends Optional<?>>> {
private final Executor<Iterable<? extends VariableDeclarationStatement>, List<? extends List<LocalVariable<?>>>> variableDeclarer;
private final Executor<Iterable<? extends Expression>, List<? extends Object>> expressionExecutor;
private final CodeExecutor<Method, Object> methodExecutor;
@Inject
public StatementExecutor(
Executor<Iterable<? extends VariableDeclarationStatement>, List<? extends List<LocalVariable<?>>>> variableDeclarer,
Executor<Iterable<? extends Expression>, List<? extends Object>> expressionExecutor,
MethodExecutorFactory factory) {
this.variableDeclarer = variableDeclarer;
this.expressionExecutor = expressionExecutor;
methodExecutor = factory.create();
}
@Override
public List<? extends Optional<?>> execute(Environment env, Block input) throws ExecutionException {
List<Statement> statements = new ArrayList<>();
Class<?> current = null;
List<Optional<?>> ret = new ArrayList<>();
for (Statement st : (List<Statement>) input.statements()) {
Class<?> temp;
if (st instanceof VariableDeclarationStatement) {
temp = VariableDeclarationStatement.class;
} else if (st instanceof ExpressionStatement) {
temp = ExpressionStatement.class;
} else {
temp = Statement.class;
}
if (temp == current) {
statements.add(st);
} else {
execute(env, current, statements).ifPresent(l -> ret.addAll(Optionals.optionalize(l)));
current = temp;
statements.clear();
statements.add(st);
}
}
execute(env, current, statements).ifPresent(l -> ret.addAll(Optionals.optionalize(l)));
return ret;
}
@SuppressWarnings("unchecked")
private Optional<List<Object>> execute(Environment env, Class<?> current, List<Statement> statements)
throws ExecutionException {
if (current == null || statements.isEmpty()) {
return Optional.empty();
}
if (current == Statement.class) {
GeneratedMethod method = new GeneratedMethod(env);
for (Statement st : statements) {
method.addChild(SourceCode.from(st));
}
Object ret = methodExecutor.execute(method);
if (ret == null) {
return Optional.empty();
} else {
return Optional.of(Collections.singletonList(ret));
}
}
List<Object> ret = new ArrayList<>();
List<? extends Statement> l = statements;
if (current == VariableDeclarationStatement.class) {
variableDeclarer.execute(env, (List<VariableDeclarationStatement>) l).forEach(ret::addAll);
} else if (current == ExpressionStatement.class) {
List<Expression> expressions = l.stream()
.map(s -> ((ExpressionStatement) s).getExpression())
.collect(Collectors.toList());
expressionExecutor.execute(env, expressions).forEach(ret::add);
} else {
throw new AssertionError("Should only have been one of these three types.");
}
return Optional.of(ret);
}
}
|
package fi.csc.microarray.client;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.TimeUnit;
import javax.jms.JMSException;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JSplitPane;
import javax.swing.LookAndFeel;
import javax.swing.SwingUtilities;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileFilter;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.FontUIResource;
import org.apache.log4j.Logger;
import com.jgoodies.looks.HeaderStyle;
import com.jgoodies.looks.Options;
import com.jgoodies.looks.plastic.Plastic3DLookAndFeel;
import com.jgoodies.looks.plastic.PlasticTheme;
import com.jgoodies.looks.plastic.theme.ExperienceBlue;
import com.jgoodies.uif_lite.panel.SimpleInternalFrame;
import fi.csc.microarray.client.dataimport.ImportItem;
import fi.csc.microarray.client.dataimport.ImportScreen;
import fi.csc.microarray.client.dataimport.ImportSession;
import fi.csc.microarray.client.dataimport.ImportUtils;
import fi.csc.microarray.client.dataimport.ImportUtils.FileLoaderProcess;
import fi.csc.microarray.client.dataimport.table.InformationDialog;
import fi.csc.microarray.client.dataview.DetailsPanel;
import fi.csc.microarray.client.dataview.GraphPanel;
import fi.csc.microarray.client.dataview.TreePanel;
import fi.csc.microarray.client.dialog.ChipsterDialog;
import fi.csc.microarray.client.dialog.DialogInfo;
import fi.csc.microarray.client.dialog.ErrorDialogUtils;
import fi.csc.microarray.client.dialog.ImportSettingsAccessory;
import fi.csc.microarray.client.dialog.SessionRestoreDialog;
import fi.csc.microarray.client.dialog.SnapshotAccessory;
import fi.csc.microarray.client.dialog.URLImportDialog;
import fi.csc.microarray.client.dialog.ChipsterDialog.DetailsVisibility;
import fi.csc.microarray.client.dialog.ChipsterDialog.PluginButton;
import fi.csc.microarray.client.dialog.DialogInfo.Severity;
import fi.csc.microarray.client.dialog.DialogInfo.Type;
import fi.csc.microarray.client.operation.Operation;
import fi.csc.microarray.client.operation.OperationDefinition;
import fi.csc.microarray.client.operation.OperationRecord;
import fi.csc.microarray.client.operation.ToolPanel;
import fi.csc.microarray.client.screen.ChildScreenPool;
import fi.csc.microarray.client.screen.HistoryScreen;
import fi.csc.microarray.client.screen.Screen;
import fi.csc.microarray.client.screen.ShowSourceScreen;
import fi.csc.microarray.client.screen.TaskManagerScreen;
import fi.csc.microarray.client.selection.DatasetChoiceEvent;
import fi.csc.microarray.client.session.UserSession;
import fi.csc.microarray.client.tasks.Task;
import fi.csc.microarray.client.tasks.TaskException;
import fi.csc.microarray.client.tasks.TaskExecutor;
import fi.csc.microarray.client.tasks.Task.State;
import fi.csc.microarray.client.visualisation.VisualisationFrameManager;
import fi.csc.microarray.client.visualisation.VisualisationMethod;
import fi.csc.microarray.client.visualisation.Visualisation.Variable;
import fi.csc.microarray.client.visualisation.VisualisationFrameManager.FrameType;
import fi.csc.microarray.client.waiting.WaitGlassPane;
import fi.csc.microarray.client.workflow.WorkflowManager;
import fi.csc.microarray.config.Configuration;
import fi.csc.microarray.config.DirectoryLayout;
import fi.csc.microarray.config.ConfigurationLoader.IllegalConfigurationException;
import fi.csc.microarray.constants.ApplicationConstants;
import fi.csc.microarray.constants.VisualConstants;
import fi.csc.microarray.databeans.ContentType;
import fi.csc.microarray.databeans.DataBean;
import fi.csc.microarray.databeans.DataFolder;
import fi.csc.microarray.databeans.DataItem;
import fi.csc.microarray.databeans.DataManager;
import fi.csc.microarray.databeans.DataBean.Link;
import fi.csc.microarray.databeans.DataBean.Traversal;
import fi.csc.microarray.description.SADLParser.ParseException;
import fi.csc.microarray.exception.ErrorReportAsException;
import fi.csc.microarray.exception.MicroarrayException;
import fi.csc.microarray.messaging.auth.AuthenticationRequestListener;
import fi.csc.microarray.module.Module;
import fi.csc.microarray.module.chipster.ChipsterInputTypes;
import fi.csc.microarray.util.BrowserLauncher;
import fi.csc.microarray.util.Exceptions;
import fi.csc.microarray.util.Files;
import fi.csc.microarray.util.GeneralFileFilter;
import fi.csc.microarray.util.SplashScreen;
import fi.csc.microarray.util.Strings;
public class SwingClientApplication extends ClientApplication {
private static final int METADATA_FETCH_TIMEOUT_SECONDS = 15;
private static final long SLOW_VISUALISATION_LIMIT = 5 * 1000;
private static final long VERY_SLOW_VISUALISATION_LIMIT = 20 * 1000;
/**
* Logger for this class
*/
private static Logger logger;
private JFrame mainFrame = null;
private JPanel rightSideViewChanger = null;
private JPanel leftSideContentPane = null;
private JSplitPane rightSplit = null;
private JSplitPane leftSplit = null;
private JSplitPane mainSplit = null;
private MicroarrayMenuBar menuBar;
private TaskManagerScreen taskManagerScreen;
private StatusBar statusBar;
private SimpleInternalFrame treeFrame;
private SimpleInternalFrame graphFrame;
private SimpleInternalFrame operationsFrame;
private JPanel visualisationArea;
private SimpleInternalFrame detailsFrame;
private ChildScreenPool childScreens;
private TreePanel tree;
private DetailsPanel details;
private GraphPanel graphPanel;
private ToolPanel toolPanel;
private VisualisationFrameManager visualisationFrameManager;
private HistoryScreen historyScreen;
private SplashScreen splashScreen;
private ClientListener clientListener;
private WaitGlassPane waitPanel = new WaitGlassPane();
private static float fontSize = VisualConstants.DEFAULT_FONT_SIZE;
private JFileChooser importExportFileChooser;
private JFileChooser sessionFileChooser;
private JFileChooser workflowFileChooser;
public SwingClientApplication(ClientListener clientListener, AuthenticationRequestListener overridingARL, String module, boolean isStandalone)
throws MicroarrayException, IOException, IllegalConfigurationException {
super(isStandalone, overridingARL);
this.clientListener = clientListener;
// this had to be delayed as logging is not available before loading configuration
logger = Logger.getLogger(SwingClientApplication.class);
// set the module that user wants to load
this.requestedModule = module;
// show splash screen
splashScreen = new SplashScreen(VisualConstants.SPLASH_SCREEN);
reportInitialisation("Initialising " + ApplicationConstants.TITLE, true);
// try to initialise and handle exceptions gracefully
try {
initialiseApplication();
} catch (Exception e) {
showDialog("Starting Chipster failed.", "There could be a problem with the network connection, or the remote services could be down. " +
"Please see the details below for more information about the problem.\n\n" +
"Chipster also fails to start if there has been a version update with a change in configurations. In such case please delete Chipster application settings directory.",
Exceptions.getStackTrace(e), Severity.ERROR, false, ChipsterDialog.DetailsVisibility.DETAILS_HIDDEN,
new PluginButton() {
@Override
public void actionPerformed() {
try {
new SwingClientApplication(getShutdownListener(), null, null, true);
} catch (Exception e) {
// ignore
}
}
@Override
public String getText() {
return "Start standalone";
}
});
splashScreen.close();
logger.error(e);
}
}
public void reportInitialisation(String report, boolean newline) {
if (newline) {
splashScreen.writeLine(report);
} else {
splashScreen.write(report);
}
}
protected void initialiseGUI() throws MicroarrayException, IOException {
// assert state of initialisation
try {
definitionsInitialisedLatch.await(METADATA_FETCH_TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (toolModules == null) {
throw new MicroarrayException("metadata was not received (analyser not functional?)");
}
// initialize the main frame
this.mainFrame = new JFrame();
updateWindowTitle();
childScreens = new ChildScreenPool(mainFrame);
Frames frames = new Frames(mainFrame);
Session.getSession().setFrames(frames);
// Sets look 'n' feel
setPlastic3DLookAndFeel(mainFrame);
// set location
mainFrame.setLocationByPlatform(true);
// initialise joblist popup menu
// do this method before getStatusBar to avoid null pointer exception
this.taskManagerScreen = this.getTaskManagerScreen();
// initialise child screens
historyScreen = new HistoryScreen();
childScreens.put("History", historyScreen);
childScreens.put("ShowSource", new ShowSourceScreen());
childScreens.put("Import", new ImportScreen());
childScreens.put("TaskList", taskManagerScreen);
// create operation panel using metadata
try {
toolPanel = new ToolPanel(toolModules);
} catch (ParseException e) {
logger.error("SADL parse failed", e);
throw new MicroarrayException(e);
}
operationsFrame = getOperationsFrame();
visualisationFrameManager = new VisualisationFrameManager();
visualisationArea = getVisualisationFrameManager().getFramesPanel();
rightSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, operationsFrame, visualisationArea);
rightSplit.setDividerLocation(VisualConstants.TREE_PANEL_HEIGHT);
rightSplit.setResizeWeight(0.1);
// initialise left side
leftSideContentPane = new JPanel(new BorderLayout());
details = new DetailsPanel(leftSideContentPane);
leftSideContentPane.setBorder(BorderFactory.createEmptyBorder());
/* Initialize tree and graph */
//moved to getTreeFrame
// this.tree = new TreePanel(manager.getRootFolder());
this.graphPanel = new GraphPanel();
treeFrame = getTreeFrame();
graphFrame = getGraphFrame();
leftSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, treeFrame, graphFrame);
leftSplit.setDividerLocation(VisualConstants.TREE_PANEL_HEIGHT);
leftSplit.setResizeWeight(0.1);
detailsFrame = getDetailsFrame();
leftSideContentPane.add(leftSplit, BorderLayout.CENTER);
leftSideContentPane.add(detailsFrame, BorderLayout.SOUTH);
rightSideViewChanger = new JPanel(new BorderLayout());
if (this.isStandalone()) {
rightSideViewChanger.add(visualisationArea, BorderLayout.CENTER);
} else {
rightSideViewChanger.add(rightSplit, BorderLayout.CENTER);
}
rightSideViewChanger.setBorder(BorderFactory.createEmptyBorder());
// construct the whole main content pane
mainSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftSideContentPane, rightSideViewChanger);
mainSplit.setDividerLocation(VisualConstants.LEFT_PANEL_WIDTH);
mainSplit.setResizeWeight(0.1);
// add menus
menuBar = new MicroarrayMenuBar(this);
// create status bar
statusBar = new StatusBar(this);
// sets 3D-look (JGoodies property)
menuBar.putClientProperty(Options.HEADER_STYLE_KEY, HeaderStyle.SINGLE);
// put everything together
mainFrame.getContentPane().setLayout(new BorderLayout());
mainFrame.getContentPane().add(mainSplit, BorderLayout.CENTER);
mainFrame.getContentPane().add(statusBar.getStatusPanel(), BorderLayout.SOUTH);
mainFrame.setJMenuBar(menuBar);
menuBar.updateMenuStatus();
// add glass wait panel
JRootPane rootPane = SwingUtilities.getRootPane(mainFrame);
rootPane.setGlassPane(waitPanel);
// add shutdown listener
mainFrame.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
quit();
}
});
// make window visible
mainFrame.setIconImage(VisualConstants.APPLICATION_ICON.getImage());
mainFrame.pack();
mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
// it's alive!
super.setEventsEnabled(true);
manager.setEventsEnabled(true);
// hide splashscreen
splashScreen.close();
// notify listener
if (clientListener != null) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
clientListener.onSuccessfulInitialisation();
}
});
}
// final touches
customiseFocusTraversal();
restoreDefaultView();
// check for session restore need
File mostRecentDeadTempDirectory = checkTempDirectories();
if (mostRecentDeadTempDirectory != null) {
File sessionFile = UserSession.findBackupFile(mostRecentDeadTempDirectory, false);
new SessionRestoreDialog(this, sessionFile).setVisible(true);
}
}
private void customiseFocusTraversal() throws MicroarrayException {
Vector<Component> order = new Vector<Component>();
order.addAll(tree.getFocusComponents());
order.addAll(toolPanel.getFocusComponents());
order.addAll(visualisationFrameManager.getFocusComponents());
getMainFrame().setFocusTraversalPolicy(new ClientFocusTraversalPolicy(order));
}
private String windowTitleJobPrefix = null;
private String windowTitleBlockingPrefix = null;
public void updateWindowTitleJobCount(Integer jobCount) {
windowTitleJobPrefix = jobCount > 0 ? jobCount + " tasks / " : null;
updateWindowTitle();
}
public void updateWindowTitleBlockingState(String operation) {
if (operation != null) {
windowTitleBlockingPrefix = Strings.startWithUppercase(operation) + " / ";
} else {
windowTitleBlockingPrefix = null;
}
updateWindowTitle();
}
public void updateWindowTitle() {
if (windowTitleBlockingPrefix != null) {
this.mainFrame.setTitle(windowTitleBlockingPrefix + Session.getSession().getPrimaryModule().getDisplayName() + " " + ApplicationConstants.VERSION);
} else if (windowTitleJobPrefix != null) {
this.mainFrame.setTitle(windowTitleJobPrefix + Session.getSession().getPrimaryModule().getDisplayName() + " " + ApplicationConstants.VERSION);
} else {
this.mainFrame.setTitle(Session.getSession().getPrimaryModule().getDisplayName() + " " + ApplicationConstants.VERSION);
}
}
public SimpleInternalFrame getOperationsFrame() {
if (operationsFrame == null) {
operationsFrame = new SimpleInternalFrame("Analysis tools");
operationsFrame.setContent(toolPanel);
}
return operationsFrame;
}
public SimpleInternalFrame getGraphFrame() throws MicroarrayException {
if (graphFrame == null) {
graphFrame = new SimpleInternalFrame("Workflow", graphPanel.getButtonToolBar(), graphPanel.getScroller());
}
return graphFrame;
}
public SimpleInternalFrame getTreeFrame() throws MicroarrayException {
if (treeFrame == null) {
treeFrame = new SimpleInternalFrame("Datasets");
CardLayout cardLayout = new CardLayout();
JPanel cardPanel = new JPanel(cardLayout);
QuickLinkPanel linkPanel = new QuickLinkPanel();
this.tree = new TreePanel(manager.getRootFolder(), cardPanel, cardLayout);
cardPanel.add(linkPanel, "LINKS");
cardPanel.add(tree, "TREE");
treeFrame.add(cardPanel);
cardLayout.first(cardPanel);
return treeFrame;
} else {
return treeFrame;
}
}
public SimpleInternalFrame getDetailsFrame() throws MicroarrayException {
if (detailsFrame == null) {
class DetailsFrame extends SimpleInternalFrame implements PropertyChangeListener {
public DetailsFrame() {
super("Notes for dataset");
}
public void propertyChange(PropertyChangeEvent evt) {
if (evt instanceof DatasetChoiceEvent) {
DatasetChoiceEvent dce = (DatasetChoiceEvent) evt;
if (dce.getNewValue() != null) {
this.setTitle("Notes for dataset " + dce.getNewValue());
} else {
this.setTitle("Notes for dataset");
}
}
}
}
DetailsFrame detailsFrameWithListener = new DetailsFrame();
addClientEventListener(detailsFrameWithListener);
this.detailsFrame = detailsFrameWithListener;
detailsFrame.add(details);
return detailsFrame;
} else {
return detailsFrame;
}
}
/**
* ExperienceBlue is very nice color theme, but it has ugly orange borders
* around focused components. This helper class customizes the theme a bit.
*
* @author mkoski
*/
private static class CustomExperienceBlue extends ExperienceBlue {
/**
* Removes the ugly orange focus color
*/
@Override
public ColorUIResource getFocusColor() {
return new ColorUIResource(VisualConstants.PLASTIC3D_FOCUS_COLOR);
}
@Override
public FontUIResource getControlTextFont() {
return new FontUIResource(super.getControlTextFont().deriveFont(fontSize));
}
@Override
public FontUIResource getTitleTextFont() {
return new FontUIResource(super.getTitleTextFont().deriveFont(fontSize));
}
@Override
public FontUIResource getSubTextFont() {
return new FontUIResource(super.getSubTextFont().deriveFont(fontSize));
}
@Override
public FontUIResource getSystemTextFont() {
return new FontUIResource(super.getSystemTextFont().deriveFont(fontSize));
}
@Override
public FontUIResource getUserTextFont() {
return new FontUIResource(super.getUserTextFont().deriveFont(fontSize));
}
@Override
public FontUIResource getWindowTitleFont() {
return new FontUIResource(super.getWindowTitleFont().deriveFont(fontSize));
}
@Override
public FontUIResource getMenuTextFont() {
return new FontUIResource(super.getMenuTextFont().deriveFont(fontSize));
}
}
private static PlasticTheme theme;
private static LookAndFeel lnf;
/**
* This method sets applications appearance to new level by using Plastic3D
* Look And Feel and ExperienceBlue color theme.
*
* The method sets look and feel and updates UIDefault values. After that it
* updates all the components to the new appearance.
*
* @param componentTreeRoot
* root component of component tree (frame component in most
* cases)
*
*/
public static void setPlastic3DLookAndFeel(Component componentTreeRoot) {
// Look and Feel change must be done only once, otherwise the custom
// values
// from the components get overridden. However this method is called
// several
// times for different child windows, but these ifs do the job.
if (theme == null) {
theme = new CustomExperienceBlue();
Plastic3DLookAndFeel.setPlasticTheme(theme);
}
if (lnf == null) {
lnf = new Plastic3DLookAndFeel();
try {
UIManager.installLookAndFeel("Plastic3D", lnf.getClass().getName());
UIManager.setLookAndFeel(lnf);
} catch (UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
}
// set the UI defaults
UIDefaults defaults = UIManager.getDefaults();
// Done several times, but luckily map rejects duplicates
defaults.putAll(VisualConstants.getUIDefaults());
SwingUtilities.updateComponentTreeUI(componentTreeRoot);
}
public void setFontSize(float size) {
fontSize = size;
SwingUtilities.updateComponentTreeUI(mainFrame);
fixFileChooserFontSize(importExportFileChooser);
// Running progressBar don't care about updateUI
statusBar.setFontSize(fontSize);
Iterator<Screen> iter = childScreens.getScreenIterator();
while (iter.hasNext()) {
Screen screen = iter.next();
SwingUtilities.updateComponentTreeUI(screen.getFrame());
}
}
public float getFontSize() {
return fontSize;
}
public JFrame getMainFrame() {
return mainFrame;
}
/**
* Sets the folder with given name selected or creates a new folder if it
* doesn't exist yet. Selected folder is used as a place for imported files.
* If folder name is null, root folder is returned
*
* @param folderName
* folder name
* @return just created or previously existing folder. If given folder name
* is <code>null</code>, root folder is returned
*/
public DataFolder initializeFolderForImport(String folderName) {
DataFolder root = manager.getRootFolder();
if (folderName == null || folderName.isEmpty()) {
logger.debug("initializing for import " + folderName + ": is null => using root");
return root;
} else if (ImportUtils.getFolderNames(false).contains(folderName)) {
logger.debug("initializing for import " + folderName + ": exists already");
DataFolder folderToSelect;
if (folderName.equals(root.getName())) {
folderToSelect = root;
} else {
folderToSelect = root.getChildFolder(folderName);
}
getSelectionManager().selectSingle(folderToSelect, this);
return folderToSelect;
} else {
logger.debug("initializing for import " + folderName + ": creating new ");
DataFolder folder = getDataManager().createFolder(root, folderName);
getSelectionManager().selectSingle(folder, this);
return folder;
}
}
@Override
public void importGroup(final Collection<ImportItem> datas, final String folderName) {
runBlockingTask("importing files", new Runnable() {
public void run() {
DataBean lastGroupMember = null;
try {
for (ImportItem item : datas) {
String dataSetName = item.getOutput().getName();
ContentType contentType = item.getType();
Object dataSource = item.getInput();
// Selects folder where data is imported to, or creates a
// new one
DataFolder folder = initializeFolderForImport(folderName);
// get the InputStream for the data source
InputStream input;
// create the DataBean
DataBean data = null;
if (dataSource instanceof File) {
data = manager.createDataBean(dataSetName, (File) dataSource);
} else if (dataSource instanceof URL) {
// TODO Not used anymore, URL-files are saved to the
// temp file
URL url = (URL) dataSource;
try {
input = url.openStream();
manager.createDataBean(dataSetName, input);
} catch (FileNotFoundException fnfe) {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
showDialog("File not found.", null, "File not found. Check that the typed URL is pointing to a valid location", Severity.ERROR, false);
}
});
break;
} catch (IOException ioe) {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
showDialog("Import failed.", null, "Error occured while importing data from URL", Severity.ERROR, false);
}
});
break;
}
} else if (dataSource instanceof InputStream) {
logger.info("loading data from a plain stream, caching can not be used!");
input = (InputStream) dataSource;
} else {
throw new IllegalArgumentException("unknown dataSource type: " + dataSource.getClass().getSimpleName());
}
// make sure that the new bean is not null
if (data == null) {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
showDialog("Importing dataset filed.", null, "Created DataBean was null.", Severity.WARNING, false);
}
});
return;
}
// set the content type
data.setContentType(contentType);
// add the operation (all databeans have their own import
// operation
// instance, it would be nice if they would be grouped)
Operation importOperation = new Operation(OperationDefinition.IMPORT_DEFINITION, new DataBean[] { data });
data.setOperationRecord(new OperationRecord(importOperation));
// data is ready now, make it visible
folder.addChild(data);
// Create group links only if both datas are raw type
if (lastGroupMember != null && ChipsterInputTypes.hasRawType(lastGroupMember) && ChipsterInputTypes.hasRawType(data)) {
DataBean targetData = data;
// Link new data to all group linked datas of given cell
for (DataBean sourceData : lastGroupMember.traverseLinks(new Link[] { Link.GROUPING }, Traversal.BIDIRECTIONAL)) {
logger.debug("Created GROUPING link between " + sourceData.getName() + " and " + targetData.getName());
createLink(sourceData, targetData, DataBean.Link.GROUPING);
}
// Create link to the given cell after looping to avoid
// link duplication
createLink(lastGroupMember, targetData, DataBean.Link.GROUPING);
}
lastGroupMember = data;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
/**
* Convenience method for showing exception dialogs with hand written
* messages and stack traces hidden first.
*
* @see #showDialog(String, String, String, Severity)
*/
public void showErrorDialog(String title, Exception error) {
showDialog(title, null, Exceptions.getStackTrace(error), Severity.ERROR, false);
}
/**
* @see #showDialog(String, String, String, Severity)
*/
public void showDialog(String title, Severity severity, boolean modal) {
showDialog(title, null, null, severity, modal);
}
public void showDialog(String title, String message, String details, Severity severity, boolean modal) {
showDialog(title, message, details, severity, modal, ChipsterDialog.DetailsVisibility.DETAILS_HIDDEN, null);
}
/**
* Shows a modal Chipster-styled dialog box to user. Use only when you need
* user's immediate attention.
*
* @param message
* message that is always shown to user
* @param details
* information that is shown in text box that if first closed
* @param severity
* severity level, affects icon choice
*/
public void showDialog(String title, String message, String details, Severity severity, boolean modal, ChipsterDialog.DetailsVisibility detailsVisibility, PluginButton button) {
DialogInfo dialogInfo = new DialogInfo(severity, title, message, details);
ChipsterDialog.showDialog(this, dialogInfo, detailsVisibility, modal, null, button);
}
public void showDialog(String title, String message, String details, Severity severity, boolean modal, ChipsterDialog.DetailsVisibility detailsVisibility, PluginButton button, boolean feedbackEnabled) {
DialogInfo dialogInfo = new DialogInfo(severity, title, message, details);
dialogInfo.setFeedbackVisible(feedbackEnabled);
ChipsterDialog.showDialog(this, dialogInfo, detailsVisibility, modal, null, button);
}
@Override
public File saveWorkflow() {
try {
JFileChooser fileChooser = this.getWorkflowFileChooser();
int ret = fileChooser.showSaveDialog(this.getMainFrame());
if (ret == JFileChooser.APPROVE_OPTION) {
File selected = fileChooser.getSelectedFile();
File newFile = selected.getName().endsWith(WorkflowManager.SCRIPT_EXTENSION) ? selected : new File(selected.getCanonicalPath() + "." + WorkflowManager.SCRIPT_EXTENSION);
workflowManager.saveSelectedWorkflow(newFile);
unsavedChanges = false;
menuBar.addRecentWorkflow(newFile.getName(), Files.toUrl(newFile));
menuBar.updateMenuStatus();
return newFile;
}
menuBar.updateMenuStatus();
} catch (IOException e) {
reportException(e);
}
return null;
}
public void runWorkflow(URL workflowScript) {
runWorkflow(workflowScript, null);
}
public void runWorkflow(URL workflowScript, final AtEndListener atEndListener) {
workflowManager.runScript(workflowScript, atEndListener);
}
@Override
public File openWorkflow() {
try {
JFileChooser fileChooser = this.getWorkflowFileChooser();
int ret = fileChooser.showOpenDialog(this.getMainFrame());
if (ret == JFileChooser.APPROVE_OPTION) {
runWorkflow(fileChooser.getSelectedFile().toURI().toURL());
menuBar.updateMenuStatus();
return fileChooser.getSelectedFile();
} else {
menuBar.updateMenuStatus();
return null;
}
} catch (MalformedURLException e) {
reportException(e);
return null;
}
}
public void showHistoryScreenFor(DataBean data) {
historyScreen.setData(data);
childScreens.show("History", true);
}
public void showDetailsFor(DataBean data) {
details.setViewedData(data);
}
public Icon getIconFor(DataItem element) {
if (element instanceof DataFolder) {
return VisualConstants.ICON_TYPE_FOLDER;
} else {
DataBean bean = (DataBean) element;
if (bean.queryFeatures("/phenodata").exists()) {
return VisualConstants.ICON_TYPE_PHENODATA;
} else {
return bean.getContentType().getIcon();
}
}
}
public void restoreDefaultView() {
leftSplit.setDividerLocation(VisualConstants.TREE_PANEL_HEIGHT);
mainSplit.setDividerLocation(VisualConstants.LEFT_PANEL_WIDTH);
rightSplit.setDividerLocation(VisualConstants.TREE_PANEL_HEIGHT);
mainSplit.validate();
}
public void reportTaskError(Task task) throws MicroarrayException {
String title;
String message;
boolean userFixable = task.getState() == State.FAILED_USER_ERROR && task.getErrorMessage() != null && !task.getErrorMessage().equals("");
// user-friendly message
if (userFixable) {
title = task.getErrorMessage();
message = task.getNamePrettyPrinted() + " was stopped. ";
}
// generic message
else {
title = task.getNamePrettyPrinted() + " did not complete successfully. ";
message = "You may have used a tool or parameters which are unsuitable for the selected dataset, or " + "there might be a bug in the analysis tool itself.\n\n" + "The details below may provide hints about the problem.";
}
// details
String details = "";
if (task.getErrorMessage() != null) {
details += task.getErrorMessage() + "\n\n";
}
details += "
if (task.getScreenOutput() != null) {
details += task.getScreenOutput();
}
DetailsVisibility detailsVisibility = userFixable ? DetailsVisibility.DETAILS_ALWAYS_HIDDEN : DetailsVisibility.DETAILS_HIDDEN;
// show dialog
DialogInfo dialogInfo = new DialogInfo(Severity.INFO, title, message, details);
if (!userFixable) {
dialogInfo.setFeedbackVisible(true);
}
ChipsterDialog.showDialog(this, dialogInfo, detailsVisibility, false);
}
public void reportException(Exception e) {
// collect error information to dialogInfo
DialogInfo dialogInfo = new DialogInfo(Severity.ERROR,
"An error has occurred and the action was not performed successfully.",
"If problem persist, please check that your data is valid. For more information open the details panel below.", null);
dialogInfo.setFeedbackVisible(true);
// exception has extra info
if (e instanceof ErrorReportAsException) {
// exception has everything we need
ErrorReportAsException report = (ErrorReportAsException) e;
dialogInfo.setTitle(report.getTitle());
dialogInfo.setMessage(report.getMessage());
dialogInfo.setDetails(report.getDetails());
} else if (e instanceof MicroarrayException) {
// exception can be scavenged for details
MicroarrayException me = (MicroarrayException) e;
String details = "";
if (ErrorDialogUtils.getMessage(me.getExtraInfo()) != null) {
details += ErrorDialogUtils.getMessage(me.getExtraInfo()) + "\n";
}
if (ErrorDialogUtils.getScreenOutput(me.getExtraInfo()) != null) {
details += ErrorDialogUtils.getScreenOutput(me.getExtraInfo());
}
dialogInfo.setDetails(details);
} else {
// use stack trace as details
dialogInfo.setDetails(Exceptions.getStackTrace(e));
}
// show dialog
ChipsterDialog.showDialog(this, dialogInfo, ChipsterDialog.DetailsVisibility.DETAILS_HIDDEN, false);
// we'll always output these to console and log for traceability and
// easier IDE navigation
e.printStackTrace();
if (logger != null) {
logger.error("client got exception", e);
}
}
public void onException(JMSException e) {
reportException(e);
}
public void showChildScreen(String name, boolean packed) {
childScreens.show(name, packed);
}
public void showMaximisedVisualisation(boolean maximised) {
if (maximised) {
mainSplit.setDividerLocation(0);
rightSplit.setDividerLocation(0);
} else {
restoreDefaultView();
}
rightSideViewChanger.validate();
}
public void showPopupMenuFor(MouseEvent e, DataItem data) {
List<DataItem> datas = new ArrayList<DataItem>();
datas.add(data);
showPopupMenuFor(e, datas);
}
public void showPopupMenuFor(MouseEvent e, List<DataItem> datas) {
ClientContextMenu popup = new ClientContextMenu(this);
popup.setOptionsFor(datas);
popup.show(e.getComponent(), e.getX(), e.getY());
}
/**
* Is the selected databeans possible to visualise
*/
public boolean isSelectedDataVisualisable() {
return getDefaultVisualisationForSelection() != VisualisationMethod.NONE;
}
/**
* Gets default visualisation method for selected databeans. The method is
* selected by following steps:
*
* <ol>
* <li>If no dataset is selected, return
* <code>VisualisationMethod.NONE</code> </li>
* <li>If only one dataset is selected, return the default method for the
* data </li>
* </li>
* <li>If multiple datasets are selected, check the best method for each
* dataset. If the best method is same for all selected datasets and it can
* be used with multiple data, the best method is returned. </li>
* <li>If the best method is not same for all of the datas, try to find
* just some method which is suitable for all datas and can be used with
* multiple datasets. </li>
* <li>If there were no method to fill the requirements above, return
* <code>VisualisationMethod.NONE</code> </li>
*
* @return default visualisation method which is suitable for all selected
* datasets
*/
private VisualisationMethod getDefaultVisualisationForSelection() {
logger.debug("getting default visualisation");
if (getSelectionManager().getSelectedDataBeans() == null || getSelectionManager().getSelectedDataBeans().size() == 0) {
return VisualisationMethod.NONE;
}
try {
List<DataBean> beans = getSelectionManager().getSelectedDataBeans();
if (beans.size() == 1) {
return Session.getSession().getVisualisations().getDefaultVisualisationFor(beans.get(0));
} else if (beans.size() > 1)
for (VisualisationMethod method : Session.getSession().getVisualisations().getOrderedDefaultCandidates()) {
if (method == VisualisationMethod.NONE || !method.getHeadlessVisualiser().isForMultipleDatas()) {
continue;
}
if (method.isApplicableTo(beans)) {
return method;
}
}
/*
*
* VisualisationMethod defaultMethodForDatas = null; // First, try
* to find best suitable visualisation for all for (DataBean bean :
* beans) { VisualisationMethod method = new
* BioBean(bean).getDefaultVisualisation(); if
* (defaultMethodForDatas == null &&
* VisualisationMethod.isApplicableForMultipleDatas(method)) {
* defaultMethodForDatas = method; } else { if
* (defaultMethodForDatas != method) { // Searching for best method
* for all failed defaultMethodForDatas = null; logger.debug("Method " +
* method + " can not be used to visualise selected datas"); break; } } }
*
* if (defaultMethodForDatas != null) { // Visualise datas if the
* best method was found logger.debug("Method " +
* defaultMethodForDatas + " will be used to visualise selected
* datas"); return defaultMethodForDatas; } // Keep looking for
* suitable visualisation DataBean firstData = beans.get(0);
*
* for (VisualisationMethod method :
* VisualisationMethod.getApplicableForMultipleDatas()) { if (method ==
* VisualisationMethod.NONE) { continue; }
*
* if (method.isApplicableTo(firstData)) { // The method is
* applicable to one of the selected datas // Check that the same
* method is applicable to the other // datasets too boolean
* isSuitableMethod = true; for (DataBean otherData : beans) { if
* (otherData.equals(firstData)) { continue; }
*
* if (!method.isApplicableTo(otherData)) { isSuitableMethod =
* false; logger.debug("Method " + method + " can not be used to
* visualise selected datas"); break; } }
*
* if (isSuitableMethod) { logger.debug("Method " + method + " will
* be used to visualise selected datas"); return method; } } }
*/
return VisualisationMethod.NONE;
} catch (Exception e) {
reportException(e);
return VisualisationMethod.NONE;
}
}
public void visualiseWithBestMethod(FrameType target) {
setVisualisationMethod(getDefaultVisualisationForSelection(), null, getSelectionManager().getSelectedDataBeans(), target);
}
public void deleteDatas(DataItem... datas) {
// check that we have something to delete
if (datas.length == 0) {
return; // no selection, do nothing
}
// choose confirm dialog message
JLabel confirmMessage = null;
if (datas.length > 1) {
confirmMessage = new JLabel("Really delete " + datas.length + " data items?");
} else if (datas[0] instanceof DataFolder) {
confirmMessage = new JLabel("Really delete " + datas[0].getName() + " and all of its contents?");
} else if (datas[0] instanceof DataBean) {
confirmMessage = new JLabel("Really delete " + datas[0].getName() + " ?");
} else {
throw new IllegalArgumentException("datas is illegal");
}
// confirm delete
if (JOptionPane.showConfirmDialog(this.mainFrame, confirmMessage, "Delete items", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) {
return; // deletion was not confirmed
}
// delete actually
deleteDatasWithoutConfirming(datas);
}
public void deleteDatasWithoutConfirming(DataItem... datas) {
// check that we have something to delete
if (datas.length == 0) {
return; // no selection, do nothing
}
// remove all selections
getSelectionManager().clearAll(true, this);
// do actual delete
for (DataItem data : datas) {
manager.delete(data);
}
}
public void fixFileChooserFontSize(JFileChooser fileChooser) {
// Some special care has to be taken to get the fileChooser list update
// also
if (fileChooser != null) {
UIManager.put("FileChooser.listFont", UIManager.getFont("List.font").deriveFont(fontSize));
SwingUtilities.updateComponentTreeUI(fileChooser);
}
}
public void openFileImport() throws MicroarrayException, IOException {
JFileChooser fc = getImportExportFileChooser();
fc.setMultiSelectionEnabled(true);
ImportSettingsAccessory access = (ImportSettingsAccessory) importExportFileChooser.getAccessory();
access.setDefaults();
int ret = fc.showOpenDialog(getMainFrame());
if (ret == JFileChooser.APPROVE_OPTION) {
List<File> files = new ArrayList<File>();
for (File file : fc.getSelectedFiles()) {
files.add(file);
}
ImportSession importSession = new ImportSession(ImportSession.Source.FILES, files, access.getImportFolder(), access.skipActionChooser());
ImportUtils.executeImport(importSession);
}
}
public void openDirectoryImportDialog() {
JFileChooser fc = getImportExportDirChooser();
fc.setSelectedFile(new File(""));
int ret = fc.showOpenDialog(this.getMainFrame());
if (ret == JFileChooser.APPROVE_OPTION) {
File selectedFile = fc.getSelectedFile();
super.importWholeDirectory(selectedFile);
}
}
public void openURLImport() throws MicroarrayException, IOException {
URLImportDialog urlImportDlg = new URLImportDialog(this);
URL selectedURL = urlImportDlg.getSelectedURL();
String importFolder = urlImportDlg.getSelectedFolderName();
if (selectedURL != null) {
File file = ImportUtils.createTempFile(ImportUtils.URLToFilename(selectedURL), ImportUtils.getExtension(ImportUtils.URLToFilename(selectedURL)));
ImportUtils.getURLFileLoader().loadFileFromURL(selectedURL, file, importFolder, urlImportDlg.isSkipSelected());
}
}
protected void quit() {
int returnValue = JOptionPane.DEFAULT_OPTION;
// Check the running tasks
if (taskExecutor.getRunningTaskCount() > 0) {
String message = "";
if (taskExecutor.getRunningTaskCount() == 1) {
message += "There is a running task. Are you sure you want to cancel the running task?";
} else {
message += "There are " + taskExecutor.getRunningTaskCount() + " running tasks. " + "Are you sure you want to cancel all running tasks?";
}
Object[] options = { "Cancel running tasks", "Cancel" };
returnValue = JOptionPane.showOptionDialog(this.getMainFrame(), message, "Confirm close", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (returnValue == JOptionPane.YES_OPTION) {
taskExecutor.killAll();
} else {
return;
}
}
// Check for unsaved changes
returnValue = JOptionPane.DEFAULT_OPTION;
if (unsavedChanges) {
Object[] options = { "Save and close", "Close without saving", "Cancel" };
returnValue = JOptionPane.showOptionDialog(this.getMainFrame(), "Do you want the session to be saved before closing Chipster?", "Confirm close", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (returnValue == 0) {
try {
saveSessionAndQuit();
return;
} catch (Exception exp) {
this.showErrorDialog("Session saving failed", exp);
return;
}
// cancel also if the dialog is closed from the corner x
} else if (returnValue != 1) {
return;
}
}
quitImmediately();
}
public void quitImmediately() {
// hide immediately to look more reactive...
childScreens.disposeAll();
mainFrame.setVisible(false);
super.quit();
// this closes the application
mainFrame.dispose();
System.exit(0);
}
public static void startStandalone(String module) throws IOException {
try {
DirectoryLayout.initialiseStandaloneClientLayout();
Configuration config = DirectoryLayout.getInstance().getConfiguration();
config.getRootModule().getModule("messaging").getEntry("broker-host").setValue("(none)");
config.getRootModule().getModule("messaging").getEntry("broker-protocol").setValue("");
config.getRootModule().getModule("messaging").getEntry("broker-port").setValue("0");
config.getRootModule().getModule("security").getEntry("username").setValue("");
config.getRootModule().getModule("security").getEntry("password").setValue("");
} catch (IllegalConfigurationException e) {
reportIllegalConfigurationException(e);
}
ClientListener shutdownListener = getShutdownListener();
try {
new SwingClientApplication(shutdownListener, null, module, true);
} catch (Throwable t) {
t.printStackTrace();
if (logger != null) {
logger.error(t.getMessage());
logger.error(t);
}
}
}
private static ClientListener getShutdownListener() {
ClientListener shutdownListener = new ClientListener() {
public void onSuccessfulInitialisation() {
// do nothing
}
public void onFailedInitialisation() {
System.exit(1);
}
};
return shutdownListener;
}
/**
* Starts Chipster client. Configuration (logging) should be initialised
* before calling this method.
*/
public static void start(String configURL, String module) throws IOException {
try {
DirectoryLayout.initialiseClientLayout(configURL);
} catch (IllegalConfigurationException e) {
reportIllegalConfigurationException(e);
}
ClientListener shutdownListener = getShutdownListener();
try {
new SwingClientApplication(shutdownListener, null, module, false);
} catch (Throwable t) {
t.printStackTrace();
if (logger != null) {
logger.error(t.getMessage());
logger.error(t);
}
}
}
public static void main(String[] args) throws IOException {
start(null, "fi.csc.microarray.module.chipster.MicroarrayModule");
}
public static void reportIllegalConfigurationException(IllegalConfigurationException e) {
DialogInfo dialogInfo = new DialogInfo(Severity.ERROR, "Illegal configuration", "Chipster could not start because the provided configuration file is illegal. Please contact your system administrator.", "Reason: " + e.getMessage());
ChipsterDialog.showDialog(null, dialogInfo, DetailsVisibility.DETAILS_HIDDEN, true);
throw new RuntimeException("configuration not compatible, will not start");
}
@Override
public void showSourceFor(String operationID) throws TaskException {
childScreens.show("ShowSource", true, operationID);
}
/**
* Opens JFileChooser to ask location for the export, then calls
* exportDataDirectory to do the job.
*
* @param data
* @throws MicroarrayException
* @throws IOException
*/
public void exportFolder(DataFolder data) throws MicroarrayException, IOException {
File file = new File(data.getName().replace(" ", "_"));
// file.mkdirs();
JFileChooser fc = getImportExportDirChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setSelectedFile(file);
logger.debug("Exporting File: " + fc.getSelectedFile().getAbsolutePath());
int ret = fc.showSaveDialog(getMainFrame());
if (ret == JFileChooser.APPROVE_OPTION) {
File selected = new File(fc.getSelectedFile().getAbsolutePath() + File.separator + file.getName());
selected.mkdirs();
exportDataFolder(data, selected);
}
}
/**
* Method to export recursively all descendants of the source
*
*/
private void exportDataFolder(DataFolder source, File dir) throws IOException, MicroarrayException {
for (DataItem child : source.getChildren()) {
if (child instanceof DataBean) {
String filename = createFilename((DataBean) child);
filename = dir.getAbsolutePath() + File.separator + filename;
logger.debug("Exporting dataBean " + child.getName() + " into " + filename);
exportToFile((DataBean) child, new File(filename));
} else if (child instanceof DataFolder) {
logger.debug("Exporting dataFolder " + child.getName());
String foldername = dir.getAbsolutePath() + File.separator + child.getName().replace(" ", "_");
File file = new File(foldername);
file.mkdir();
exportDataFolder((DataFolder) child, file);
}
}
}
public void exportDataset(DataBean data) throws MicroarrayException, IOException {
JFileChooser fc = this.getImportExportFileChooser();
fc.setDialogType(JFileChooser.SAVE_DIALOG);
String proposedName = createFilename(data);
fc.setSelectedFile(new File(proposedName));
int ret = fc.showSaveDialog(getMainFrame());
if (ret == JFileChooser.APPROVE_OPTION) {
File selectedFile = fc.getSelectedFile();
exportToFile(data, selectedFile);
}
}
private String createFilename(DataBean data) {
String proposedName = data.getName().replace(" ", "_");
/*
* TODO does not work with mime content types if
* (!proposedName.endsWith(data.getContentType())) { proposedName =
* proposedName + "." + data.getContentType(); }
*/
return proposedName;
}
@Override
public void setMaximisedVisualisationMode(boolean maximisedVisualisationMode) {
showMaximisedVisualisation(maximisedVisualisationMode);
}
@Override
public void setVisualisationMethod(VisualisationMethod method, List<Variable> variables, List<DataBean> datas, FrameType target) {
if (method == null || datas == null) {
super.setVisualisationMethod(VisualisationMethod.NONE, null, null, target);
return;
}
long estimate = method.estimateDuration(datas);
if (estimate > SLOW_VISUALISATION_LIMIT) {
int returnValue = JOptionPane.DEFAULT_OPTION;
String message = "";
int severity;
// Check the running tasks
if (estimate > VERY_SLOW_VISUALISATION_LIMIT) {
message += "Visualising the selected large dataset with this method might stop Chipster from responding. \n" + "If you choose to continue, it's recommended to save the session before visualising.";
severity = JOptionPane.WARNING_MESSAGE;
} else {
message += "Are you sure you want to visualise large dataset, which may " + "take several seconds?";
severity = JOptionPane.QUESTION_MESSAGE;
}
Object[] options = { "Cancel", "Visualise" };
returnValue = JOptionPane.showOptionDialog(this.getMainFrame(), message, "Cancel visualisation", JOptionPane.YES_NO_OPTION, severity, null, options, options[0]);
if (returnValue == 1) {
super.setVisualisationMethod(method, variables, datas, target);
} else {
return;
}
} else {
super.setVisualisationMethod(method, variables, datas, target);
}
}
public void exportSelectedItems() {
try {
for (DataItem item : getSelectionManager().getSelectedDataItems()) {
if (item instanceof DataBean) {
exportDataset((DataBean) item);
} else if (item instanceof DataFolder) {
exportFolder((DataFolder) item);
}
}
} catch (Exception e) {
reportException(e);
}
}
private JFileChooser getImportExportDirChooser() {
if (importExportFileChooser == null) {
importExportFileChooser = ImportUtils.getFixedFileChooser();
}
importExportFileChooser.setAccessory(null);
importExportFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
String description = "Data Directory";
String[] extensions = {}; // only directories
for (FileFilter filter : importExportFileChooser.getChoosableFileFilters()) {
importExportFileChooser.removeChoosableFileFilter(filter);
}
importExportFileChooser.addChoosableFileFilter(new GeneralFileFilter(description, extensions));
importExportFileChooser.setAcceptAllFileFilterUsed(false);
fixFileChooserFontSize(importExportFileChooser);
return importExportFileChooser;
}
/**
* This is public to give access to file filter from ImportUtils
*
* @return The default JFileChooser with an assigned MicroarrayFileFilter.
*/
public JFileChooser getImportExportFileChooser() {
if (importExportFileChooser == null) {
importExportFileChooser = ImportUtils.getFixedFileChooser();
}
// remove previous filters, otherwise they duplicate
for (FileFilter filter : importExportFileChooser.getChoosableFileFilters()) {
importExportFileChooser.removeChoosableFileFilter(filter);
}
importExportFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
for (Module module : Session.getSession().getModules()) {
for (FileFilter filter : module.getImportFileFilter()) {
importExportFileChooser.addChoosableFileFilter(filter);
importExportFileChooser.setFileFilter(filter);
}
}
importExportFileChooser.setAcceptAllFileFilterUsed(true);
ImportSettingsAccessory access = new ImportSettingsAccessory(importExportFileChooser);
importExportFileChooser.setAccessory(access);
fixFileChooserFontSize(importExportFileChooser);
return importExportFileChooser;
}
private JFileChooser getSessionFileChooser(JComponent accessory) {
if (sessionFileChooser == null) {
sessionFileChooser = ImportUtils.getFixedFileChooser();
String[] extensions = { UserSession.SESSION_FILE_EXTENSION };
sessionFileChooser.setFileFilter(new GeneralFileFilter("Chipster Session (." + UserSession.SESSION_FILE_EXTENSION + ")", extensions));
sessionFileChooser.setSelectedFile(new File("session." + UserSession.SESSION_FILE_EXTENSION));
sessionFileChooser.setAcceptAllFileFilterUsed(false);
sessionFileChooser.setMultiSelectionEnabled(false);
}
sessionFileChooser.setAccessory(accessory);
fixFileChooserFontSize(sessionFileChooser);
return sessionFileChooser;
}
private JFileChooser getWorkflowFileChooser() {
if (workflowFileChooser == null) {
workflowFileChooser = ImportUtils.getFixedFileChooser(workflowManager.getScriptDirectory());
workflowFileChooser.setFileFilter(WorkflowManager.FILE_FILTER);
workflowFileChooser.setSelectedFile(new File("workflow.bsh"));
workflowFileChooser.setAcceptAllFileFilterUsed(false);
workflowFileChooser.setMultiSelectionEnabled(false);
}
fixFileChooserFontSize(workflowFileChooser);
return workflowFileChooser;
}
/**
* Opens import tool directly
*
* @param useSameSettings
*
* @param file
*/
public void openImportTool(ImportSession importSession) {
ImportScreen importScreen = (ImportScreen) childScreens.get("Import");
importScreen.setImportSession(importSession);
importScreen.updateTable(false);
childScreens.show("Import", false);
}
/**
* <p>Run a task in background thread and block GUI in a friendly way while the task is being
* run. <strong>Note!</strong> If the task modifies GUI, it must use SwingUtilities.invokeAndWait so that
* modifications are done in event dispatch thread.</p>
*
* @param taskName
* name of the task we will be running, like "importing" or
* "loading"
* @param runnable
* the task
*/
public void runBlockingTask(String taskName, final Runnable runnable) {
Thread backgroundThread = new Thread(new Runnable() {
public void run() {
try {
runnable.run();
} catch (final Exception e) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
reportException(e);
}
});
} finally {
waitPanel.stopWaiting();
updateWindowTitleBlockingState(null);
}
}
});
waitPanel.startWaiting("<html>Please wait while " + taskName + "..." + "</html>");
updateWindowTitleBlockingState(taskName);
backgroundThread.start();
}
public void viewHelpFor(OperationDefinition definition) {
String url = definition.getHelpURL();
if (url != null && !url.isEmpty()) {
// Link is stored in operation definition
url = definition.getHelpURL();
viewHelp(url);
} else {
// Mostly for microarray
// TODO: consider refactoring so that url is stored in definition
// and this "else" branch is not needed
viewHelp(HelpMapping.mapToHelppage(definition));
}
}
public void viewHelp(String page) {
try {
BrowserLauncher.openURL(page);
} catch (Exception e) {
reportException(e);
}
}
protected void garbageCollect() {
System.gc();
statusBar.updateMemoryIndicator();
}
public TaskManagerScreen getTaskManagerScreen() {
TaskExecutor taskExecutor = Session.getSession().getServiceAccessor().getTaskExecutor();
return new TaskManagerScreen(taskExecutor);
}
public void createLink(DataBean source, DataBean target, Link type) {
source.addLink(type, target);
}
public void removeLink(DataBean source, DataBean target, Link type) {
source.removeLink(type, target);
}
@Override
public void showImportToolFor(File file, String destinationFolder, boolean skipActionChooser) {
ImportSession importSession = new ImportSession(ImportSession.Source.FILES, new File[] { file }, destinationFolder, skipActionChooser);
openImportTool(importSession);
}
@Override
public void loadSessionFrom(File file) {
loadSessionImpl(file, false);
}
@Override
public void restoreSessionFrom(File file) {
loadSessionImpl(file, true);
}
@Override
public void loadSessionFrom(URL url) {
try {
final File tempFile = ImportUtils.createTempFile(ImportUtils.URLToFilename(url), ImportUtils.getExtension(ImportUtils.URLToFilename(url)));
InformationDialog info = new InformationDialog("Loading session", "Loading session from the specified URL", null);
FileLoaderProcess fileLoaderProcess = new FileLoaderProcess(tempFile, url, info) {
@Override
protected void postProcess() {
loadSessionImpl(tempFile, false);
};
};
fileLoaderProcess.runProcess();
} catch (IOException e) {
reportException(e);
}
}
@Override
public void loadSession() {
SnapshotAccessory accessory = new SnapshotAccessory();
final JFileChooser fileChooser = getSessionFileChooser(accessory);
int ret = fileChooser.showOpenDialog(this.getMainFrame());
// user has selected a file
if (ret == JFileChooser.APPROVE_OPTION) {
File sessionFile = fileChooser.getSelectedFile();
// check that file exists
if (!sessionFile.exists()) {
DialogInfo info = new DialogInfo(Severity.INFO, "Could not open session file.", "File '" + sessionFile.getName() + "' not found.", "", Type.MESSAGE);
ChipsterDialog.showDialog(this, info, DetailsVisibility.DETAILS_ALWAYS_HIDDEN, true);
return;
}
// check that the file is a session file
if (!UserSession.isValidSessionFile(sessionFile)) {
DialogInfo info = new DialogInfo(Severity.INFO, "Could not open session file.", "File '" + sessionFile.getName() + "' is not a valid session file.", "", Type.MESSAGE);
ChipsterDialog.showDialog(this, info, DetailsVisibility.DETAILS_ALWAYS_HIDDEN, true);
return;
}
// clear previous session
if (accessory.clearSession()) {
if (!clearSession()) {
return; // loading cancelled
}
}
// load the new session
loadSessionImpl(fileChooser.getSelectedFile(), false);
}
menuBar.updateMenuStatus();
}
private void loadSessionImpl(final File sessionFile, final boolean restoreSession) {
// check that it's a valid session file
if (!UserSession.isValidSessionFile(sessionFile)) {
DialogInfo dialogInfo = new DialogInfo(Severity.INFO, "Could not open session file.", "The given file is not a valid session file.", "");
ChipsterDialog.showDialog(this, dialogInfo, DetailsVisibility.DETAILS_ALWAYS_HIDDEN, true);
return;
}
// start loading the session
runBlockingTask("loading the session", new Runnable() {
public void run() {
/* If there wasn't data or it was just cleared, there is no need to warn about
* saving after opening session. However, if there was datasets already, combination
* of them and new session can be necessary to save. This has to set after the import, because
*/
boolean somethingToSave = manager.databeans().size() != 0;
manager.loadSession(sessionFile, restoreSession);
unsavedChanges = somethingToSave;
if (restoreSession) {
clearDeadTempDirectories();
}
}
});
}
@Override
public void saveSession() {
saveSession(false);
}
public void saveSessionAndQuit() {
saveSession(true);
}
public void saveSession(final boolean quit) {
JFileChooser fileChooser = getSessionFileChooser(null);
int ret = fileChooser.showSaveDialog(this.getMainFrame());
if (ret == JFileChooser.APPROVE_OPTION) {
try {
final File file = fileChooser.getSelectedFile().getName().endsWith("." + UserSession.SESSION_FILE_EXTENSION) ? fileChooser.getSelectedFile() : new File(fileChooser.getSelectedFile().getCanonicalPath() + "." + UserSession.SESSION_FILE_EXTENSION);
if (file.exists()) {
int returnValue = JOptionPane.DEFAULT_OPTION;
String message = "The file " + file.getCanonicalPath() + " already exists. Do you want " + "to replace it?";
Object[] options = { "Cancel", "Replace" };
returnValue = JOptionPane.showOptionDialog(this.getMainFrame(), message, "Confirm replace", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (returnValue != 1) {
return;
}
}
// save
runBlockingTask("saving session", new Runnable() {
public void run() {
// save
boolean saveSuccessful;
saveSuccessful = getDataManager().saveSession(file);
if (saveSuccessful) {
// quit
if (quit) {
quitImmediately();
}
menuBar.updateMenuStatus();
unsavedChanges = false;
}
}
});
} catch (Exception exp) {
showErrorDialog("Saving session failed.", exp);
return;
}
}
menuBar.updateMenuStatus();
}
/**
* @return true if cleared, false if canceled
*/
public boolean clearSession() {
int returnValue = JOptionPane.DEFAULT_OPTION;
if (unsavedChanges) {
String message = "The current session contains unsaved changes.\nDo you want to clear it anyway?";
Object[] options = { "Cancel", "Clear" };
returnValue = JOptionPane.showOptionDialog(this.getMainFrame(), message, "Clear session", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
}
if (!unsavedChanges || returnValue == 1) {
this.deleteDatasWithoutConfirming(manager.getRootFolder());
unsavedChanges = false;
return true;
}
return false;
}
@Override
public void checkFreeMemory() {
statusBar.updateMemoryIndicator();
}
public DataManager getDataManager() {
return manager;
}
public VisualisationFrameManager getVisualisationFrameManager() {
return visualisationFrameManager;
}
@Override
public void flipTaskListVisibility(boolean closeIfVisible) {
statusBar.flipTaskListVisibility(closeIfVisible);
}
@Override
protected void taskCountChanged(int newTaskCount, boolean attractAttention) {
int completion = 0;
if (newTaskCount > 0) {
completion = taskExecutor.getTasks(true, false).iterator().next().getCompletionPercentage();
}
statusBar.taskCountChanged(newTaskCount, completion, attractAttention);
}
public void refreshTaskList() {
this.taskManagerScreen.refreshTasks();
}
public Screen getTaskListScreen() {
return childScreens.get("TaskList");
}
}
|
package com.systematic.trading.backtest.output.elastic;
import java.util.AbstractMap.SimpleEntry;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import com.systematic.trading.backtest.configuration.BacktestBootstrapConfiguration;
import com.systematic.trading.backtest.display.BacktestOutput;
import com.systematic.trading.backtest.exception.BacktestInitialisationException;
import com.systematic.trading.backtest.model.BacktestSimulationDates;
import com.systematic.trading.data.TradingDayPrices;
import com.systematic.trading.model.TickerSymbolTradingData;
import com.systematic.trading.signals.model.event.SignalAnalysisEvent;
import com.systematic.trading.simulation.analysis.networth.NetWorthEvent;
import com.systematic.trading.simulation.analysis.roi.CulmativeTotalReturnOnInvestmentCalculator;
import com.systematic.trading.simulation.analysis.roi.event.ReturnOnInvestmentEvent;
import com.systematic.trading.simulation.analysis.statistics.EventStatistics;
import com.systematic.trading.simulation.brokerage.event.BrokerageEvent;
import com.systematic.trading.simulation.cash.event.CashEvent;
import com.systematic.trading.simulation.equity.event.EquityEvent;
import com.systematic.trading.simulation.order.event.OrderEvent;
/**
* Puts the event data into Elastic Search using the rest HTTP end point.
*
* @author CJ Hare
*/
public class ElasticBacktestOutput implements BacktestOutput {
/** Location of the elastic search end point. */
private static final String ELASTIC_ENDPOINT_URL = "http://localhost:9200";
/** Base of the elastic search Restful end point. */
private final WebTarget root;
//TODO use an exectuor pool for the Java-RS operations?
// final ExecutorService pool
public ElasticBacktestOutput() {
// Registering the provider for POJO -> JSON
final ClientConfig clientConfig = new ClientConfig().register(JacksonJsonProvider.class);
// End point target root
root = ClientBuilder.newClient(clientConfig).target(ELASTIC_ENDPOINT_URL);
}
@Override
public void event( final SignalAnalysisEvent event ) {
// TODO Auto-generated method stub
}
@Override
public void event( final CashEvent event ) {
// TODO Auto-generated method stub
}
@Override
public void event( final OrderEvent event ) {
// TODO Auto-generated method stub
}
@Override
public void event( final BrokerageEvent event ) {
//TODO convert the object to the JSON format expected by elastic
// let's create an index called articles
Response response = root.path("brokerage-events").request(MediaType.APPLICATION_JSON).put(Entity.json(event));
System.out.println("Response code: " + response.getStatus());
System.out.println("Response :" + response.readEntity(String.class));
}
@Override
public void event( final ReturnOnInvestmentEvent event ) {
// TODO Auto-generated method stub
}
@Override
public void stateChanged( final SimulationState transitionedState ) {
// TODO Auto-generated method stub
}
@Override
public void event( final NetWorthEvent event, final SimulationState state ) {
// TODO Auto-generated method stub
}
@Override
public void event( final EquityEvent event ) {
// TODO Auto-generated method stub
}
@Override
public void init( final BacktestBootstrapConfiguration configuration, final TickerSymbolTradingData tradingData,
final BacktestSimulationDates simulationDates, final EventStatistics eventStatistics,
final CulmativeTotalReturnOnInvestmentCalculator cumulativeRoi, final TradingDayPrices lastTradingDay )
throws BacktestInitialisationException {
final Map<String, Object> index = new HashMap<>();
final Map<String, Object> mappings = new HashMap<>();
final Map<String, Object> properties = new HashMap<>();
final Map<String, Object> message = new HashMap<>();
final SimpleEntry<String, String> messageType = new SimpleEntry<String, String>("type", "text");
message.put("message", messageType);
properties.put("properties", message);
mappings.put("tweet", properties);
index.put("mappings", mappings);
Response response = root.path("twitter").request(MediaType.APPLICATION_JSON).put(Entity.json(index));
System.out.println("Response code: " + response.getStatus());
System.out.println("Response :" + response.readEntity(String.class));
//TODO test around these JSON conversions
//TODO store the unqiueness value for the elastic index:
//TODO start off with every event in their own index, then extract data with graphana / kinana to refine
}
}
|
package fi.csc.microarray.client;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.TimeUnit;
import javax.jms.JMSException;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JSplitPane;
import javax.swing.LookAndFeel;
import javax.swing.SwingUtilities;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileFilter;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.FontUIResource;
import org.apache.log4j.Logger;
import com.jgoodies.looks.HeaderStyle;
import com.jgoodies.looks.Options;
import com.jgoodies.looks.plastic.Plastic3DLookAndFeel;
import com.jgoodies.looks.plastic.PlasticTheme;
import com.jgoodies.looks.plastic.theme.ExperienceBlue;
import com.jgoodies.uif_lite.panel.SimpleInternalFrame;
import fi.csc.microarray.ApplicationConstants;
import fi.csc.microarray.ErrorReportAsException;
import fi.csc.microarray.MicroarrayException;
import fi.csc.microarray.client.dataimport.ImportItem;
import fi.csc.microarray.client.dataimport.ImportScreen;
import fi.csc.microarray.client.dataimport.ImportSession;
import fi.csc.microarray.client.dataimport.ImportUtils;
import fi.csc.microarray.client.dataimport.ImportUtils.FileLoaderProcess;
import fi.csc.microarray.client.dataimport.table.InformationDialog;
import fi.csc.microarray.client.dataview.DetailsPanel;
import fi.csc.microarray.client.dataview.GraphPanel;
import fi.csc.microarray.client.dataview.TreePanel;
import fi.csc.microarray.client.dialog.ChipsterDialog;
import fi.csc.microarray.client.dialog.ClipboardImportDialog;
import fi.csc.microarray.client.dialog.DialogInfo;
import fi.csc.microarray.client.dialog.ErrorDialogUtils;
import fi.csc.microarray.client.dialog.ImportSettingsAccessory;
import fi.csc.microarray.client.dialog.SnapshotAccessory;
import fi.csc.microarray.client.dialog.URLImportDialog;
import fi.csc.microarray.client.dialog.ChipsterDialog.DetailsVisibility;
import fi.csc.microarray.client.dialog.DialogInfo.Severity;
import fi.csc.microarray.client.operation.Operation;
import fi.csc.microarray.client.operation.OperationDefinition;
import fi.csc.microarray.client.operation.OperationPanel;
import fi.csc.microarray.client.screen.ChildScreenPool;
import fi.csc.microarray.client.screen.HistoryScreen;
import fi.csc.microarray.client.screen.Screen;
import fi.csc.microarray.client.screen.ShowSourceScreen;
import fi.csc.microarray.client.screen.TaskManagerScreen;
import fi.csc.microarray.client.selection.DatasetChoiceEvent;
import fi.csc.microarray.client.tasks.Task;
import fi.csc.microarray.client.tasks.TaskException;
import fi.csc.microarray.client.tasks.TaskExecutor;
import fi.csc.microarray.client.visualisation.VisualisationFrameManager;
import fi.csc.microarray.client.visualisation.VisualisationMethod;
import fi.csc.microarray.client.visualisation.Visualisation.Variable;
import fi.csc.microarray.client.visualisation.VisualisationFrameManager.FrameType;
import fi.csc.microarray.client.waiting.WaitGlassPane;
import fi.csc.microarray.client.workflow.WorkflowManager;
import fi.csc.microarray.config.DirectoryLayout;
import fi.csc.microarray.config.ConfigurationLoader.IllegalConfigurationException;
import fi.csc.microarray.databeans.ContentType;
import fi.csc.microarray.databeans.DataBean;
import fi.csc.microarray.databeans.DataChangeEvent;
import fi.csc.microarray.databeans.DataChangeListener;
import fi.csc.microarray.databeans.DataFolder;
import fi.csc.microarray.databeans.DataItem;
import fi.csc.microarray.databeans.DataManager;
import fi.csc.microarray.databeans.DataBean.Link;
import fi.csc.microarray.databeans.DataBean.Traversal;
import fi.csc.microarray.databeans.fs.FSSnapshottingSession;
import fi.csc.microarray.description.VVSADLParser.ParseException;
import fi.csc.microarray.messaging.auth.AuthenticationRequestListener;
import fi.csc.microarray.messaging.auth.ClientLoginListener;
import fi.csc.microarray.module.chipster.ChipsterInputTypes;
import fi.csc.microarray.util.BrowserLauncher;
import fi.csc.microarray.util.Exceptions;
import fi.csc.microarray.util.GeneralFileFilter;
import fi.csc.microarray.util.SplashScreen;
import fi.csc.microarray.util.Strings;
public class SwingClientApplication extends ClientApplication {
private static final int METADATA_FETCH_TIMEOUT_SECONDS = 15;
private static final long SLOW_VISUALISATION_LIMIT = 5 * 1000;
private static final long VERY_SLOW_VISUALISATION_LIMIT = 20 * 1000;
/**W
* Logger for this class
*/
private static Logger logger;
private JFrame mainFrame = null;
private JPanel rightSideViewChanger = null;
private JPanel leftSideContentPane = null;
private JSplitPane rightSplit = null;
private JSplitPane leftSplit = null;
private JSplitPane mainSplit = null;
private MicroarrayMenuBar menuBar;
private TaskManagerScreen taskManagerScreen;
private StatusBar statusBar;
private SimpleInternalFrame treeFrame;
private SimpleInternalFrame graphFrame;
private SimpleInternalFrame operationsFrame;
private JPanel visualisationArea;
private SimpleInternalFrame detailsFrame;
private ChildScreenPool childScreens;
private TreePanel tree;
private DetailsPanel details;
private GraphPanel graphPanel;
private OperationPanel operationsPanel;
private VisualisationFrameManager visualisationFrameManager;
private HistoryScreen historyScreen;
private SplashScreen splashScreen;
private ClientListener clientListener;
private AuthenticationRequestListener overridingARL;
private WaitGlassPane waitPanel = new WaitGlassPane();
private static float fontSize = VisualConstants.DEFAULT_FONT_SIZE;
private boolean unsavedChanges = false;
private JFileChooser importExportFileChooser;
private JFileChooser snapshotFileChooser;
private JFileChooser workflowFileChooser;
public SwingClientApplication(ClientListener clientListener, AuthenticationRequestListener overridingARL) throws MicroarrayException, IOException, IllegalConfigurationException {
super();
this.clientListener = clientListener;
this.overridingARL = overridingARL;
splashScreen = new SplashScreen(VisualConstants.SPLASH_SCREEN);
reportInitialisation("Initialising " + ApplicationConstants.APPLICATION_TITLE, true);
// we want to close the splash screen exception occurs
try {
initialiseApplication();
} catch (Exception e) {
splashScreen.close();
throw new MicroarrayException(e);
}
// this had to be delayed as logging is not available before loading
// configuration
logger = Logger.getLogger(SwingClientApplication.class);
}
public void reportInitialisation(String report, boolean newline) {
if (newline) {
splashScreen.writeLine(report);
} else {
splashScreen.write(report);
}
}
protected void initialiseGUI() throws MicroarrayException, IOException {
// assert state of initialisation
try {
definitionsInitialisedLatch.await(METADATA_FETCH_TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (parsedCategories == null) {
throw new MicroarrayException("metadata was not received (analyser not functional?)");
}
// initialize the main frame
mainFrame = new JFrame();
updateWindowTitle();
childScreens = new ChildScreenPool(mainFrame);
// Sets look 'n' feel
setPlastic3DLookAndFeel(mainFrame);
// set location
mainFrame.setLocationByPlatform(true);
// initialise joblist popup menu
// do this method before getStatusBar to avoid null pointer exception
this.taskManagerScreen = this.getTaskManagerScreen();
// initialise child screens
historyScreen = new HistoryScreen();
childScreens.put("History", historyScreen);
childScreens.put("ShowSource", new ShowSourceScreen());
childScreens.put("Import", new ImportScreen());
childScreens.put("TaskList", taskManagerScreen);
// create operation panel using metadata
try {
operationsPanel = new OperationPanel(parsedCategories);
} catch (ParseException e) {
logger.error("VVSADL parse failed", e);
throw new MicroarrayException(e);
}
operationsFrame = getOperationsFrame();
visualisationFrameManager = new VisualisationFrameManager();
visualisationArea = getVisualisationFrameManager().getFramesPanel();
rightSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, operationsFrame, visualisationArea);
rightSplit.setDividerLocation(VisualConstants.TREE_PANEL_HEIGHT);
rightSplit.setResizeWeight(0.1);
// initialise left side
leftSideContentPane = new JPanel(new BorderLayout());
details = new DetailsPanel(leftSideContentPane);
leftSideContentPane.setBorder(BorderFactory.createEmptyBorder());
/* Initialize tree and graph */
//moved to getTreeFrame
// this.tree = new TreePanel(manager.getRootFolder());
this.graphPanel = new GraphPanel();
treeFrame = getTreeFrame();
graphFrame = getGraphFrame();
leftSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, treeFrame, graphFrame);
leftSplit.setDividerLocation(VisualConstants.TREE_PANEL_HEIGHT);
leftSplit.setResizeWeight(0.1);
detailsFrame = getDetailsFrame();
leftSideContentPane.add(leftSplit, BorderLayout.CENTER);
leftSideContentPane.add(detailsFrame, BorderLayout.SOUTH);
rightSideViewChanger = new JPanel(new BorderLayout());
rightSideViewChanger.add(rightSplit, BorderLayout.CENTER);
rightSideViewChanger.setBorder(BorderFactory.createEmptyBorder());
// construct the whole main content pane
mainSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftSideContentPane, rightSideViewChanger);
mainSplit.setDividerLocation(VisualConstants.LEFT_PANEL_WIDTH);
mainSplit.setResizeWeight(0.1);
// add menus
menuBar = new MicroarrayMenuBar(this);
// create status bar
statusBar = new StatusBar(this);
// sets 3D-look (JGoodies property)
menuBar.putClientProperty(Options.HEADER_STYLE_KEY, HeaderStyle.SINGLE);
// put everything together
mainFrame.getContentPane().setLayout(new BorderLayout());
mainFrame.getContentPane().add(mainSplit, BorderLayout.CENTER);
mainFrame.getContentPane().add(statusBar.getStatusPanel(), BorderLayout.SOUTH);
mainFrame.setJMenuBar(menuBar);
menuBar.updateMenuStatus();
// add glass wait panel
JRootPane rootPane = SwingUtilities.getRootPane(mainFrame);
rootPane.setGlassPane(waitPanel);
// add shutdown listener
mainFrame.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
quit();
}
});
// make window visible
mainFrame.setIconImage(VisualConstants.APPLICATION_ICON.getImage());
mainFrame.pack();
mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
// Remember changes to confirm close only when necessary
manager.addDataChangeListener(new DataChangeListener() {
public void dataChanged(DataChangeEvent event) {
unsavedChanges = true;
}
});
// it's alive!
super.setEventsEnabled(true);
manager.setEventsEnabled(true);
// hide splashscreen
splashScreen.close();
// notify listener
if (clientListener != null) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
clientListener.onSuccessfulInitialisation();
}
});
}
customiseFocusTraversal();
restoreDefaultView();
}
private void customiseFocusTraversal() throws MicroarrayException {
Vector<Component> order = new Vector<Component>();
order.addAll(tree.getFocusComponents());
order.addAll(operationsPanel.getFocusComponents());
order.addAll(visualisationFrameManager.getFocusComponents());
getMainFrame().setFocusTraversalPolicy(new ClientFocusTraversalPolicy(order));
}
private String windowTitleJobPrefix = null;
private String windowTitleBlockingPrefix = null;
public void updateWindowTitleJobCount(Integer jobCount) {
windowTitleJobPrefix = jobCount > 0 ? jobCount + " jobs / " : null;
updateWindowTitle();
}
public void updateWindowTitleBlockingState(String operation) {
if (operation != null) {
windowTitleBlockingPrefix = Strings.startWithUppercase(operation) + " / ";
} else {
windowTitleBlockingPrefix = null;
}
updateWindowTitle();
}
public void updateWindowTitle() {
if (windowTitleBlockingPrefix != null) {
this.mainFrame.setTitle(windowTitleBlockingPrefix + ApplicationConstants.APPLICATION_TITLE);
} else if (windowTitleJobPrefix != null) {
this.mainFrame.setTitle(windowTitleJobPrefix + ApplicationConstants.APPLICATION_TITLE);
} else {
this.mainFrame.setTitle(ApplicationConstants.APPLICATION_TITLE);
}
}
public SimpleInternalFrame getOperationsFrame() {
if (operationsFrame == null) {
operationsFrame = new SimpleInternalFrame("Analysis tools");
operationsFrame.setContent(operationsPanel);
}
return operationsFrame;
}
public SimpleInternalFrame getGraphFrame() throws MicroarrayException {
if (graphFrame == null) {
graphFrame = new SimpleInternalFrame("Workflow", graphPanel.getButtonToolBar(), graphPanel.getScroller());
}
return graphFrame;
}
public SimpleInternalFrame getTreeFrame() throws MicroarrayException {
if (treeFrame == null) {
treeFrame = new SimpleInternalFrame("Datasets");
CardLayout cardLayout = new CardLayout();
JPanel cardPanel = new JPanel(cardLayout);
QuickLinkPanel linkPanel = new QuickLinkPanel();
this.tree = new TreePanel(manager.getRootFolder(), cardPanel, cardLayout);
cardPanel.add(linkPanel, "LINKS");
cardPanel.add(tree, "TREE");
treeFrame.add(cardPanel);
cardLayout.first(cardPanel);
return treeFrame;
} else {
return treeFrame;
}
}
public SimpleInternalFrame getDetailsFrame() throws MicroarrayException {
if (detailsFrame == null) {
class DetailsFrame extends SimpleInternalFrame implements PropertyChangeListener {
public DetailsFrame() {
super("Notes for dataset");
}
public void propertyChange(PropertyChangeEvent evt) {
if (evt instanceof DatasetChoiceEvent) {
DatasetChoiceEvent dce = (DatasetChoiceEvent) evt;
if (dce.getNewValue() != null) {
this.setTitle("Notes for dataset " + dce.getNewValue());
} else {
this.setTitle("Notes for dataset");
}
}
}
}
DetailsFrame detailsFrameWithListener = new DetailsFrame();
addPropertyChangeListener(detailsFrameWithListener);
this.detailsFrame = detailsFrameWithListener;
detailsFrame.add(details);
return detailsFrame;
} else {
return detailsFrame;
}
}
/**
* ExperienceBlue is very nice color theme, but it has ugly orange borders
* around focused components. This helper class customizes the theme a bit.
*
* @author mkoski
*/
private static class CustomExperienceBlue extends ExperienceBlue {
/**
* Removes the ugly orange focus color
*/
@Override
public ColorUIResource getFocusColor() {
return new ColorUIResource(VisualConstants.PLASTIC3D_FOCUS_COLOR);
}
@Override
public FontUIResource getControlTextFont() {
return new FontUIResource(super.getControlTextFont().deriveFont(fontSize));
}
@Override
public FontUIResource getTitleTextFont() {
return new FontUIResource(super.getTitleTextFont().deriveFont(fontSize));
}
@Override
public FontUIResource getSubTextFont() {
return new FontUIResource(super.getSubTextFont().deriveFont(fontSize));
}
@Override
public FontUIResource getSystemTextFont() {
return new FontUIResource(super.getSystemTextFont().deriveFont(fontSize));
}
@Override
public FontUIResource getUserTextFont() {
return new FontUIResource(super.getUserTextFont().deriveFont(fontSize));
}
@Override
public FontUIResource getWindowTitleFont() {
return new FontUIResource(super.getWindowTitleFont().deriveFont(fontSize));
}
@Override
public FontUIResource getMenuTextFont() {
return new FontUIResource(super.getMenuTextFont().deriveFont(fontSize));
}
}
private static PlasticTheme theme;
private static LookAndFeel lnf;
/**
* This method sets applications appearance to new level by using Plastic3D
* Look And Feel and ExperienceBlue color theme.
*
* The method sets look and feel and updates UIDefault values. After that it
* updates all the components to the new appearance.
*
* @param componentTreeRoot
* root component of component tree (frame component in most
* cases)
*
*/
public static void setPlastic3DLookAndFeel(Component componentTreeRoot) {
// Look and Feel change must be done only once, otherwise the custom
// values
// from the components get overridden. However this method is called
// several
// times for different child windows, but these ifs do the job.
if (theme == null) {
theme = new CustomExperienceBlue();
Plastic3DLookAndFeel.setPlasticTheme(theme);
}
if (lnf == null) {
lnf = new Plastic3DLookAndFeel();
try {
UIManager.installLookAndFeel("Plastic3D", lnf.getClass().getName());
UIManager.setLookAndFeel(lnf);
} catch (UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
}
// set the UI defaults
UIDefaults defaults = UIManager.getDefaults();
// Done several times, but luckily map rejects duplicates
defaults.putAll(VisualConstants.getUIDefaults());
SwingUtilities.updateComponentTreeUI(componentTreeRoot);
}
public void setFontSize(float size) {
fontSize = size;
SwingUtilities.updateComponentTreeUI(mainFrame);
fixFileChooserFontSize(importExportFileChooser);
// Running progressBar don't care about updateUI
statusBar.setFontSize(fontSize);
Iterator<Screen> iter = childScreens.getScreenIterator();
while (iter.hasNext()) {
Screen screen = iter.next();
SwingUtilities.updateComponentTreeUI(screen.getFrame());
}
}
public float getFontSize() {
return fontSize;
}
public JFrame getMainFrame() {
return mainFrame;
}
/**
* Sets the folder with given name selected or creates a new folder if it
* doesn't exist yet. Selected folder is used as a place for imported files.
* If folder name is null, root folder is returned
*
* @param folderName
* folder name
* @return just created or previously existing folder. If given folder name
* is <code>null</code>, root folder is returned
*/
public DataFolder initializeFolderForImport(String folderName) {
DataFolder root = manager.getRootFolder();
if (folderName == null) {
logger.debug("initializing for import " + folderName + ": is null => using root");
return root;
} else if (ImportUtils.getFolderNames(false).contains(folderName)) {
logger.debug("initializing for import " + folderName + ": exists already");
DataFolder folderToSelect;
if (folderName.equals(root.getName())) {
folderToSelect = root;
} else {
folderToSelect = root.getChildFolder(folderName);
}
getSelectionManager().selectSingle(folderToSelect, this);
return folderToSelect;
} else {
logger.debug("initializing for import " + folderName + ": creating new ");
DataFolder folder = getDataManager().createFolder(root, folderName);
getSelectionManager().selectSingle(folder, this);
return folder;
}
}
@Override
public void importGroup(final Collection<ImportItem> datas, final String folderName) {
runBlockingTask("importing files", new Runnable() {
public void run() {
DataBean lastGroupMember = null;
try {
for (ImportItem item : datas) {
String dataSetName = item.getOutput().getName();
ContentType contentType = item.getType();
Object dataSource = item.getInput();
// Selects folder where data is imported to, or creates a
// new one
DataFolder folder = initializeFolderForImport(folderName);
// get the InputStream for the data source
InputStream input;
if (dataSource instanceof File) {
input = new FileInputStream((File) (dataSource));
} else if (dataSource instanceof URL) {
// TODO Not used anymore, URL-files are saved to the
// temp file
URL url = (URL) dataSource;
try {
input = url.openStream();
} catch (FileNotFoundException fnfe) {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
showDialog("File not found.", null, "File not found. Check that the typed URL is pointing to a valid location", Severity.ERROR, false);
}
});
break;
} catch (IOException ioe) {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
showDialog("Import failed.", null, "Error occured while importing data from URL", Severity.ERROR, false);
}
});
break;
}
} else if (dataSource instanceof InputStream) {
logger.info("loading data from a plain stream, caching can not be used!");
input = (InputStream) dataSource;
} else {
throw new IllegalArgumentException("unknown dataSource type: " + dataSource.getClass().getSimpleName());
}
// create new data
DataBean data = manager.createDataBean(dataSetName, input);
data.setContentType(contentType);
// add the operation (all databeans have their own import
// operation
// instance, it would be nice if they would be grouped)
Operation importOperation = new Operation(OperationDefinition.IMPORT_DEFINITION, new DataBean[] { data });
data.setOperation(importOperation);
// data is ready now, make it visible
folder.addChild(data);
// Create group links only if both datas are raw type
if (lastGroupMember != null && ChipsterInputTypes.hasRawType(lastGroupMember) && ChipsterInputTypes.hasRawType(data)) {
DataBean targetData = data;
// Link new data to all group linked datas of given cell
for (DataBean sourceData : lastGroupMember.traverseLinks(new Link[] { Link.GROUPING }, Traversal.BIDIRECTIONAL)) {
logger.debug("Created GROUPING link between " + sourceData.getName() + " and " + targetData.getName());
createLink(sourceData, targetData, DataBean.Link.GROUPING);
}
// Create link to the given cell after looping to avoid
// link duplication
createLink(lastGroupMember, targetData, DataBean.Link.GROUPING);
}
lastGroupMember = data;
}
// select data
final DataBean selectedBean = lastGroupMember;
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
getSelectionManager().selectSingle(selectedBean, this);
}
});
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
/**
* Convenience method for showing exception dialogs with hand written
* messages and stack traces hidden first.
*
* @see #showDialog(String, String, String, Severity)
*/
public void showErrorDialog(String title, Exception error) {
showDialog(title, null, Exceptions.getStackTrace(error), Severity.ERROR, false);
}
/**
* @see #showDialog(String, String, String, Severity)
*/
public void showDialog(String title, Severity severity, boolean modal) {
showDialog(title, null, null, severity, modal);
}
public void showDialog(String title, String message, String details, Severity severity, boolean modal) {
showDialog(title, message, details, severity, modal, ChipsterDialog.DetailsVisibility.DETAILS_HIDDEN);
}
/**
* Shows a modal Chipster-styled dialog box to user. Use only when you need
* user's immediate attention.
*
* @param message
* message that is always shown to user
* @param details
* information that is shown in text box that if first closed
* @param severity
* severity level, affects icon choice
*/
public void showDialog(String title, String message, String details, Severity severity, boolean modal, ChipsterDialog.DetailsVisibility detailsVisibility) {
DialogInfo dialogInfo = new DialogInfo(severity, title, message, details);
ChipsterDialog.showDialog(mainFrame, dialogInfo, detailsVisibility, modal);
}
@Override
public File saveWorkflow() {
try {
JFileChooser fileChooser = this.getWorkflowFileChooser();
int ret = fileChooser.showSaveDialog(this.getMainFrame());
if (ret == JFileChooser.APPROVE_OPTION) {
File selected = fileChooser.getSelectedFile();
File newFile = selected.getName().endsWith(WorkflowManager.SCRIPT_EXTENSION) ? selected : new File(selected.getCanonicalPath() + "." + WorkflowManager.SCRIPT_EXTENSION);
workflowManager.saveSelectedWorkflow(newFile);
unsavedChanges = false;
menuBar.updateMenuStatus();
return newFile;
}
menuBar.updateMenuStatus();
} catch (IOException e) {
reportException(e);
}
return null;
}
public void runWorkflow(URL workflowScript) {
runWorkflow(workflowScript, null);
}
public void runWorkflow(URL workflowScript, final AtEndListener atEndListener) {
workflowManager.runScript(workflowScript, atEndListener);
}
@Override
public File openWorkflow() {
try {
JFileChooser fileChooser = this.getWorkflowFileChooser();
int ret = fileChooser.showOpenDialog(this.getMainFrame());
if (ret == JFileChooser.APPROVE_OPTION) {
runWorkflow(fileChooser.getSelectedFile().toURL());
menuBar.updateMenuStatus();
return fileChooser.getSelectedFile();
} else {
menuBar.updateMenuStatus();
return null;
}
} catch (MalformedURLException e) {
reportException(e);
return null;
}
}
public void showHistoryScreenFor(DataBean data) {
historyScreen.setData(data);
childScreens.show("History", true);
}
public void showDetailsFor(DataBean data) {
details.setViewedData(data);
}
public Icon getIconFor(DataItem element) {
if (element instanceof DataFolder) {
return VisualConstants.ICON_TYPE_FOLDER;
} else {
DataBean bean = (DataBean) element;
if (bean.queryFeatures("/phenodata").exists()) {
return VisualConstants.ICON_TYPE_PHENODATA;
} else {
return bean.getContentType().getIcon();
}
}
}
public void restoreDefaultView() {
leftSplit.setDividerLocation(VisualConstants.TREE_PANEL_HEIGHT);
mainSplit.setDividerLocation(VisualConstants.LEFT_PANEL_WIDTH);
rightSplit.setDividerLocation(VisualConstants.TREE_PANEL_HEIGHT);
mainSplit.validate();
}
public void reportTaskError(Task task) throws MicroarrayException {
String title = "Running " + task.getNamePrettyPrinted() + " failed. ";
String message = "You may have used a tool or parameters which are unsuitable for the selected dataset, or " + "there might be a bug in the analysis tool itself.\n\n" + "The details below may provide hints about the problem. The most useful information is usually at the few last lines.";
String details = "";
if (task.getErrorMessage() != null) {
details = task.getErrorMessage();
}
if (task.getScreenOutput() != null) {
details = details + "\n\n" + task.getScreenOutput();
}
DialogInfo dialogInfo = new DialogInfo(Severity.WARNING, title, message, details);
ChipsterDialog.showDialog(mainFrame, dialogInfo, ChipsterDialog.DetailsVisibility.DETAILS_ALWAYS_VISIBLE, false);
}
public void reportException(Exception e) {
// collect error information to dialogInfo
DialogInfo dialogInfo = new DialogInfo(Severity.ERROR, "An error has occurred and the action was not performed successfully.", "If problem persist, please check that your data is valid. For more information open the details panel below.", null);
// exception has extra info
if (e instanceof ErrorReportAsException) {
// exception has everything we need
ErrorReportAsException report = (ErrorReportAsException) e;
dialogInfo.setTitle(report.getTitle());
dialogInfo.setMessage(report.getMessage());
dialogInfo.setDetails(report.getDetails());
} else if (e instanceof MicroarrayException) {
// exception can be scavenged for details
MicroarrayException me = (MicroarrayException) e;
String details = "";
if (ErrorDialogUtils.getMessage(me.getExtraInfo()) != null) {
details += ErrorDialogUtils.getMessage(me.getExtraInfo()) + "\n";
}
if (ErrorDialogUtils.getScreenOutput(me.getExtraInfo()) != null) {
details += ErrorDialogUtils.getScreenOutput(me.getExtraInfo());
}
dialogInfo.setDetails(details);
} else {
// use stack trace as details
dialogInfo.setDetails(Exceptions.getStackTrace(e));
}
// show dialog
ChipsterDialog.showDialog(this.mainFrame, dialogInfo, ChipsterDialog.DetailsVisibility.DETAILS_HIDDEN, false);
// we'll always output these to console and log for traceability and
// easier IDE navigation
e.printStackTrace();
if (logger != null) {
logger.error("client got exception", e);
}
}
public void onException(JMSException e) {
reportException(e);
}
public void showChildScreen(String name, boolean packed) {
childScreens.show(name, packed);
}
public void showMaximisedVisualisation(boolean maximised) {
if (maximised) {
mainSplit.setDividerLocation(0);
rightSplit.setDividerLocation(0);
} else {
restoreDefaultView();
}
rightSideViewChanger.validate();
}
public void showPopupMenuFor(MouseEvent e, DataItem data) {
List<DataItem> datas = new ArrayList<DataItem>();
datas.add(data);
showPopupMenuFor(e, datas);
}
public void showPopupMenuFor(MouseEvent e, List<DataItem> datas) {
ClientContextMenu popup = new ClientContextMenu(this);
popup.setOptionsFor(datas);
popup.show(e.getComponent(), e.getX(), e.getY());
}
/**
* Is the selected databeans possible to visualise
*/
public boolean isSelectedDataVisualisable() {
return getDefaultVisualisationForSelection() != VisualisationMethod.NONE;
}
/**
* Gets default visualisation method for selected databeans. The method is
* selected by following steps:
*
* <ol>
* <li>If no dataset is selected, return
* <code>VisualisationMethod.NONE</code> </li>
* <li>If only one dataset is selected, return the default method for the
* data </li>
* </li>
* <li>If multiple datasets are selected, check the best method for each
* dataset. If the best method is same for all selected datasets and it can
* be used with multiple data, the best method is returned. </li>
* <li>If the best method is not same for all of the datas, try to find
* just some method which is suitable for all datas and can be used with
* multiple datasets. </li>
* <li>If there were no method to fill the requirements above, return
* <code>VisualisationMethod.NONE</code> </li>
*
* @return default visualisation method which is suitable for all selected
* datasets
*/
private VisualisationMethod getDefaultVisualisationForSelection() {
logger.debug("getting default visualisation");
if (getSelectionManager().getSelectedDataBeans() == null || getSelectionManager().getSelectedDataBeans().size() == 0) {
return VisualisationMethod.NONE;
}
try {
List<DataBean> beans = getSelectionManager().getSelectedDataBeans();
if (beans.size() == 1) {
return VisualisationMethod.getDefaultVisualisationFor(beans.get(0));
} else if (beans.size() > 1)
for (VisualisationMethod method : VisualisationMethod.orderedDefaultCandidates()) {
if (method == VisualisationMethod.NONE || !method.getHeadlessVisualiser().isForMultipleDatas()) {
continue;
}
if (method.isApplicableTo(beans)) {
return method;
}
}
/*
*
* VisualisationMethod defaultMethodForDatas = null; // First, try
* to find best suitable visualisation for all for (DataBean bean :
* beans) { VisualisationMethod method = new
* BioBean(bean).getDefaultVisualisation(); if
* (defaultMethodForDatas == null &&
* VisualisationMethod.isApplicableForMultipleDatas(method)) {
* defaultMethodForDatas = method; } else { if
* (defaultMethodForDatas != method) { // Searching for best method
* for all failed defaultMethodForDatas = null; logger.debug("Method " +
* method + " can not be used to visualise selected datas"); break; } } }
*
* if (defaultMethodForDatas != null) { // Visualise datas if the
* best method was found logger.debug("Method " +
* defaultMethodForDatas + " will be used to visualise selected
* datas"); return defaultMethodForDatas; } // Keep looking for
* suitable visualisation DataBean firstData = beans.get(0);
*
* for (VisualisationMethod method :
* VisualisationMethod.getApplicableForMultipleDatas()) { if (method ==
* VisualisationMethod.NONE) { continue; }
*
* if (method.isApplicableTo(firstData)) { // The method is
* applicable to one of the selected datas // Check that the same
* method is applicable to the other // datasets too boolean
* isSuitableMethod = true; for (DataBean otherData : beans) { if
* (otherData.equals(firstData)) { continue; }
*
* if (!method.isApplicableTo(otherData)) { isSuitableMethod =
* false; logger.debug("Method " + method + " can not be used to
* visualise selected datas"); break; } }
*
* if (isSuitableMethod) { logger.debug("Method " + method + " will
* be used to visualise selected datas"); return method; } } }
*/
return VisualisationMethod.NONE;
} catch (Exception e) {
reportException(e);
return VisualisationMethod.NONE;
}
}
public void visualiseWithBestMethod(FrameType target) {
setVisualisationMethod(getDefaultVisualisationForSelection(), null, getSelectionManager().getSelectedDataBeans(), target);
}
public void deleteDatas(DataItem... datas) {
// check that we have something to delete
if (datas.length == 0) {
return; // no selection, do nothing
}
// choose confirm dialog message
JLabel confirmMessage = null;
if (datas.length > 1) {
confirmMessage = new JLabel("Really delete " + datas.length + " data items?");
} else if (datas[0] instanceof DataFolder) {
confirmMessage = new JLabel("Really delete " + datas[0].getName() + " and all of its contents?");
} else if (datas[0] instanceof DataBean) {
confirmMessage = new JLabel("Really delete " + datas[0].getName() + " ?");
} else {
throw new IllegalArgumentException("datas is illegal");
}
// confirm delete
if (JOptionPane.showConfirmDialog(this.mainFrame, confirmMessage, "Delete items", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) {
return; // deletion was not confirmed
}
// delete actually
deleteDatasWithoutConfirming(datas);
}
public void deleteDatasWithoutConfirming(DataItem... datas) {
// check that we have something to delete
if (datas.length == 0) {
return; // no selection, do nothing
}
// remove all selections
getSelectionManager().clearAll(true, this);
// do actual delete
for (DataItem data : datas) {
manager.delete(data);
}
}
public void fixFileChooserFontSize(JFileChooser fileChooser) {
// Some special care has to be taken to get the fileChooser list update
// also
if (fileChooser != null) {
UIManager.put("FileChooser.listFont", UIManager.getFont("List.font").deriveFont(fontSize));
SwingUtilities.updateComponentTreeUI(fileChooser);
}
}
public void openFileImport() throws MicroarrayException, IOException {
JFileChooser fc = getImportExportFileChooser();
fc.setMultiSelectionEnabled(true);
ImportSettingsAccessory access = (ImportSettingsAccessory) importExportFileChooser.getAccessory();
access.setDefaults();
int ret = fc.showOpenDialog(getMainFrame());
if (ret == JFileChooser.APPROVE_OPTION) {
List<File> files = new ArrayList<File>();
for (File file : fc.getSelectedFiles()) {
files.add(file);
}
ImportSession importSession = new ImportSession(ImportSession.Source.FILES, files, access.getImportFolder(), access.skipActionChooser());
ImportUtils.executeImport(importSession);
}
}
public void openDirectoryImportDialog() {
JFileChooser fc = getImportExportDirChooser();
fc.setSelectedFile(new File(""));
int ret = fc.showOpenDialog(this.getMainFrame());
if (ret == JFileChooser.APPROVE_OPTION) {
File selectedFile = fc.getSelectedFile();
super.importWholeDirectory(selectedFile);
}
}
public void openURLImport() throws MicroarrayException, IOException {
URLImportDialog urlImportDlg = new URLImportDialog(this);
URL selectedURL = urlImportDlg.getSelectedURL();
String importFolder = urlImportDlg.getSelectedFolderName();
if (selectedURL != null) {
File file = ImportUtils.createTempFile(ImportUtils.URLToFilename(selectedURL), ImportUtils.getExtension(ImportUtils.URLToFilename(selectedURL)));
ImportUtils.getURLFileLoader().loadFileFromURL(selectedURL, file, importFolder, urlImportDlg.isSkipSelected());
}
}
public void openClipboardImport() throws MicroarrayException, IOException {
new ClipboardImportDialog(this);
}
protected void quit() {
int returnValue = JOptionPane.DEFAULT_OPTION;
// Check the running tasks
if (taskExecutor.getRunningTaskCount() > 0) {
String message = "";
if (taskExecutor.getRunningTaskCount() == 1) {
message += "There is a running task. Are you sure you want to cancel the running task?";
} else {
message += "There are " + taskExecutor.getRunningTaskCount() + " running tasks. " + "Are you sure you want to cancel all running tasks?";
}
Object[] options = { "Cancel running tasks", "Cancel" };
returnValue = JOptionPane.showOptionDialog(this.getMainFrame(), message, "Confirm close", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (returnValue == JOptionPane.YES_OPTION) {
taskExecutor.killAll();
} else {
return;
}
}
// Check for unsaved changes
returnValue = JOptionPane.DEFAULT_OPTION;
if (unsavedChanges) {
Object[] options = { "Save and close", "Close without saving", "Cancel" };
returnValue = JOptionPane.showOptionDialog(this.getMainFrame(), "Do you want the session to be saved before closing Chipster?", "Confirm close", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (returnValue == 0) {
try {
saveSession();
} catch (Exception exp) {
this.showErrorDialog("Session saving failed", exp);
return;
}
// cancel also if the dialog is closed from the corner x
} else if (returnValue != 1) {
return;
}
}
// hide immediately to look more reactive...
childScreens.disposeAll();
mainFrame.setVisible(false);
super.quit();
// this closes the application
mainFrame.dispose();
System.exit(0);
}
/**
* Starts Chipster client. Configuration (logging) should be initialised
* before calling this method.
*/
public static void start(String configURL) throws IOException {
try {
DirectoryLayout.initialiseClientLayout(configURL);
} catch (IllegalConfigurationException e) {
reportIllegalConfigurationException(e);
}
ClientListener shutdownListener = new ClientListener() {
public void onSuccessfulInitialisation() {
// do nothing
}
public void onFailedInitialisation() {
System.exit(1);
}
};
try {
new SwingClientApplication(shutdownListener, null);
} catch (Throwable t) {
t.printStackTrace();
if (logger != null) {
logger.error(t.getMessage());
logger.error(t);
}
}
}
public static void main(String[] args) throws IOException {
start(null);
}
public static void reportIllegalConfigurationException(IllegalConfigurationException e) {
DialogInfo dialogInfo = new DialogInfo(Severity.ERROR, "Illegal configuration", "Chipster could not start because the provided configuration file is illegal. Please contact your system administrator.", "Reason: " + e.getMessage());
ChipsterDialog.showDialog(null, dialogInfo, DetailsVisibility.DETAILS_HIDDEN, true);
throw new RuntimeException("configuration not compatible, will not start");
}
@Override
public void showSourceFor(String operationName) throws TaskException {
childScreens.show("ShowSource", true, operationName);
}
/**
* Opens JFileChooser to ask location for the export, then calls
* exportDataDirectory to do the job.
*
* @param data
* @throws MicroarrayException
* @throws IOException
*/
public void exportFolder(DataFolder data) throws MicroarrayException, IOException {
File file = new File(data.getName().replace(" ", "_"));
// file.mkdirs();
JFileChooser fc = getImportExportDirChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setSelectedFile(file);
logger.debug("Exporting File: " + fc.getSelectedFile().getAbsolutePath());
int ret = fc.showSaveDialog(getMainFrame());
if (ret == JFileChooser.APPROVE_OPTION) {
File selected = new File(fc.getSelectedFile().getAbsolutePath() + File.separator + file.getName());
selected.mkdirs();
exportDataFolder(data, selected);
}
}
/**
* Method to export recursively all descendants of the source
*
*/
private void exportDataFolder(DataFolder source, File dir) throws IOException, MicroarrayException {
for (DataItem child : source.getChildren()) {
if (child instanceof DataBean) {
String filename = createFilename((DataBean) child);
filename = dir.getAbsolutePath() + File.separator + filename;
logger.debug("Exporting dataBean " + child.getName() + " into " + filename);
exportToFile((DataBean) child, new File(filename));
} else if (child instanceof DataFolder) {
logger.debug("Exporting dataFolder " + child.getName());
String foldername = dir.getAbsolutePath() + File.separator + child.getName().replace(" ", "_");
File file = new File(foldername);
file.mkdir();
exportDataFolder((DataFolder) child, file);
}
}
}
public void exportDataset(DataBean data) throws MicroarrayException, IOException {
JFileChooser fc = this.getImportExportFileChooser();
fc.setDialogType(JFileChooser.SAVE_DIALOG);
String proposedName = createFilename(data);
fc.setSelectedFile(new File(proposedName));
int ret = fc.showSaveDialog(getMainFrame());
if (ret == JFileChooser.APPROVE_OPTION) {
File selectedFile = fc.getSelectedFile();
exportToFile(data, selectedFile);
}
}
private String createFilename(DataBean data) {
String proposedName = data.getName().replace(" ", "_");
/*
* TODO does not work with mime content types if
* (!proposedName.endsWith(data.getContentType())) { proposedName =
* proposedName + "." + data.getContentType(); }
*/
return proposedName;
}
@Override
protected AuthenticationRequestListener getAuthenticationRequestListener() {
AuthenticationRequestListener authenticator;
if (overridingARL != null) {
authenticator = overridingARL;
} else {
authenticator = new Authenticator();
}
authenticator.setLoginListener(new ClientLoginListener() {
public void firstLogin() {
try {
initialiseGUI();
} catch (Exception e) {
reportException(e);
}
}
public void loginCancelled() {
System.exit(1);
}
});
return authenticator;
}
@Override
public void setMaximisedVisualisationMode(boolean maximisedVisualisationMode) {
showMaximisedVisualisation(maximisedVisualisationMode);
}
@Override
public void setVisualisationMethod(VisualisationMethod method, List<Variable> variables, List<DataBean> datas, FrameType target) {
if (method == null || datas == null) {
super.setVisualisationMethod(VisualisationMethod.NONE, null, null, target);
return;
}
long estimate = method.estimateDuration(datas);
if (estimate > SLOW_VISUALISATION_LIMIT) {
int returnValue = JOptionPane.DEFAULT_OPTION;
String message = "";
int severity;
// Check the running tasks
if (estimate > VERY_SLOW_VISUALISATION_LIMIT) {
message += "Visualising the selected large dataset with this method might stop Chipster from responding. \n" + "If you choose to continue, it's recommended to save the session before visualising.";
severity = JOptionPane.WARNING_MESSAGE;
} else {
message += "Are you sure you want to visualise large dataset, which may " + "take several seconds?";
severity = JOptionPane.QUESTION_MESSAGE;
}
Object[] options = { "Cancel", "Visualise" };
returnValue = JOptionPane.showOptionDialog(this.getMainFrame(), message, "Cancel visualisation", JOptionPane.YES_NO_OPTION, severity, null, options, options[0]);
if (returnValue == 1) {
super.setVisualisationMethod(method, variables, datas, target);
} else {
return;
}
} else {
super.setVisualisationMethod(method, variables, datas, target);
}
}
public void exportSelectedItems() {
try {
for (DataItem item : getSelectionManager().getSelectedDataItems()) {
if (item instanceof DataBean) {
exportDataset((DataBean) item);
} else if (item instanceof DataFolder) {
exportFolder((DataFolder) item);
}
}
} catch (Exception e) {
reportException(e);
}
}
private JFileChooser getImportExportDirChooser() {
if (importExportFileChooser == null) {
importExportFileChooser = ImportUtils.getFixedFileChooser();
}
importExportFileChooser.setAccessory(null);
importExportFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
String description = "Data Directory";
String[] extensions = {}; // only directories
for (FileFilter filter : importExportFileChooser.getChoosableFileFilters()) {
importExportFileChooser.removeChoosableFileFilter(filter);
}
importExportFileChooser.addChoosableFileFilter(new GeneralFileFilter(description, extensions));
importExportFileChooser.setAcceptAllFileFilterUsed(false);
fixFileChooserFontSize(importExportFileChooser);
return importExportFileChooser;
}
/**
* This is public to give access to file filter from ImportUtils
*
* @return The default JFileChooser with an assigned MicroarrayFileFilter.
*/
public JFileChooser getImportExportFileChooser() {
if (importExportFileChooser == null) {
importExportFileChooser = ImportUtils.getFixedFileChooser();
}
// FIXME All files to default filter and other as a single file
// filters
String description = "Common microarray filetypes (cel, spot, gpr, txt, csv, tsv)";
String[] extensions = { "cel", // affymetrix
"spot", // SPOT files
"gpr", // GenePix
"txt", "csv", // illumina
"tsv" // chipster
};
for (FileFilter filter : importExportFileChooser.getChoosableFileFilters()) {
importExportFileChooser.removeChoosableFileFilter(filter);
}
importExportFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
importExportFileChooser.setAcceptAllFileFilterUsed(true);
FileFilter filter = new GeneralFileFilter(description, extensions);
importExportFileChooser.addChoosableFileFilter(filter);
importExportFileChooser.setFileFilter(filter);
ImportSettingsAccessory access = new ImportSettingsAccessory(importExportFileChooser);
importExportFileChooser.setAccessory(access);
fixFileChooserFontSize(importExportFileChooser);
return importExportFileChooser;
}
private JFileChooser getSnapshotFileChooser(JComponent accessory) {
if (snapshotFileChooser == null) {
snapshotFileChooser = ImportUtils.getFixedFileChooser();
String[] extensions = { FSSnapshottingSession.SNAPSHOT_EXTENSION };
snapshotFileChooser.setFileFilter(new GeneralFileFilter("Chipster Session", extensions));
snapshotFileChooser.setSelectedFile(new File("session." + FSSnapshottingSession.SNAPSHOT_EXTENSION));
snapshotFileChooser.setAcceptAllFileFilterUsed(false);
snapshotFileChooser.setMultiSelectionEnabled(false);
}
snapshotFileChooser.setAccessory(accessory);
fixFileChooserFontSize(snapshotFileChooser);
return snapshotFileChooser;
}
private JFileChooser getWorkflowFileChooser() {
if (workflowFileChooser == null) {
workflowFileChooser = ImportUtils.getFixedFileChooser(workflowManager.getScriptDirectory());
workflowFileChooser.setFileFilter(WorkflowManager.FILE_FILTER);
workflowFileChooser.setSelectedFile(new File("workflow.bsh"));
workflowFileChooser.setAcceptAllFileFilterUsed(false);
workflowFileChooser.setMultiSelectionEnabled(false);
}
fixFileChooserFontSize(workflowFileChooser);
return workflowFileChooser;
}
/**
* Opens import tool directly
*
* @param useSameSettings
*
* @param file
*/
public void openImportTool(ImportSession importSession) {
ImportScreen importScreen = (ImportScreen) childScreens.get("Import");
importScreen.setImportSession(importSession);
importScreen.updateTable(false);
childScreens.show("Import", false);
}
/**
* <p>Run a task in background thread and block GUI in a friendly way while the task is being
* run. <strong>Note!</strong> If the task modifies GUI, it must use SwingUtilities.invokeAndWait so that
* modifications are done in event dispatch thread.</p>
*
* @param taskName
* name of the task we will be running, like "importing" or
* "loading"
* @param runnable
* the task
*/
public void runBlockingTask(String taskName, final Runnable runnable) {
Thread backgroundThread = new Thread(new Runnable() {
public void run() {
try {
runnable.run();
} catch (final Exception e) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
reportException(e);
}
});
} finally {
waitPanel.stopWaiting();
updateWindowTitleBlockingState(null);
}
}
});
waitPanel.startWaiting("Please wait while " + taskName + "...");
updateWindowTitleBlockingState(taskName);
backgroundThread.start();
}
public void viewHelpFor(OperationDefinition definition) {
viewHelp(HelpMapping.mapToHelppage(definition));
}
public void viewHelp(String page) {
try {
BrowserLauncher.openURL("https://extras.csc.fi/biosciences/" + page);
} catch (Exception e) {
reportException(e);
}
}
protected void garbageCollect() {
System.gc();
statusBar.updateMemoryIndicator();
}
public TaskManagerScreen getTaskManagerScreen() {
TaskExecutor jobExecutor = Session.getSession().getJobExecutor("client-job-executor");
return new TaskManagerScreen(jobExecutor);
}
public void createLink(DataBean source, DataBean target, Link type) {
source.addLink(type, target);
}
public void removeLink(DataBean source, DataBean target, Link type) {
source.removeLink(type, target);
}
@Override
public void showImportToolFor(File file, String destinationFolder, boolean skipActionChooser) {
ImportSession importSession = new ImportSession(ImportSession.Source.FILES, new File[] { file }, destinationFolder, skipActionChooser);
openImportTool(importSession);
}
@Override
public void loadSessionFrom(URL url) {
try {
final File tempFile = ImportUtils.createTempFile(ImportUtils.URLToFilename(url), ImportUtils.getExtension(ImportUtils.URLToFilename(url)));
InformationDialog info = new InformationDialog("Loading session", "Loading session from the specified URL", null);
FileLoaderProcess fileLoaderProcess = new FileLoaderProcess(tempFile, url, info) {
@Override
protected void postProcess() {
loadSessionImpl(tempFile);
};
};
fileLoaderProcess.runProcess();
} catch (IOException e) {
reportException(e);
}
}
@Override
public void loadSession() {
SnapshotAccessory accessory = new SnapshotAccessory();
final JFileChooser fileChooser = getSnapshotFileChooser(accessory);
int ret = fileChooser.showOpenDialog(this.getMainFrame());
if (ret == JFileChooser.APPROVE_OPTION) {
if (accessory.clearSession()) {
if (!clearSession()) {
return; // loading cancelled
}
}
loadSessionImpl(fileChooser.getSelectedFile());
}
menuBar.updateMenuStatus();
}
private void loadSessionImpl(final File sessionFile) {
final ClientApplication application = this; // for inner class
runBlockingTask("loading the session", new Runnable() {
public void run() {
try {
/* If there wasn't data or it was just cleared, there is no need to warn about
* saving after opening session. However, if there was datasets already, combination
* of them and new session can be necessary to save. This has to set after the import, because
*/
boolean somethingToSave = getAllDataBeans().size() != 0;
final List<DataItem> newItems = manager.loadSnapshot(sessionFile, manager.getRootFolder(), application);
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
getSelectionManager().selectSingle(newItems.get(newItems.size() - 1), this); // select last
}
});
unsavedChanges = somethingToSave;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
@Override
public void saveSession() {
JFileChooser fileChooser = getSnapshotFileChooser(null);
int ret = fileChooser.showSaveDialog(this.getMainFrame());
final ClientApplication application = this; // for inner class
if (ret == JFileChooser.APPROVE_OPTION) {
try {
final File file = fileChooser.getSelectedFile().getName().endsWith("." + FSSnapshottingSession.SNAPSHOT_EXTENSION) ? fileChooser.getSelectedFile() : new File(fileChooser.getSelectedFile().getCanonicalPath() + "." + FSSnapshottingSession.SNAPSHOT_EXTENSION);
if (file.exists()) {
int returnValue = JOptionPane.DEFAULT_OPTION;
String message = "The file " + file.getCanonicalPath() + " exists already. Do you want " + "to replace it with the one you are saving?";
Object[] options = { "Cancel", "Replace" };
returnValue = JOptionPane.showOptionDialog(this.getMainFrame(), message, "Confirm replace", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (returnValue != 1) {
return;
}
}
runBlockingTask("saving session", new Runnable() {
public void run() {
try {
getDataManager().saveSnapshot(file, application);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
menuBar.updateMenuStatus();
unsavedChanges = false;
} catch (Exception exp) {
showErrorDialog("Saving session failed.", exp);
}
}
menuBar.updateMenuStatus();
}
/**
* @return true if cleared, false if canceled
*/
public boolean clearSession() {
int returnValue = JOptionPane.DEFAULT_OPTION;
if (unsavedChanges) {
String message = "The current session contains unsaved changes.\nDo you want to clear it anyway?";
Object[] options = { "Cancel", "Clear" };
returnValue = JOptionPane.showOptionDialog(this.getMainFrame(), message, "Clear session", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
}
if (!unsavedChanges || returnValue == 1) {
this.deleteDatasWithoutConfirming(manager.getRootFolder());
unsavedChanges = false;
return true;
}
return false;
}
@Override
public void heartBeat() {
statusBar.updateMemoryIndicator();
}
public DataManager getDataManager() {
return manager;
}
public VisualisationFrameManager getVisualisationFrameManager() {
return visualisationFrameManager;
}
@Override
public void flipTaskListVisibility(boolean closeIfVisible) {
statusBar.flipTaskListVisibility(closeIfVisible);
}
@Override
protected void taskCountChanged(int newTaskCount, boolean attractAttention) {
int completion = 0;
if (newTaskCount > 0) {
completion = taskExecutor.getTasks(true, false).iterator().next().getCompletionPercentage();
}
statusBar.taskCountChanged(newTaskCount, completion, attractAttention);
}
public void refreshTaskList() {
this.taskManagerScreen.refreshTasks();
}
public Screen getTaskListScreen() {
return childScreens.get("TaskList");
}
}
|
package com.team687.frc2017.utilities;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
* Linear interpolation / extrapolation unit testing
*
* @author tedlin
*
*/
@RunWith(Parameterized.class)
public class LinearInterpolatorTest {
private final static double[] InputValues1 = { 0, 1, 2, 3, 4, 5, 6, 7 };
private final static double[] OutputValues1 = { 0, 1, 2, 3, 4, 5, 6, 7 };
private final static double[] InputValues2 = { 0, 1, 2, 3, 4, 5, 6, 7 };
private final static double[] OutputValues2 = { 0, 2, 4, 6, 8, 10, 12, 14 };
private final static double[] InputValues3 = { 5, 7, 9, 11, 13 };
private final static double[] OutputValues3 = { 15, 21, 27, 33, 39 };
private final static double[] InputValues4 = { 3, 6, 1, 4, 5, 2, 3 };
private final static double[] OutputValues4 = { 1, 6, 2, 6, 2, 7, 3 };
private final static double[] InputValues5 = { 1690, 971, 1114, 987, 973, 1241, 2056 };
private final static double[] OutputValues5 = { 6, 2, 3, 2.54, 2.33, 3.3, 6.7 };
@Parameters
public static Collection<Object[]> testCases() {
return Arrays.asList(new Object[][] { { InputValues1, OutputValues1 }, { InputValues2, OutputValues2 },
{ InputValues3, OutputValues3 }, { InputValues4, OutputValues4 }, { InputValues5, OutputValues5 } });
}
private double[] m_sortedInputValues;
private double[] m_sortedOutputValues;
private LinearInterpolator m_estimator;
public LinearInterpolatorTest(double[] inputValues, double[] outputValues) {
m_estimator = new LinearInterpolator(inputValues, outputValues);
m_sortedInputValues = m_estimator.getSortedKeys();
m_sortedOutputValues = m_estimator.getSortedValues();
}
private static final double kEpsilon = 1E-9;
@Test
public void testSort() {
for (int i = 0; i < m_estimator.getMaxLength() - 2; i++) {
assertTrue(m_sortedInputValues[i] <= m_sortedInputValues[i + 1]);
assertTrue(m_sortedOutputValues[i] <= m_sortedOutputValues[i + 1]);
}
}
@Test
public void testDifferentLengths() {
double[] inputValues = { 33, 67, 118, 148 };
double[] outputValues = { 254, 330, 469, 971, 973, 987 };
LinearInterpolator estimator = new LinearInterpolator(inputValues, outputValues);
double[] sortedInputValues = estimator.getSortedKeys();
double[] sortedOutputValues = estimator.getSortedValues();
Assert.assertNotNull(sortedInputValues[estimator.getMaxLength() - 1]);
Assert.assertNotNull(sortedOutputValues[estimator.getMaxLength() - 1]);
}
@Test
public void testLowerBound() {
double output = m_estimator.estimate(-100);
assertEquals(output, m_sortedOutputValues[0], kEpsilon);
}
@Test
public void testInterpolatedSlope() {
for (int i = 0; i < m_estimator.getMaxLength() - 2; i++) {
double input = m_sortedInputValues[i] + (m_sortedInputValues[i + 1] - m_sortedInputValues[i]) / 3;
double output = m_estimator.estimate(input);
double expectedSlope = (m_sortedOutputValues[i + 1] - m_sortedOutputValues[i])
/ (m_sortedInputValues[i + 1] - m_sortedInputValues[i]);
double estimatedSlope = (m_sortedOutputValues[i + 1] - output) / (m_sortedInputValues[i + 1] - input);
assertEquals(expectedSlope, estimatedSlope, kEpsilon);
}
}
@Test
public void testExtrapolatedSlope() {
double input = 3 * m_sortedInputValues[m_estimator.getMaxLength() - 1] / 2;
double output = m_estimator.estimate(input);
double expectedSlope = (m_sortedOutputValues[m_estimator.getMaxLength() - 1] - m_sortedOutputValues[0])
/ (m_sortedInputValues[m_estimator.getMaxLength() - 1] - m_sortedInputValues[0]);
double estimatedSlope = (m_sortedOutputValues[m_estimator.getMaxLength() - 1] - output)
/ (m_sortedInputValues[m_estimator.getMaxLength() - 1] - input);
assertEquals(expectedSlope, estimatedSlope, kEpsilon);
}
}
|
package gl8080.lifegame.logic.definition;
import static javax.persistence.CascadeType.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Version;
import gl8080.lifegame.logic.AbstractEntity;
import gl8080.lifegame.logic.LifeGame;
import gl8080.lifegame.logic.LifeGameCell;
import gl8080.lifegame.logic.Position;
import gl8080.lifegame.logic.exception.IllegalParameterException;
import gl8080.lifegame.util.NestedLoop;
@Entity
@Table(name="GAME_DEFINITION")
public class GameDefinition extends AbstractEntity implements LifeGame {
private static final long serialVersionUID = 1L;
public static final int MAX_SIZE = 50;
private int size;
@Version
private Long version;
@OneToMany(cascade={PERSIST, MERGE, REMOVE})
@JoinColumn(name="GAME_DEFINITION_ID")
private Map<Position, CellDefinition> cells;
public GameDefinition(int size) {
if (size < 1) {
throw new IllegalParameterException(" size =" + size);
} else if (MAX_SIZE < size) {
throw new IllegalParameterException(" " + MAX_SIZE + " size =" + size);
}
this.size = size;
this.cells = NestedLoop.collectMap(size, Position::new, CellDefinition::new);
}
@Override
public Map<Position, ? extends LifeGameCell> getCells() {
return new HashMap<>(this.cells);
}
public void setStatus(Position position, boolean status) {
Objects.requireNonNull(position, " null ");
if (!this.cells.containsKey(position)) {
throw new IllegalParameterException(" (size = " + this.size + ", position = " + position + ")");
}
this.cells.get(position).setStatus(status);
}
/**
*
*
* @return
*/
public int getSize() {
return this.size;
}
@Override
public Long getVersion() {
return this.version;
}
public void setVersion(long version) {
this.version = version;
}
@Override
public String toString() {
return "GameDefinition [size=" + size + ", version=" + version + ", cells=" + cells + ", getId()=" + getId() + "]";
}
/**
* @deprecated
*/
@Deprecated @SuppressWarnings("unused")
private GameDefinition() {}
}
|
package info.faceland.strife.attributes;
public enum StrifeAttribute {
// modify any attributes here
HEALTH("Health", 20, false),
REGENERATION("Regeneration", 1.0, true),
ARMOR("Armor", 0, true),
RESISTANCE("Resistance", 0, true),
BLOCK("Block", 0.1, true, 0.85),
ABSORB_CHANCE("Absorb Chance", 0, true, 0.35),
PARRY("Parry Chance", 0, true, 0.75),
EVASION("Evasion", 0, true),
MOVEMENT_SPEED("Movement Speed", 100, false),
MELEE_DAMAGE("Melee Damage", 1, false),
RANGED_DAMAGE("Ranged Damage", 3, false),
SNARE_CHANCE("Snare Chance", 0, true),
ATTACK_SPEED("Attack Speed", 2D, true),
OVERCHARGE("Overcharge", 0.1, true),
ARMOR_PENETRATION("Armor Penetration", 0, true),
ACCURACY("Accuracy", 0, true),
CRITICAL_RATE("Critical Rate", 0.05, true),
CRITICAL_DAMAGE("Critical Damage", 1.5D, true),
FIRE_DAMAGE("Fire Damage", 0, false),
LIGHTNING_DAMAGE("Lightning Damage", 0, false),
ICE_DAMAGE("Ice Damage", 0, false),
IGNITE_CHANCE("Ignite Chance", 0.15, true),
SHOCK_CHANCE("Shock Chance", 0.15, true),
FREEZE_CHANCE("Freeze Chance", 0.15, true),
LIFE_STEAL("Life Steal", 0, true),
XP_GAIN("Experience Gain", 0D, true),
ITEM_DISCOVERY("Item Discovery", 0D, true),
GOLD_FIND("Gold Find", 0D, true),
HEAD_DROP("Head Drop", 0D, true),
LEVEL_REQUIREMENT("Level Requirement", 0, false),
DOGE("Doge Chance", 0D, true, 100D);
private final String name;
private final double baseValue;
private final boolean percentage;
private final double cap;
StrifeAttribute(String name, double baseValue, boolean percentage) {
this(name, baseValue, percentage, -1D);
}
StrifeAttribute(String name, double baseValue, boolean percentage, double cap) {
this.name = name;
this.baseValue = baseValue;
this.percentage = percentage;
this.cap = cap;
}
public static StrifeAttribute fromName(String s) {
for (StrifeAttribute val : values()) {
if (val.name.equalsIgnoreCase(s) || val.name().equalsIgnoreCase(s) || val.name.replace(" ", "-")
.equalsIgnoreCase(s) ||
val.name().replace("_", "-").equalsIgnoreCase(s)) {
return val;
}
}
return null;
}
public String getName() { return name; }
public double getBaseValue() {
return baseValue;
}
public boolean isPercentage() { return percentage; }
public double getCap() {
return cap;
}
}
|
package org.csstudio.opibuilder.actions;
import org.csstudio.opibuilder.OPIBuilderPlugin;
import org.csstudio.opibuilder.preferences.PreferencesHelper;
import org.csstudio.opibuilder.util.WorkbenchWindowService;
import org.csstudio.opibuilder.visualparts.TipDialog;
import org.csstudio.ui.util.CustomMediaFactory;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.internal.WorkbenchWindow;
/**The action to make CSS full screen.
* @author Xihui Chen
*
*/
@SuppressWarnings("restriction")
public class FullScreenAction extends Action implements
IWorkbenchWindowActionDelegate {
public static final String ID = "org.csstudio.opibuilder.actions.fullscreen";
private static final String FULLSCREEN = "Full Screen";
private static final String EXIT_FULL_SCREEN = "Exit Full Screen";
private Menu menuBar;
private boolean inFullScreen = false;
private Shell shell;
private ImageDescriptor fullScreenImage =
CustomMediaFactory.getInstance().getImageDescriptorFromPlugin(
OPIBuilderPlugin.PLUGIN_ID, "icons/fullscreen.png");
private ImageDescriptor exitFullScreenImage =
CustomMediaFactory.getInstance().getImageDescriptorFromPlugin(
OPIBuilderPlugin.PLUGIN_ID, "icons/exitfullscreen.png");
private IWorkbenchWindow window;
private boolean toolbarWasInvisible;
private boolean menuBarWasInvisible;
/**
* Constructor.
* @param part The workbench part associated with this PrintAction
*/
public FullScreenAction() {
setActionDefinitionId(ID);
}
/**
* @see org.eclipse.jface.action.Action#run()
*/
@Override
public void run() {
if (inFullScreen) {
shell.setFullScreen(false);
CompactModeAction compactAction = WorkbenchWindowService.getInstance().getCompactModeAction(window);
// set status line visibility depending on compact mode status
WorkbenchWindowService.setStatusLineVisibility((WorkbenchWindow) window,
compactAction.isInCompactMode() ? PreferencesHelper.showStatusLineInCompactMode() : true);
if (!toolbarWasInvisible){
WorkbenchWindowService.setToolbarVisibility((WorkbenchWindow) window, true);
}
if(!menuBarWasInvisible)
shell.setMenuBar(menuBar);
inFullScreen = false;
WorkbenchWindowService.setInFullScreenMode(false);
setText(FULLSCREEN);
setImageDescriptor(fullScreenImage);
}
else {
//enable or disable status line visibility
WorkbenchWindowService.setStatusLineVisibility((WorkbenchWindow) window, PreferencesHelper.showStatusLineInFullScreenMode());
if(PreferencesHelper.isShowFullScreenDialog()){
TipDialog dialog = new TipDialog(shell, "Tip",
"Press F11 to exit full screen.");
dialog.open();
if(!dialog.isShowThisDialogAgain())
PreferencesHelper.setShowFullScreenDialog(false);
}
shell.setFullScreen(true);
if (window instanceof WorkbenchWindow
&& !((WorkbenchWindow) window).getCoolBarVisible()) {
toolbarWasInvisible = true;
} else {
toolbarWasInvisible = false;
WorkbenchWindowService.setToolbarVisibility((WorkbenchWindow) window, false);
}
if(shell.getMenuBar() == null)
menuBarWasInvisible = true;
else{
menuBar = shell.getMenuBar();
menuBarWasInvisible = false;
}
shell.setMenuBar(null);
inFullScreen = true;
WorkbenchWindowService.setInFullScreenMode(true);
setText(EXIT_FULL_SCREEN);
setImageDescriptor(exitFullScreenImage);
}
}
@Override
public void run(IAction action) {
run();
}
@Override
public void selectionChanged(IAction action, ISelection selection) {
}
@Override
public void init(IWorkbenchWindow window) {
setId(ID);
this.window = window;
shell = window.getShell();
menuBar = shell.getMenuBar();
FullScreenAction registeredAction =
WorkbenchWindowService.getInstance().getFullScreenAction(window);
//copy states
if(registeredAction != null){
inFullScreen = registeredAction.inFullScreen;
menuBarWasInvisible = registeredAction.menuBarWasInvisible;
toolbarWasInvisible = registeredAction.toolbarWasInvisible;
menuBar = registeredAction.menuBar;
}
WorkbenchWindowService.getInstance().registerFullScreenAction(this, window);
setText(FULLSCREEN);
setImageDescriptor(fullScreenImage);
}
public boolean isInFullScreen() {
return inFullScreen;
}
@Override
public void dispose() {
WorkbenchWindowService.getInstance().unregisterFullScreenAction(window);
}
}
|
package info.u_team.u_team_core.data;
import java.io.IOException;
import java.nio.file.Path;
import java.util.*;
import java.util.function.*;
import java.util.stream.Collectors;
import com.google.common.collect.Maps;
import com.google.gson.JsonObject;
import net.minecraft.data.*;
import net.minecraft.data.TagsProvider.Builder;
import net.minecraft.tags.*;
import net.minecraft.tags.ITag.*;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.Registry;
public abstract class CommonTagsProvider<T> extends CommonProvider {
protected final Registry<T> registry;
protected final Map<ResourceLocation, ITag.Builder> tagToBuilder = Maps.newLinkedHashMap();
public CommonTagsProvider(GenerationData data, Registry<T> registry) {
super(data);
this.registry = registry;
}
protected abstract void registerTags();
@Override
public void act(DirectoryCache cache) {
tagToBuilder.clear();
registerTags();
tagToBuilder.forEach((location, builder) -> {
final List<ITag.Proxy> list = builder.func_232963_b_(id -> Tag.func_241284_a_(), id -> registry.func_241873_b(id).orElse(null)).collect(Collectors.toList());
if (!list.isEmpty()) {
throw new IllegalArgumentException(String.format("Couldn't define tag %s as it is missing following references: %s", location, list.stream().map(Objects::toString).collect(Collectors.joining(","))));
}
final JsonObject object = builder.serialize();
final Path path = makePath(location);
try {
write(cache, object, path);
} catch (final IOException ex) {
LOGGER.error(marker, "Could not write data.", ex);
}
});
}
protected abstract Path makePath(ResourceLocation location);
protected TagsProvider.Builder<T> getBuilder(ITag.INamedTag<T> tag) {
final ITag.Builder tagBuilder = getTagBuilder(tag);
return new Builder<>(tagBuilder, registry, modid);
}
protected ITag.Builder getTagBuilder(ITag.INamedTag<T> tag) {
return this.tagToBuilder.computeIfAbsent(tag.getName(), location -> new ITag.Builder());
}
/*public static class UniqueBuilder<T> extends TagsProvider.Builder<T> {
private final Registry<T> registry;
public UniqueBuilder(ITag.Builder builder, Registry<T> registry, String id) {
super(builder, registry, id);
this.registry = registry;
}
@Override
public Builder<T> addItemEntry(T item) {
final ResourceLocation location = registry.getKey(item);
return addUniqueItemEntry(ItemEntry.class, entry -> entry.identifier.equals(location), () -> super.addItemEntry(item));
}
@Override
public Builder<T> addTag(INamedTag<T> tag) {
final ResourceLocation location = tag.getName();
return addUniqueTagEntry(TagEntry.class, entry -> entry.id.equals(location), () -> super.addTag(tag));
}
@Override
public Builder<T> add(ITagEntry tag) {
return super.add(tag);
}
private <C extends ItemEntry> Builder<T> addUniqueItemEntry(Class<C> clazz, Predicate<C> predicate, Supplier<Builder<T>> add) {
return addUnique(clazz, predicate, add);
}
private <C extends OptionalItemEntry> Builder<T> addUniqueOptionalItemEntry(Class<C> clazz, Predicate<C> predicate, Supplier<Builder<T>> add) {
return addUnique(clazz, predicate, add);
}
private <C extends TagEntry> Builder<T> addUniqueTagEntry(Class<C> clazz, Predicate<C> predicate, Supplier<Builder<T>> add) {
return addUnique(clazz, predicate, add);
}
private <C extends OptionalTagEntry> Builder<T> addUniqueOptionalTagEntry(Class<C> clazz, Predicate<C> predicate, Supplier<Builder<T>> add) {
return addUnique(clazz, predicate, add);
}
private <C extends ITagEntry> Builder<T> addUnique(Class<C> clazz, Predicate<C> predicate, Supplier<Builder<T>> add) {
final boolean duplicate = getInternalBuilder().getProxyStream() //
.map(Proxy::getEntry) //
.filter(clazz::isInstance) //
.map(clazz::cast) //
.anyMatch(predicate);
if (!duplicate) {
return add.get();
}
return this;
}
}*/
}
|
package org.opencms.search.gallery;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsProperty;
import org.opencms.file.CmsResource.CmsResourceUndoMode;
import org.opencms.file.types.CmsResourceTypePlain;
import org.opencms.main.OpenCms;
import org.opencms.report.CmsShellReport;
import org.opencms.report.I_CmsReport;
import org.opencms.search.CmsSearchIndex;
import org.opencms.search.CmsSearchParameters;
import org.opencms.search.CmsSearchResultList;
import org.opencms.search.galleries.CmsGallerySearch;
import org.opencms.search.galleries.CmsGallerySearchIndex;
import org.opencms.search.galleries.CmsGallerySearchParameters;
import org.opencms.search.galleries.CmsGallerySearchParameters.CmsGallerySortParam;
import org.opencms.search.galleries.CmsGallerySearchResult;
import org.opencms.search.galleries.CmsGallerySearchResultList;
import org.opencms.test.OpenCmsTestCase;
import org.opencms.test.OpenCmsTestProperties;
import org.opencms.util.CmsDateUtil;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import java.text.DateFormat;
import java.util.Collections;
import java.util.Iterator;
import java.util.Locale;
import junit.extensions.TestSetup;
import junit.framework.Test;
import junit.framework.TestSuite;
/**
* Unit test for the basic OpenCms gallery search functions.<p>
*/
public class TestCmsGallerySearchBasic extends OpenCmsTestCase {
/**
* Default JUnit constructor.<p>
*
* @param arg0 JUnit parameters
*/
public TestCmsGallerySearchBasic(String arg0) {
super(arg0);
}
/**
* Prints the given list of search results to STDOUT.<p>
*
* @param searchResult the list to print
* @param cms the current OpenCms user context
*/
public static void printResults(CmsGallerySearchResultList searchResult, CmsObject cms) {
printResults(searchResult, cms, false);
}
/**
* Prints the given list of search results to STDOUT.<p>
*
* @param searchResult the list to print
* @param cms the current OpenCms user context
* @param showExcerpt if <code>true</code>, the generated excerpt is also displayed
*/
public static void printResults(CmsGallerySearchResultList searchResult, CmsObject cms, boolean showExcerpt) {
Iterator<CmsGallerySearchResult> i = searchResult.iterator();
int count = 0;
int colPath = 0;
int colTitle = 0;
while (i.hasNext()) {
CmsGallerySearchResult res = i.next();
String path = cms.getRequestContext().removeSiteRoot(res.getPath());
colPath = Math.max(colPath, path.length() + 3);
String title = res.getTitle();
if (title == null) {
title = "";
} else {
title = title.trim();
}
colTitle = Math.max(colTitle, title.length() + 3);
}
i = searchResult.iterator();
while (i.hasNext()) {
CmsGallerySearchResult res = i.next();
count++;
System.out.print(CmsStringUtil.padRight("" + count, 4));
System.out.print(CmsStringUtil.padRight(cms.getRequestContext().removeSiteRoot(res.getPath()), colPath));
String title = res.getTitle();
if (title == null) {
title = "";
} else {
title = title.trim();
}
System.out.print(CmsStringUtil.padRight(title, colTitle));
String type = res.getResourceType();
if (type == null) {
type = "";
}
System.out.print(CmsStringUtil.padRight(type, 10));
if (res.getDateLastModified() != null) {
System.out.print(CmsStringUtil.padRight(
"" + CmsDateUtil.getDateTime(res.getDateLastModified(), DateFormat.SHORT, Locale.GERMAN),
17));
}
System.out.println("score: " + res.getScore());
if (showExcerpt) {
System.out.println(res.getExcerpt());
}
}
}
/**
* Test suite for this test class.<p>
*
* @return the test suite
*/
public static Test suite() {
OpenCmsTestProperties.initialize(org.opencms.test.AllTests.TEST_PROPERTIES_PATH);
TestSuite suite = new TestSuite();
suite.setName(TestCmsGallerySearchBasic.class.getName());
suite.addTest(new TestCmsGallerySearchBasic("testGallerySearchIndexCreation"));
suite.addTest(new TestCmsGallerySearchBasic("testGallerySortSearchResults"));
suite.addTest(new TestCmsGallerySearchBasic("testSearchById"));
suite.addTest(new TestCmsGallerySearchBasic("testSearchForMovedFiles"));
TestSetup wrapper = new TestSetup(suite) {
@Override
protected void setUp() {
setupOpenCms("simpletest", "/sites/default/", "/../org/opencms/search/gallery");
}
@Override
protected void tearDown() {
removeOpenCms();
}
};
return wrapper;
}
/**
* Creates the configured search indexes for all other test cases in this class.<p>
*
* @throws Exception in case the test fails
*/
public void testGallerySearchIndexCreation() throws Exception {
echo("Testing dynamic creation of special index for galleries");
I_CmsReport report = new CmsShellReport(Locale.ENGLISH);
// rebuild all indexes
OpenCms.getSearchManager().rebuildAllIndexes(report);
// make sure the ADE index actually exists
CmsSearchIndex adeIndex = OpenCms.getSearchManager().getIndex(CmsGallerySearchIndex.GALLERY_INDEX_NAME);
assertNotNull("Index for galleries not initialized", adeIndex);
assertEquals("Index for galleries not of required class", CmsGallerySearchIndex.class, adeIndex.getClass());
}
/**
* Tests sorting of search results.<p>
*
* @throws Exception if the test fails
*/
public void testGallerySortSearchResults() throws Exception {
CmsObject cms = getCmsObject();
echo("Testing sorting of search results for galleries");
// perform a search on the newly generated index
CmsGallerySearch searchBean = new CmsGallerySearch();
CmsGallerySearchParameters searchParams = new CmsGallerySearchParameters();
CmsGallerySearchResultList searchResult;
String query = "OpenCms";
searchBean.init(cms);
searchBean.setIndex(CmsGallerySearchIndex.GALLERY_INDEX_NAME);
searchParams.setSearchWords(query);
searchParams.setMatchesPerPage(50);
// first run is default sort order
searchParams.setSortOrder(CmsGallerySortParam.score);
searchResult = searchBean.getResult(searchParams);
System.out.println("Result sorted by score:");
printResults(searchResult, cms);
// second run use Title sort order
String lastTitle = null;
searchParams.setSortOrder(CmsGallerySortParam.title_asc);
searchResult = searchBean.getResult(searchParams);
System.out.println("Result sorted by title ascending:");
printResults(searchResult, cms);
Iterator<CmsGallerySearchResult> i = searchResult.iterator();
while (i.hasNext()) {
CmsGallerySearchResult res = i.next();
if (lastTitle != null) {
// make sure result is sorted correctly
assertTrue(lastTitle.compareTo(res.getTitle()) <= 0);
}
lastTitle = res.getTitle();
}
searchParams.setSortOrder(CmsGallerySortParam.title_desc);
searchResult = searchBean.getResult(searchParams);
System.out.println("Result sorted by title descending:");
printResults(searchResult, cms);
i = searchResult.iterator();
while (i.hasNext()) {
CmsGallerySearchResult res = i.next();
if (lastTitle != null) {
// make sure result is sorted correctly
assertTrue(lastTitle.compareTo(res.getTitle()) >= 0);
}
lastTitle = res.getTitle();
}
// third run use date last modified
long lastTime = 0;
searchParams.setSortOrder(CmsGallerySortParam.dateLastModified_desc);
searchResult = searchBean.getResult(searchParams);
System.out.println("Result sorted by date last modified descending:");
printResults(searchResult, cms);
i = searchResult.iterator();
while (i.hasNext()) {
CmsGallerySearchResult res = i.next();
if (lastTime > 0) {
// make sure result is sorted correctly
assertTrue(lastTime >= res.getDateLastModified().getTime());
assertTrue(res.getScore() <= 100);
}
lastTime = res.getDateLastModified().getTime();
}
searchParams.setSortOrder(CmsGallerySortParam.dateLastModified_asc);
searchResult = searchBean.getResult(searchParams);
System.out.println("Result sorted by date last modified ascending:");
printResults(searchResult, cms);
i = searchResult.iterator();
while (i.hasNext()) {
CmsGallerySearchResult res = i.next();
if (lastTime > 0) {
// make sure result is sorted correctly
assertTrue(lastTime <= res.getDateLastModified().getTime());
assertTrue(res.getScore() <= 100);
}
lastTime = res.getDateLastModified().getTime();
}
// forth run date created
searchParams.setSortOrder(CmsGallerySortParam.dateCreated_desc);
searchResult = searchBean.getResult(searchParams);
System.out.println("Result sorted by date created descending:");
printResults(searchResult, cms);
i = searchResult.iterator();
while (i.hasNext()) {
CmsGallerySearchResult res = i.next();
if (lastTime > 0) {
// make sure result is sorted correctly
assertTrue(lastTime >= res.getDateCreated().getTime());
assertTrue(res.getScore() <= 100);
}
lastTime = res.getDateCreated().getTime();
}
searchParams.setSortOrder(CmsGallerySortParam.dateCreated_asc);
searchResult = searchBean.getResult(searchParams);
System.out.println("Result sorted by date created ascending:");
printResults(searchResult, cms);
i = searchResult.iterator();
while (i.hasNext()) {
CmsGallerySearchResult res = i.next();
if (lastTime > 0) {
// make sure result is sorted correctly
assertTrue(lastTime <= res.getDateCreated().getTime());
assertTrue(res.getScore() <= 100);
}
lastTime = res.getDateCreated().getTime();
}
// content length (size)
searchParams.setSortOrder(CmsGallerySortParam.length_asc);
searchResult = searchBean.getResult(searchParams);
System.out.println("Result sorted by content length (size) ascending:");
printResults(searchResult, cms);
int lastLength = -1;
i = searchResult.iterator();
while (i.hasNext()) {
CmsGallerySearchResult res = i.next();
if (lastLength > 0) {
// make sure result is sorted correctly
assertTrue(lastLength <= res.getLength());
assertTrue(res.getScore() <= 100);
}
lastLength = res.getLength();
}
searchParams.setSortOrder(CmsGallerySortParam.length_desc);
searchResult = searchBean.getResult(searchParams);
System.out.println("Result sorted by content length (size) descending:");
printResults(searchResult, cms);
lastLength = -1;
i = searchResult.iterator();
while (i.hasNext()) {
CmsGallerySearchResult res = i.next();
if (lastLength > 0) {
// make sure result is sorted correctly
assertTrue(lastLength >= res.getLength());
assertTrue(res.getScore() <= 100);
}
lastLength = res.getLength();
}
}
/**
* Tests searching documents by their structure ID.<p>
*
* @throws Exception
*/
public void testSearchById() throws Exception {
CmsObject cms = getCmsObject();
echo("Testing search by id");
CmsGallerySearch search = new CmsGallerySearch();
search.init(cms);
search.setIndex(CmsGallerySearchIndex.GALLERY_INDEX_NAME);
CmsGallerySearchResult result = search.searchById(
new CmsUUID("7d6c22cd-4e3a-11db-9016-5bf59c6009b3"),
new Locale("en"));
assertTrue(result.getPath().endsWith("/index.html"));
}
/**
* Test that search results don't get "duplicated" after moving a resource.
*
* @throws Exception
*/
public void testSearchForMovedFiles() throws Exception {
CmsObject cms = getCmsObject();
// rebuild all indexes
cms.createResource(
"/foo1.txt",
CmsResourceTypePlain.getStaticTypeId(),
"foo1".getBytes(),
Collections.singletonList(new CmsProperty("Title", "foo1", "foo1")));
I_CmsReport report = new CmsShellReport(Locale.ENGLISH);
// rebuild all indexes
OpenCms.getSearchManager().rebuildAllIndexes(report);
OpenCms.getPublishManager().publishProject(cms);
OpenCms.getPublishManager().waitWhileRunning();
cms.lockResource("/foo1.txt");
cms.moveResource("/foo1.txt", "/foo2.txt");
OpenCms.getSearchManager().updateOfflineIndexes(5000);
CmsSearchIndex index = OpenCms.getSearchManager().getIndex(CmsGallerySearchIndex.GALLERY_INDEX_NAME);
CmsSearchParameters params = new CmsSearchParameters("/foo1.txt");
CmsSearchResultList results = index.search(cms, params);
assertEquals(1, results.size());
assertTrue(results.get(0).getPath().contains("foo2"));
cms.undoChanges("/foo2.txt", CmsResourceUndoMode.MODE_UNDO_MOVE_CONTENT);
OpenCms.getSearchManager().updateOfflineIndexes(5000);
results = index.search(cms, params);
assertEquals(1, results.size());
assertTrue(results.get(0).getPath().contains("foo1"));
}
}
|
package org.eclipse.birt.report.engine.emitter.ods.layout;
import java.io.IOException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.birt.report.engine.content.ICellContent;
import org.eclipse.birt.report.engine.content.IContainerContent;
import org.eclipse.birt.report.engine.content.IContent;
import org.eclipse.birt.report.engine.content.IDataContent;
import org.eclipse.birt.report.engine.content.IHyperlinkAction;
import org.eclipse.birt.report.engine.content.IImageContent;
import org.eclipse.birt.report.engine.content.IStyle;
import org.eclipse.birt.report.engine.emitter.EmitterUtil;
import org.eclipse.birt.report.engine.emitter.ods.BlankData;
import org.eclipse.birt.report.engine.emitter.ods.BookmarkDef;
import org.eclipse.birt.report.engine.emitter.ods.Data;
import org.eclipse.birt.report.engine.emitter.ods.DataCache;
import org.eclipse.birt.report.engine.emitter.ods.DateTimeUtil;
import org.eclipse.birt.report.engine.emitter.ods.ImageData;
import org.eclipse.birt.report.engine.emitter.ods.OdsEmitter;
import org.eclipse.birt.report.engine.emitter.ods.OdsUtil;
import org.eclipse.birt.report.engine.emitter.ods.RowData;
import org.eclipse.birt.report.engine.emitter.ods.SheetData;
import org.eclipse.birt.report.engine.emitter.ods.StyleEngine;
import org.eclipse.birt.report.engine.emitter.ods.BlankData.Type;
import org.eclipse.birt.report.engine.i18n.EngineResourceHandle;
import org.eclipse.birt.report.engine.i18n.MessageConstants;
import org.eclipse.birt.report.engine.layout.emitter.Image;
import org.eclipse.birt.report.engine.layout.pdf.util.PropertyUtil;
import org.eclipse.birt.report.engine.odf.pkg.ImageEntry;
import org.eclipse.birt.report.engine.odf.style.HyperlinkInfo;
import org.eclipse.birt.report.engine.odf.style.StyleBuilder;
import org.eclipse.birt.report.engine.odf.style.StyleConstant;
import org.eclipse.birt.report.engine.odf.style.StyleEntry;
import org.eclipse.birt.report.engine.odf.style.StyleManager;
import org.eclipse.birt.report.engine.util.FlashFile;
import com.ibm.icu.util.ULocale;
public class OdsLayoutEngine
{
protected static Logger logger = Logger.getLogger( OdsLayoutEngine.class
.getName( ) );
public final static String EMPTY = "";
public static final float DEFAULT_ROW_HEIGHT = 15;
private int autoBookmarkIndex = 0;
public static final String AUTO_GENERATED_BOOKMARK = "auto_generated_bookmark_";
private int maxRow = 65535;
private int maxCol = 255;
private HashMap<String, String> cachedBookmarks = new HashMap<String, String>( );
protected DataCache cache;
private AxisProcessor axis;
protected StyleEngine engine;
private OdsEmitter emitter;
private Stack<OdsContainer> containers = new Stack<OdsContainer>( );
private Stack<OdsTable> tables = new Stack<OdsTable>( );
private OdsContext context = null;
private String messageFlashObjectNotSupported;
private ULocale locale;
private HashMap<String, BookmarkDef> bookmarkList = new HashMap<String, BookmarkDef>( );
protected int reportDpi;
protected Stack<Boolean> rowVisibilities = new Stack<Boolean>( );
public OdsLayoutEngine( OdsContext context,
OdsEmitter emitter )
{
this.context = context;
this.emitter = emitter;
this.locale = context.getLocale( );
EngineResourceHandle resourceHandle = new EngineResourceHandle( locale );
messageFlashObjectNotSupported = resourceHandle
.getMessage( MessageConstants.FLASH_OBJECT_NOT_SUPPORTED_PROMPT );
}
public void initalize( int contentWidth, IStyle style, int dpi, StyleManager styleManager )
{
axis = new AxisProcessor( );
axis.addCoordinate( contentWidth );
ContainerSizeInfo rule = new ContainerSizeInfo( 0, contentWidth );
cache = createDataCache( maxCol, maxRow );
engine = new StyleEngine( this, styleManager );
containers.push( createContainer( rule, style, null ) );
this.reportDpi = dpi;
}
protected DataCache createDataCache( int maxColumn, int maxRow )
{
return new DataCache( maxColumn, maxRow );
}
public OdsContainer getCurrentContainer( )
{
return (OdsContainer) containers.peek( );
}
public Stack<OdsContainer> getContainers( )
{
return containers;
}
public void addTable( IContainerContent content, ColumnsInfo table,
ContainerSizeInfo size )
{
IStyle style = content.getComputedStyle( );
OdsContainer currentContainer = getCurrentContainer( );
ContainerSizeInfo parentSizeInfo = currentContainer.getSizeInfo( );
int[] columnStartCoordinates = splitColumns( table, parentSizeInfo );
createTable( table, style, currentContainer, columnStartCoordinates );
}
protected int[] splitColumns( ColumnsInfo columnsInfo,
ContainerSizeInfo parentSizeInfo )
{
int startCoordinate = parentSizeInfo.getStartCoordinate( );
int endCoordinate = parentSizeInfo.getEndCoordinate( );
int[] columnStartCoordinates = calculateColumnCoordinates( columnsInfo,
startCoordinate, endCoordinate );
splitColumns( startCoordinate, endCoordinate, columnStartCoordinates );
return columnStartCoordinates;
}
private void createTable( ColumnsInfo tableInfo, IStyle style,
OdsContainer currentContainer, int[] columnStartCoordinates )
{
int leftCordinate = columnStartCoordinates[0];
int width = columnStartCoordinates[columnStartCoordinates.length - 1]
- leftCordinate;
ContainerSizeInfo sizeInfo = new ContainerSizeInfo( leftCordinate,
width );
StyleEntry styleEntry = engine.createEntry( sizeInfo, style,
getParentStyle( ) );
context.addStyle( styleEntry );
OdsTable table = new OdsTable( tableInfo, styleEntry,
sizeInfo, currentContainer );
tables.push( table );
addContainer( table );
}
protected StyleEntry getParentStyle( )
{
return getParentStyle( getCurrentContainer( ) );
}
private void splitColumns( int startCoordinate, int endCoordinate,
int[] columnStartCoordinates )
{
int[] scale = axis.getColumnCoordinatesInRange( startCoordinate,
endCoordinate );
for ( int i = 0; i < scale.length - 1; i++ )
{
int startPosition = scale[i];
int endPostion = scale[i + 1];
int[] range = inRange( startPosition, endPostion, columnStartCoordinates );
if ( range.length > 0 )
{
int pos = axis.getColumnIndexByCoordinate( startPosition );
cache.insertColumns( pos, range.length );
for ( int j = 0; j < range.length; j++ )
{
axis.addCoordinate( range[j] );
}
}
}
}
private int[] calculateColumnCoordinates( ColumnsInfo table,
int startCoordinate,
int endCoordinate )
{
if ( table == null )
{
return new int[]{
startCoordinate
};
}
int columnCount = table.getColumnCount( );
int[] columnStartCoordinates = new int[ columnCount + 1 ];
columnStartCoordinates[0] = startCoordinate;
for ( int i = 1; i <= columnCount; i++ )
{
if ( ( columnStartCoordinates[i - 1] + table.getColumnWidth( i - 1 ) ) > endCoordinate )
{
columnStartCoordinates[i] = endCoordinate;
}
else
columnStartCoordinates[i] = columnStartCoordinates[i - 1]
+ table.getColumnWidth( i - 1 );
}
return columnStartCoordinates;
}
private int[] inRange( int start, int end, int[] data )
{
int[] range = new int[data.length];
int count = 0;
for ( int i = 0; i < data.length; i++ )
{
if ( ( data[i] > start ) && ( data[i] < end ) )
{
count++;
range[count] = data[i];
}
}
int[] result = new int[count];
int j = 0;
for ( int i = 0; i < range.length; i++ )
{
if ( range[i] != 0 )
{
result[j] = range[i];
j++;
}
}
return result;
}
public void addCell( int col, int colSpan, int rowSpan, IStyle style )
{
OdsTable table = tables.peek( );
ContainerSizeInfo cellSizeInfo = table.getColumnSizeInfo( col, colSpan );
StyleEntry aStyle = engine.createEntry( cellSizeInfo, style,
getParentStyle( ) );
context.addStyle( aStyle );
OdsCell cell = new OdsCell( aStyle,
cellSizeInfo, getCurrentContainer( ), rowSpan );
addContainer( cell );
}
private boolean isHidden( IContent content )
{
if ( content != null )
{
IStyle style = content.getStyle( );
if ( IStyle.NONE_VALUE.equals( style
.getProperty( IStyle.STYLE_DISPLAY ) ) )
{
return true;
}
}
return false;
}
public void addCell( ICellContent cellcontent, int col, int colSpan,
int rowSpan, IStyle style )
{
if ( !isHidden( cellcontent ) )
{
rowVisibilities.pop( );
rowVisibilities.push( true );
OdsTable table = tables.peek( );
ContainerSizeInfo cellSizeInfo = table.getColumnSizeInfo( col,
colSpan );
int diagonalNumber = cellcontent.getDiagonalNumber( );
StyleEntry cellStyleEntry = null;
if ( diagonalNumber != 0 )
{
String diagonalColor = cellcontent.getDiagonalColor( );
String diagonalStyle = cellcontent.getDiagonalStyle( );
int diagonalWidth = PropertyUtil.getDimensionValue(
cellcontent, cellcontent.getDiagonalWidth( ),
cellSizeInfo.getWidth( ) );
cellStyleEntry = engine.createCellEntry( cellSizeInfo, style,
diagonalColor, diagonalStyle, diagonalWidth,
getParentStyle( ) );
}
else
{
cellStyleEntry = engine.createEntry( cellSizeInfo, style,
getParentStyle( ) );
}
context.addStyle( cellStyleEntry );
OdsCell cell = new OdsCell( cellStyleEntry, cellSizeInfo,
getCurrentContainer( ), rowSpan );
addContainer( cell );
}
}
public void endCell( ICellContent cell )
{
if ( !isHidden( cell ) )
{
endNormalContainer( );
}
}
public void addRow( IStyle style )
{
rowVisibilities.push( false );
OdsContainer parent = getCurrentContainer( );
ContainerSizeInfo sizeInfo = parent.getSizeInfo( );
OdsContainer container = createContainer( sizeInfo, style,
parent );
container.setEmpty( false );
addContainer( container );
}
public void endRow( float rowHeight )
{
if ( rowVisibilities.pop( ) )
{
synchronize( rowHeight );
}
endContainer( );
}
protected void synchronize( float height )
{
OdsContainer rowContainer = getCurrentContainer( );
ContainerSizeInfo rowSizeInfo = rowContainer.getSizeInfo( );
int startCoordinate = rowSizeInfo.getStartCoordinate( );
int endCoordinate = rowSizeInfo.getEndCoordinate( );
int startColumnIndex = axis.getColumnIndexByCoordinate( startCoordinate );
int endColumnIndex = axis.getColumnIndexByCoordinate( endCoordinate );
int maxRowIndex = 0;
int rowIndexes[] = new int[endColumnIndex - startColumnIndex];
for ( int currentColumnIndex = startColumnIndex; currentColumnIndex < endColumnIndex; currentColumnIndex++ )
{
int rowIndex = cache.getMaxRowIndex( currentColumnIndex );
SheetData lastData = cache.getColumnLastData( currentColumnIndex );
rowIndexes[currentColumnIndex - startColumnIndex] = rowIndex;
int span = lastData != null ? lastData.getRowSpanInDesign( ) : 0;
if ( span == 0
|| ( span == 1 && !isInContainer( lastData, rowContainer ) ) )
{
maxRowIndex = maxRowIndex > rowIndex ? maxRowIndex : rowIndex;
}
}
int startRowIndex = rowContainer.getRowIndex( );
if ( maxRowIndex <= startRowIndex )
{
maxRowIndex = startRowIndex + 1;
}
rowContainer.setRowIndex( maxRowIndex );
float resize = height / ( maxRowIndex - startRowIndex );
for ( int i = startRowIndex; i < maxRowIndex; i++ )
{
cache.setRowHeight( i, resize );
}
for ( int currentColumnIndex = startColumnIndex; currentColumnIndex < endColumnIndex; currentColumnIndex++ )
{
int rowspan = maxRowIndex - rowIndexes[currentColumnIndex - startColumnIndex];
SheetData upstair = cache.getColumnLastData( currentColumnIndex );
if ( rowspan > 0 )
{
if ( upstair != null && canSpan( upstair, rowContainer, currentColumnIndex ) )
{
Type blankType = Type.VERTICAL;
if ( upstair.isBlank( ) )
{
BlankData blankData = (BlankData) upstair;
if ( blankData.getType( ) == Type.VERTICAL )
{
upstair
.setRowSpan( upstair.getRowSpan( )
+ rowspan );
if ( !isInContainer( blankData, rowContainer ) )
{
upstair.decreasRowSpanInDesign( );
}
}
blankType = blankData.getType( );
}
else
{
upstair.setRowSpan( upstair.getRowSpan( ) + rowspan );
if ( !isInContainer( upstair, rowContainer ) )
{
upstair.decreasRowSpanInDesign( );
}
}
int rowIndex = upstair.getRowIndex( );
for ( int p = 1; p <= rowspan; p++ )
{
BlankData blank = new BlankData( upstair );
blank.setRowIndex( rowIndex + p );
blank.setType( blankType );
cache.addData( currentColumnIndex, blank );
}
}
}
else if ( upstair != null && upstair.getRowSpanInDesign( ) > 0
&& !isInContainer( upstair, rowContainer ) )
{
upstair.decreasRowSpanInDesign( );
}
}
}
private void calculateRowHeight( SheetData[] rowData, boolean isAuto )
{
float rowHeight = 0;
int rowIndex = getRowIndex( rowData );
float lastRowHeight = rowIndex > 0
? cache.getRowHeight( rowIndex - 1 )
: 0;
boolean hasCurrentRowHeight = cache.hasRowHeight( rowIndex );
if ( !hasCurrentRowHeight || isAuto )
{
for ( int i = 0; i < rowData.length; i++ )
{
SheetData data = rowData[i];
if ( data != null )
{
if ( data.isBlank( ) )
{
// if the data spans last row,then recalculate data
// height.
// if current row is the last row of real data, then
// adjust
// row height.
BlankData blankData = (BlankData) data;
if ( blankData.getType( ) == Type.VERTICAL )
{
data.setHeight( data.getHeight( ) - lastRowHeight );
}
}
SheetData realData = getRealData( data );
if ( realData != null )
{
int realDataRowEnd = realData.getRowIndex( )
+ realData.getRowSpan( );
if ( realDataRowEnd == data.getRowIndex( ) )
{
rowHeight = data.getHeight( ) > rowHeight ? data
.getHeight( ) : rowHeight;
}
}
}
}
cache.setRowHeight( rowIndex, rowHeight );
}
}
private int getRowIndex( SheetData[] rowData )
{
for ( int j = 0; j < rowData.length; j++ )
{
SheetData data = rowData[j];
if ( data != null )
{
return data.getRowIndex( ) - 1;
}
}
return 0;
}
private boolean canSpan( SheetData upstair, OdsContainer rowContainer, int currentColumn )
{
SheetData realData = getRealData( upstair );
if ( realData == null )
return false;
if ( isInContainer( realData, rowContainer ) )
{
return true;
}
// for two dimensional spanning, the horizontal spanned cells in the
// last spanning row will accept zero rowSpanInDesign.
if ( isInLastSpanningRow( upstair, realData, currentColumn ) )
{
return realData.getRowSpanInDesign( ) >= 0;
}
return realData.getRowSpanInDesign( ) > 0;
}
private boolean isInLastSpanningRow( SheetData upstair, SheetData realData,
int currentColumn )
{
int realColumn = axis.getColumnIndexByCoordinate( realData.getStartX( ) );
int span = axis.getColumnIndexByCoordinate( realData.getEndX( ) )
- realColumn;
return currentColumn > realColumn
&& currentColumn < realColumn + span
&& upstair.getRowIndex( ) == realData.getRowIndex( )
+ realData.getRowSpan( ) - 1;
}
private SheetData getRealData( SheetData data )
{
while ( data != null && data.isBlank( ) )
{
data = ( (BlankData) data ).getData( );
}
return data;
}
private boolean isInContainer( SheetData data, OdsContainer rowContainer )
{
return data.getRowIndex( ) > rowContainer.getStartRowId( );
}
public void endTable( IContent content )
{
if ( !tables.isEmpty( ) )
{
tables.pop( );
endContainer( );
}
}
public void addContainer( IStyle style, HyperlinkInfo link )
{
OdsContainer parent = getCurrentContainer( );
ContainerSizeInfo sizeInfo = parent.getSizeInfo( );
StyleEntry entry = engine.createEntry( sizeInfo, style,
getParentStyle( parent ) );
context.addStyle(entry);
addContainer( new OdsContainer( entry, sizeInfo, parent ) );
}
private StyleEntry getParentStyle( OdsContainer parent )
{
return parent == null ? null : parent.getStyle( );
}
private void addContainer( OdsContainer child )
{
OdsContainer parent = child.getParent( );
if ( parent instanceof OdsCell )
{
addEmptyDataToContainer( child, parent );
}
if ( parent != null )
{
parent.setEmpty( false );
}
containers.push( child);
}
private void addEmptyDataToContainer( OdsContainer child,
OdsContainer parent )
{
ContainerSizeInfo childSizeInfo = child.getSizeInfo( );
int childStartCoordinate = childSizeInfo.getStartCoordinate( );
int childEndCoordinate = childSizeInfo.getEndCoordinate( );
ContainerSizeInfo parentSizeInfo = parent.getSizeInfo( );
int parentStartCoordinate = parentSizeInfo.getStartCoordinate( );
int parentEndCoordinate = parent.getSizeInfo( ).getEndCoordinate( );
if ( childEndCoordinate < parentEndCoordinate )
{
StyleEntry style = parent.getStyle( );
removeLeftBorder( style );
removeDiagonalLine( style );
addEmptyDataToContainer( style, parent, childEndCoordinate,
parentEndCoordinate - childEndCoordinate );
}
if ( childStartCoordinate > parentStartCoordinate )
{
StyleEntry style = parent.getStyle( );
removeRightBorder( style );
removeDiagonalLine( style );
addEmptyDataToContainer( style, parent, childStartCoordinate,
parentStartCoordinate - childStartCoordinate );
}
}
private void addEmptyDataToContainer( StyleEntry style,
OdsContainer parent, int startCoordinate, int width )
{
Data data = createEmptyData( style );
data.setStartX( startCoordinate );
data.setEndX( startCoordinate + width );
addData( data );
}
public void endContainer( )
{
setParentContainerIndex( );
endNormalContainer( );
}
private void setParentContainerIndex( )
{
OdsContainer container = getCurrentContainer( );
OdsContainer parent = container.getParent( );
if ( parent != null )
parent.setRowIndex( container.getRowIndex( ) );
}
public void endNormalContainer( )
{
OdsContainer container = getCurrentContainer( );
if ( container.isEmpty( ) )
{
Data data = createData( EMPTY, container.getStyle( ) );
ContainerSizeInfo containerSize = container.getSizeInfo( );
data.setStartX( containerSize.getStartCoordinate( ) );
data.setEndX( containerSize.getEndCoordinate( ) );
addData( data );
}
engine.applyContainerBottomStyle( );
containers.pop( );
}
public Data addData( Object txt, IStyle style, HyperlinkInfo link,
BookmarkDef bookmark, float height )
{
return addData( txt, style, link, bookmark, null, height );
}
public Data addData( Object value, IStyle style, HyperlinkInfo link,
BookmarkDef bookmark, String locale, float height )
{
OdsContainer container = getCurrentContainer( );
ContainerSizeInfo containerSize = container.getSizeInfo( );
StyleEntry entry = engine.getStyle( style, containerSize,
getParentStyle( container ) );
context.addStyle( entry );
setDataType( entry, value, locale );
Data data = createData( value, entry );
data.setHeight( height );
data.setHyperlinkDef( link );
data.setBookmark( bookmark );
data.setStartX( containerSize.getStartCoordinate( ) );
data.setEndX( containerSize.getEndCoordinate( ) );
addData( data );
return data;
}
public void addImageData( IImageContent image, IStyle style,
HyperlinkInfo link, BookmarkDef bookmark )
{
OdsContainer container = getCurrentContainer( );
ContainerSizeInfo parentSizeInfo = container.getSizeInfo( );
int imageWidthDpi = reportDpi;
int imageHeightDpi = reportDpi;
int imageHeight;
int imageWidth;
byte[] imageData = null;
try
{
Image imageInfo = EmitterUtil
.parseImage( image, image.getImageSource( ),
image.getURI( ), image.getMIMEType( ), image
.getExtension( ) );
imageData = imageInfo.getData( );
int[] imageSize = getImageSize( image, imageInfo, parentSizeInfo,
imageWidthDpi, imageHeightDpi );
imageHeight = imageSize[0];
imageWidth = imageSize[1];
}
catch ( IOException ex )
{
imageHeight = LayoutUtil.getImageHeight( image.getHeight( ), 0,
imageHeightDpi );
imageWidth = LayoutUtil.getImageWidth( image.getWidth( ),
parentSizeInfo.getWidth( ), 0, imageWidthDpi );
}
ColumnsInfo imageColumnsInfo = LayoutUtil.createImage( imageWidth );
splitColumns( imageColumnsInfo, parentSizeInfo );
ContainerSizeInfo imageSize = new ContainerSizeInfo( parentSizeInfo
.getStartCoordinate( ), imageColumnsInfo.getTotalWidth( ) );
StyleEntry entry = engine.getStyle( style, imageSize, parentSizeInfo,
getParentStyle( container ) );
SheetData data = createImageData( image, imageData, imageSize
.getWidth( ), imageHeight, entry, container );
data.setHyperlinkDef( link );
data.setBookmark( bookmark );
data.setStartX( imageSize.getStartCoordinate( ) );
data.setEndX( imageSize.getEndCoordinate( ) );
addData( data );
}
private int[] getImageSize( IImageContent image, Image imageInfo,
ContainerSizeInfo parentSizeInfo, int imageWidthDpi,
int imageHeightDpi )
{
int imageHeight;
int imageWidth;
if ( image.getWidth( ) == null && image.getHeight( ) == null )
{
int imageFileWidthDpi = imageInfo.getPhysicalWidthDpi( ) == -1
? 0
: imageInfo.getPhysicalWidthDpi( );
int imageFileHeightDpi = imageInfo.getPhysicalHeightDpi( ) == -1
? 0
: imageInfo.getPhysicalHeightDpi( );
imageWidthDpi = PropertyUtil.getImageDpi( image, imageFileWidthDpi,
0 );
imageHeightDpi = PropertyUtil.getImageDpi( image,
imageFileHeightDpi, 0 );
}
int imageInfoHeight = (int) ( imageInfo.getHeight( ) * 1000
* OdsUtil.INCH_PT / imageHeightDpi );
int imageInfoWidth = (int) ( imageInfo.getWidth( ) * 1000
* OdsUtil.INCH_PT / imageWidthDpi );
if ( image.getWidth( ) == null && image.getHeight( ) != null )
{
imageHeight = LayoutUtil.getImageHeight( image.getHeight( ),
imageInfoHeight, imageHeightDpi );
float scale = ( (float) imageInfoHeight )
/ ( (float) imageInfoWidth );
imageWidth = (int) ( imageHeight / scale );
}
else if ( image.getHeight( ) == null && image.getWidth( ) != null )
{
imageWidth = LayoutUtil.getImageWidth( image.getWidth( ),
parentSizeInfo.getWidth( ), imageInfoWidth, imageWidthDpi );
float scale = ( (float) imageInfoHeight )
/ ( (float) imageInfoWidth );
imageHeight = (int) ( imageWidth * scale );
}
else
{
imageHeight = LayoutUtil.getImageHeight( image.getHeight( ),
imageInfoHeight, imageHeightDpi );
imageWidth = LayoutUtil.getImageWidth( image.getWidth( ),
parentSizeInfo.getWidth( ), imageInfoWidth, imageWidthDpi );
}
int[] imageSize = {imageHeight, imageWidth};
return imageSize;
}
private SheetData createImageData( IImageContent image, byte[] imageData,
int imageWidth, int imageHeight, StyleEntry entry,
OdsContainer container )
{
int type = SheetData.IMAGE;
entry.setProperty( StyleConstant.DATA_TYPE_PROP, type );
String uri = image.getURI( );
String mimeType = image.getMIMEType( );
String extension = image.getExtension( );
String altText = image.getAltText( );
if ( FlashFile.isFlash( mimeType, uri, extension ) )
{
if ( null == altText )
{
altText = messageFlashObjectNotSupported;
}
entry.setProperty( StyleConstant.DATA_TYPE_PROP, SheetData.STRING );
return createData( altText, entry );
}
if ( imageData != null )
{
ImageEntry imageEntry = null;
try
{
imageEntry = context.getImageManager( ).addImage( image );
}
catch ( IOException e )
{
logger.log( Level.SEVERE, e.getLocalizedMessage( ), e );
}
SheetData imageData1 = new ImageData( imageEntry.getUri(), image.getAltText( ), imageWidth,
imageHeight, entry, type, container );
return imageData1;
}
else
{
entry.setProperty( StyleConstant.DATA_TYPE_PROP, SheetData.STRING );
return createData( image.getAltText( ), entry );
}
}
public Data addDateTime( Object txt, IStyle style, HyperlinkInfo link,
BookmarkDef bookmark, String dateTimeLocale, float height )
{
OdsContainer currentContainer = getCurrentContainer( );
ContainerSizeInfo containerSize = currentContainer.getSizeInfo( );
StyleEntry entry = engine.getStyle( style, containerSize,
getParentStyle( currentContainer ) );
context.addStyle( entry );
Data data = null;
IDataContent dataContent = (IDataContent)txt;
Object value = dataContent.getValue( );
Date date = OdsUtil.getDate( value );
//If date time is before 1900, it must be output as string, otherwise, else can't format the date.
if ( date != null
&& ( ( date instanceof Time ) || date.getYear( ) >= 0 ) )
{
data = createDateData( value, entry, style.getDateTimeFormat( ),
dateTimeLocale );
data.setHeight( height );
data.setBookmark( bookmark );
data.setHyperlinkDef( link );
data.setStartX( containerSize.getStartCoordinate( ) );
data.setEndX( containerSize.getEndCoordinate( ) );
addData( data );
return data;
}
else
{
entry.setProperty( StyleConstant.DATA_TYPE_PROP, SheetData.STRING );
return addData( dataContent.getText( ), style, link, bookmark,
dateTimeLocale, height );
}
}
public void addCaption( String text, IStyle style )
{
ContainerSizeInfo containerSize = getCurrentContainer( ).getSizeInfo( );
StyleEntry entry = StyleBuilder.createEmptyStyleEntry( StyleConstant.TYPE_PARAGRAPH );
entry.setProperty( StyleEntry.H_ALIGN_PROP, "Center" );
entry.setProperty( StyleEntry.FONT_SIZE_PROP, StyleBuilder
.convertFontSize( style
.getProperty( IStyle.STYLE_FONT_SIZE ) ) );
entry.setProperty( StyleEntry.DATA_TYPE_PROP, SheetData.STRING );
Data data = createData( text, entry );
data.setStartX( containerSize.getStartCoordinate( ) );
data.setEndX( containerSize.getEndCoordinate( ) );
addData( data );
}
private void setDataType( StyleEntry entry, Object value, String dataLocale )
{
ULocale locale = getLocale( dataLocale );
setDataType( entry, value, locale );
}
private void setDataType( StyleEntry entry, Object value, ULocale locale )
{
int type = SheetData.STRING;
if ( SheetData.NUMBER == OdsUtil.getType( value ) )
{
String format = OdsUtil.getPattern( value, (String) entry
.getProperty( StyleConstant.NUMBER_FORMAT_PROP ) );
format = OdsUtil.formatNumberPattern( format, locale );
entry.setProperty( StyleConstant.NUMBER_FORMAT_PROP, format );
type = SheetData.NUMBER;
}
else if ( SheetData.DATE == OdsUtil.getType( value ) )
{
String format = OdsUtil.getPattern( value, (String) entry
.getProperty( StyleConstant.DATE_FORMAT_PROP ) );
entry.setProperty( StyleConstant.DATE_FORMAT_PROP, format );
type = Data.DATE;
}
entry.setProperty( StyleConstant.DATA_TYPE_PROP, type );
}
private Data createDateData( Object txt, StyleEntry entry,
String timeFormat, String dlocale )
{
ULocale dateLocale = getLocale( dlocale );
timeFormat = OdsUtil.parse( txt, timeFormat, dateLocale );
timeFormat = DateTimeUtil.formatDateTime( timeFormat, dateLocale );
entry.setProperty( StyleConstant.DATE_FORMAT_PROP, timeFormat );
entry.setProperty( StyleConstant.DATA_TYPE_PROP, SheetData.DATE );
return createData( txt, entry );
}
private ULocale getLocale( String dlocale )
{
return dlocale == null ? locale : new ULocale( dlocale );
}
protected void addData( SheetData data )
{
OdsContainer container = getCurrentContainer( );
container.setEmpty( false );
if ( data.getStartX( ) == data.getEndX( ) )
return;
int col = axis.getColumnIndexByCoordinate( data.getStartX( ) );
if ( col == -1 || col >= cache.getColumnCount( ) )
return;
int span = axis.getColumnIndexByCoordinate( data.getEndX( ) ) - col;
// FIXME: there is a bug when this data is in middle of a row.
outputDataIfBufferIsFull( );
updataRowIndex( data, container );
addDatatoCache( col, data );
for ( int i = col + 1; i < col + span; i++ )
{
BlankData blankData = new BlankData( data );
blankData.setType( Type.HORIZONTAL );
addDatatoCache( i, blankData );
}
if ( data.getDataType( ) == SheetData.IMAGE )
{
addEmptyData( data, container );
}
while ( container != null )
{
if ( container instanceof OdsCell )
{
OdsCell cell = (OdsCell) container;
data.setRowSpanInDesign( cell.getRowSpan( ) - 1 );
break;
}
else
{
container = container.getParent( );
}
}
}
protected void addEmptyData( SheetData data, OdsContainer container )
{
int parentStartCoordinate = container.getSizeInfo( )
.getStartCoordinate( );
int parentEndCoordinate = container.getSizeInfo( ).getEndCoordinate( );
int childStartCoordinate = data.getStartX( );
int childEndCoordinate = data.getEndX( );
if ( childEndCoordinate < parentEndCoordinate )
{
StyleEntry style = container.getStyle( );
removeLeftBorder( style );
int column = axis.getColumnIndexByCoordinate( childEndCoordinate );
int num = axis.getColumnIndexByCoordinate( parentEndCoordinate )
- column - 1;
Data empty = createEmptyData( style );
empty.setStartX( childEndCoordinate );
empty.setEndX( parentEndCoordinate );
empty.setRowIndex( data.getRowIndex( ) );
addDatatoCache( column, empty );
addBlankData( column, num, empty );
}
if ( childStartCoordinate > parentStartCoordinate )
{
StyleEntry style = container.getStyle( );
removeRightBorder( style );
int column = axis.getColumnIndexByCoordinate( childStartCoordinate );
int num = column
- axis.getColumnIndexByCoordinate( parentStartCoordinate )
- 1;
Data empty = createEmptyData( style );
empty.setStartX( childStartCoordinate );
empty.setEndX( parentEndCoordinate );
empty.setRowIndex( data.getRowIndex( ) );
addDatatoCache( column, empty );
addBlankData( column - num - 1, num, empty );
}
}
private void addBlankData( int column, int num, Data empty )
{
for ( int i = 1; i <= num; i++ )
{
BlankData blank = new BlankData( empty );
blank.setRowIndex( empty.getRowIndex( ) );
addDatatoCache( column + i, blank );
}
}
private void removeRightBorder( StyleEntry style )
{
style.setProperty( StyleConstant.BORDER_RIGHT_COLOR_PROP, null );
style.setProperty( StyleConstant.BORDER_RIGHT_STYLE_PROP, null );
style.setProperty( StyleConstant.BORDER_RIGHT_WIDTH_PROP, null );
}
private void removeLeftBorder( StyleEntry style )
{
style.setProperty( StyleConstant.BORDER_LEFT_COLOR_PROP, null );
style.setProperty( StyleConstant.BORDER_LEFT_STYLE_PROP, null );
style.setProperty( StyleConstant.BORDER_LEFT_WIDTH_PROP, null );
}
private void removeDiagonalLine( StyleEntry style )
{
style.setProperty( StyleConstant.BORDER_DIAGONAL_COLOR_PROP, null );
style.setProperty( StyleConstant.BORDER_DIAGONAL_STYLE_PROP, null );
style.setProperty( StyleConstant.BORDER_DIAGONAL_WIDTH_PROP, null );
style.setProperty( StyleConstant.BORDER_ANTIDIAGONAL_COLOR_PROP, null );
style.setProperty( StyleConstant.BORDER_ANTIDIAGONAL_STYLE_PROP, null );
style.setProperty( StyleConstant.BORDER_ANTIDIAGONAL_WIDTH_PROP, null );
}
protected Data createEmptyData( StyleEntry style )
{
return createData( EMPTY, style );
}
protected void updataRowIndex( SheetData data, OdsContainer container )
{
int rowIndex = container.getRowIndex( ) + 1;
data.setRowIndex( rowIndex );
container.setRowIndex( rowIndex );
}
private void outputDataIfBufferIsFull( )
{
if ( getCurrentContainer( ).getRowIndex( ) >= maxRow )
{
emitter.outputSheet( );
cache.clearCachedSheetData( );
resetContainers( );
}
}
public OdsContainer createContainer( ContainerSizeInfo sizeInfo,
IStyle style, OdsContainer parent )
{
StyleEntry aStyle = engine
.createEntry( sizeInfo, style, getParentStyle( parent ) );
context.addStyle( aStyle );
return new OdsContainer( aStyle ,
sizeInfo, parent );
}
public OdsContainer createCellContainer( IStyle style, OdsContainer parent, int rowSpan )
{
ContainerSizeInfo sizeInfo = parent.getSizeInfo( );
StyleEntry aStyle = engine.createEntry( sizeInfo, style,
getParentStyle( parent ));
context.addStyle( aStyle );
return new OdsCell( aStyle,
sizeInfo, parent, rowSpan );
}
public int[] getCoordinates( )
{
int[] coord = axis.getColumnWidths( );
if ( coord.length <= maxCol )
{
return coord;
}
else
{
int[] ncoord = new int[maxCol];
System.arraycopy( coord, 0, ncoord, 0, maxCol );
return ncoord;
}
}
public int getRowCount( )
{
return cache.getMaxRow( );
}
public AxisProcessor getAxis( )
{
return axis;
}
public SheetData getColumnLastData( int column )
{
return cache.getColumnLastData( column );
}
private void addDatatoCache( int col, SheetData value )
{
cache.addData( col, value );
}
public void complete( boolean isAuto )
{
engine.applyContainerBottomStyle( containers.get( 0 ) );
Iterator<SheetData[]> iterator = cache.getRowIterator( );
while ( iterator.hasNext( ) )
{
SheetData[] rowData = iterator.next( );
for ( int j = 0; j < rowData.length; j++ )
{
SheetData data = rowData[j];
if ( data == null || data.isBlank( ) )
{
continue;
}
HyperlinkInfo hyperLink = data.getHyperlinkDef( );
if ( hyperLink != null )
{
if ( hyperLink.getType( ) == IHyperlinkAction.ACTION_BOOKMARK )
{
setLinkedBookmark( data, hyperLink );
}
}
}
calculateRowHeight( rowData, isAuto );
}
}
public int getStartColumn( SheetData data )
{
// row index Starts From 1
int start = axis.getColumnIndexByCoordinate( data.getStartX( ) ) + 1;
return Math.min( start, maxCol );
}
public int getEndColumn( SheetData data )
{
// column index Starts From 1
int end = axis.getColumnIndexByCoordinate( data.getEndX( ) ) + 1;
return Math.min( end, maxCol );
}
/**
* @param data
* @param hyperLink
*/
private void setLinkedBookmark( SheetData data, HyperlinkInfo hyperLink )
{
String bookmarkName = hyperLink.getUrl( );
BookmarkDef linkedBookmark = bookmarkList
.get( bookmarkName );
if ( linkedBookmark != null )
{
data.setLinkedBookmark( linkedBookmark );
}
else
{
BookmarkDef newBookmark;
if ( OdsUtil.isValidBookmarkName( bookmarkName ) )
newBookmark = new BookmarkDef( bookmarkName );
else
{
String generateBookmarkName = getGenerateBookmark( bookmarkName );
newBookmark = new BookmarkDef(
generateBookmarkName );
cachedBookmarks.put( bookmarkName,
generateBookmarkName );
}
data.setLinkedBookmark( newBookmark );
}
}
public Stack<OdsTable> getTable( )
{
return tables;
}
public void addContainerStyle( IStyle computedStyle )
{
engine.addContainderStyle( computedStyle, getParentStyle( ) );
}
public void removeContainerStyle( )
{
engine.removeForeignContainerStyle( );
}
public void resetContainers( )
{
for ( OdsContainer container : containers )
{
container.setRowIndex( 0 );
container.setStartRowId( 0 );
}
for ( OdsTable table : tables )
{
table.setRowIndex( 0 );
}
}
public OdsLayoutEngineIterator getIterator( )
{
return new OdsLayoutEngineIterator( );
}
private class OdsLayoutEngineIterator implements Iterator<RowData>
{
Iterator<SheetData[]> rowIterator;
public OdsLayoutEngineIterator( )
{
rowIterator = cache.getRowIterator( );
}
public boolean hasNext( )
{
return rowIterator.hasNext( );
}
public RowData next( )
{
SheetData[] row = rowIterator.next( );
List<SheetData> data = new ArrayList<SheetData>( );
int width = Math.min( row.length, maxCol - 1 );
int rowIndex = 0;
for ( int i = 0; i < width; i++ )
{
SheetData d = row[i];
if ( d == null )
{
continue;
}
rowIndex = d.getRowIndex( );
data.add( row[i] );
}
SheetData[] rowdata = new SheetData[data.size( )];
double rowHeight = Math.max( DEFAULT_ROW_HEIGHT, cache
.getRowHeight( rowIndex - 1 ) );
data.toArray( rowdata );
return new RowData( rowdata, rowHeight );
}
public void remove( )
{
throw new UnsupportedOperationException( );
}
}
public void cacheBookmarks( String sheetName )
{
List<BookmarkDef> currentSheetBookmarks = cache.getBookmarks( );
for ( BookmarkDef book : currentSheetBookmarks )
{
book.setSheetName( sheetName );
bookmarkList.put( book.getName( ), book );
}
}
public HashMap<String, BookmarkDef> getAllBookmarks( )
{
return this.bookmarkList;
}
/**
* @param bookmarkName
* @return generatedBookmarkName
*/
public String getGenerateBookmark( String bookmarkName )
{
String generatedName = cachedBookmarks.get( bookmarkName );
return generatedName != null ? generatedName : AUTO_GENERATED_BOOKMARK
+ autoBookmarkIndex++;
}
protected Data createData( )
{
return new Data( );
}
protected Data createData( Object text, StyleEntry style )
{
return createData( text, style, 0 );
}
protected Data createData( Object text, StyleEntry style,
int rowSpanOfDesign )
{
Data data = createData( );
int dataType = SheetData.STRING;
if ( style != null )
{
Object property = style.getProperty( StyleConstant.DATA_TYPE_PROP );
if ( property instanceof Integer )
{
dataType = (Integer) property;
}
}
data.setDataType( dataType );
data.setValue( text );
data.setStyleId( style );
data.setRowSpanInDesign( rowSpanOfDesign );
return data;
}
}
|
package mcjty.rftools.items.smartwrench;
import cofh.api.item.IToolHammer;
import mcjty.lib.api.smartwrench.SmartWrench;
import mcjty.lib.api.smartwrench.SmartWrenchMode;
import mcjty.lib.api.smartwrench.SmartWrenchSelector;
import mcjty.lib.compat.CompatBlock;
import mcjty.lib.compat.CompatItem;
import mcjty.lib.container.GenericBlock;
import mcjty.lib.varia.BlockPosTools;
import mcjty.lib.varia.GlobalCoordinate;
import mcjty.lib.varia.Logging;
import mcjty.rftools.RFTools;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.ItemMeshDefinition;
import net.minecraft.client.renderer.block.model.ModelBakery;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.World;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.List;
public class SmartWrenchItem extends CompatItem implements IToolHammer, SmartWrench {
public SmartWrenchItem() {
setUnlocalizedName("smartwrench");
setRegistryName("smartwrench");
setCreativeTab(RFTools.tabRfTools);
setMaxStackSize(1);
GameRegistry.register(this);
}
@SideOnly(Side.CLIENT)
public void initModel() {
ModelResourceLocation selectedModel = new ModelResourceLocation(getRegistryName() + "_select", "inventory");
ModelResourceLocation normalModel = new ModelResourceLocation(getRegistryName(), "inventory");
ModelBakery.registerItemVariants(this, selectedModel, normalModel);
ModelLoader.setCustomMeshDefinition(this, new ItemMeshDefinition() {
@Override
public ModelResourceLocation getModelLocation(ItemStack stack) {
SmartWrenchMode mode = getCurrentMode(stack);
if (mode == SmartWrenchMode.MODE_SELECT) {
return selectedModel;
} else {
return normalModel;
}
}
});
}
@Override
public boolean isUsable(ItemStack item, EntityLivingBase user, BlockPos pos) {
SmartWrenchMode mode = getCurrentMode(item);
return mode == SmartWrenchMode.MODE_WRENCH;
}
@Override
public boolean isUsable(ItemStack item, EntityLivingBase user, Entity entity) {
SmartWrenchMode mode = getCurrentMode(item);
return mode == SmartWrenchMode.MODE_WRENCH;
}
@Override
public void toolUsed(ItemStack item, EntityLivingBase user, BlockPos pos) {
}
@Override
public void toolUsed(ItemStack item, EntityLivingBase user, Entity entity) {
}
@Override
protected ActionResult<ItemStack> clOnItemRightClick(World world, EntityPlayer player, EnumHand hand) {
ItemStack stack = player.getHeldItem(hand);
if (!world.isRemote) {
SmartWrenchMode mode = getCurrentMode(stack);
if (mode == SmartWrenchMode.MODE_WRENCH) {
mode = SmartWrenchMode.MODE_SELECT;
} else {
mode = SmartWrenchMode.MODE_WRENCH;
}
NBTTagCompound tagCompound = stack.getTagCompound();
if (tagCompound == null) {
tagCompound = new NBTTagCompound();
stack.setTagCompound(tagCompound);
}
tagCompound.setString("mode", mode.getCode());
Logging.message(player, TextFormatting.YELLOW + "Smart wrench is now in " + mode.getName() + " mode.");
}
return super.clOnItemRightClick(world, player, hand);
}
@Override
protected EnumActionResult clOnItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) {
ItemStack stack = player.getHeldItem(hand);
if (!world.isRemote) {
if (player.isSneaking()) {
// Make sure the block get activated if it is a GenericBlock
IBlockState state = world.getBlockState(pos);
Block block = state.getBlock();
if (block instanceof GenericBlock) {
if (CompatBlock.activateBlock(block, world, pos, state, player, hand, facing, hitX, hitY, hitZ)) {
return EnumActionResult.SUCCESS;
}
}
}
SmartWrenchMode mode = getCurrentMode(stack);
if (mode == SmartWrenchMode.MODE_SELECT) {
GlobalCoordinate b = getCurrentBlock(stack);
if (b != null) {
if (b.getDimension() != world.provider.getDimension()) {
Logging.message(player, TextFormatting.RED + "The selected block is in another dimension!");
return EnumActionResult.FAIL;
}
TileEntity te = world.getTileEntity(b.getCoordinate());
if (te instanceof SmartWrenchSelector) {
SmartWrenchSelector smartWrenchSelector = (SmartWrenchSelector) te;
smartWrenchSelector.selectBlock(player, pos);
}
}
}
}
return EnumActionResult.SUCCESS;
}
// @Override
// public boolean doesSneakBypassUse(ItemStack stack, IBlockAccess world, BlockPos pos, EntityPlayer player) {
// return true;
@SideOnly(Side.CLIENT)
@Override
public void addInformation(ItemStack itemStack, EntityPlayer player, List<String> list, boolean whatIsThis) {
super.addInformation(itemStack, player, list, whatIsThis);
GlobalCoordinate b = getCurrentBlock(itemStack);
if (b != null) {
list.add(TextFormatting.GREEN + "Block: " + BlockPosTools.toString(b.getCoordinate()) + " at dimension " + b.getDimension());
}
SmartWrenchMode mode = getCurrentMode(itemStack);
list.add(TextFormatting.WHITE + "Right-click on air to change mode.");
list.add(TextFormatting.GREEN + "Mode: " + mode.getName());
if (mode == SmartWrenchMode.MODE_WRENCH) {
list.add(TextFormatting.WHITE + "Use as a normal wrench:");
list.add(TextFormatting.WHITE + " Sneak-right-click to pick up machines.");
list.add(TextFormatting.WHITE + " Right-click to rotate machines.");
} else if (mode == SmartWrenchMode.MODE_SELECT) {
list.add(TextFormatting.WHITE + "Use as a block selector:");
list.add(TextFormatting.WHITE + " Sneak-right-click select master block.");
list.add(TextFormatting.WHITE + " Right-click to associate blocks with master.");
}
}
@Override
public SmartWrenchMode getMode(ItemStack itemStack) {
SmartWrenchMode mode = SmartWrenchMode.MODE_WRENCH;
NBTTagCompound tagCompound = itemStack.getTagCompound();
if (tagCompound != null) {
String modeString = tagCompound.getString("mode");
if (modeString != null && !modeString.isEmpty()) {
mode = SmartWrenchMode.getMode(modeString);
}
}
return mode;
}
public static SmartWrenchMode getCurrentMode(ItemStack itemStack) {
SmartWrenchMode mode = SmartWrenchMode.MODE_WRENCH;
NBTTagCompound tagCompound = itemStack.getTagCompound();
if (tagCompound != null) {
String modeString = tagCompound.getString("mode");
if (modeString != null && !modeString.isEmpty()) {
mode = SmartWrenchMode.getMode(modeString);
}
}
return mode;
}
public static void setCurrentBlock(ItemStack itemStack, GlobalCoordinate c) {
NBTTagCompound tagCompound = itemStack.getTagCompound();
if (tagCompound == null) {
tagCompound = new NBTTagCompound();
itemStack.setTagCompound(tagCompound);
}
if (c == null) {
tagCompound.removeTag("selectedX");
tagCompound.removeTag("selectedY");
tagCompound.removeTag("selectedZ");
tagCompound.removeTag("selectedDim");
} else {
tagCompound.setInteger("selectedX", c.getCoordinate().getX());
tagCompound.setInteger("selectedY", c.getCoordinate().getY());
tagCompound.setInteger("selectedZ", c.getCoordinate().getZ());
tagCompound.setInteger("selectedDim", c.getDimension());
}
}
public static GlobalCoordinate getCurrentBlock(ItemStack itemStack) {
NBTTagCompound tagCompound = itemStack.getTagCompound();
if (tagCompound != null && tagCompound.hasKey("selectedX")) {
int x = tagCompound.getInteger("selectedX");
int y = tagCompound.getInteger("selectedY");
int z = tagCompound.getInteger("selectedZ");
int dim = tagCompound.getInteger("selectedDim");
return new GlobalCoordinate(new BlockPos(x, y, z), dim);
}
return null;
}
@Override
public int getMaxItemUseDuration(ItemStack stack) {
return 1;
}
}
|
package com.ray3k.skincomposer.dialog;
import com.ray3k.skincomposer.panel.PanelStatusBar;
import com.ray3k.skincomposer.data.ColorData;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.Dialog;
import com.badlogic.gdx.scenes.scene2d.ui.ImageTextButton;
import com.badlogic.gdx.scenes.scene2d.ui.ImageTextButton.ImageTextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane;
import com.badlogic.gdx.scenes.scene2d.ui.SelectBox;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Sort;
import com.ray3k.skincomposer.IbeamListener;
import com.ray3k.skincomposer.Main;
import com.ray3k.skincomposer.data.JsonData;
import com.ray3k.skincomposer.data.ProjectData;
import com.ray3k.skincomposer.data.StyleData;
import com.ray3k.skincomposer.data.StyleProperty;
import com.ray3k.skincomposer.panel.PanelClassBar;
import com.ray3k.skincomposer.panel.PanelPreviewProperties;
import com.ray3k.skincomposer.panel.PanelStyleProperties;
import com.ray3k.skincomposer.utils.Utils;
import java.util.Comparator;
public class DialogColors extends Dialog {
private Array<ColorData> colors;
private Table colorTable;
private Skin skin;
private StyleProperty styleProperty;
private boolean selectingForTintedDrawable;
private SelectBox<String> selectBox;
private DialogColorsListener listener;
private ScrollPane scrollPane;
public DialogColors(Skin skin, StyleProperty styleProperty, DialogColorsListener listener) {
this(skin, "default", styleProperty, listener);
}
public DialogColors(final Skin skin, String styleName, StyleProperty styleProperty, boolean selectingForTintedDrawable, DialogColorsListener listener) {
super("", skin, styleName);
Main.instance.setListeningForKeys(false);
this.listener = listener;
this.skin = skin;
this.styleProperty = styleProperty;
this.selectingForTintedDrawable = selectingForTintedDrawable;
colors = JsonData.getInstance().getColors();
getContentTable().defaults().expandX();
if (styleProperty != null) {
Label label = new Label("Select a color...", skin, "title");
label.setAlignment(Align.center);
getContentTable().add(label);
getContentTable().row();
} else if (selectingForTintedDrawable) {
Label label = new Label("Select a color for tinted drawable...", skin, "title");
label.setAlignment(Align.center);
getContentTable().add(label);
getContentTable().row();
} else {
Label label = new Label("Colors", skin, "title");
label.setAlignment(Align.center);
getContentTable().add(label);
getContentTable().row();
}
Table table = new Table();
table.defaults().pad(2.0f);
table.add(new Label("Sort by: ", skin)).padLeft(20.0f);
selectBox = new SelectBox<String>(skin);
selectBox.setItems(new String[] {"A-Z", "Z-A"});
selectBox.addListener(new ChangeListener() {
@Override
public void changed(ChangeListener.ChangeEvent event, Actor actor) {
sortBySelectedMode();
}
});
table.add(selectBox);
ImageTextButtonStyle imageButtonStyle = new ImageTextButtonStyle();
imageButtonStyle.imageUp = skin.getDrawable("image-plus");
imageButtonStyle.imageDown = skin.getDrawable("image-plus-down");
imageButtonStyle.up = skin.getDrawable("button-orange");
imageButtonStyle.down = skin.getDrawable("button-orange-down");
imageButtonStyle.over = skin.getDrawable("button-orange-over");
imageButtonStyle.font = skin.getFont("font");
imageButtonStyle.fontColor = skin.getColor("white");
imageButtonStyle.downFontColor = skin.getColor("maroon");
ImageTextButton imageButton = new ImageTextButton(" New Color", imageButtonStyle);
imageButton.addListener(new ChangeListener() {
@Override
public void changed(ChangeListener.ChangeEvent event, Actor actor) {
showColorPicker();
}
});
table.add(imageButton).expandX().left();
getContentTable().add(table).left().expandX();
getContentTable().row();
colorTable = new Table();
populate();
table = new Table();
table.add(colorTable).pad(5.0f);
scrollPane = new ScrollPane(table, skin, "no-bg");
scrollPane.setFadeScrollBars(false);
getContentTable().add(scrollPane).grow();
if (styleProperty != null) {
button("Clear Color", true);
button("Cancel", false);
} else if (selectingForTintedDrawable) {
button("Cancel", false);
} else {
button("Close", false);
}
key(Keys.ESCAPE, false);
}
public DialogColors(final Skin skin, String styleName, StyleProperty styleProperty, DialogColorsListener listener) {
this(skin, styleName, styleProperty, false, listener);
}
@Override
public Dialog show(Stage stage) {
Dialog dialog = super.show(stage);
stage.setScrollFocus(scrollPane);
return dialog;
}
@Override
public boolean remove() {
if (!selectingForTintedDrawable) {
Main.instance.setListeningForKeys(true);
}
return super.remove();
}
private void showColorPicker() {
Main.instance.showDialogColorPicker(new DialogColorPicker.ColorListener() {
@Override
public void selected(Color color) {
if (color != null) {
final TextField field = new TextField("RGBA_" + (int) (color.r * 255) + "_" + (int) (color.g * 255) + "_" + (int) (color.b * 255) + "_" + (int) (color.a * 255), skin);
final Dialog dialog = new Dialog("Color name...", skin, "dialog") {
@Override
protected void result(Object object) {
if ((Boolean) object == true) {
newColor(field.getText(), color);
}
}
};
dialog.button("Ok", true).button("Cancel", false).key(Keys.ESCAPE, false);
final TextButton button = (TextButton) dialog.getButtonTable().getCells().first().getActor();
field.setTextFieldListener(new TextField.TextFieldListener() {
@Override
public void keyTyped(TextField textField, char c) {
if (c == '\n') {
if (!button.isDisabled()) {
String name = field.getText();
if (newColor(name, color)) {
dialog.hide();
}
}
Main.instance.getStage().setKeyboardFocus(textField);
}
}
});
field.addListener(IbeamListener.get());
dialog.getContentTable().padLeft(10.0f).padRight(10.0f);
dialog.text("Please enter a name for the new color: ");
dialog.getContentTable().row();
dialog.getContentTable().add(field).growX();
dialog.getContentTable().row();
dialog.text("Preview:");
dialog.getContentTable().row();
Table table = new Table(skin);
table.setBackground("white");
table.setColor(color);
dialog.getContentTable().add(table).minSize(50.0f);
button.setDisabled(!ColorData.validate(field.getText()));
field.addListener(new ChangeListener() {
@Override
public void changed(ChangeListener.ChangeEvent event, Actor actor) {
boolean disable = !ColorData.validate(field.getText());
if (!disable) {
for (ColorData data : JsonData.getInstance().getColors()) {
if (data.getName().equals(field.getText())) {
disable = true;
break;
}
}
}
button.setDisabled(disable);
}
});
dialog.show(getStage());
getStage().setKeyboardFocus(field);
field.selectAll();
}
}
});
}
public void populate() {
colorTable.clear();
if (colors.size > 0) {
colorTable.defaults().padTop(5.0f);
for (ColorData color : colors) {
Button button = new Button(skin);
Label label = new Label(color.toString(), skin, "white");
label.setTouchable(Touchable.disabled);
float brightness = Utils.brightness(color.color);
Color borderColor;
if (brightness > .35f) {
borderColor = Color.BLACK;
label.setColor(borderColor);
} else {
borderColor = Color.WHITE;
label.setColor(borderColor);
}
Color bgColor = color.color;
Table table = new Table(skin);
table.setBackground("white");
table.setColor(bgColor);
table.add(label).pad(3.0f);
if (styleProperty == null && !selectingForTintedDrawable) {
table.addCaptureListener(new ChangeListener() {
@Override
public void changed(ChangeListener.ChangeEvent event, Actor actor) {
event.setBubbles(false);
populate();
}
});
table.addCaptureListener(new InputListener() {
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
event.setBubbles(false);
return true;
}
});
}
Table borderTable = new Table(skin);
borderTable.setBackground("white");
borderTable.setColor(borderColor);
borderTable.add(table).growX().pad(1.0f);
button.add(borderTable).growX();
//rename button
Button renameButton = new Button(skin, "name");
renameButton.addListener(new ChangeListener() {
@Override
public void changed(ChangeListener.ChangeEvent event, Actor actor) {
renameDialog(color);
event.setBubbles(false);
}
});
renameButton.addListener(new InputListener() {
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
event.setBubbles(false);
return true;
}
});
button.add(renameButton);
//recolor button
Button recolorButton = new Button(skin, "color");
recolorButton.addListener(new ChangeListener() {
@Override
public void changed(ChangeListener.ChangeEvent event, Actor actor) {
recolorDialog(color);
event.setBubbles(false);
}
});
recolorButton.addListener(new InputListener() {
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
event.setBubbles(false);
return true;
}
});
button.add(recolorButton);
label = new Label("(" + ((int)(color.color.r * 255)) + ", " + ((int)(color.color.g * 255)) + ", " + ((int)(color.color.b * 255)) + ", " + ((int)(color.color.a * 255)) + ")", skin, "white");
label.setTouchable(Touchable.disabled);
label.setAlignment(Align.center);
if (styleProperty == null && !selectingForTintedDrawable) {
label.addCaptureListener(new ChangeListener() {
@Override
public void changed(ChangeListener.ChangeEvent event, Actor actor) {
event.setBubbles(false);
populate();
}
});
label.addCaptureListener(new InputListener() {
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
event.setBubbles(false);
return true;
}
});
}
button.add(label).padLeft(5.0f).minWidth(160.0f);
//delete color button
Button closeButton = new Button(skin, "close");
final ColorData deleteColor = color;
closeButton.addListener(new ChangeListener() {
@Override
public void changed(ChangeListener.ChangeEvent event, Actor actor) {
colors.removeValue(deleteColor, true);
for (Array<StyleData> datas : JsonData.getInstance().getClassStyleMap().values()) {
for (StyleData data : datas) {
for (StyleProperty property : data.properties.values()) {
if (property != null && property.type.equals(Color.class) && property.value != null && property.value.equals(deleteColor.getName())) {
property.value = null;
}
}
}
}
Main.instance.clearUndoables();
PanelStyleProperties.instance.populate(PanelClassBar.instance.getStyleSelectBox().getSelected());
PanelPreviewProperties.instance.render();
event.setBubbles(false);
populate();
}
});
closeButton.addListener(new InputListener() {
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
event.setBubbles(false);
return true;
}
});
button.add(closeButton).padLeft(5.0f);
if (styleProperty == null && !selectingForTintedDrawable) {
button.setTouchable(Touchable.childrenOnly);
} else {
setObject(button, color);
final ColorData result = color;
button.addListener(new ChangeListener() {
@Override
public void changed(ChangeListener.ChangeEvent event, Actor actor) {
result(result);
hide();
}
});
}
colorTable.add(button).growX();
colorTable.row();
}
} else {
colorTable.add(new Label("No colors have been set!", skin, "error"));
}
}
private void recolorDialog(ColorData colorData) {
Main.instance.showDialogColorPicker(new DialogColorPicker.ColorListener() {
@Override
public void selected(Color color) {
if (color != null) {
recolorColor(colorData, color);
}
}
});
}
private void recolorColor(ColorData colorData, Color color) {
colorData.color = color;
Main.instance.clearUndoables();
PanelStyleProperties.instance.populate(PanelClassBar.instance.getStyleSelectBox().getSelected());
PanelPreviewProperties.instance.render();
ProjectData.instance().setChangesSaved(false);
populate();
}
private void renameDialog(ColorData color) {
TextField textField = new TextField("", skin);
TextButton okButton;
Dialog dialog = new Dialog("Rename Color?", skin) {
@Override
protected void result(Object object) {
if ((boolean) object) {
renameColor(color, textField.getText());
}
}
@Override
public Dialog show(Stage stage) {
Dialog dialog = super.show(stage);
Main.instance.getStage().setKeyboardFocus(textField);
return dialog;
}
};
float brightness = Utils.brightness(color.color);
Color borderColor;
if (brightness > .35f) {
borderColor = Color.BLACK;
} else {
borderColor = Color.WHITE;
}
Table bg = new Table(skin);
bg.setBackground("white");
bg.setColor(borderColor);
dialog.getContentTable().add(bg);
Label label = new Label(color.getName(), skin, "white");
label.setColor(color.color);
bg.add(label).pad(10);
dialog.getContentTable().row();
label = new Label("What do you want to rename the color to?", skin);
dialog.getContentTable().add(label);
dialog.getContentTable().row();
textField.setText(color.getName());
textField.selectAll();
dialog.getContentTable().add(textField);
dialog.button("OK", true);
dialog.button("Cancel", false).key(Keys.ESCAPE, false);
okButton = (TextButton) dialog.getButtonTable().getCells().first().getActor();
okButton.setDisabled(true);
textField.addListener(new ChangeListener() {
@Override
public void changed(ChangeListener.ChangeEvent event, Actor actor) {
boolean disable = !ColorData.validate(textField.getText());
if (!disable) {
for (ColorData data : JsonData.getInstance().getColors()) {
if (data.getName().equals(textField.getText())) {
disable = true;
break;
}
}
}
okButton.setDisabled(disable);
}
});
textField.setTextFieldListener(new TextField.TextFieldListener() {
@Override
public void keyTyped(TextField textField, char c) {
if (c == '\n') {
if (!okButton.isDisabled()) {
renameColor(color, textField.getText());
dialog.hide();
}
}
}
});
dialog.show(getStage());
}
private void renameColor(ColorData color, String newName) {
for (Array<StyleData> datas : JsonData.getInstance().getClassStyleMap().values()) {
for (StyleData data : datas) {
for (StyleProperty property : data.properties.values()) {
if (property != null && property.type.equals(Color.class) && property.value != null && property.value.equals(color.getName())) {
property.value = newName;
}
}
}
}
try {
color.setName(newName);
} catch (ColorData.NameFormatException ex) {
Gdx.app.error(getClass().getName(), "Error trying to rename a color.", ex);
}
Main.instance.clearUndoables();
PanelStyleProperties.instance.populate(PanelClassBar.instance.getStyleSelectBox().getSelected());
PanelPreviewProperties.instance.render();
ProjectData.instance().setChangesSaved(false);
populate();
}
private boolean newColor(String name, Color color) {
if (ColorData.validate(name)) {
try {
ProjectData.instance().setChangesSaved(false);
colors.add(new ColorData(name, color));
sortBySelectedMode();
populate();
return true;
} catch (Exception e) {
Gdx.app.log(getClass().getName(), "Error trying to add color.", e);
return false;
}
} else {
return false;
}
}
@Override
protected void result(Object object) {
if (styleProperty != null) {
if (object instanceof ColorData) {
ProjectData.instance().setChangesSaved(false);
ColorData color = (ColorData) object;
PanelStatusBar.instance.message("Selected color " + color.getName() + " for \"" + styleProperty.name + "\"");
styleProperty.value = color.getName();
PanelStyleProperties.instance.populate(PanelClassBar.instance.getStyleSelectBox().getSelected());
} else if (object instanceof Boolean) {
if ((boolean) object) {
ProjectData.instance().setChangesSaved(false);
styleProperty.value = null;
PanelStatusBar.instance.message("Emptied color for \"" + styleProperty.name + "\"");
PanelStyleProperties.instance.populate(PanelClassBar.instance.getStyleSelectBox().getSelected());
} else {
boolean hasColor = false;
for (ColorData color : JsonData.getInstance().getColors()) {
if (color.getName().equals(styleProperty.value)) {
hasColor = true;
break;
}
}
if (!hasColor) {
ProjectData.instance().setChangesSaved(false);
styleProperty.value = null;
PanelStatusBar.instance.message("Deleted color for \"" + styleProperty.name + "\"");
PanelStyleProperties.instance.populate(PanelClassBar.instance.getStyleSelectBox().getSelected());
}
}
}
}
if (listener != null) {
if (object instanceof ColorData) {
listener.handle((ColorData) object);
} else {
listener.handle(null);
}
}
}
private void sortBySelectedMode() {
switch (selectBox.getSelectedIndex()) {
case 0:
sortFontsAZ();
break;
case 1:
sortFontsZA();
break;
}
}
private void sortFontsAZ() {
Sort.instance().sort(colors, new Comparator<ColorData>() {
@Override
public int compare(ColorData o1, ColorData o2) {
return o1.toString().compareToIgnoreCase(o2.toString());
}
});
populate();
}
private void sortFontsZA() {
Sort.instance().sort(colors, new Comparator<ColorData>() {
@Override
public int compare(ColorData o1, ColorData o2) {
return o1.toString().compareToIgnoreCase(o2.toString()) * -1;
}
});
populate();
}
public static interface DialogColorsListener {
public void handle(ColorData colorData);
}
}
|
package me.nallar.javatransformer.internal;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.val;
import me.nallar.javatransformer.api.*;
import me.nallar.javatransformer.internal.util.AnnotationParser;
import me.nallar.javatransformer.internal.util.CollectionUtil;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
@Data
@AllArgsConstructor
@SuppressWarnings("unchecked")
public class ByteCodeInfo implements ClassInfoStreams {
private final Supplier<ClassNode> node;
@Getter(lazy = true)
private final List<Annotation> annotations = getAnnotationsInternal();
private String className;
@Override
public String getName() {
return className;
}
@Override
public void setName(String name) {
className = name;
node.get().name = name.replace('.', '/');
}
@Override
public AccessFlags getAccessFlags() {
return new AccessFlags(node.get().access);
}
@Override
public void setAccessFlags(AccessFlags accessFlags) {
node.get().access = accessFlags.access;
}
public void add(MethodInfo method) {
MethodNode node = new MethodNode();
if (method instanceof MethodNodeInfo) {
val other = ((MethodNodeInfo) method).node;
node.desc = other.desc;
node.signature = other.signature;
node.access = other.access;
node.name = other.name;
node.attrs = other.attrs;
node.annotationDefault = other.annotationDefault;
node.exceptions = other.exceptions;
node.instructions = other.instructions;
node.invisibleAnnotations = other.invisibleAnnotations;
node.invisibleLocalVariableAnnotations = other.invisibleLocalVariableAnnotations;
node.invisibleParameterAnnotations = other.invisibleParameterAnnotations;
node.invisibleTypeAnnotations = other.invisibleTypeAnnotations;
node.visibleAnnotations = other.visibleAnnotations;
node.visibleLocalVariableAnnotations = other.visibleLocalVariableAnnotations;
node.visibleParameterAnnotations = other.visibleParameterAnnotations;
node.visibleTypeAnnotations = other.visibleTypeAnnotations;
node.localVariables = other.localVariables;
node.tryCatchBlocks = other.tryCatchBlocks;
} else {
node.desc = "()V";
node.exceptions = new ArrayList<>();
MethodInfo info = new MethodNodeInfo(node);
info.setAll(method);
}
this.node.get().methods.add(node);
}
public void add(FieldInfo field) {
FieldNode node;
if (field instanceof FieldNodeInfo) {
val other = ((FieldNodeInfo) field).node;
node = new FieldNode(other.access, other.name, other.desc, other.signature, other.value);
node.attrs = other.attrs;
node.invisibleAnnotations = other.invisibleAnnotations;
node.invisibleTypeAnnotations = other.invisibleTypeAnnotations;
node.visibleAnnotations = other.visibleAnnotations;
node.visibleTypeAnnotations = other.visibleTypeAnnotations;
} else {
node = new FieldNode(0, null, "V", null, null);
val nodeInfo = new FieldNodeInfo(node);
nodeInfo.setAll(field);
}
this.node.get().fields.add(node);
}
@Override
public void remove(MethodInfo method) {
MethodNodeInfo methodNodeInfo = !(method instanceof MethodNodeInfo) ? (MethodNodeInfo) get(method) : (MethodNodeInfo) method;
if (methodNodeInfo == null)
throw new RuntimeException("Method " + method + " can not be removed as it is not present");
node.get().methods.remove(methodNodeInfo.node);
}
@Override
public void remove(FieldInfo field) {
FieldNodeInfo fieldNodeInfo = !(field instanceof FieldNodeInfo) ? (FieldNodeInfo) get(field) : (FieldNodeInfo) field;
if (fieldNodeInfo == null)
throw new RuntimeException("Field " + field + " can not be removed as it is not present");
node.get().fields.remove(fieldNodeInfo.node);
}
@Override
public Type getSuperType() {
return new Type("L" + node.get().superName + ";");
}
@Override
public List<Type> getInterfaceTypes() {
return node.get().interfaces.stream().map((it) -> new Type("L" + it + ";")).collect(Collectors.toList());
}
public Stream<MethodInfo> getMethodStream() {
return node.get().methods.stream().map(MethodNodeInfo::new);
}
public Stream<FieldInfo> getFieldStream() {
return node.get().fields.stream().map(FieldNodeInfo::new);
}
private List<Annotation> getAnnotationsInternal() {
return CollectionUtil.union(node.get().invisibleAnnotations, node.get().visibleAnnotations).map(AnnotationParser::annotationFromAnnotationNode).collect(Collectors.toList());
}
@Override
public ClassInfo getClassInfo() {
return this;
}
MethodInfo wrap(MethodNode node) {
return new MethodNodeInfo(node);
}
class FieldNodeInfo implements FieldInfo {
public final FieldNode node;
private Type type;
FieldNodeInfo(FieldNode node) {
this.node = node;
type = new Type(node.desc, node.signature);
}
@Override
public String getName() {
return node.name;
}
@Override
public void setName(String name) {
node.name = name;
}
@Override
public AccessFlags getAccessFlags() {
return new AccessFlags(node.access);
}
@Override
public void setAccessFlags(AccessFlags accessFlags) {
node.access = accessFlags.access;
}
@Override
public Type getType() {
return type;
}
@Override
public void setType(Type type) {
this.type = type;
node.desc = type.descriptor;
node.signature = type.signature;
}
@Override
public List<Annotation> getAnnotations() {
return CollectionUtil.union(node.invisibleAnnotations, node.visibleAnnotations).map(AnnotationParser::annotationFromAnnotationNode).collect(Collectors.toList());
}
@Override
public ClassInfo getClassInfo() {
return ByteCodeInfo.this;
}
}
class MethodNodeInfo implements MethodInfo {
private final MethodNode node;
private MethodDescriptor descriptor;
MethodNodeInfo(MethodNode node) {
this.node = node;
descriptor = new MethodDescriptor(node.desc, node.signature);
}
@Override
public AccessFlags getAccessFlags() {
return new AccessFlags(node.access);
}
@Override
public void setAccessFlags(AccessFlags accessFlags) {
node.access = accessFlags.access;
}
@Override
public String getName() {
return node.name;
}
@Override
public void setName(String name) {
node.name = name;
}
@Override
public Type getReturnType() {
return new MethodDescriptor(node.desc, node.signature).getReturnType();
}
@Override
public void setReturnType(Type returnType) {
descriptor = descriptor.withReturnType(returnType);
descriptor.saveTo(node);
}
@Override
public List<Parameter> getParameters() {
val descriptor = new MethodDescriptor(node.desc, node.signature);
return descriptor.getParameters();
}
@Override
public void setParameters(List<Parameter> parameters) {
descriptor = descriptor.withParameters(parameters);
descriptor.saveTo(node);
}
public String getDescriptor() {
return descriptor.getDescriptor();
}
@Override
public List<Annotation> getAnnotations() {
return CollectionUtil.union(node.invisibleAnnotations, node.visibleAnnotations).map(AnnotationParser::annotationFromAnnotationNode).collect(Collectors.toList());
}
@Override
public ClassInfo getClassInfo() {
return ByteCodeInfo.this;
}
}
}
|
package net.imagej.ops.create.img;
import net.imagej.ops.OpService;
import net.imagej.ops.Ops;
import net.imagej.ops.Output;
import net.imglib2.Interval;
import net.imglib2.img.Img;
import net.imglib2.img.ImgFactory;
import net.imglib2.img.ImgView;
import net.imglib2.type.Type;
import net.imglib2.view.Views;
import org.scijava.ItemIO;
import org.scijava.Priority;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
/**
* Creates an {@link Img} from an {@link Interval}. Minimum and maximum of
* resulting {@link Img} are the same as the minimum and maximum of the incoming
* {@link Interval}.
*
* @author Christian Dietz (University of Konstanz)
* @param <T>
*/
@Plugin(type = Ops.Create.Img.class, name = Ops.Create.Img.NAME,
priority = Priority.HIGH_PRIORITY)
public class CreateImgFromInterval<T extends Type<T>> implements
Ops.Create.Img, Output<Img<T>>
{
@Parameter
private OpService ops;
@Parameter(type = ItemIO.OUTPUT)
private Img<T> output;
@Parameter
private Interval interval;
@Parameter(required = false)
private T outType;
@Parameter(required = false)
private ImgFactory<T> fac;
@SuppressWarnings("unchecked")
@Override
public void run() {
output = (Img<T>) ops.run(DefaultCreateImg.class, interval, outType, fac);
long[] min = new long[interval.numDimensions()];
interval.min(min);
for (int d = 0; d < min.length; d++) {
if (min[d] != 0) {
output = ImgView.wrap(Views.translate(output, min), output.factory());
break;
}
}
}
@Override
public Img<T> getOutput() {
return output;
}
}
|
package io.sniffy.tls;
import io.qameta.allure.Issue;
import io.sniffy.*;
import io.sniffy.configuration.SniffyConfiguration;
import io.sniffy.log.Polyglog;
import io.sniffy.log.PolyglogFactory;
import io.sniffy.log.PolyglogLevel;
import io.sniffy.socket.AddressMatchers;
import io.sniffy.socket.NetworkPacket;
import io.sniffy.socket.SocketMetaData;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockserver.integration.ClientAndServer;
import org.mockserver.logging.MockServerLogger;
import org.mockserver.socket.PortFactory;
import org.mockserver.socket.tls.KeyStoreFactory;
import org.xnio.*;
import org.xnio.channels.Channels;
import org.xnio.channels.ConnectedStreamChannel;
import javax.net.ssl.HttpsURLConnection;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static io.sniffy.socket.NetworkPacket.convertNetworkPacketsToString;
import static org.junit.Assert.*;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
public class DecryptLocalhostHttpsTrafficXNIOTest {
static {
ScheduledThreadDump.scheduleThreadDump(10); // last mile resort for troubleshooting
}
private static final Polyglog LOG = PolyglogFactory.log(DecryptLocalhostHttpsTrafficXNIOTest.class);
@BeforeClass
public static void loadTlsModule() {
HttpsURLConnection.setDefaultSSLSocketFactory(new KeyStoreFactory(new MockServerLogger()).sslContext().getSocketFactory());
SniffyConfiguration.INSTANCE.setDecryptTls(true);
SniffyConfiguration.INSTANCE.setMonitorSocket(true);
SniffyConfiguration.INSTANCE.setMonitorNio(true);
SniffyConfiguration.INSTANCE.setLogLevel(PolyglogLevel.TRACE);
SniffyConfiguration.INSTANCE.setPacketMergeThreshold(10000);
Sniffy.initialize();
}
private ClientAndServer mockServer;
private int port = PortFactory.findFreePort();
@Before
public void startMockServer() {
mockServer = startClientAndServer(port);
mockServer.when(
request()
.withMethod("GET")
.withPath("/")
)
.respond(
response()
.withStatusCode(200)
);
}
@After
public void stopMockServer() {
mockServer.stop();
}
@SuppressWarnings("CharsetObjectCanBeUsed")
@Test
@Issue("issues/539")
public void testLocalhostHttpsTraffic() throws Exception {
try (Spy<?> spy = Sniffy.spy(SpyConfiguration.builder().captureNetworkTraffic(true).captureStackTraces(true).build())) {
//try {
final Charset charset = Charset.forName("utf-8");
final Xnio xnio = Xnio.getInstance();
final XnioWorker worker = xnio.createWorker(OptionMap.EMPTY);
try {
final IoFuture<ConnectedStreamChannel> futureConnection = worker.connectStream(new InetSocketAddress("localhost", port), null, OptionMap.EMPTY);
final ConnectedStreamChannel channel = futureConnection.get(); // throws exceptions
try {
// Send the greeting
Channels.writeBlocking(channel, ByteBuffer.wrap("GET / HTTP/1.1\nHost: localhost\nConnection: Close\n\n".getBytes(charset)));
// Make sure all data is written
Channels.flushBlocking(channel);
// And send EOF
channel.shutdownWrites();
ByteBuffer recvBuf = ByteBuffer.allocate(128);
// Now receive and print the whole response
while (Channels.readBlocking(channel, recvBuf) != -1) {
recvBuf.flip();
final CharBuffer chars = charset.decode(recvBuf);
recvBuf.clear();
}
} finally {
IoUtils.safeClose(channel);
}
} finally {
worker.shutdown();
}
Map<SocketMetaData, List<NetworkPacket>> networkTraffic = spy.getNetworkTraffic(
Threads.ANY,
AddressMatchers.exactAddressMatcher("localhost:" + port),
GroupingOptions.builder().
groupByConnection(false).
groupByStackTrace(false).
groupByThread(false).
build()
);
assertEquals(1, networkTraffic.size());
Map.Entry<SocketMetaData, List<NetworkPacket>> entry = networkTraffic.entrySet().iterator().next();
assertNotNull(entry);
assertNotNull(entry.getKey());
assertNotNull(entry.getValue());
assertEquals("Expected 2 packets, but instead got " + convertNetworkPacketsToString(entry.getValue()), 2, entry.getValue().size());
NetworkPacket request = entry.getValue().get(0);
NetworkPacket response = entry.getValue().get(1);
//noinspection SimplifiableAssertion
assertEquals(true, request.isSent());
//noinspection SimplifiableAssertion
assertEquals(false, response.isSent());
assertTrue(new String(request.getBytes(), Charset.forName("US-ASCII")).toLowerCase(Locale.ROOT).contains("host: localhost"));
assertTrue(new String(response.getBytes(), Charset.forName("US-ASCII")).contains("200"));
} catch (Exception e) {
System.err.flush();
System.err.println("Caught interresting exception! <<<");
e.printStackTrace();
System.err.println("Caught interresting exception! >>>");
System.err.flush();
throw e;
}
}
}
|
package hudson.maven;
import hudson.AbortException;
import hudson.Launcher;
import hudson.FilePath;
import hudson.maven.MavenBuild.ProxyImpl2;
import hudson.FilePath.FileCallable;
import hudson.model.AbstractBuild;
import hudson.model.Action;
import hudson.model.Build;
import hudson.model.BuildListener;
import hudson.model.Hudson;
import hudson.model.Result;
import hudson.model.AbstractProject;
import hudson.remoting.VirtualChannel;
import hudson.remoting.Channel;
import hudson.util.ArgumentListBuilder;
import org.apache.maven.BuildFailureException;
import org.apache.maven.embedder.MavenEmbedderException;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.execution.ReactorManager;
import org.apache.maven.lifecycle.LifecycleExecutionException;
import org.apache.maven.monitor.event.EventDispatcher;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuildingException;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* {@link Build} for {@link MavenModuleSet}.
*
* <p>
* A "build" of {@link MavenModuleSet} consists of:
*
* <ol>
* <li>Update the workspace.
* <li>Parse POMs
* <li>Trigger module builds.
* </ol>
*
* This object remembers the changelog and what {@link MavenBuild}s are done
* on this.
*
* @author Kohsuke Kawaguchi
*/
public final class MavenModuleSetBuild extends AbstractBuild<MavenModuleSet,MavenModuleSetBuild> {
public MavenModuleSetBuild(MavenModuleSet job) throws IOException {
super(job);
}
public MavenModuleSetBuild(MavenModuleSet project, File buildDir) throws IOException {
super(project, buildDir);
}
/**
* Displays the combined status of all modules.
* <p>
* More precisely, this picks up the status of this build itself,
* plus all the latest builds of the modules that belongs to this build.
*/
@Override
public Result getResult() {
Result r = super.getResult();
for (MavenBuild b : getModuleLastBuilds().values()) {
Result br = b.getResult();
if(r==null)
r = br;
else
if(br==Result.NOT_BUILT)
continue; // UGLY: when computing combined status, ignore the modules that were not built
else
if(br!=null)
r = r.combine(br);
}
return r;
}
/**
* Computes the module builds that correspond to this build.
* <p>
* A module may be built multiple times (by the user action),
* so the value is a list.
*/
public Map<MavenModule,List<MavenBuild>> getModuleBuilds() {
Collection<MavenModule> mods = getParent().getModules();
// identify the build number range. [start,end)
MavenModuleSetBuild nb = getNextBuild();
int end = nb!=null ? nb.getNumber() : Integer.MAX_VALUE;
// preserve the order by using LinkedHashMap
Map<MavenModule,List<MavenBuild>> r = new LinkedHashMap<MavenModule,List<MavenBuild>>(mods.size());
for (MavenModule m : mods) {
List<MavenBuild> builds = new ArrayList<MavenBuild>();
MavenBuild b = m.getNearestBuild(number);
while(b!=null && b.getNumber()<end) {
builds.add(b);
b = b.getNextBuild();
}
r.put(m,builds);
}
return r;
}
/**
* Computes the latest module builds that correspond to this build.
*/
public Map<MavenModule,MavenBuild> getModuleLastBuilds() {
Collection<MavenModule> mods = getParent().getModules();
// identify the build number range. [start,end)
MavenModuleSetBuild nb = getNextBuild();
int end = nb!=null ? nb.getNumber() : Integer.MAX_VALUE;
// preserve the order by using LinkedHashMap
Map<MavenModule,MavenBuild> r = new LinkedHashMap<MavenModule,MavenBuild>(mods.size());
for (MavenModule m : mods) {
MavenBuild b = m.getNearestOldBuild(end - 1);
if(b!=null && b.getNumber()>=getNumber())
r.put(m,b);
}
return r;
}
/**
* Finds {@link Action}s from all the module builds that belong to this
* {@link MavenModuleSetBuild}. One action per one {@link MavenModule},
* and newer ones take precedence over older ones.
*/
public <T extends Action> List<T> findModuleBuildActions(Class<T> action) {
Collection<MavenModule> mods = getParent().getModules();
List<T> r = new ArrayList<T>(mods.size());
// identify the build number range. [start,end)
MavenModuleSetBuild nb = getNextBuild();
int end = nb!=null ? nb.getNumber()-1 : Integer.MAX_VALUE;
for (MavenModule m : mods) {
MavenBuild b = m.getNearestOldBuild(end);
while(b!=null && b.getNumber()>=number) {
T a = b.getAction(action);
if(a!=null) {
r.add(a);
break;
}
b = b.getPreviousBuild();
}
}
return r;
}
public void run() {
run(new RunnerImpl());
getProject().updateTransientActions();
}
/**
* Called when a module build that corresponds to this module set build
* has completed.
*/
/*package*/ void notifyModuleBuild(MavenBuild newBuild) {
try {
// update module set build number
getParent().updateNextBuildNumber();
// update actions
Map<MavenModule, List<MavenBuild>> moduleBuilds = getModuleBuilds();
// actions need to be replaced atomically especially
// given that two builds might complete simultaneously.
synchronized(this) {
boolean modified = false;
List<Action> actions = getActions();
Set<Class<? extends AggregatableAction>> individuals = new HashSet<Class<? extends AggregatableAction>>();
for (Action a : actions) {
if(a instanceof MavenAggregatedReport) {
MavenAggregatedReport mar = (MavenAggregatedReport) a;
mar.update(moduleBuilds,newBuild);
individuals.add(mar.getIndividualActionType());
modified = true;
}
}
// see if the new build has any new aggregatable action that we haven't seen.
for (Action a : newBuild.getActions()) {
if (a instanceof AggregatableAction) {
AggregatableAction aa = (AggregatableAction) a;
if(individuals.add(aa.getClass())) {
// new AggregatableAction
MavenAggregatedReport mar = aa.createAggregatedAction(this, moduleBuilds);
mar.update(moduleBuilds,newBuild);
actions.add(mar);
modified = true;
}
}
}
if(modified) {
save();
getProject().updateTransientActions();
}
}
} catch (IOException e) {
LOGGER.log(Level.WARNING,"Failed to update "+this,e);
}
}
/**
* The sole job of the {@link MavenModuleSet} build is to update SCM
* and triggers module builds.
*/
private class RunnerImpl extends AbstractRunner {
private Map<ModuleName,MavenBuild.ProxyImpl2> proxies;
protected Result doRun(final BuildListener listener) throws Exception {
PrintStream logger = listener.getLogger();
try {
parsePoms(listener, logger);
if(!project.isAggregatorStyleBuild()) {
// start module builds
logger.println("Triggering "+project.getRootModule().getModuleName());
project.getRootModule().scheduleBuild();
} else {
// do builds here
SplittableBuildListener slistener = new SplittableBuildListener(listener);
proxies = new HashMap<ModuleName, ProxyImpl2>();
for (MavenModule m : project.sortedActiveModules)
proxies.put(m.getModuleName(),m.newBuild().new ProxyImpl2(MavenModuleSetBuild.this,slistener));
// run the complete build here
FilePath pom = project.getModuleRoot().child(project.getRootPOM());
Map<String,String> envVars = getEnvVars();
ProcessCache.MavenProcess process = MavenBuild.mavenProcessCache.get(launcher.getChannel(), slistener,
new MavenProcessFactory(project,launcher,envVars,pom.getParent()));
ArgumentListBuilder margs = new ArgumentListBuilder();
margs.add("-B").add("-f", pom.getRemote());
margs.addTokenized(project.getGoals());
Builder builder = new Builder(slistener, proxies, project.sortedActiveModules, margs.toList(), envVars);
MavenProbeAction mpa=null;
try {
mpa = new MavenProbeAction(project,process.channel);
addAction(mpa);
return process.channel.call(builder);
} finally {
builder.end(launcher);
getActions().remove(mpa);
process.discard();
}
}
return null;
} catch (AbortException e) {
// error should have been already reported.
return Result.FAILURE;
} catch (IOException e) {
e.printStackTrace(listener.error("Failed to parse POMs"));
return Result.FAILURE;
} catch (InterruptedException e) {
listener.error("Aborted");
return Result.ABORTED;
} catch (RuntimeException e) {
// bug in the code.
e.printStackTrace(listener.error("Processing failed due to a bug in the code. Please report thus to users@hudson.dev.java.net"));
logger.println("project="+project);
logger.println("project.getModules()="+project.getModules());
logger.println("project.getRootModule()="+project.getRootModule());
throw e;
}
}
private void parsePoms(BuildListener listener, PrintStream logger) throws IOException, InterruptedException {
logger.println("Parsing POMs");
List<PomInfo> poms;
try {
poms = project.getModuleRoot().act(new PomParser(listener,project.getRootPOM(),project.getProfiles()));
} catch (IOException e) {
if (e.getCause() instanceof AbortException)
throw (AbortException) e.getCause();
throw e;
} catch (MavenExecutionException e) {
// Maven failed to parse POM
e.getCause().printStackTrace(listener.error("Failed to parse POM"));
throw new AbortException();
}
// update the module list
Map<ModuleName,MavenModule> modules = project.modules;
synchronized(modules) {
Map<ModuleName,MavenModule> old = new HashMap<ModuleName, MavenModule>(modules);
List<MavenModule> sortedModules = new ArrayList<MavenModule>();
modules.clear();
if(debug)
logger.println("Root POM is "+poms.get(0).name);
project.reconfigure(poms.get(0));
for (PomInfo pom : poms) {
MavenModule mm = old.get(pom.name);
if(mm!=null) {// found an existing matching module
if(debug)
logger.println("Reconfiguring "+mm);
mm.reconfigure(pom);
modules.put(pom.name,mm);
} else {// this looks like a new module
logger.println("Discovered a new module "+pom.name+" "+pom.displayName);
mm = new MavenModule(project,pom,getNumber());
modules.put(mm.getModuleName(),mm);
}
sortedModules.add(mm);
mm.save();
}
// at this point the list contains all the live modules
project.sortedActiveModules = sortedModules;
// remaining modules are no longer active.
old.keySet().removeAll(modules.keySet());
for (MavenModule om : old.values()) {
if(debug)
logger.println("Disabling "+om);
om.disable();
}
modules.putAll(old);
}
// we might have added new modules
Hudson.getInstance().rebuildDependencyGraph();
// module builds must start with this build's number
for (MavenModule m : modules.values())
m.updateNextBuildNumber(getNumber());
}
protected void post2(BuildListener listener) throws Exception {
// asynchronous executions from the build might have left some unsaved state,
// so just to be safe, save them all.
for (MavenBuild b : getModuleLastBuilds().values())
b.save();
}
@Override
public void cleanUp(BuildListener listener) throws Exception {
if(project.isAggregatorStyleBuild()) {
// schedule downstream builds. for non aggregator style builds,
// this is done by each module
if(getResult().isBetterOrEqualTo(Result.SUCCESS)) {
HashSet<AbstractProject> downstreams = new HashSet<AbstractProject>(project.modules.values());
downstreams.add(project);
for (ProxyImpl2 p : proxies.values())
p.owner().scheduleDownstreamBuilds(listener,downstreams);
}
}
}
}
/**
* Runs Maven and builds the project.
*
* This is only used for
* {@link MavenModuleSet#isAggregatorStyleBuild() the aggregator style build}.
*/
private static final class Builder extends MavenBuilder {
private final Map<ModuleName,MavenBuildProxy2> proxies;
private final Map<ModuleName,List<MavenReporter>> reporters = new HashMap<ModuleName,List<MavenReporter>>();
private final Map<ModuleName,List<ExecutedMojo>> executedMojos = new HashMap<ModuleName,List<ExecutedMojo>>();
private long mojoStartTime;
private MavenBuildProxy2 lastProxy;
/**
* Kept so that we can finalize them in the end method.
*/
private final transient Map<ModuleName,ProxyImpl2> sourceProxies;
public Builder(BuildListener listener,Map<ModuleName,ProxyImpl2> proxies, Collection<MavenModule> modules, List<String> goals, Map<String,String> systemProps) {
super(listener,goals,systemProps);
this.sourceProxies = proxies;
this.proxies = new HashMap<ModuleName, MavenBuildProxy2>(proxies);
for (Entry<ModuleName,MavenBuildProxy2> e : this.proxies.entrySet())
e.setValue(new FilterImpl(e.getValue()));
for (MavenModule m : modules)
reporters.put(m.getModuleName(),m.createReporters());
}
private class FilterImpl extends MavenBuildProxy2.Filter<MavenBuildProxy2> implements Serializable {
public FilterImpl(MavenBuildProxy2 core) {
super(core);
}
public void executeAsync(final BuildCallable<?,?> program) throws IOException {
futures.add(Channel.current().callAsync(new AsyncInvoker(core,program)));
}
private static final long serialVersionUID = 1L;
}
/**
* Invoked after the maven has finished running, and in the master, not in the maven process.
*/
void end(Launcher launcher) throws IOException, InterruptedException {
for (Map.Entry<ModuleName,ProxyImpl2> e : sourceProxies.entrySet()) {
ProxyImpl2 p = e.getValue();
for (MavenReporter r : reporters.get(e.getKey())) {
// we'd love to do this when the module build ends, but doing so requires
// we know how many task segments are in the current build.
r.end(p.owner(),launcher,listener);
p.appendLastLog();
}
p.close();
}
}
public Result call() throws IOException {
try {
return super.call();
} finally {
if(lastProxy!=null)
lastProxy.appendLastLog();
}
}
void preBuild(MavenSession session, ReactorManager rm, EventDispatcher dispatcher) throws BuildFailureException, LifecycleExecutionException, IOException, InterruptedException {
// TODO
}
void postBuild(MavenSession session, ReactorManager rm, EventDispatcher dispatcher) throws BuildFailureException, LifecycleExecutionException, IOException, InterruptedException {
// TODO
}
void preModule(MavenProject project) throws InterruptedException, IOException, hudson.maven.agent.AbortException {
ModuleName name = new ModuleName(project);
MavenBuildProxy2 proxy = proxies.get(name);
listener.getLogger().flush(); // make sure the data until here are all written
proxy.start();
for (MavenReporter r : reporters.get(name))
if(!r.preBuild(proxy,project,listener))
throw new hudson.maven.agent.AbortException(r+" failed");
}
void postModule(MavenProject project) throws InterruptedException, IOException, hudson.maven.agent.AbortException {
ModuleName name = new ModuleName(project);
MavenBuildProxy2 proxy = proxies.get(name);
List<MavenReporter> rs = reporters.get(name);
if(rs==null) { // probe for issue #906
throw new AssertionError("reporters.get("+name+")==null. reporters="+reporters+" proxies="+proxies);
}
for (MavenReporter r : rs)
if(!r.postBuild(proxy,project,listener))
throw new hudson.maven.agent.AbortException(r+" failed");
proxy.setExecutedMojos(executedMojos.get(name));
listener.getLogger().flush(); // make sure the data until here are all written
proxy.end();
lastProxy = proxy;
}
void preExecute(MavenProject project, MojoInfo mojoInfo) throws IOException, InterruptedException, hudson.maven.agent.AbortException {
ModuleName name = new ModuleName(project);
MavenBuildProxy proxy = proxies.get(name);
for (MavenReporter r : reporters.get(name))
if(!r.preExecute(proxy,project,mojoInfo,listener))
throw new hudson.maven.agent.AbortException(r+" failed");
mojoStartTime = System.currentTimeMillis();
}
void postExecute(MavenProject project, MojoInfo mojoInfo, Exception exception) throws IOException, InterruptedException, hudson.maven.agent.AbortException {
ModuleName name = new ModuleName(project);
List<ExecutedMojo> mojoList = executedMojos.get(name);
if(mojoList==null)
executedMojos.put(name,mojoList=new ArrayList<ExecutedMojo>());
mojoList.add(new ExecutedMojo(mojoInfo,System.currentTimeMillis()-mojoStartTime));
MavenBuildProxy2 proxy = proxies.get(name);
for (MavenReporter r : reporters.get(name))
if(!r.postExecute(proxy,project,mojoInfo,listener,exception))
throw new hudson.maven.agent.AbortException(r+" failed");
if(exception!=null)
proxy.setResult(Result.FAILURE);
}
private static final long serialVersionUID = 1L;
}
/**
* Used to tunnel exception from Maven through remoting.
*/
private static final class MavenExecutionException extends RuntimeException {
private MavenExecutionException(Exception cause) {
super(cause);
}
public Exception getCause() {
return (Exception)super.getCause();
}
private static final long serialVersionUID = 1L;
}
/**
* Executed on the slave to parse POM and extract information into {@link PomInfo},
* which will be then brought back to the master.
*/
private static final class PomParser implements FileCallable<List<PomInfo>> {
private final BuildListener listener;
private final String rootPOM;
/**
* Capture the value of the static field so that the debug flag
* takes an effect even when {@link PomParser} runs in a slave.
*/
private final boolean versbose = debug;
private final String profiles;
public PomParser(BuildListener listener, String rootPOM, String profiles) {
this.listener = listener;
this.rootPOM = rootPOM;
this.profiles = profiles;
}
/**
* Computes the path of {@link #rootPOM}.
*
* Returns "abc" if rootPOM="abc/pom.xml"
* If rootPOM="pom.xml", this method returns "".
*/
private String getRootPath() {
int idx = Math.max(rootPOM.lastIndexOf('/'), rootPOM.lastIndexOf('\\'));
if(idx==-1) return "";
return rootPOM.substring(0,idx);
}
public List<PomInfo> invoke(File ws, VirtualChannel channel) throws IOException {
File pom = new File(ws,rootPOM);
PrintStream logger = listener.getLogger();
if(!pom.exists()) {
logger.println("No such file "+pom);
logger.println("Perhaps you need to specify the correct POM file path in the project configuration?");
throw new AbortException();
}
if(versbose)
logger.println("Parsing "+pom);
try {
MavenEmbedder embedder = MavenUtil.createEmbedder(listener, profiles);
MavenProject mp = embedder.readProject(pom);
Map<MavenProject,String> relPath = new HashMap<MavenProject,String>();
MavenUtil.resolveModules(embedder,mp,getRootPath(),relPath,listener);
if(versbose) {
for (Entry<MavenProject, String> e : relPath.entrySet())
logger.printf("Discovered %s at %s\n",e.getKey().getId(),e.getValue());
}
List<PomInfo> infos = new ArrayList<PomInfo>();
toPomInfo(mp,null,relPath,infos);
for (PomInfo pi : infos)
pi.cutCycle();
embedder.stop();
return infos;
} catch (MavenEmbedderException e) {
throw new MavenExecutionException(e);
} catch (ProjectBuildingException e) {
throw new MavenExecutionException(e);
}
}
private void toPomInfo(MavenProject mp, PomInfo parent, Map<MavenProject,String> relPath, List<PomInfo> infos) {
PomInfo pi = new PomInfo(mp, parent, relPath.get(mp));
infos.add(pi);
for (MavenProject child : (List<MavenProject>)mp.getCollectedProjects())
toPomInfo(child,pi,relPath,infos);
}
private static final long serialVersionUID = 1L;
}
private static final Logger LOGGER = Logger.getLogger(MavenModuleSetBuild.class.getName());
/**
* Extra versbose debug switch.
*/
public static boolean debug = false;
}
|
package com.github.TKnudsen.activeLearning.models.activeLearning.queryByCommittee;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.github.TKnudsen.ComplexDataObject.data.entry.EntryWithComparableKey;
import com.github.TKnudsen.ComplexDataObject.data.features.AbstractFeatureVector;
import com.github.TKnudsen.ComplexDataObject.data.features.Feature;
import com.github.TKnudsen.ComplexDataObject.data.ranking.Ranking;
import com.github.TKnudsen.DMandML.data.classification.IProbabilisticClassificationResultSupplier;
import com.github.TKnudsen.DMandML.model.supervised.classifier.Classifier;
public class KullbackLeiblerQueryByCommittee<O, FV extends AbstractFeatureVector<O, ? extends Feature<O>>> extends AbstractQueryByCommitteeActiveLearning<O, FV> {
private boolean positiveDivergences = true;
private boolean normalizeAlphabetLength = true;
protected KullbackLeiblerQueryByCommittee() {
}
public KullbackLeiblerQueryByCommittee(List<Classifier<O, FV>> learningModels) {
super(learningModels);
}
// TODO add constructor with IProbabilisticClassificationResultSupplier
public KullbackLeiblerQueryByCommittee(List<IProbabilisticClassificationResultSupplier<FV>> classificationResultSuppliers, boolean fakeBooleanToBeDifferentThanDeprecateConstructor) {
super(classificationResultSuppliers, false);
}
@Override
public String getComparisonMethod() {
return "Uses entropy to identify instances where models disagree";
}
@Override
protected void calculateRanking(int count) {
for (Classifier<O, FV> classifier : getLearningModels())
classifier.test(learningCandidateFeatureVectors);
ranking = new Ranking<>();
queryApplicabilities = new HashMap<>();
remainingUncertainty = 0.0;
// calculate overall score
for (FV fv : learningCandidateFeatureVectors) {
List<Map<String, Double>> labelDistributions = new ArrayList<>();
for (Classifier<O, FV> classifier : getLearningModels())
labelDistributions.add(classifier.getLabelDistribution(fv));
// create unified distribution arrays
Set<String> labelSet = new HashSet<>();
for (Map<String, Double> map : labelDistributions)
if (map != null)
for (String s : map.keySet())
labelSet.add(s);
List<List<Double>> distributions = new ArrayList<>();
for (Map<String, Double> map : labelDistributions) {
if (map == null)
continue;
List<Double> values = new ArrayList<>();
for (String s : labelSet)
if (map.get(s) != null)
values.add(map.get(s));
else
values.add(0.0);
distributions.add(values);
}
double dist = 0;
if (distributions != null && distributions.size() > 0) {
dist = calculateKLDivergence(distributions);
} else
dist = 1;
// update ranking
ranking.add(new EntryWithComparableKey<Double, FV>(1 - dist, fv));
queryApplicabilities.put(fv, dist);
remainingUncertainty += dist;
if (ranking.size() > count)
ranking.remove(ranking.size() - 1);
}
remainingUncertainty /= (double) learningCandidateFeatureVectors.size();
System.out.println("KullbackLeiblerQueryByCommittee: remaining uncertainty = " + remainingUncertainty);
}
private List<Double> calculateConsensusDistribution(List<List<Double>> distributions) {
// not weighted votes
int distributionSize = distributions.get(0).size();
List<Double> consensusDistribution = new ArrayList<>();
for (int i = 0; i < distributionSize; i++)
consensusDistribution.add(0d);
for (List<Double> learnerDistribution : distributions) {
for (int i = 0; i < distributionSize; i++) {
double d = consensusDistribution.get(i) + learnerDistribution.get(i);
consensusDistribution.set(i, d);
}
}
// normalize
for (int i = 0; i < distributionSize; i++) {
// double d = consensusDistribution.get(i) / distributionSize;
double d = consensusDistribution.get(i) / distributions.size();
consensusDistribution.set(i, d);
}
return consensusDistribution;
}
private double calculateKLDivergence(List<List<Double>> distributions) {
List<Double> consensusDistribution = calculateConsensusDistribution(distributions);
int learnerCounts = distributions.size();
double result = 0;
for (int i = 0; i < learnerCounts; i++) {
// double consensus = consensusDistribution.get(i);
// for (Double d : distributions.get(i)) {
// result += d * Math.log(d / consensus);
// made some changes here
for (int j = 0; j < consensusDistribution.size(); j++) {
double consensus = consensusDistribution.get(j);
Double d = distributions.get(i).get(j);
if (d <= 0)
result += 0;
else if (consensus == 0)
result += 1;
else if (positiveDivergences)
result += Math.abs(d * Math.log(d / consensus));
else
result += d * Math.log(d / consensus);
}
}
// normalize?
if (normalizeAlphabetLength)
result = result / learnerCounts;
return result;
}
public boolean isPositiveDivergences() {
return positiveDivergences;
}
public void setPositiveDivergences(boolean positiveDivergences) {
this.positiveDivergences = positiveDivergences;
}
public boolean isNormalizeAlphabetLength() {
return normalizeAlphabetLength;
}
public void setNormalizeAlphabetLength(boolean normalizeAlphabetLength) {
this.normalizeAlphabetLength = normalizeAlphabetLength;
}
@Override
public String getName() {
return "Kullback Leibler QBC";
}
@Override
public String getDescription() {
return "Active Learning Model using the Kullback Leibler Divergence in combination with a Query by Committee approach";
}
}
|
package io.ddf.content;
import io.ddf.DDF;
import io.ddf.exception.DDFException;
import io.ddf.misc.ADDFFunctionalGroupHandler;
public class MutabilityHandler extends ADDFFunctionalGroupHandler implements IHandleMutability {
public MutabilityHandler(DDF theDDF) {
super(theDDF);
// TODO Auto-generated constructor stub
}
private boolean isMutable = true;
@Override
public boolean isMutable() {
return isMutable;
}
@Override
public void setMutable(boolean isMutable) {
this.isMutable = isMutable;
}
@Override
public DDF updateInplace(DDF newddf) throws DDFException {
//copy content of newddf to this ddf
DDF curDDF = this.getDDF();
curDDF.getRepresentationHandler().reset();
curDDF.getRepresentationHandler().setRepresentations(newddf.getRepresentationHandler().getAllRepresentations());
newddf.getMetaDataHandler().copyFactor(this.getDDF());
curDDF.getSchemaHandler().setSchema(newddf.getSchema());
return curDDF;
}
}
|
package uk.gov.nationalarchives.discovery.taxonomy.common.service.impl;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import uk.gov.nationalarchives.discovery.taxonomy.common.domain.repository.lucene.InformationAssetViewFields;
import uk.gov.nationalarchives.discovery.taxonomy.common.domain.repository.mongo.CategoryLight;
import uk.gov.nationalarchives.discovery.taxonomy.common.domain.repository.mongo.IAViewUpdate;
import uk.gov.nationalarchives.discovery.taxonomy.common.domain.repository.mongo.MongoInformationAssetView;
import uk.gov.nationalarchives.discovery.taxonomy.common.repository.mongo.InformationAssetViewMongoRepository;
import uk.gov.nationalarchives.discovery.taxonomy.common.repository.solr.SolrCloudIAViewRepository;
import uk.gov.nationalarchives.discovery.taxonomy.common.service.UpdateSolrCloudService;
import java.util.*;
@Service
@ConditionalOnProperty(prefix = "solr.cloud.", value = "host")
public class UpdateSolrCloudServiceImpl implements UpdateSolrCloudService {
private static final String FIELD_MODIFIER_KEY_SET = "set";
private static final Logger logger = LoggerFactory.getLogger(UpdateSolrCloudServiceImpl.class);
private final SolrCloudIAViewRepository solrIAViewRepository;
private final InformationAssetViewMongoRepository informationAssetViewMongoRepository;
@Autowired
public UpdateSolrCloudServiceImpl(SolrCloudIAViewRepository solrIAViewRepository,
InformationAssetViewMongoRepository informationAssetViewMongoRepository) {
super();
this.solrIAViewRepository = solrIAViewRepository;
this.informationAssetViewMongoRepository = informationAssetViewMongoRepository;
}
@Override
public void updateCategoriesOnIAView(String docReference) {
logger.info(".updateCategoriesOnIAView: {}", docReference);
List<CategoryLight> categories = retrieveCategoriesForIAView(docReference);
SolrInputDocument document = createDocumentForAtomicUpdate(docReference, categories);
solrIAViewRepository.save(document);
}
private List<CategoryLight> retrieveCategoriesForIAView(String docReference) {
MongoInformationAssetView iaViewWithCategories = informationAssetViewMongoRepository
.findByDocReference(docReference);
List<CategoryLight> categories = iaViewWithCategories.getCategories();
return categories;
}
@Override
public void bulkUpdateCategoriesOnIAViews(List<IAViewUpdate> listOfIAViewUpdatesToProcess) {
logger.info(".updateCategoriesOnIAView: {}",
Arrays.toString(retrieveArrayOfDocRefsFromListOfIAViewUpdates(listOfIAViewUpdatesToProcess)));
List<SolrInputDocument> listOfUpdatesToSubmitToSolr = new ArrayList<SolrInputDocument>();
for (IAViewUpdate iaViewUpdate : listOfIAViewUpdatesToProcess) {
SolrInputDocument document = createDocumentForAtomicUpdate(iaViewUpdate.getDocReference(),
iaViewUpdate.getCategories());
listOfUpdatesToSubmitToSolr.add(document);
}
solrIAViewRepository.saveAll(listOfUpdatesToSubmitToSolr);
}
private String[] retrieveArrayOfDocRefsFromListOfIAViewUpdates(List<IAViewUpdate> listOfIAViewUpdatesToProcess) {
List<String> listOfDocReferences = new ArrayList<String>();
for (IAViewUpdate iaViewUpdate : listOfIAViewUpdatesToProcess) {
listOfDocReferences.add(iaViewUpdate.getDocReference());
}
return listOfDocReferences.toArray(new String[0]);
}
private SolrInputDocument createDocumentForAtomicUpdate(String docReference, List<CategoryLight> categories) {
SolrInputDocument solrInputDocument = new SolrInputDocument();
solrInputDocument.addField(InformationAssetViewFields.DOCREFERENCE.toString(), docReference);
List<String> listOfCiaidAndTtls = new ArrayList<String>();
List<String> listOfCiaids = new ArrayList<String>();
for (CategoryLight category : categories) {
listOfCiaidAndTtls.add(category.getCiaidAndTtl());
listOfCiaids.add(category.getCiaid());
}
Map<String, List<String>> partialUpdateOnListOfCiaidAndTtls = new HashMap<>();
partialUpdateOnListOfCiaidAndTtls.put("set", listOfCiaidAndTtls);
solrInputDocument.addField(InformationAssetViewFields.TAXONOMY.toString(), partialUpdateOnListOfCiaidAndTtls);
Map<String, List<String>> partialUpdateOnListOfCiaids = new HashMap<>();
partialUpdateOnListOfCiaids.put("set", listOfCiaids);
solrInputDocument.addField(InformationAssetViewFields.TAXONOMYID.toString(), partialUpdateOnListOfCiaids);
return solrInputDocument;
}
}
|
package net.petrovicky.quicksort.impl;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
/**
* Parallel quicksort implementation, leveraging JDK 7's fork-join implementation. When the length of the unsorted range
* drops under {@link #CONCURRENCY_THRESHOLD}, the algorithm switches to {@link Quicksort}.
*
* @param <T>
* Type of the values that are being sorted.
*/
public final class ParallelQuicksort<T extends Comparable<T>> extends RecursiveTask<Boolean> {
/**
* The sole purpose of this class is to prevent {@link #ParallelQuicksort} from referencing two objects. Since there
* will be millions of those objects in memory, saving even one reference in each will be significant.
*
* This class is static for that same reason.
*
*/
private static final class Holder {
@SuppressWarnings("rawtypes")
private final Comparable[] input;
@SuppressWarnings("rawtypes")
private final PartitioningStrategy strategy;
@SuppressWarnings("rawtypes")
public Holder(final Comparable[] input, final PartitioningStrategy strategy) {
this.input = input;
this.strategy = strategy;
}
}
/**
* When the range is shorter than this number, we don't use concurrency anymore.
*/
private static final int CONCURRENCY_THRESHOLD = 1000;
private static final long serialVersionUID = -5434239700032599439L;
private final Holder holder;
private final int left, right;
protected ParallelQuicksort(final Holder holder, final int left, final int right) {
super();
this.holder = holder;
this.left = left;
this.right = right;
}
public ParallelQuicksort(final PartitioningStrategy<T> partitioner, final T[] input) {
this(new Holder(input, partitioner), 0, input.length - 1);
}
@SuppressWarnings("unchecked")
@Override
protected Boolean compute() {
final int size = this.right - this.left + 1;
if (size < 1) {
return true;
} else if (size < ParallelQuicksort.CONCURRENCY_THRESHOLD) {
new Quicksort<T>(this.holder.strategy).sort((T[]) this.holder.input, this.left, this.right);
return true;
}
final int pivotIndex = this.holder.strategy.execute(this.holder.input, this.left, this.right);
final ForkJoinTask<Boolean> left = new ParallelQuicksort<T>(this.holder, this.left, pivotIndex - 1).fork();
new ParallelQuicksort<T>(this.holder, pivotIndex + 1, this.right).fork().join();
left.join();
return true;
}
}
|
package org.jpos.qi.util;
import com.vaadin.ui.renderers.DateRenderer;
import com.vaadin.ui.renderers.NumberRenderer;
import com.vaadin.ui.renderers.Renderer;
import org.apache.commons.lang3.StringUtils;
import org.jpos.qi.QI;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
public class QIUtils {
public static String getCaptionFromId(String id) {
//try to get caption from messages file
String fieldPrefix="field.";
String columnPrefix="column.";
String caption = QI.getQI().getMessage(id);
if (caption.equals(id)) {
//try to get caption without prefix
id = id.startsWith(fieldPrefix) ? id.substring(fieldPrefix.length()) : (id.startsWith(columnPrefix) ? id.substring(columnPrefix.length()) : id);
caption = QI.getQI().getMessage(id);
if (caption.equals(id)) {
//parse existing id to a readable format
return StringUtils.join(StringUtils.splitByCharacterTypeCamelCase(id), ' ');
}
}
return caption;
}
public static Renderer createAmountRenderer () {
NumberFormat amountFormat = NumberFormat.getInstance();
amountFormat.setGroupingUsed(true);
amountFormat.setMinimumFractionDigits(2);
return new NumberRenderer(amountFormat);
}
public static Renderer createTimestampRenderer () {
DateFormat dateFormat = new SimpleDateFormat(QI.getQI().getMessage("timestampformat"));
return new DateRenderer(dateFormat);
}
public static Renderer createDateRenderer () {
DateFormat dateFormat = new SimpleDateFormat(QI.getQI().getMessage("dateformat"));
return new DateRenderer(dateFormat);
}
}
|
package net.shadowfacts.enfusion.entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.projectile.EntityThrowable;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.World;
import net.shadowfacts.enfusion.EnFusion;
import net.shadowfacts.enfusion.config.Configurator;
import cpw.mods.fml.common.registry.EntityRegistry;
public class EntityLaserBolt extends EntityThrowable {
public static void initialize() {
EntityRegistry.registerModEntity(EntityLaserBolt.class, "LaserBolt", Configurator.laserBoltEntityId, EnFusion.instance, 120, 3, true);
}
public EntityLaserBolt(World par1World) {
super(par1World);
this.motionX *= 8;
this.motionY *= 8;
this.motionZ *= 8;
}
public EntityLaserBolt(World par1World, EntityLivingBase par2EntityLivingBase) {
super(par1World, par2EntityLivingBase);
this.motionX *= 8;
this.motionY *= 8;
this.motionZ *= 8;
}
public EntityLaserBolt(World par1World, double par2, double par4, double par6) {
super(par1World, par2, par4, par6);
this.motionX *= 8;
this.motionY *= 8;
this.motionZ *= 8;
}
@Override
public void onImpact(MovingObjectPosition movingobjectposition) {
if (!this.worldObj.isRemote) {
this.worldObj.createExplosion(this, this.posX, this.posY, this.posZ, (float) 6, true);
this.setDead();
}
}
@Override
public float getGravityVelocity() {
return 0;
}
}
|
package org.eclipse.birt.report.designer.internal.ui.wizards;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.birt.report.designer.internal.ui.util.graphics.ImageCanvas;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.ReportPlugin;
import org.eclipse.jface.wizard.WizardPage;
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.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
/**
* Supplies template selection page of new report wizard
*
*/
public class WizardTemplateChoicePage extends WizardPage
{
private static final String MESSAGE_DESCRIPTION = Messages.getString( "WizardTemplateChoicePage.label.Description" ); //$NON-NLS-1$
private static final String MESSAGE_PREVIEW = Messages.getString( "WizardTemplateChoicePage.label.Preview" ); //$NON-NLS-1$
private static final String MESSAGE_REPORT_TEMPLATES = Messages.getString( "WizardTemplateChoicePage.label.ReportTemplates" ); //$NON-NLS-1$
private static final String MESSAGE_SHOW_CHEATSHEET = Messages.getString( "WizardTemplateChoicePage.label.ShowCheatSheets" ); //$NON-NLS-1$)
private static final String TITLE_LETTER = Messages.getString( "WizardTemplateChoicePage.title.Letter" ); //$NON-NLS-1$
private static final String TITLE_SIDE_BY_SIDE_CHART_LISTING = Messages.getString( "WizardTemplateChoicePage.title.SideBySideChartListing" ); //$NON-NLS-1$
private static final String TITLE_CHART_LISTING = Messages.getString( "WizardTemplateChoicePage.title.ChartListing" ); //$NON-NLS-1$
private static final String TITLE_GROUPED_LISTING = Messages.getString( "WizardTemplateChoicePage.title.GroupedListing" ); //$NON-NLS-1$
private static final String TITLE_SIMPLE_LISTING = Messages.getString( "WizardTemplateChoicePage.title.SimpleListing" ); //$NON-NLS-1$
private static final String TITLE_BLANK_REPORT = Messages.getString( "WizardTemplateChoicePage.title.BlankReport" ); //$NON-NLS-1$
private static final String TITLE_DUAL_CHART_LISTING = Messages.getString( "WizardTemplateChoicePage.title.DualChartListing" ); //$NON-NLS-1$
private static final String TITLE_DUAL_COLUMN_LISTING = Messages.getString( "WizardTemplateChoicePage.title.DualColumnListing" ); //$NON-NLS-1$
private static final String TITLE_FIRST_REPORT = Messages.getString( "WizardTemplateChoicePage.title.FirstReport" ); //$NON-NLS-1$
private static final String DESCRIPTION_LETTER = Messages.getString( "WizardTemplateChoicePage.message.Letter" ); //$NON-NLS-1$
private static final String DESCRIPTION_SIDE_BY_SIDE_CHART_LISTING = Messages.getString( "WizardTemplateChoicePage.message.SideBySideChartListing" ); //$NON-NLS-1$
private static final String DESCRIPTION_CHART_LISTING = Messages.getString( "WizardTemplateChoicePage.message.ChartListing" ); //$NON-NLS-1$
private static final String DESCRIPTION_GROUPED_LISTING = Messages.getString( "WizardTemplateChoicePage.message.GroupedListing" ); //$NON-NLS-1$
private static final String DESCRIPTION_SIMPLE_LISTING = Messages.getString( "WizardTemplateChoicePage.message.SimpleListing" ); //$NON-NLS-1$
private static final String DESCRIPTION_BLANK_REPORT = Messages.getString( "WizardTemplateChoicePage.message.BlankReport" ); //$NON-NLS-1$
private static final String DESCRIPTION_DUAL_CHART_LISTING = Messages.getString( "WizardTemplateChoicePage.message.DualChartListing" ); //$NON-NLS-1$
private static final String DESCRIPTION_DUAL_COLUMN_LISTING = Messages.getString( "WizardTemplateChoicePage.message.DualColumnListing" ); //$NON-NLS-1$
private static final String DESCRIPTION_FIRST_REPORT = Messages.getString( "WizardTemplateChoicePage.message.FirstReport" ); //$NON-NLS-1$
private List templateList;
private ImageCanvas previewCanvas;
private Button chkBox;
private Label description;
protected class Template
{
public Template( String name, String description, String reportPath,
String picturePath, String cheatSheetId )
{
this.name = name;
this.descript = description;
this.reportPath = reportPath;
this.picturePath = picturePath;
this.cheatSheetId = cheatSheetId;
}
public String name;
public String descript;
public String reportPath;
public String picturePath;
public String cheatSheetId;
}
protected Template[] templates = new Template[]{
new Template( TITLE_BLANK_REPORT,
DESCRIPTION_BLANK_REPORT,
"/templates/blank_report.rptdesign", //$NON-NLS-1$
"/templates/blank_report.gif", //$NON-NLS-1$
"" ), //$NON-NLS-1$
new Template( TITLE_FIRST_REPORT,
DESCRIPTION_FIRST_REPORT,
"/templates/blank_report.rptdesign", //$NON-NLS-1$
"/templates/blank_report.gif", //$NON-NLS-1$
"org.eclipse.birt.report.designer.ui.cheatsheet.firstreport" ), //$NON-NLS-1$
new Template( TITLE_SIMPLE_LISTING,
DESCRIPTION_SIMPLE_LISTING,
"/templates/simple_listing.rptdesign", //$NON-NLS-1$
"/templates/simple_listing.gif", //$NON-NLS-1$
"org.eclipse.birt.report.designer.ui.cheatsheet.simplelisting" ), //$NON-NLS-1$
new Template( TITLE_GROUPED_LISTING,
DESCRIPTION_GROUPED_LISTING,
"/templates/grouped_listing.rptdesign", //$NON-NLS-1$
"/templates/grouped_listing.gif", //$NON-NLS-1$
"org.eclipse.birt.report.designer.ui.cheatsheet.groupedlisting" ), //$NON-NLS-1$
new Template( TITLE_DUAL_COLUMN_LISTING,
DESCRIPTION_DUAL_COLUMN_LISTING,
"/templates/dual_column_listing.rptdesign", //$NON-NLS-1$
"/templates/dual_column_listing.gif", //$NON-NLS-1$
"org.eclipse.birt.report.designer.ui.cheatsheet.dualcolumnlisting" ), //$NON-NLS-1$
new Template( TITLE_CHART_LISTING,
DESCRIPTION_CHART_LISTING,
"/templates/chart_listing.rptdesign", //$NON-NLS-1$
"/templates/chart_listing.gif", //$NON-NLS-1$
"org.eclipse.birt.report.designer.ui.cheatsheet.chartlisting" ), //$NON-NLS-1$
new Template( TITLE_DUAL_CHART_LISTING,
DESCRIPTION_DUAL_CHART_LISTING,
"/templates/dual_column_chart_listing.rptdesign", //$NON-NLS-1$
"/templates/dual_column_chart_listing.gif", //$NON-NLS-1$
"org.eclipse.birt.report.designer.ui.cheatsheet.dualchartlisting" ), //$NON-NLS-1$
new Template( TITLE_SIDE_BY_SIDE_CHART_LISTING,
DESCRIPTION_SIDE_BY_SIDE_CHART_LISTING,
"/templates/sidebyside_chart_listing.rptdesign", //$NON-NLS-1$
"/templates/sidebyside_chart_listing.gif", //$NON-NLS-1$
"org.eclipse.birt.report.designer.ui.cheatsheet.sidebysidechartlisting" ), //$NON-NLS-1$
/*new Template( TITLE_MAILING_LABELS,
DESCRIPTION_MAILING_LABELS,
"/templates/mailing_labels.rptdesign", //$NON-NLS-1$
"/templates/mailing_labels.gif", //$NON-NLS-1$
"" ), //$NON-NLS-1$*/
new Template( TITLE_LETTER,
DESCRIPTION_LETTER,
"/templates/letter.rptdesign", //$NON-NLS-1$
"/templates/letter.gif", //$NON-NLS-1$
"" ) //$NON-NLS-1$
};
protected int selectedIndex;
protected Map imageMap;
private Composite previewPane;
public class TemplateType
{
public static final int BLANK_REPORT = 0;
public static final int SIMPLE_LISTING = 1;
public static final int GROUPED_LISTING = 2;
public static final int CHART_LISTING = 3;
public static final int CROSSTAB = 4;
public static final int MAILING_LABELS = 5;
public static final int FREE_FORMAT = 6;
public static final int GROUPED_LISTING_HEADING_OUTSIDE = 7;
public static final int DUALCHART_LISTING = 8;
public static final int LETTER = 9;
public static final int SIDEBYSIDE_CHART_LISTING = 10;
public static final int DUAL_COLUMN_CHART_LISTING = 11;
public static final int DASHBOARD_REPORT = 12;
}
/**
* @param pageName
*/
protected WizardTemplateChoicePage( String pageName )
{
super( pageName );
imageMap = new HashMap( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
*/
public void createControl( Composite parent )
{
Composite composite = new Composite( parent, SWT.NONE );
GridLayout gridLayout = new GridLayout( );
gridLayout.numColumns = 2;
gridLayout.marginHeight = 10;
gridLayout.marginWidth = 10;
gridLayout.horizontalSpacing = 10;
gridLayout.verticalSpacing = 10;
composite.setLayout( gridLayout );
Label label0 = new Label( composite, SWT.NONE );
label0.setText( MESSAGE_REPORT_TEMPLATES );
Label previewLabel = new Label( composite, SWT.NONE );
previewLabel.setText( MESSAGE_PREVIEW );
GridData data = new GridData( GridData.BEGINNING );
previewLabel.setLayoutData( data );
templateList = new List( composite, SWT.BORDER );
for ( int i = 0; i < templates.length; i++ )
{
templateList.add( templates[i].name );
}
data = new GridData( GridData.BEGINNING | GridData.FILL_VERTICAL );
data.widthHint = 170;
templateList.setLayoutData( data );
previewPane = new Composite( composite, 0 );
data = new GridData( GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL );
previewPane.setLayoutData( data );
gridLayout = new GridLayout( );
gridLayout.verticalSpacing = 10;
previewPane.setLayout( gridLayout );
previewCanvas = new ImageCanvas( previewPane, SWT.BORDER
| SWT.H_SCROLL
| SWT.V_SCROLL );
data = new GridData( GridData.FILL_VERTICAL | GridData.FILL_HORIZONTAL );
data.grabExcessHorizontalSpace = true;
data.grabExcessVerticalSpace = true;
data.heightHint = 230;
data.widthHint = 185;
previewCanvas.setLayoutData( data );
Label descriptionTitle = new Label( previewPane, SWT.NONE );
descriptionTitle.setText( MESSAGE_DESCRIPTION );
data = new GridData( GridData.FILL_HORIZONTAL );
descriptionTitle.setLayoutData( data );
description = new Label( previewPane, SWT.WRAP );
data = new GridData( GridData.FILL_HORIZONTAL );
data.horizontalIndent = 20;
description.setLayoutData( data );
chkBox = new Button( composite, SWT.CHECK );
chkBox.setText( MESSAGE_SHOW_CHEATSHEET );
chkBox.setSelection( ReportPlugin.readCheatSheetPreference( ) );
chkBox.addSelectionListener( new SelectionListener( ) {
public void widgetSelected( SelectionEvent e )
{
ReportPlugin.writeCheatSheetPreference( chkBox.getSelection( ) );
}
public void widgetDefaultSelected( SelectionEvent e )
{
ReportPlugin.writeCheatSheetPreference( chkBox.getSelection( ) );
}
} );
hookListeners( );
templateList.select( 0 );
templateListener.handleEvent( new Event( ) );
setControl( composite );
}
private void hookListeners( )
{
templateList.addListener( SWT.Selection, templateListener );
}
private Listener templateListener = new Listener( ) {
public void handleEvent( Event event )
{
//change description/image
selectedIndex = templateList.getSelectionIndex( );
description.setText( templates[selectedIndex].descript );
String key = templates[selectedIndex].picturePath;
Object img = imageMap.get( key );
if ( img == null )
{
img = ReportPlugin.getImage( key );
imageMap.put( key, img );
}
previewCanvas.clear( );
previewCanvas.loadImage( ( (Image) img ) );
previewCanvas.showOriginal( );
chkBox.setEnabled( !templates[selectedIndex].cheatSheetId.equals( "" ) ); //$NON-NLS-1$
}
};
/**
* @return Returns the templates of selected item.
*/
public Template getTemplate( )
{
return templates[selectedIndex];
}
/**
* @return Returns the blank report template.
*/
public Template getBlankTemplate( )
{
return templates[0];
}
/**
* @return true if show CheatSheets is checked.
*/
public boolean getShowCheatSheet( )
{
return chkBox.getSelection( );
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.